tabletop-frog/ttfrog/db/bootstrap.py

43 lines
1.3 KiB
Python
Raw Normal View History

2024-01-28 00:46:19 -08:00
import logging
from ttfrog.db import db, session
# move this to json or whatever
data = {
'ancestry': [
{'name': 'human'},
{'name': 'dragonborn'},
2024-01-28 14:31:50 -08:00
{'name': 'tiefling'},
2024-01-28 00:46:19 -08:00
],
2024-01-28 14:31:50 -08:00
'character': [
{'name': 'Sabetha', 'ancestry_name': 'tiefling', 'level': 10, 'str': 10, 'dex': 10, 'con': 10, 'int': 10, 'wis': 10, 'cha': 10},
]
2024-01-28 00:46:19 -08:00
}
def bootstrap():
"""
Initialize the database with source data. Idempotent; will skip anything that already exists.
"""
db.init_model()
for table_name, table in db.tables.items():
if table_name not in data:
logging.debug("No bootstrap data for table {table_name}; skipping.")
continue
for rec in data[table_name]:
stmt = table.insert().values(**rec).prefix_with("OR IGNORE")
2024-01-28 22:14:50 -08:00
result, error = db.execute(stmt)
if error:
raise RuntimeError(error)
rec['id'] = result.inserted_primary_key[0]
if rec['id'] == 0:
2024-01-28 00:46:19 -08:00
logging.info(f"Skipped existing {table_name} {rec}")
2024-01-28 22:14:50 -08:00
continue
if 'slug' in table.columns:
rec['slug'] = db.slugify(rec)
db.update(table, **rec)
logging.info(f"Created {table_name} {rec}")