summaryrefslogtreecommitdiffhomepage
path: root/apioforum/db.py
diff options
context:
space:
mode:
authorubq323 <ubq323>2021-05-21 16:34:45 +0000
committerubq323 <ubq323>2021-05-21 16:34:45 +0000
commitbab4893709e736e30f208a810b46d21aed6cef0e (patch)
tree409bdbd25206051f0762fafb75311bba6ac9afde /apioforum/db.py
parentc8681bb17437e316c82f89c792458cda019ba74e (diff)
database infrastructure
Diffstat (limited to 'apioforum/db.py')
-rw-r--r--apioforum/db.py40
1 files changed, 40 insertions, 0 deletions
diff --git a/apioforum/db.py b/apioforum/db.py
new file mode 100644
index 0000000..be2d7e0
--- /dev/null
+++ b/apioforum/db.py
@@ -0,0 +1,40 @@
+import sqlite3
+import click
+from flask import current_app, g
+from flask.cli import with_appcontext
+
+def get_db():
+ if 'db' not in g:
+ g.db = sqlite3.connect('database.db',detect_types=sqlite3.PARSE_DECLTYPES)
+ g.db.row_factory = sqlite3.Row
+ g.db.execute("PRAGMA foreighn_keys = ON;")
+ return g.db
+
+def close_db(e=None):
+ db = g.pop('db', None)
+ if db is not None:
+ db.close()
+
+migrations = [
+]
+
+def init_db():
+ db = get_db()
+ version = db.execute("PRAGMA user_version;").fetchone()[0]
+ for i in range(version, len(migrations)):
+ db.executescript(migrations[i])
+ db.execute(f"PRAGMA user_version = {i+1}")
+ db.commit()
+ click.echo(f"migration {i}")
+
+@click.command("migrate")
+@with_appcontext
+def migrate_command():
+ """update database scheme etc"""
+ init_db()
+ click.echo("ok")
+
+def init_app(app):
+ app.teardown_appcontext(close_db)
+ app.cli.add_command(migrate_command)
+