-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyamlpolicy-event.py
87 lines (73 loc) · 2.46 KB
/
yamlpolicy-event.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
# 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_event(cursor, event):
insert_query = sql.SQL("""
INSERT INTO "policy-event" (policy_id, event, signoff, date, notes, tags)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING id
""")
cursor.execute(insert_query, (
event.get('policy_id'),
event.get('event'),
event.get('signoff'),
event.get('date'),
event.get('notes')
event.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-event.yaml', 'r') as file:
events_data = yaml.safe_load(file)
try:
# Connect to the database
conn = psycopg2.connect(**db_params)
cursor = conn.cursor()
# Insert each policy event
for event in events_data['policy_events']:
try:
# Convert date string to datetime object
if 'date' in event:
event['date'] = parse_date(event['date'])
event_id = insert_policy_event(cursor, event)
print(f"Inserted policy event with ID: {event_id}")
except ValueError as e:
print(f"Error parsing date for event: {e}")
print(f"Event data: {event}")
except Exception as e:
print(f"Error inserting event: {e}")
print(f"Event data: {event}")
# 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()