-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
63 lines (60 loc) · 2.08 KB
/
database.py
File metadata and controls
63 lines (60 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import psycopg2
from psycopg2.extensions import connection
from datetime import datetime
import os
import glob
import hashlib
import binascii
def mk_conn():
ret = psycopg2.connect(
dbname='myai',
user='myai',
password='myai',
host='localhost',
port='5432'
)
ret.autocommit = False
return ret
def init_database(conn: connection):
with conn.cursor() as cur:
cur.execute(
"""
CREATE TABLE IF NOT EXISTS migrations (
order_executed INTEGER GENERATED ALWAYS AS IDENTITY,
name VARCHAR(255) NOT NULL,
hash CHARACTER(64) NOT NULL,
start_time TIMESTAMP NOT NULL,
end_time TIMESTAMP NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS migrations_name ON migrations (name);
"""
)
conn.commit()
migration_dir = 'migrations'
migration_files = sorted(glob.glob(os.path.join(migration_dir, '*.sql')))
for migration_file in migration_files:
migration_name = os.path.basename(migration_file)
with conn.cursor() as cur:
cur.execute("SELECT 1 FROM migrations WHERE name = %s", (migration_name,))
if cur.fetchone():
print(f'Skipping already executed migration: {migration_name}')
continue
with open(migration_file, 'r') as f:
sql = f.read()
with conn.cursor() as cur:
cur.execute(sql)
start_time = datetime.now()
hash_bytes = hashlib.sha256(migration_name.encode('utf-8')).digest()
hash_str = binascii.hexlify(hash_bytes).decode('utf-8')
end_time = datetime.now()
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO migrations (name, hash, start_time, end_time)
VALUES (%s, %s, %s, %s)
""",
(migration_name, hash_str, start_time, end_time)
)
conn.commit()
print(f'Applied migration: {migration_file}')
print('Migrations completed')