{"record":{"id":"e8580c40ce28d14a","repo":"yikart/AiToEarn","slug":"database-is-not-initialized","errorCode":null,"errorMessage":"Database is not initialized","messagePattern":"Database is not initialized","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"project/aitoearn-electron/electron/db/index.ts","lineNumber":93,"sourceCode":"      // await AppDataSource.runMigrations(); // 上面已经有自动迁移\n      return true;\n    } catch (error) {\n      logger.error('Error during database initialization:', error);\n      return false;\n    }\n  }\n  return true;\n}\n\n/**\n * 导出数据库到SQL文件\n * @param filePath 导出文件路径\n */\nexport async function exportDatabase(filePath: string): Promise<void> {\n  try {\n    if (!AppDataSource.isInitialized) {\n      logger.error('Database is not initialized');\n      throw new Error('Database is not initialized');\n    }\n\n    const queryRunner = AppDataSource.createQueryRunner();\n    await queryRunner.connect();\n\n    // 获取所有表的数据\n    const tables = AppDataSource.entityMetadatas.map(\n      (entity) => entity.tableName,\n    );\n    let sqlContent = '';\n\n    for (const table of tables) {\n      const records = await queryRunner.query(`SELECT * FROM ${table}`);\n      if (records.length > 0) {\n        sqlContent += `-- Table: ${table}\\n`;\n        for (const record of records) {\n          const columns = Object.keys(record).join(', ');\n          const values = Object.values(record)","sourceCodeStart":75,"sourceCodeEnd":111,"githubUrl":"https://github.com/yikart/AiToEarn/blob/d3aa8bea5b146a8675607cf0144d891aad3e9683/project/aitoearn-electron/electron/db/index.ts#L75-L111","documentation":"exportDatabase serializes the local SQLite database to a SQL file for backup. It checks AppDataSource.isInitialized first and throws a plain Error if the TypeORM DataSource has not been initialized, since no query runner or tables can be accessed before initialization.","triggerScenarios":"createBackup is invoked before the app finished database initialization (e.g. during startup races), or after initialization failed (bad DB file, migration error) so isInitialized stayed false.","commonSituations":"User triggers backup immediately on app launch before DB init completes; database file locked/corrupt causing init failure; init awaited nowhere before the backup routine runs.","solutions":["Await database initialization (AppDataSource.initialize()) before calling exportDatabase/createBackup","Check startup logs for the underlying initialization failure and fix it (corrupt/locked DB file)","Gate the backup UI/action on an 'db ready' flag","Retry the backup after the app reports the database as ready"],"exampleFix":"// before\nawait createBackup();\n// after\nif (!AppDataSource.isInitialized) await AppDataSource.initialize();\nawait createBackup();","handlingStrategy":"retry","validationCode":"import { AppDataSource } from './db';\nif (!AppDataSource.isInitialized) {\n  await AppDataSource.initialize();\n}\nawait createBackup(path);","typeGuard":"function isDbReady(ds: { isInitialized: boolean }): boolean {\n  return ds.isInitialized === true;\n}","tryCatchPattern":"try {\n  await createBackup(path);\n} catch (e) {\n  if (e.message === 'Database is not initialized') {\n    await waitForDbReady();\n    await createBackup(path);\n  } else throw e;\n}","preventionTips":["Await DB initialization before exposing backup actions in the UI","Gate backup features on an app 'dbReady' event/flag","Monitor init failures (corrupt/locked DB file) and surface them to the user","Serialize startup tasks so backups never race initialization"],"tags":["typeorm","sqlite","electron","database-initialization"],"backgroundTag":"database-not-initialized","analyzedSha":"d3aa8bea5b146a8675607cf0144d891aad3e9683","analyzedAt":"2026-08-31T14:19:24.185Z","schemaVersion":2},"datasetVersion":"2026-08-31T19:17:28.585Z"}