|
| 1 | +import logging |
| 2 | + |
| 3 | + |
| 4 | +# { table_name => { 'sqlite': ['query1', 'query2'], 'pgsql': "query1; query2" } } |
| 5 | +table_creations = { |
| 6 | + 'user_request_nonces': { |
| 7 | + 'sqlite': [ |
| 8 | + """ |
| 9 | +CREATE TABLE user_request_nonces ( |
| 10 | + user INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, |
| 11 | + nonce BLOB NOT NULL UNIQUE, |
| 12 | + expiry FLOAT NOT NULL DEFAULT ((julianday('now') - 2440587.5 + 1.0)*86400.0) /* now + 24h */ |
| 13 | +) |
| 14 | +""", |
| 15 | + """ |
| 16 | +CREATE INDEX user_request_nonces_expiry ON user_request_nonces(expiry) |
| 17 | +""", |
| 18 | + ], |
| 19 | + 'pgsql': """ |
| 20 | +CREATE TABLE user_request_nonces ( |
| 21 | + "user" BIGINT NOT NULL REFERENCES users ON DELETE CASCADE, |
| 22 | + nonce BYTEA NOT NULL UNIQUE, |
| 23 | + expiry FLOAT NOT NULL DEFAULT (extract(epoch from now() + '24 hours')) |
| 24 | +); |
| 25 | +CREATE INDEX user_request_nonces_expiry ON user_request_nonces(expiry) |
| 26 | +""", |
| 27 | + }, |
| 28 | + 'inbox': { |
| 29 | + 'sqlite': [ |
| 30 | + """ |
| 31 | +CREATE TABLE inbox ( |
| 32 | + id INTEGER PRIMARY KEY, |
| 33 | + recipient INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, |
| 34 | + sender INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, |
| 35 | + body BLOB NOT NULL, |
| 36 | + posted_at FLOAT DEFAULT ((julianday('now') - 2440587.5)*86400.0), |
| 37 | + expiry FLOAT DEFAULT ((julianday('now') - 2440587.5 + 1.0)*86400.0) /* now + 24h */ |
| 38 | +) |
| 39 | +""", |
| 40 | + """ |
| 41 | +CREATE INDEX inbox_recipient ON inbox(recipient) |
| 42 | +""", |
| 43 | + ], |
| 44 | + 'pgsql': """ |
| 45 | +CREATE TABLE inbox ( |
| 46 | + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, |
| 47 | + recipient BIGINT NOT NULL REFERENCES users ON DELETE CASCADE, |
| 48 | + sender BIGINT NOT NULL REFERENCES users ON DELETE CASCADE, |
| 49 | + body BYTEA NOT NULL, |
| 50 | + posted_at FLOAT DEFAULT (extract(epoch from now())), |
| 51 | + expiry FLOAT DEFAULT (extract(epoch from now() + '15 days')) |
| 52 | +); |
| 53 | +CREATE INDEX inbox_recipient ON inbox(recipient); |
| 54 | +""", |
| 55 | + }, |
| 56 | +} |
| 57 | + |
| 58 | + |
| 59 | +def migrate(conn): |
| 60 | + """Adds new tables that don't have any special migration requirement beyond creation""" |
| 61 | + |
| 62 | + from .. import db |
| 63 | + |
| 64 | + added = False |
| 65 | + |
| 66 | + for table, v in table_creations.items(): |
| 67 | + if table in db.metadata.tables: |
| 68 | + continue |
| 69 | + |
| 70 | + logging.warning(f"DB migration: Adding new table {table}") |
| 71 | + |
| 72 | + if db.engine.name == 'sqlite': |
| 73 | + for query in v['sqlite']: |
| 74 | + conn.execute(query) |
| 75 | + else: |
| 76 | + conn.execute(v['pgsql']) |
| 77 | + |
| 78 | + added = True |
| 79 | + |
| 80 | + return added |
0 commit comments