-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyamlpolicy-0.py
92 lines (78 loc) · 2.73 KB
/
yamlpolicy-0.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# licensed under terms of MIT License -- Copyright (c) 2024 i4 Ops, inc. and hubbert Smith
import psycopg2
from psycopg2 import sql
import yaml
from datetime import datetime, date
# Database connection parameters
db_params = {
'dbname': 'i4catalog-v1',
'user': 'hubbert',
'password': 'u0',
'host': 'u0',
'port': 5432
}
def insert_policy(cursor, policy):
insert_query = sql.SQL("""
INSERT INTO "policy-0" (policy, policy_oversight, policy_owner, signoff, date, decommission, notes)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
RETURNING policy_id
""")
cursor.execute(insert_query, (
policy.get('policy'),
policy.get('policy_oversight'),
policy.get('policy_owner'),
policy.get('signoff'),
policy.get('date'),
policy.get('decommission'),
policy.get('notes')
policy.get('tags')
))
return cursor.fetchone()[0]
def parse_date(date_value):
if isinstance(date_value, str):
return datetime.strptime(date_value, '%Y-%m-%d').date()
elif isinstance(date_value, date):
return date_value
elif date_value is None:
return None
else:
raise ValueError(f"Unexpected date format: {date_value}")
def main():
# Load data from YAML file
with open('yamlpolicy-0.yaml', 'r') as file:
policies_data = yaml.safe_load(file)
try:
# Connect to the database
conn = psycopg2.connect(**db_params)
cursor = conn.cursor()
# Insert each policy
for policy in policies_data['policies']:
# Convert date strings to datetime objects
for date_field in ['date', 'decommission']:
if date_field in policy:
try:
policy[date_field] = parse_date(policy[date_field])
except ValueError as e:
print(f"Error parsing {date_field} for policy: {e}")
print(f"Policy data: {policy}")
continue
try:
policy_id = insert_policy(cursor, policy)
print(f"Inserted policy with ID: {policy_id}")
except Exception as e:
print(f"Error inserting policy: {e}")
print(f"Policy data: {policy}")
# Commit the changes
conn.commit()
except (Exception, psycopg2.Error) as error:
print("Error while connecting to PostgreSQL or inserting data:", error)
if conn:
conn.rollback()
finally:
# Close the database connection
if conn:
cursor.close()
conn.close()
print("PostgreSQL connection is closed")
if __name__ == "__main__":
main()