-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyamlasset-0.py
66 lines (54 loc) · 1.73 KB
/
yamlasset-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
# licensed under terms of MIT License -- Copyright (c) 2024 i4 Ops, inc. and hubbert Smith
import psycopg2
from psycopg2 import sql
import yaml
# Database connection parameters
db_params = {
'dbname': 'i4catalog-v1',
'user': 'hubbert',
'password': 'u0',
'host': 'u0',
'port': 5432
}
def insert_asset(cursor, asset):
insert_query = sql.SQL("""
INSERT INTO "asset-0" (asset_name, asset_oversight, asset_owner, policy, born_on, decommission, notes, tags)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
RETURNING asset_id
""")
cursor.execute(insert_query, (
asset.get('asset_name'),
asset.get('asset_oversight'),
asset.get('asset_owner'),
asset.get('policy'),
asset.get('born_on'),
asset.get('decommission'),
asset.get('notes'),
asset.get('tags') or []
))
return cursor.fetchone()[0]
def main():
# Load data from YAML file
with open('yamlasset-0.yaml', 'r') as file:
assets_data = yaml.safe_load(file)
try:
# Connect to the database
conn = psycopg2.connect(**db_params)
cursor = conn.cursor()
# Insert each asset
for asset in assets_data['assets']:
asset_id = insert_asset(cursor, asset)
print(f"Inserted asset with ID: {asset_id}")
# Commit the changes
conn.commit()
except (Exception, psycopg2.Error) as error:
print("Error while connecting to PostgreSQL or inserting data:", error)
conn.rollback()
finally:
# Close the database connection
if conn:
cursor.close()
conn.close()
print("PostgreSQL connection is closed")
if __name__ == "__main__":
main()