{"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":["import type { Knex } from 'knex';\n\nimport path from 'node:path';\n\nimport { Dialect, getDialect } from './dialects';\nimport { createSchemaProvider, SchemaProvider } from './schema';\nimport { createMetadata, Metadata } from './metadata';\nimport { createEntityManager, EntityManager } from './entity-manager';\nimport { createMigrationsProvider, MigrationProvider } from './migrations';\nimport { createLifecyclesProvider, LifecycleProvider } from './lifecycles';\nimport { createConnection } from './connection';\nimport * as errors from './errors';\nimport { Callback, transactionCtx, TransactionObject } from './transaction-context';\nimport { validateDatabase } from './validations';\nimport { appendCallerStack } from './utils/async-stack';\nimport type { Model } from './types';\nimport { createRepairManager, type RepairManager } from './repairs';\nimport { installPoolDiagnostics, type PoolDiagnostics } from './pool-diagnostics';\nimport { withStrapiKnexLog } from './utils/knex-log';\n\n/**\n * Commit and rollback hooks run after the transaction has already settled.\n * Log a useful message for Error instances and for thrown non-errors.\n */\nconst formatHookError = (error: unknown): string => {\n  if (error instanceof Error) {\n    return error.stack ?? error.message;\n  }\n\n  if (typeof error === 'string') {\n    return error;\n  }\n\n  try {\n    const serialized = JSON.stringify(error);\n    return typeof serialized === 'string' ? serialized : '';\n  } catch {\n    // Circular values have no JSON form.\n    return 'Unserializable value';\n  }\n};\n\n/** Drivers and hooks can reject with any value. Callers receive an Error. */\nconst asThrownError = (error: unknown): Error =>\n  error instanceof Error ? error : new Error(String(error));\n\nexport { isKnexQuery } from './utils/knex';\nexport { isDatabaseClientKind } from './connection';\nexport { attributeNaming } from './metadata';\nexport { createField } from './fields';\nexport type { AttributeNaming, Meta } from './metadata';\nexport type {\n  AttributeRenamesOperation,\n  Migration,\n  BuiltMigrationFile,\n  MigrationFileBuilder,\n  MigrationFileFormat,\n  MigrationFileOperation,\n} from './migrations';\nexport type { Event } from './lifecycles';\nexport type { Attribute, Model, JoinTable } from './types';\nexport type { AttributeRenameHandler, AttributeRenames } from './schema';\nexport type { Identifiers } from './utils/identifiers';\nexport { POOL_TIMEOUT_CODE } from './pool-diagnostics';\nexport type {\n  EventLoopDelay,\n  PoolDiagnostics,\n  PoolState,\n  PoolTimeoutDetails,\n} from './pool-diagnostics';\n\ninterface Settings {\n  forceMigration?: boolean;\n  runMigrations?: boolean;\n  /**\n   * Describe the pool on knex connection pool timeouts (details on the error, a docs link, one\n   * warning block per 30 s). Defaults to true; false leaves knex's error untouched. Must be a\n   * boolean (for example `env.bool('DATABASE_POOL_TIMEOUT_DIAGNOSTICS', true)`): a string is not\n   * read as false.\n   */\n  poolTimeoutDiagnostics?: boolean;\n  /**\n   * Maximum time in milliseconds a query run through the query builder's `execute()` may run\n   * before the database cancels it. Unset by default (no limit). Only applied on clients that\n   * can cancel queries (postgres, mysql); ignored on sqlite. Streams, direct `db.connection`\n   * queries, schema sync, and migrations are not covered. Must be a positive number (for\n   * example `env.int('DATABASE_QUERY_TIMEOUT')`).\n   */\n  queryTimeout?: number;\n  migrations: {\n    dir: string;\n  };\n  [key: string]: unknown;\n}\n\nexport type Logger = Record<\n  'info' | 'warn' | 'error' | 'debug',\n  (message: string | Record<string, unknown>) => void\n>;\n\nexport interface DatabaseConfig {\n  connection: Knex.Config;\n  settings: Settings;\n  logger?: Logger;\n  /** Lifecycle phase of the host application, e.g. \"boot\" or \"runtime\", for pool timeout reports. */\n  getPhase?: () => string | undefined;\n}\n\nconst assertValidQueryTimeout = (queryTimeout: unknown) => {\n  if (queryTimeout === undefined) {\n    return;\n  }\n\n  // A string (e.g. a raw `env('DATABASE_QUERY_TIMEOUT')`) would be silently ignored by knex, leaving\n  // users thinking they are protected when they are not\n  if (typeof queryTimeout !== 'number' || !Number.isFinite(queryTimeout) || queryTimeout <= 0) {\n    // JSON.stringify keeps strings quoted (\"5000\" vs 5000) but turns NaN and Infinity into null\n    const received =\n      typeof queryTimeout === 'string' ? JSON.stringify(queryTimeout) : String(queryTimeout);\n\n    throw new Error(\n      `Invalid database setting \"queryTimeout\": expected a positive number of milliseconds, received ${received}. Use env.int() when reading it from an environment variable.`\n    );\n  }\n};\n\nconst afterCreate =\n  (db: Database) =>\n  (\n    nativeConnection: unknown,\n    done: (error: Error | null, nativeConnection: unknown) => Promise<void>\n  ) => {\n    // run initialize for it since commands such as postgres SET and sqlite PRAGMA are per-connection\n    db.dialect.initialize(nativeConnection).then(() => {\n      return done(null, nativeConnection);\n    });\n  };\n\nclass Database {\n  connection: Knex;\n\n  dialect: Dialect;\n\n  config: DatabaseConfig;\n\n  metadata: Metadata;\n\n  schema: SchemaProvider;\n\n  migrations: MigrationProvider;\n\n  lifecycles: LifecycleProvider;\n\n  entityManager: EntityManager;\n\n  repair: RepairManager;\n\n  logger: Logger;\n\n  /** Set unless `settings.poolTimeoutDiagnostics` is false or the install failed. */\n  private poolDiagnostics?: PoolDiagnostics;\n\n  private phase?: string;\n\n  constructor(config: DatabaseConfig) {\n    this.config = {\n      ...config,\n      settings: {\n        forceMigration: true,\n        runMigrations: true,\n        ...config.settings,\n      },\n    };\n\n    this.logger = config.logger ?? console;\n\n    assertValidQueryTimeout(this.config.settings.queryTimeout);\n\n    this.dialect = getDialect(this);\n\n    let knexConfig: Knex.Config = this.config.connection;\n\n    // for object connections, we can configure the dialect synchronously\n    if (typeof this.config.connection.connection !== 'function') {\n      this.dialect.configure();\n    }\n    // for connection functions, we wrap it so that we can modify it with dialect configure before it reaches knex\n    else {\n      this.logger.warn(\n        'Knex connection functions are currently experimental. Attempting to access the connection object before database initialization will result in errors.'\n      );\n\n      knexConfig = {\n        ...this.config.connection,\n        connection: async () => {\n          // @ts-expect-error confirmed it was a function above\n          const conn = await this.config.connection.connection();\n          this.dialect.configure(conn);\n          return conn;\n        },\n      };\n    }\n\n    this.metadata = createMetadata([]);\n\n    this.connection = createConnection(withStrapiKnexLog(knexConfig, this.logger), {\n      pool: { afterCreate: afterCreate(this) },\n    });\n\n    if (this.config.settings.poolTimeoutDiagnostics !== false) {\n      try {\n        this.poolDiagnostics = installPoolDiagnostics(this.connection, {\n          logger: { warn: (message) => this.logger.warn(message) },\n          getPhase: () => this.phase ?? this.config.getPhase?.(),\n        });\n      } catch (error) {\n        // Diagnostics are optional: failing to install them must not stop the application booting\n        const reason = error instanceof Error ? error.message : String(error);\n        this.logger.debug(`[database] pool timeout diagnostics not installed: ${reason}`);\n      }\n    }\n\n    this.schema = createSchemaProvider(this);\n\n    this.migrations = createMigrationsProvider(this);\n    this.lifecycles = createLifecyclesProvider(this);\n\n    this.entityManager = createEntityManager(this);\n\n    this.repair = createRepairManager(this);\n  }\n\n  async init({ models }: { models: Model[] }) {\n    if (typeof this.config.connection.connection === 'function') {\n      /*\n       * User code needs to be able to access `connection.connection` directly as if\n       * it were always an object. For a connection function, that doesn't happen\n       * until the pool is created, so we need to do that here\n       *\n       * TODO: In the next major version, we need to replace all internal code that\n       * directly references `connection.connection` prior to init, and make a breaking\n       * change that it cannot be relied on to exist before init so that we can call\n       * this feature stable.\n       */\n      this.logger.debug('Forcing Knex to make real connection to db');\n\n      // sqlite does not support connection pooling so acquireConnection doesn't work\n      if (this.config.connection.client === 'sqlite') {\n        await this.connection.raw('SELECT 1');\n      } else {\n        // release it straight away, otherwise it holds a pool slot for the life of the process\n        const conn = await this.connection.client.acquireConnection();\n        await this.connection.client.releaseConnection(conn);\n      }\n    }\n\n    this.metadata.loadModels(models);\n    await validateDatabase(this);\n    return this;\n  }\n\n  query(uid: string) {\n    if (!this.metadata.has(uid)) {\n      throw new Error(`Model ${uid} not found`);\n    }\n\n    return this.entityManager.getRepository(uid);\n  }\n\n  inTransaction() {\n    return !!transactionCtx.get();\n  }\n\n  /**\n   * Labels pool timeout reports raised while `fn` runs, for example \"schema sync\". Nested calls\n   * restore the outer label. Calls that overlap without nesting can restore the wrong label; core\n   * only nests them (schema sync, then a migration).\n   *\n   * The label is process-wide, not per call: a call made at runtime relabels every concurrent\n   * timeout report until it returns. It is meant for boot-time work (schema sync, migrations).\n   *\n   * @internal\n   */\n  async runInPhase<T>(phase: string, fn: () => Promise<T>): Promise<T> {\n    const previous = this.phase;\n    this.phase = phase;\n\n    try {\n      return await fn();\n    } finally {\n      this.phase = previous;\n    }\n  }\n\n  /**\n   * Run work inside a DB transaction. On a fulfilled callback, the transaction\n   * is committed; on rejection, it is rolled back. The callback receives Knex\n   * `commit` and `rollback` helpers: if you call `rollback` and return without\n   * throwing, the implementation avoids attempting a second `commit` on an\n   * already-finalised transactor.\n   *\n   * A call inside another transaction joins it, without a savepoint: it neither commits nor rolls\n   * back on its own. If `cb` throws and a caller catches the error, the writes `cb` made before\n   * the error are committed with the outer transaction. Use `savepoint` to undo them.\n   */\n  transaction(): Promise<TransactionObject>;\n  transaction<TCallback extends Callback>(c: TCallback): Promise<ReturnType<TCallback>>;\n  async transaction<TCallback extends Callback>(\n    cb?: TCallback\n  ): Promise<ReturnType<TCallback> | TransactionObject> {\n    const notNestedTransaction = !transactionCtx.get();\n    const trx = notNestedTransaction\n      ? await this.startTransaction()\n      : (transactionCtx.get() as Knex.Transaction);\n    const logger = this.logger;\n\n    async function commit() {\n      if (notNestedTransaction) {\n        await transactionCtx.commit(trx, (error) => {\n          logger.error(\n            `Commit hook failed after the transaction committed: ${formatHookError(error)}`\n          );\n        });\n      }\n    }\n\n    async function rollback() {\n      if (notNestedTransaction) {\n        await transactionCtx.rollback(trx, (error) => {\n          logger.error(\n            `Rollback hook failed after the transaction rolled back: ${formatHookError(error)}`\n          );\n        });\n      }\n    }\n\n    if (!cb) {\n      return { commit, rollback, get: () => trx };\n    }\n\n    return await transactionCtx.run(\n      trx,\n      async () => {\n        try {\n          const callbackParams = {\n            trx,\n            commit,\n            rollback,\n            onCommit: transactionCtx.onCommit,\n            onRollback: transactionCtx.onRollback,\n          };\n          const res = await cb(callbackParams);\n          await commit();\n          return res;\n        } catch (error) {\n          await rollback();\n          throw error;\n        }\n      },\n      this\n    );\n  }\n\n  /**\n   * Runs `cb` in a savepoint of the current transaction, so a failure undoes only `cb`'s writes.\n   * If `cb` throws, its writes are rolled back, the `onCommit` callbacks registered in it are\n   * dropped, its `onRollback` callbacks run, and the error is rethrown. The transaction stays\n   * usable, on Postgres also after a database error, but not after a MySQL deadlock, which rolls\n   * back the whole transaction: the savepoint then can't be rolled back to, and it throws an\n   * `errors.SavepointError`, as when it can't be released. Throws if called outside a transaction.\n   */\n  savepoint<T>(cb: () => Promise<T> | T): Promise<T> {\n    return transactionCtx.savepoint(cb);\n  }\n\n  /**\n   * Starts a top-level knex transaction. knex resolves it through a promise chain that async stack\n   * traces cannot follow, so on failure the stack is extended with the frames of our callers.\n   */\n  private async startTransaction(): Promise<Knex.Transaction> {\n    try {\n      return await this.connection.transaction();\n    } catch (error) {\n      appendCallerStack(error);\n      throw error;\n    }\n  }\n\n  getSchemaName(): string | undefined {\n    return this.connection.client.connectionSettings.schema;\n  }\n\n  getConnection(): Knex;\n  getConnection(tableName?: string): Knex.QueryBuilder;\n  getConnection(tableName?: string): Knex | Knex.QueryBuilder {\n    const schema = this.getSchemaName();\n    const connection = tableName ? this.connection(tableName) : this.connection;\n    return schema ? connection.withSchema(schema) : connection;\n  }\n\n  // Returns basic info about the database connection\n  getInfo() {\n    const connectionSettings = this.connection?.client?.connectionSettings || {};\n    const client = this.dialect?.client || '';\n\n    let displayName = '';\n    let schema;\n\n    // For SQLite, get the relative filename\n    if (client === 'sqlite') {\n      const absolutePath = connectionSettings?.filename;\n      if (absolutePath) {\n        displayName = path.relative(process.cwd(), absolutePath);\n      }\n    }\n    // For other dialects, get the database name\n    else {\n      displayName = connectionSettings?.database;\n      schema = connectionSettings?.schema;\n    }\n\n    return {\n      displayName,\n      schema,\n      client,\n    };\n  }\n\n  getSchemaConnection(trx = this.connection) {\n    const schema = this.getSchemaName();\n    return schema ? trx.schema.withSchema(schema) : trx.schema;\n  }\n\n  queryBuilder(uid: string) {\n    return this.entityManager.createQueryBuilder(uid);\n  }\n\n  /**\n   * Wait for `onCommit` and `onRollback` hooks still running on this database.\n   * The transaction call itself does not wait, so a test that reads a hook's\n   * side effect does. `destroy()` stops waiting after 10 seconds.\n   */\n  settleTransactionHooks(timeoutMs?: number) {\n    return transactionCtx.settleHooks(this, timeoutMs);\n  }\n\n  async destroy() {\n    // A commit hook can still write. Timestamp and model subscribers have to\n    // stay registered until that write finishes. Clearing them first stores\n    // the row with NULL createdAt and updatedAt.\n    let drained = true;\n    let settleError: unknown;\n    let failedToSettle = false;\n    try {\n      drained = await this.settleTransactionHooks();\n    } catch (error) {\n      failedToSettle = true;\n      settleError = error;\n    }\n\n    try {\n      await this.lifecycles.clear();\n    } finally {\n      this.poolDiagnostics?.dispose();\n    }\n\n    // Close the pool before reporting a drain failure. Throwing from `finally`\n    // hides a close failure, and lint rejects that throw.\n    let closeError: unknown;\n    let failedToClose = false;\n    try {\n      if (!drained) {\n        this.logger.warn('Closing the database connection with transaction hooks still running');\n      }\n      await this.connection.destroy();\n    } catch (error) {\n      failedToClose = true;\n      closeError = error;\n    }\n\n    if (failedToSettle) {\n      throw asThrownError(settleError);\n    }\n\n    if (failedToClose) {\n      throw asThrownError(closeError);\n    }\n  }\n}\n\nexport { Database, errors };\n"],"names":["formatHookError","error","Error","stack","message","serialized","JSON","stringify","asThrownError","String","assertValidQueryTimeout","queryTimeout","undefined","Number","isFinite","received","afterCreate","db","nativeConnection","done","dialect","initialize","then","Database","init","models","config","connection","logger","debug","client","raw","conn","acquireConnection","releaseConnection","metadata","loadModels","validateDatabase","query","uid","has","entityManager","getRepository","inTransaction","transactionCtx","get","runInPhase","phase","fn","previous","transaction","cb","notNestedTransaction","trx","startTransaction","commit","rollback","run","callbackParams","onCommit","onRollback","res","savepoint","appendCallerStack","getSchemaName","connectionSettings","schema","getConnection","tableName","withSchema","getInfo","displayName","absolutePath","filename","path","relative","process","cwd","database","getSchemaConnection","queryBuilder","createQueryBuilder","settleTransactionHooks","timeoutMs","settleHooks","destroy","drained","settleError","failedToSettle","lifecycles","clear","poolDiagnostics","dispose","closeError","failedToClose","warn","settings","forceMigration","runMigrations","console","getDialect","knexConfig","configure","createMetadata","createConnection","withStrapiKnexLog","pool","poolTimeoutDiagnostics","installPoolDiagnostics","getPhase","reason","createSchemaProvider","migrations","createMigrationsProvider","createLifecyclesProvider","createEntityManager","repair","createRepairManager"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoBA;;;IAIA,MAAMA,kBAAkB,CAACC,KAAAA,GAAAA;AACvB,IAAA,IAAIA,iBAAiBC,KAAAA,EAAO;AAC1B,QAAA,OAAOD,KAAAA,CAAME,KAAK,IAAIF,KAAAA,CAAMG,OAAO;AACrC,IAAA;IAEA,IAAI,OAAOH,UAAU,QAAA,EAAU;QAC7B,OAAOA,KAAAA;AACT,IAAA;IAEA,IAAI;QACF,MAAMI,UAAAA,GAAaC,IAAAA,CAAKC,SAAS,CAACN,KAAAA,CAAAA;QAClC,OAAO,OAAOI,UAAAA,KAAe,QAAA,GAAWA,UAAAA,GAAa,EAAA;AACvD,IAAA,CAAA,CAAE,OAAM;;QAEN,OAAO,sBAAA;AACT,IAAA;AACF,CAAA;AAEA,8EACA,MAAMG,aAAAA,GAAgB,CAACP,KAAAA,GACrBA,iBAAiBC,KAAAA,GAAQD,KAAAA,GAAQ,IAAIC,KAAAA,CAAMO,MAAAA,CAAOR,KAAAA,CAAAA,CAAAA;AAgEpD,MAAMS,0BAA0B,CAACC,YAAAA,GAAAA;AAC/B,IAAA,IAAIA,iBAAiBC,SAAAA,EAAW;AAC9B,QAAA;AACF,IAAA;;;IAIA,IAAI,OAAOD,iBAAiB,QAAA,IAAY,CAACE,OAAOC,QAAQ,CAACH,YAAAA,CAAAA,IAAiBA,YAAAA,IAAgB,CAAA,EAAG;;QAE3F,MAAMI,QAAAA,GACJ,OAAOJ,YAAAA,KAAiB,QAAA,GAAWL,KAAKC,SAAS,CAACI,gBAAgBF,MAAAA,CAAOE,YAAAA,CAAAA;AAE3E,QAAA,MAAM,IAAIT,KAAAA,CACR,CAAC,8FAA8F,EAAEa,QAAAA,CAAS,6DAA6D,CAAC,CAAA;AAE5K,IAAA;AACF,CAAA;AAEA,MAAMC,WAA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