tabletop-frog/ttfrog/db/bootstrap.py

40 lines
1.1 KiB
Python
Raw Normal View History

2024-01-28 00:46:19 -08:00
import logging
2024-01-30 01:25:02 -08:00
from ttfrog.db.manager import db
from ttfrog.db import schema
2024-01-28 00:46:19 -08:00
2024-01-30 01:25:02 -08:00
from sqlalchemy.exc import IntegrityError
2024-01-28 00:46:19 -08:00
# move this to json or whatever
data = {
2024-01-30 01:25:02 -08:00
'Ancestry': [
{'id': 1, 'name': 'human'},
{'id': 2, 'name': 'dragonborn'},
{'id': 3, 'name': 'tiefling'},
2024-01-28 00:46:19 -08:00
],
2024-01-30 01:25:02 -08:00
'Character': [
{'id': 1, 'name': 'Sabetha', 'ancestry': 'tiefling', 'level': 10, 'str': 10, 'dex': 10, 'con': 10, 'int': 10, 'wis': 10, 'cha': 10},
2024-01-28 14:31:50 -08:00
]
2024-01-28 00:46:19 -08:00
}
def bootstrap():
"""
Initialize the database with source data. Idempotent; will skip anything that already exists.
"""
2024-01-30 01:25:02 -08:00
db.init()
for table, records in data.items():
model = getattr(schema, table)
2024-01-28 22:14:50 -08:00
2024-01-30 01:25:02 -08:00
for rec in records:
2024-01-31 22:39:54 -08:00
obj = model(**rec)
try:
with db.transaction():
db.session.add(obj)
except IntegrityError as e:
if 'UNIQUE constraint failed' in str(e):
logging.info(f"Skipping existing {table} {obj}")
continue
raise
logging.info(f"Created {table} {obj}")