|
| 1 | +from tortoise import connections |
| 2 | + |
| 3 | + |
| 4 | +def _need_upgrade(columns: list[tuple]) -> bool: |
| 5 | + for column in columns: |
| 6 | + # PRAGMA table_info 返回 (cid, name, type, notnull, dflt_value, pk) |
| 7 | + if column[1] == "size": |
| 8 | + column_type = (column[2] or "").upper() |
| 9 | + return "BIGINT" not in column_type |
| 10 | + return False |
| 11 | + |
| 12 | + |
| 13 | +async def migrate(): |
| 14 | + conn = connections.get("default") |
| 15 | + result = await conn.execute_query("PRAGMA table_info(filecodes)") |
| 16 | + columns = result[1] if result and len(result) > 1 else [] |
| 17 | + |
| 18 | + if not columns or not _need_upgrade(columns): |
| 19 | + return |
| 20 | + |
| 21 | + await conn.execute_script( |
| 22 | + """ |
| 23 | + BEGIN; |
| 24 | + CREATE TABLE IF NOT EXISTS filecodes_new |
| 25 | + ( |
| 26 | + id INTEGER not null |
| 27 | + primary key autoincrement, |
| 28 | + code VARCHAR(255) not null |
| 29 | + unique, |
| 30 | + prefix VARCHAR(255) default '' not null, |
| 31 | + suffix VARCHAR(255) default '' not null, |
| 32 | + uuid_file_name VARCHAR(255), |
| 33 | + file_path VARCHAR(255), |
| 34 | + size BIGINT default 0 not null, |
| 35 | + text TEXT, |
| 36 | + expired_at TIMESTAMP, |
| 37 | + expired_count INT default 0 not null, |
| 38 | + used_count INT default 0 not null, |
| 39 | + created_at TIMESTAMP default CURRENT_TIMESTAMP not null, |
| 40 | + file_hash VARCHAR(128), |
| 41 | + is_chunked BOOL default False not null, |
| 42 | + upload_id VARCHAR(128) |
| 43 | + ); |
| 44 | +
|
| 45 | + INSERT INTO filecodes_new (id, code, prefix, suffix, uuid_file_name, file_path, size, text, |
| 46 | + expired_at, expired_count, used_count, created_at, file_hash, |
| 47 | + is_chunked, upload_id) |
| 48 | + SELECT id, |
| 49 | + code, |
| 50 | + prefix, |
| 51 | + suffix, |
| 52 | + uuid_file_name, |
| 53 | + file_path, |
| 54 | + size, |
| 55 | + text, |
| 56 | + expired_at, |
| 57 | + expired_count, |
| 58 | + used_count, |
| 59 | + created_at, |
| 60 | + file_hash, |
| 61 | + is_chunked, |
| 62 | + upload_id |
| 63 | + FROM filecodes; |
| 64 | +
|
| 65 | + DROP TABLE filecodes; |
| 66 | + ALTER TABLE filecodes_new |
| 67 | + RENAME TO filecodes; |
| 68 | + CREATE INDEX IF NOT EXISTS idx_filecodes_code_1c7ee7 |
| 69 | + on filecodes (code); |
| 70 | + COMMIT; |
| 71 | + """ |
| 72 | + ) |
0 commit comments