补充迁移数据库异常的注意事项

add: sqlite迁移到postgresql的注意事项
This commit is contained in:
Carol
2025-08-22 10:55:26 +08:00
committed by GitHub
parent 724c15a68c
commit 4184d8c7ac

View File

@@ -122,6 +122,36 @@ DB_POSTGRESQL_PASSWORD=your-password
3. 启动应用,数据库表会自动创建
4. 使用数据库迁移工具或手动导入数据
#### 注意事项
完成数据迁移后需要对postgresql中的表进行索引初始值进行更新否则会出现唯一索引已存在的异常
例如:
```json
EventType.SiteUpdated
SiteChain.cache_site_userdata
(psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "siteuserdata_pkey"
DETAIL: Key (id)=(18) already exists.
[SQL: INSERT INTO siteuserdata (domain, name, username, userid, user_level, join_at, bonus, upload, download, ratio, seeding, leeching, seeding_size, leeching_size, seeding_info, message_unread, message_unread_contents, err_msg, updated_day, updated_time) VALUES (%(domain)s, %(name)s, %(username)s, %(userid)s, %(user_level)s, %(join_at)s, %(bonus)s, %(upload)s, %(download)s, %(ratio)s, %(seeding)s, %(leeching)s, %(seeding_size)s, %(leeching_size)s, %(seeding_info)s::JSON, %(message_unread)s, %(message_unread_contents)s::JSON, %(err_msg)s, %(updated_day)s, %(updated_time)s) RETURNING siteuserdata.id]
[parameters: {'domain': 'btschool.club', 'name': '', 'username': None, 'userid': None, 'user_level': None, 'join_at': None, 'bonus': 0.0, 'upload': 0, 'download': 0, 'ratio': 0.0, 'seeding': 0, 'leeching': 0, 'seeding_size': 0, 'leeching_size': 0, 'seeding_info': '[]', 'message_unread': 0, 'message_unread_contents': '[]', 'err_msg': 'cookies', 'updated_day': '2025-08-22', 'updated_time': '09:52:01'}]
(Background on this error at: https://sqlalche.me/e/20/gkpj)
```
需要对每一个表分别执行下面的语句(下面的SQL以`workflowc`数据表为例,每张表请自行修改,其中`user`表因为关键字原因,应该写成`public.user`的方式)
```sql
DO $$
DECLARE
max_id INTEGER;
BEGIN
-- 查询最大 ID 值
SELECT COALESCE(MAX(id), 0) INTO max_id FROM workflow;
-- 调整序列
EXECUTE format('ALTER SEQUENCE workflow_id_seq RESTART WITH %s', max_id + 1);
END $$;
```
### 从 PostgreSQL 迁移到 SQLite
1. 导出 PostgreSQL 数据