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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
|
""" memos: SQLite -> PostgreSQL 迁移 - memo / attachment 数据全部迁过来 - attachment.blob 留在 SQLite 不迁 - 文件本身传 S3 - 新库 attachment: storage_type='S3' + presigned URL + payload s3Object JSON """
import sqlite3 import json import logging import os import sys import time from datetime import datetime, timezone from io import BytesIO
import boto3 import psycopg2 from botocore.config import Config as BotoConfig from botocore.exceptions import ClientError
logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stderr, ) LOG = logging.getLogger("memos-migrate")
CONFIG = { "sqlite_path": "",
"pg_host": "", "pg_port": 5432, "pg_user": "", "pg_password": "", "pg_dbname": "",
"s3_endpoint": "", "s3_region": "", "s3_bucket": "", "s3_access_key": "", "s3_secret_key": "", "s3_key_prefix": "", "s3_expires": 432000,
"user_mode": "match", "user_map": {}, }
def E(msg): print(msg, file=sys.stderr, flush=True)
def make_s3(cfg): return boto3.client( "s3", endpoint_url=cfg["s3_endpoint"], region_name=cfg["s3_region"], aws_access_key_id=cfg["s3_access_key"], aws_secret_access_key=cfg["s3_secret_key"], config=BotoConfig(signature_version="s3v4"), )
def connect_sqlite(path): if not os.path.exists(path): raise SystemExit(f"X SQLite file not found: {path}") conn = sqlite3.connect(path) conn.row_factory = sqlite3.Row return conn
def connect_pg(cfg): return psycopg2.connect( host=cfg["pg_host"], port=cfg["pg_port"], user=cfg["pg_user"], password=cfg["pg_password"], dbname=cfg["pg_dbname"], )
def _now_iso_nano_z(): """返回 memos 期望的纳秒精度 + Z 时区格式,如 2026-08-02T06:08:04.729207108Z""" import time as _t ns = _t.time_ns() sec = ns // 1_000_000_000 nano = ns % 1_000_000_000 dt = _t.gmtime(sec) return f"{_t.strftime('%Y-%m-%dT%H:%M:%S', dt)}.{nano:09d}Z"
def build_payload(cfg, s3_key): """memos v0.30.x 期望的 payload 结构""" endpoint = cfg["s3_endpoint"].rstrip("/") + "/" return json.dumps({ "s3Object": { "s3Config": { "accessKeyId": cfg["s3_access_key"], "accessKeySecret": cfg["s3_secret_key"], "endpoint": endpoint, "region": cfg["s3_region"], "bucket": cfg["s3_bucket"], "usePathStyle": True, "insecureSkipTlsVerify": True, }, "key": s3_key, "lastPresignedTime": _now_iso_nano_z(), } }, ensure_ascii=False)
def migrate_users(sqlite_conn, pg_conn, cfg): src = sqlite_conn.cursor() src.execute(""" SELECT id, username, role, email, nickname, password_hash, avatar_url, description, row_status, created_ts, updated_ts FROM user """) rows = src.fetchall() LOG.info("source user count: %d", len(rows))
if cfg["user_mode"] == "skip": LOG.warning("user_mode=skip, skip user migration. " "you need to create users in new PG and provide user_map.") return {}
pg = pg_conn.cursor() pg.execute('SELECT id, username FROM "user"') pg_user_by_name = {row[1]: row[0] for row in pg.fetchall()} LOG.info("PG existing user count: %d", len(pg_user_by_name))
old_to_new = {} new_inserted = 0 matched = 0 for r in rows: sqlite_uid = r["id"] sqlite_username = r["username"]
if cfg["user_mode"] == "manual": new_id = cfg["user_map"].get(sqlite_uid) if not new_id: LOG.warning("user %s (id=%d) no mapping, skip", sqlite_username, sqlite_uid) continue old_to_new[sqlite_uid] = new_id elif cfg["user_mode"] == "match": if sqlite_username in pg_user_by_name: old_to_new[sqlite_uid] = pg_user_by_name[sqlite_username] matched += 1 LOG.info(" [MATCH] sqlite user '%s' (id=%d) -> pg user id=%d", sqlite_username, sqlite_uid, pg_user_by_name[sqlite_username]) else: pg.execute(""" INSERT INTO "user" (id, username, role, email, nickname, password_hash, avatar_url, description, row_status, created_ts, updated_ts) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (id) DO NOTHING """, (sqlite_uid, sqlite_username, r["role"], r["email"], r["nickname"], r["password_hash"], r["avatar_url"], r["description"], r["row_status"], r["created_ts"], r["updated_ts"])) old_to_new[sqlite_uid] = sqlite_uid new_inserted += 1 LOG.info(" [NEW] sqlite user '%s' (id=%d) -> inserted to PG", sqlite_username, sqlite_uid) else: pg.execute(""" INSERT INTO "user" (id, username, role, email, nickname, password_hash, avatar_url, description, row_status, created_ts, updated_ts) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (id) DO NOTHING """, (sqlite_uid, sqlite_username, r["role"], r["email"], r["nickname"], r["password_hash"], r["avatar_url"], r["description"], r["row_status"], r["created_ts"], r["updated_ts"])) old_to_new[sqlite_uid] = sqlite_uid
pg_conn.commit() if cfg["user_mode"] == "match": LOG.info("user map: %d entries (matched=%d, new=%d)", len(old_to_new), matched, new_inserted) else: LOG.info("user map: %d entries", len(old_to_new)) return old_to_new
def migrate_memos(sqlite_conn, pg_conn, user_map): src = sqlite_conn.cursor() src.execute(""" SELECT id, uid, creator_id, created_ts, updated_ts, row_status, content, visibility, pinned, payload FROM memo """) rows = src.fetchall() LOG.info("source memo count: %d", len(rows))
pg = pg_conn.cursor() for r in rows: new_creator = user_map.get(r["creator_id"], 1) pg.execute(""" INSERT INTO memo (id, uid, creator_id, created_ts, updated_ts, row_status, content, visibility, pinned, payload) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (id) DO UPDATE SET content = EXCLUDED.content, creator_id = EXCLUDED.creator_id, updated_ts = EXCLUDED.updated_ts """, (r["id"], r["uid"], new_creator, r["created_ts"], r["updated_ts"], r["row_status"], r["content"], r["visibility"], bool(r["pinned"]), r["payload"])) pg_conn.commit() LOG.info("memo migrated: %d rows", len(rows))
def migrate_attachments(sqlite_conn, pg_conn, s3, user_map, cfg): src = sqlite_conn.cursor() src.execute(""" SELECT id, uid, creator_id, created_ts, updated_ts, filename, type, size, memo_id, storage_type, reference, payload, blob FROM attachment """) rows = src.fetchall() LOG.info("source attachment count: %d", len(rows))
pg = pg_conn.cursor() ok = fail = 0 for r in rows: blob = r["blob"] if blob: try: s3_key = f"{cfg['s3_key_prefix']}{r['created_ts'] // 1000}_{r['filename']}" s3.upload_fileobj( BytesIO(bytes(blob)), cfg["s3_bucket"], s3_key, ExtraArgs={"ContentType": r["type"] or "application/octet-stream"}, ) presigned_url = s3.generate_presigned_url( "get_object", Params={"Bucket": cfg["s3_bucket"], "Key": s3_key}, ExpiresIn=cfg["s3_expires"], ) payload_json = build_payload(cfg, s3_key) storage_type = "S3" reference = presigned_url except ClientError as e: LOG.error("[S3 FAIL] attachment id=%s: %s", r["id"], e) fail += 1 continue else: storage_type = r["storage_type"] or "S3" reference = r["reference"] or "" payload_json = r["payload"] or "{}"
new_creator = user_map.get(r["creator_id"], 1)
pg.execute(""" INSERT INTO attachment (id, uid, creator_id, created_ts, updated_ts, filename, type, size, memo_id, storage_type, reference, payload, blob) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s, NULL) ON CONFLICT (id) DO UPDATE SET reference = EXCLUDED.reference, payload = EXCLUDED.payload, storage_type = EXCLUDED.storage_type, blob = NULL, creator_id = EXCLUDED.creator_id, memo_id = EXCLUDED.memo_id """, (r["id"], r["uid"], new_creator, r["created_ts"], r["updated_ts"], r["filename"], r["type"], r["size"], r["memo_id"], storage_type, reference, payload_json)) ok += 1 if ok % 20 == 0: LOG.info("processed %d / %d", ok, len(rows))
pg_conn.commit() LOG.info("attachment migrated: ok=%d fail=%d", ok, fail)
def reset_sequences(pg_conn): pg = pg_conn.cursor() for seq, table in [ ("memo_id_seq", "memo"), ("attachment_id_seq", "attachment"), ("user_id_seq", '"user"'), ]: try: pg.execute(f"SELECT setval('{seq}', COALESCE((SELECT MAX(id) FROM {table}), 1))") LOG.info("reset sequence: %s", seq) except psycopg2.errors.UndefinedTable: LOG.warning("sequence/table %s not found, skip", seq) pg_conn.commit()
def main(): E("=" * 60) E("memos: SQLite -> PostgreSQL migration") E(" sqlite: " + CONFIG["sqlite_path"]) E(" pg: " + CONFIG["pg_host"] + ":" + str(CONFIG["pg_port"]) + "/" + CONFIG["pg_dbname"]) E(" s3: " + CONFIG["s3_endpoint"] + "/" + CONFIG["s3_bucket"]) E("=" * 60)
sq = connect_sqlite(CONFIG["sqlite_path"]) pg = connect_pg(CONFIG) s3 = make_s3(CONFIG)
user_map = migrate_users(sq, pg, CONFIG) migrate_memos(sq, pg, user_map) migrate_attachments(sq, pg, s3, user_map, CONFIG) reset_sequences(pg)
E("=" * 60) E("V migration done") E(" user mapping: " + str(len(user_map))) E(" next steps: archive SQLite, VACUUM FULL on PG, verify counts") E("=" * 60)
if __name__ == "__main__": main()
|