tabletop-frog/ttfrog/db/bootstrap.py

44 lines
1.2 KiB
Python
Raw Normal View History

2024-01-28 00:46:19 -08:00
import logging
2024-01-30 01:25:02 -08:00
import transaction
2024-01-28 00:46:19 -08:00
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:
with transaction.manager as tx:
obj = model(**rec)
db.session.add(obj)
obj.slug = db.slugify(rec)
try:
tx.commit()
except IntegrityError as e:
tx.abort()
if 'UNIQUE constraint failed' in str(e):
logging.info(f"Skipping existing {table} {rec}")
continue
raise
logging.info(f"Created {table} {rec}")