Finished DB management and DB migration scripts

This commit is contained in:
Verox 2024-01-10 19:16:28 +01:00
parent a3273c6f10
commit 74e18bef7c
7 changed files with 121 additions and 0 deletions

2
.gitignore vendored
View File

@ -160,3 +160,5 @@ cython_debug/
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
db/db.sqlite

15
.idea/dataSources.xml generated Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="DB" uuid="7b8722d8-2b93-4acb-877a-915b2fd666ae">
<driver-ref>sqlite.xerial</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
<jdbc-url>jdbc:sqlite:$PROJECT_DIR$/db/db.sqlite</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

7
.idea/sqldialects.xml generated Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/db/migrate.py" dialect="SQLite" />
<file url="PROJECT" dialect="SQLite" />
</component>
</project>

1
app.py
View File

@ -1,4 +1,5 @@
from flask import Flask, render_template
from db.migrate import _CREATE_MIGRATIONS_TABLE
# Create a new Flask instance
app = Flask(__name__)

30
db/create_migration.py Normal file
View File

@ -0,0 +1,30 @@
import datetime
import os
def is_snake_case(s):
if not s:
return False
return s.islower() and all(char.isalpha() or char == '_' for char in s)
if __name__ == "__main__":
migration_name = ""
while not is_snake_case(migration_name):
if migration_name:
print(f"{migration_name} ist nicht im Camcel-Case")
migration_name = input('Gebe einen Namen für die Migration im snake_case an: ')
timestamp = datetime.datetime.now().timestamp()
migrations_path = os.path.join(os.path.dirname(__file__), 'migrations')
print(migrations_path)
try:
if not os.path.isdir(migrations_path):
raise FileNotFoundError
file = open(os.path.join(os.path.dirname(__file__), 'migrations', str(int(timestamp)) + '_' + migration_name + '.sql'), 'w')
file.close()
except FileNotFoundError:
print("migrations/ Directive could not be found within the db directory, contained in the project main directory.")

63
db/migrate.py Normal file
View File

@ -0,0 +1,63 @@
import datetime
import os
import sqlite3
from pathlib import Path
from sqlite3 import Connection
CREATE_MIGRATIONS_TABLE = """
CREATE TABLE IF NOT EXISTS migrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file TEXT,
created_at TEXT
);
"""
def init_db():
conn = sqlite3.connect("db.sqlite")
# Create migration table, if not exists yet
conn.execute(CREATE_MIGRATIONS_TABLE)
conn.commit()
def create_migration(conn: Connection, migration: str):
conn.execute(f"""
INSERT INTO migrations (file, created_at) VALUES ("{migration}", "{datetime.datetime.now()}");
""")
"""
Returns True, if the migration has already been migrates once.
"""
def check_migration(conn: Connection, migration: str):
res = conn.cursor().execute(f"""
SELECT EXISTS(SELECT file FROM migrations WHERE file = "{migration}");
""")
return res.fetchone()[0] == 1
if __name__ == "__main__":
# Init DB with migrations table
init_db()
migrations_path = os.path.join(os.path.dirname(__file__), 'migrations')
try:
if not os.path.isdir(migrations_path):
raise FileNotFoundError
conn = sqlite3.connect("db.sqlite")
for file in os.listdir(migrations_path):
if not file.endswith('.sql'):
continue
with open(os.path.join(os.path.dirname(__file__), 'migrations', file)) as migration:
migration_name = Path(file).stem
if check_migration(conn, migration_name):
continue
print(f"Migrating {migration_name}...")
create_migration(conn, migration_name)
conn.execute(migration.read())
print(f"Migrated {migration_name}\n")
conn.commit()
except FileNotFoundError:
print("migrations/ Directive could not be found within the db directory, contained in the project main directory.")

View File

@ -0,0 +1,3 @@
CREATE TABLE test (
id INTEGER PRIMARY KEY AUTOINCREMENT
);