@strapi/database 5.51.0 → 5.51.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/dialects/mysql/database-inspector.js +1 -1
  2. package/dist/dialects/mysql/database-inspector.js.map +1 -1
  3. package/dist/dialects/mysql/database-inspector.mjs +1 -1
  4. package/dist/dialects/mysql/database-inspector.mjs.map +1 -1
  5. package/dist/dialects/mysql/index.js +2 -2
  6. package/dist/dialects/mysql/index.js.map +1 -1
  7. package/dist/dialects/mysql/index.mjs +2 -2
  8. package/dist/dialects/mysql/index.mjs.map +1 -1
  9. package/dist/entity-manager/index.js +30 -30
  10. package/dist/entity-manager/index.js.map +1 -1
  11. package/dist/entity-manager/index.mjs +30 -30
  12. package/dist/entity-manager/index.mjs.map +1 -1
  13. package/dist/entity-manager/relations-orderer.js +1 -1
  14. package/dist/entity-manager/relations-orderer.js.map +1 -1
  15. package/dist/entity-manager/relations-orderer.mjs +1 -1
  16. package/dist/entity-manager/relations-orderer.mjs.map +1 -1
  17. package/dist/fields/datetime.d.ts.map +1 -1
  18. package/dist/fields/datetime.js +6 -23
  19. package/dist/fields/datetime.js.map +1 -1
  20. package/dist/fields/datetime.mjs +6 -3
  21. package/dist/fields/datetime.mjs.map +1 -1
  22. package/dist/fields/index.d.ts.map +1 -1
  23. package/dist/fields/index.js +21 -8
  24. package/dist/fields/index.js.map +1 -1
  25. package/dist/fields/index.mjs +21 -4
  26. package/dist/fields/index.mjs.map +1 -1
  27. package/dist/fields/json.js +1 -1
  28. package/dist/fields/json.js.map +1 -1
  29. package/dist/fields/json.mjs +1 -1
  30. package/dist/fields/json.mjs.map +1 -1
  31. package/dist/fields/shared/parsers.js +1 -1
  32. package/dist/fields/shared/parsers.js.map +1 -1
  33. package/dist/fields/shared/parsers.mjs +1 -1
  34. package/dist/fields/shared/parsers.mjs.map +1 -1
  35. package/dist/fields/timestamp.d.ts.map +1 -1
  36. package/dist/fields/timestamp.js +5 -23
  37. package/dist/fields/timestamp.js.map +1 -1
  38. package/dist/fields/timestamp.mjs +5 -3
  39. package/dist/fields/timestamp.mjs.map +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/index.mjs +1 -1
  43. package/dist/index.mjs.map +1 -1
  44. package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.js +1 -1
  45. package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.js.map +1 -1
  46. package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.mjs +1 -1
  47. package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.mjs.map +1 -1
  48. package/dist/query/helpers/populate/apply.d.ts.map +1 -1
  49. package/dist/query/helpers/populate/apply.js +7 -5
  50. package/dist/query/helpers/populate/apply.js.map +1 -1
  51. package/dist/query/helpers/populate/apply.mjs +7 -5
  52. package/dist/query/helpers/populate/apply.mjs.map +1 -1
  53. package/dist/query/helpers/search.d.ts +1 -0
  54. package/dist/query/helpers/search.d.ts.map +1 -1
  55. package/dist/query/helpers/search.js +1 -0
  56. package/dist/query/helpers/search.js.map +1 -1
  57. package/dist/query/helpers/search.mjs +1 -1
  58. package/dist/query/helpers/search.mjs.map +1 -1
  59. package/dist/query/helpers/transform.d.ts.map +1 -1
  60. package/dist/query/helpers/transform.js +4 -1
  61. package/dist/query/helpers/transform.js.map +1 -1
  62. package/dist/query/helpers/transform.mjs +4 -1
  63. package/dist/query/helpers/transform.mjs.map +1 -1
  64. package/dist/query/helpers/where.d.ts.map +1 -1
  65. package/dist/query/helpers/where.js +34 -14
  66. package/dist/query/helpers/where.js.map +1 -1
  67. package/dist/query/helpers/where.mjs +34 -14
  68. package/dist/query/helpers/where.mjs.map +1 -1
  69. package/package.json +5 -5
@@ -1,36 +1,18 @@
1
1
  'use strict';
2
2
 
3
- var dateFns = require('date-fns');
4
3
  var parsers = require('./shared/parsers.js');
5
4
  var field = require('./field.js');
6
5
 
7
- function _interopNamespace(e) {
8
- if (e && e.__esModule) return e;
9
- var n = Object.create(null);
10
- if (e) {
11
- Object.keys(e).forEach(function (k) {
12
- if (k !== 'default') {
13
- var d = Object.getOwnPropertyDescriptor(e, k);
14
- Object.defineProperty(n, k, d.get ? d : {
15
- enumerable: true,
16
- get: function () { return e[k]; }
17
- });
18
- }
19
- });
20
- }
21
- n.default = e;
22
- return Object.freeze(n);
23
- }
24
-
25
- var dateFns__namespace = /*#__PURE__*/_interopNamespace(dateFns);
26
-
27
6
  class TimestampField extends field {
28
7
  toDB(value) {
29
8
  return parsers.parseDateTimeOrTimestamp(value);
30
9
  }
31
10
  fromDB(value) {
32
- const cast = new Date(value);
33
- return dateFns__namespace.isValid(cast) ? dateFns__namespace.format(cast, 'T') : null;
11
+ // Same redundant re-parse as `datetime`. `format(cast, 'T')` is the epoch in
12
+ // milliseconds as a string, which `getTime()` already gives us.
13
+ const cast = value instanceof Date ? value : new Date(value);
14
+ const time = cast.getTime();
15
+ return Number.isNaN(time) ? null : String(time);
34
16
  }
35
17
  }
36
18
 
@@ -1 +1 @@
1
- {"version":3,"file":"timestamp.js","sources":["../../src/fields/timestamp.ts"],"sourcesContent":["import * as dateFns from 'date-fns';\n\nimport { parseDateTimeOrTimestamp } from './shared/parsers';\nimport Field from './field';\n\nexport default class TimestampField extends Field {\n toDB(value: unknown) {\n return parseDateTimeOrTimestamp(value);\n }\n\n fromDB(value: unknown) {\n const cast = new Date(value as any);\n return dateFns.isValid(cast) ? dateFns.format(cast, 'T') : null;\n }\n}\n"],"names":["TimestampField","Field","toDB","value","parseDateTimeOrTimestamp","fromDB","cast","Date","dateFns","isValid","format"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAKe,MAAMA,cAAAA,SAAuBC,KAAAA,CAAAA;AAC1CC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;AACnB,QAAA,OAAOC,gCAAAA,CAAyBD,KAAAA,CAAAA;AAClC,IAAA;AAEAE,IAAAA,MAAAA,CAAOF,KAAc,EAAE;QACrB,MAAMG,IAAAA,GAAO,IAAIC,IAAAA,CAAKJ,KAAAA,CAAAA;QACtB,OAAOK,kBAAAA,CAAQC,OAAO,CAACH,IAAAA,CAAAA,GAAQE,mBAAQE,MAAM,CAACJ,MAAM,GAAA,CAAA,GAAO,IAAA;AAC7D,IAAA;AACF;;;;"}
1
+ {"version":3,"file":"timestamp.js","sources":["../../src/fields/timestamp.ts"],"sourcesContent":["import { parseDateTimeOrTimestamp } from './shared/parsers';\nimport Field from './field';\n\nexport default class TimestampField extends Field {\n toDB(value: unknown) {\n return parseDateTimeOrTimestamp(value);\n }\n\n fromDB(value: unknown) {\n // Same redundant re-parse as `datetime`. `format(cast, 'T')` is the epoch in\n // milliseconds as a string, which `getTime()` already gives us.\n const cast = value instanceof Date ? value : new Date(value as any);\n const time = cast.getTime();\n return Number.isNaN(time) ? null : String(time);\n }\n}\n"],"names":["TimestampField","Field","toDB","value","parseDateTimeOrTimestamp","fromDB","cast","Date","time","getTime","Number","isNaN","String"],"mappings":";;;;;AAGe,MAAMA,cAAAA,SAAuBC,KAAAA,CAAAA;AAC1CC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;AACnB,QAAA,OAAOC,gCAAAA,CAAyBD,KAAAA,CAAAA;AAClC,IAAA;AAEAE,IAAAA,MAAAA,CAAOF,KAAc,EAAE;;;AAGrB,QAAA,MAAMG,IAAAA,GAAOH,KAAAA,YAAiBI,IAAAA,GAAOJ,KAAAA,GAAQ,IAAII,IAAAA,CAAKJ,KAAAA,CAAAA;QACtD,MAAMK,IAAAA,GAAOF,KAAKG,OAAO,EAAA;AACzB,QAAA,OAAOC,MAAAA,CAAOC,KAAK,CAACH,IAAAA,CAAAA,GAAQ,OAAOI,MAAAA,CAAOJ,IAAAA,CAAAA;AAC5C,IAAA;AACF;;;;"}
@@ -1,4 +1,3 @@
1
- import * as dateFns from 'date-fns';
2
1
  import { parseDateTimeOrTimestamp } from './shared/parsers.mjs';
3
2
  import Field from './field.mjs';
4
3
 
@@ -7,8 +6,11 @@ class TimestampField extends Field {
7
6
  return parseDateTimeOrTimestamp(value);
8
7
  }
9
8
  fromDB(value) {
10
- const cast = new Date(value);
11
- return dateFns.isValid(cast) ? dateFns.format(cast, 'T') : null;
9
+ // Same redundant re-parse as `datetime`. `format(cast, 'T')` is the epoch in
10
+ // milliseconds as a string, which `getTime()` already gives us.
11
+ const cast = value instanceof Date ? value : new Date(value);
12
+ const time = cast.getTime();
13
+ return Number.isNaN(time) ? null : String(time);
12
14
  }
13
15
  }
14
16
 
@@ -1 +1 @@
1
- {"version":3,"file":"timestamp.mjs","sources":["../../src/fields/timestamp.ts"],"sourcesContent":["import * as dateFns from 'date-fns';\n\nimport { parseDateTimeOrTimestamp } from './shared/parsers';\nimport Field from './field';\n\nexport default class TimestampField extends Field {\n toDB(value: unknown) {\n return parseDateTimeOrTimestamp(value);\n }\n\n fromDB(value: unknown) {\n const cast = new Date(value as any);\n return dateFns.isValid(cast) ? dateFns.format(cast, 'T') : null;\n }\n}\n"],"names":["TimestampField","Field","toDB","value","parseDateTimeOrTimestamp","fromDB","cast","Date","dateFns","isValid","format"],"mappings":";;;;AAKe,MAAMA,cAAAA,SAAuBC,KAAAA,CAAAA;AAC1CC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;AACnB,QAAA,OAAOC,wBAAAA,CAAyBD,KAAAA,CAAAA;AAClC,IAAA;AAEAE,IAAAA,MAAAA,CAAOF,KAAc,EAAE;QACrB,MAAMG,IAAAA,GAAO,IAAIC,IAAAA,CAAKJ,KAAAA,CAAAA;QACtB,OAAOK,OAAAA,CAAQC,OAAO,CAACH,IAAAA,CAAAA,GAAQE,QAAQE,MAAM,CAACJ,MAAM,GAAA,CAAA,GAAO,IAAA;AAC7D,IAAA;AACF;;;;"}
1
+ {"version":3,"file":"timestamp.mjs","sources":["../../src/fields/timestamp.ts"],"sourcesContent":["import { parseDateTimeOrTimestamp } from './shared/parsers';\nimport Field from './field';\n\nexport default class TimestampField extends Field {\n toDB(value: unknown) {\n return parseDateTimeOrTimestamp(value);\n }\n\n fromDB(value: unknown) {\n // Same redundant re-parse as `datetime`. `format(cast, 'T')` is the epoch in\n // milliseconds as a string, which `getTime()` already gives us.\n const cast = value instanceof Date ? value : new Date(value as any);\n const time = cast.getTime();\n return Number.isNaN(time) ? null : String(time);\n }\n}\n"],"names":["TimestampField","Field","toDB","value","parseDateTimeOrTimestamp","fromDB","cast","Date","time","getTime","Number","isNaN","String"],"mappings":";;;AAGe,MAAMA,cAAAA,SAAuBC,KAAAA,CAAAA;AAC1CC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;AACnB,QAAA,OAAOC,wBAAAA,CAAyBD,KAAAA,CAAAA;AAClC,IAAA;AAEAE,IAAAA,MAAAA,CAAOF,KAAc,EAAE;;;AAGrB,QAAA,MAAMG,IAAAA,GAAOH,KAAAA,YAAiBI,IAAAA,GAAOJ,KAAAA,GAAQ,IAAII,IAAAA,CAAKJ,KAAAA,CAAAA;QACtD,MAAMK,IAAAA,GAAOF,KAAKG,OAAO,EAAA;AACzB,QAAA,OAAOC,MAAAA,CAAOC,KAAK,CAACH,IAAAA,CAAAA,GAAQ,OAAOI,MAAAA,CAAOJ,IAAAA,CAAAA;AAC5C,IAAA;AACF;;;;"}
package/dist/index.js CHANGED
@@ -142,7 +142,7 @@ class Database {
142
142
  settings: {
143
143
  forceMigration: true,
144
144
  runMigrations: true,
145
- ...config.settings ?? {}
145
+ ...config.settings
146
146
  }
147
147
  };
148
148
  this.logger = config.logger ?? console;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","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, type Migration } from './migrations';\nimport { createLifecyclesProvider, LifecycleProvider } from './lifecycles';\nimport type { Event } from './lifecycles';\nimport { createConnection } from './connection';\nimport * as errors from './errors';\nimport { Callback, transactionCtx, TransactionObject } from './transaction-context';\nimport { validateDatabase } from './validations';\nimport type { Model, JoinTable } from './types';\nimport type { Identifiers } from './utils/identifiers';\nimport { createRepairManager, type RepairManager } from './repairs';\n\nexport { isKnexQuery } from './utils/knex';\nexport { isDatabaseClientKind } from './connection';\n\ninterface Settings {\n forceMigration?: boolean;\n runMigrations?: boolean;\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}\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 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 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(knexConfig, {\n pool: { afterCreate: afterCreate(this) },\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 await this.connection.client.acquireConnection();\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 * 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 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.connection.transaction()\n : (transactionCtx.get() as Knex.Transaction);\n\n async function commit() {\n if (notNestedTransaction) {\n await transactionCtx.commit(trx);\n }\n }\n\n async function rollback() {\n if (notNestedTransaction) {\n await transactionCtx.rollback(trx);\n }\n }\n\n if (!cb) {\n return { commit, rollback, get: () => trx };\n }\n\n return transactionCtx.run(trx, 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 }\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 async destroy() {\n await this.lifecycles.clear();\n await this.connection.destroy();\n }\n}\n\nexport { Database, errors };\nexport type { Model, JoinTable, Identifiers, Migration, Event };\n"],"names":["afterCreate","db","nativeConnection","done","dialect","initialize","then","Database","init","models","config","connection","logger","debug","client","raw","acquireConnection","metadata","loadModels","validateDatabase","query","uid","has","Error","entityManager","getRepository","inTransaction","transactionCtx","get","transaction","cb","notNestedTransaction","trx","commit","rollback","run","callbackParams","onCommit","onRollback","res","error","getSchemaName","connectionSettings","schema","getConnection","tableName","withSchema","getInfo","displayName","absolutePath","filename","path","relative","process","cwd","database","getSchemaConnection","queryBuilder","createQueryBuilder","destroy","lifecycles","clear","settings","forceMigration","runMigrations","console","getDialect","knexConfig","configure","warn","conn","createMetadata","createConnection","pool","createSchemaProvider","migrations","createMigrationsProvider","createLifecyclesProvider","createEntityManager","repair","createRepairManager"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0CA,MAAMA,WAAAA,GACJ,CAACC,EAAAA,GACD,CACEC,gBAAAA,EACAC,IAAAA,GAAAA;;AAGAF,QAAAA,EAAAA,CAAGG,OAAO,CAACC,UAAU,CAACH,gBAAAA,CAAAA,CAAkBI,IAAI,CAAC,IAAA;AAC3C,YAAA,OAAOH,KAAK,IAAA,EAAMD,gBAAAA,CAAAA;AACpB,QAAA,CAAA,CAAA;AACF,IAAA,CAAA;AAEF,MAAMK,QAAAA,CAAAA;AA0EJ,IAAA,MAAMC,IAAAA,CAAK,EAAEC,MAAM,EAAuB,EAAE;QAC1C,IAAI,OAAO,IAAI,CAACC,MAAM,CAACC,UAAU,CAACA,UAAU,KAAK,UAAA,EAAY;AAC3D;;;;;;;;;AASC,UACD,IAAI,CAACC,MAAM,CAACC,KAAK,CAAC,4CAAA,CAAA;;YAGlB,IAAI,IAAI,CAACH,MAAM,CAACC,UAAU,CAACG,MAAM,KAAK,QAAA,EAAU;AAC9C,gBAAA,MAAM,IAAI,CAACH,UAAU,CAACI,GAAG,CAAC,UAAA,CAAA;YAC5B,CAAA,MAAO;AACL,gBAAA,MAAM,IAAI,CAACJ,UAAU,CAACG,MAAM,CAACE,iBAAiB,EAAA;AAChD,YAAA;AACF,QAAA;AAEA,QAAA,IAAI,CAACC,QAAQ,CAACC,UAAU,CAACT,MAAAA,CAAAA;AACzB,QAAA,MAAMU,yBAAiB,IAAI,CAAA;AAC3B,QAAA,OAAO,IAAI;AACb,IAA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CAACD,MAAM,CAACC,UAAU,CAACA,UAAU,KAAK,UAAA,EAAY;YAC3D,IAAI,CAACP,OAAO,CAACgE,SAAS,EAAA;QACxB,CAAA,MAEK;AACH,YAAA,IAAI,CAACxD,MAAM,CAACyD,IAAI,CACd,wJAAA,CAAA;YAGFF,UAAAA,GAAa;AACX,gBAAA,GAAG,IAAI,CAACzD,MAAM,CAACC,UAAU;gBACzBA,UAAAA,EAAY,UAAA;;oBAEV,MAAM2D,IAAAA,GAAO,MAAM,IAAI,CAAC5D,MAAM,CAACC,UAAU,CAACA,UAAU,EAAA;AACpD,oBAAA,IAAI,CAACP,OAAO,CAACgE,SAAS,CAACE,IAAAA,CAAAA;oBACvB,OAAOA,IAAAA;AACT,gBAAA;AACF,aAAA;AACF,QAAA;AAEA,QAAA,IAAI,CAACrD,QAAQ,GAAGsD,sBAAAA,CAAe,EAAE,CAAA;AAEjC,QAAA,IAAI,CAAC5D,UAAU,GAAG6D,2BAAAA,CAAiBL,UAAAA,EAAY;YAC7CM,IAAAA,EAAM;AAAEzE,gBAAAA,WAAAA,EAAaA,YAAY,IAAI;AAAE;AACzC,SAAA,CAAA;AAEA,QAAA,IAAI,CAAC2C,MAAM,GAAG+B,4BAAAA,CAAqB,IAAI,CAAA;AAEvC,QAAA,IAAI,CAACC,UAAU,GAAGC,gCAAAA,CAAyB,IAAI,CAAA;AAC/C,QAAA,IAAI,CAAChB,UAAU,GAAGiB,gCAAAA,CAAyB,IAAI,CAAA;AAE/C,QAAA,IAAI,CAACrD,aAAa,GAAGsD,2BAAAA,CAAoB,IAAI,CAAA;AAE7C,QAAA,IAAI,CAACC,MAAM,GAAGC,2BAAAA,CAAoB,IAAI,CAAA;AACxC,IAAA;AAkJF;;;;;;;"}
1
+ {"version":3,"file":"index.js","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, type Migration } from './migrations';\nimport { createLifecyclesProvider, LifecycleProvider } from './lifecycles';\nimport type { Event } from './lifecycles';\nimport { createConnection } from './connection';\nimport * as errors from './errors';\nimport { Callback, transactionCtx, TransactionObject } from './transaction-context';\nimport { validateDatabase } from './validations';\nimport type { Model, JoinTable } from './types';\nimport type { Identifiers } from './utils/identifiers';\nimport { createRepairManager, type RepairManager } from './repairs';\n\nexport { isKnexQuery } from './utils/knex';\nexport { isDatabaseClientKind } from './connection';\n\ninterface Settings {\n forceMigration?: boolean;\n runMigrations?: boolean;\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}\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 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 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(knexConfig, {\n pool: { afterCreate: afterCreate(this) },\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 await this.connection.client.acquireConnection();\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 * 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 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.connection.transaction()\n : (transactionCtx.get() as Knex.Transaction);\n\n async function commit() {\n if (notNestedTransaction) {\n await transactionCtx.commit(trx);\n }\n }\n\n async function rollback() {\n if (notNestedTransaction) {\n await transactionCtx.rollback(trx);\n }\n }\n\n if (!cb) {\n return { commit, rollback, get: () => trx };\n }\n\n return transactionCtx.run(trx, 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 }\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 async destroy() {\n await this.lifecycles.clear();\n await this.connection.destroy();\n }\n}\n\nexport { Database, errors };\nexport type { Model, JoinTable, Identifiers, Migration, Event };\n"],"names":["afterCreate","db","nativeConnection","done","dialect","initialize","then","Database","init","models","config","connection","logger","debug","client","raw","acquireConnection","metadata","loadModels","validateDatabase","query","uid","has","Error","entityManager","getRepository","inTransaction","transactionCtx","get","transaction","cb","notNestedTransaction","trx","commit","rollback","run","callbackParams","onCommit","onRollback","res","error","getSchemaName","connectionSettings","schema","getConnection","tableName","withSchema","getInfo","displayName","absolutePath","filename","path","relative","process","cwd","database","getSchemaConnection","queryBuilder","createQueryBuilder","destroy","lifecycles","clear","settings","forceMigration","runMigrations","console","getDialect","knexConfig","configure","warn","conn","createMetadata","createConnection","pool","createSchemaProvider","migrations","createMigrationsProvider","createLifecyclesProvider","createEntityManager","repair","createRepairManager"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0CA,MAAMA,WAAAA,GACJ,CAACC,EAAAA,GACD,CACEC,gBAAAA,EACAC,IAAAA,GAAAA;;AAGAF,QAAAA,EAAAA,CAAGG,OAAO,CAACC,UAAU,CAACH,gBAAAA,CAAAA,CAAkBI,IAAI,CAAC,IAAA;AAC3C,YAAA,OAAOH,KAAK,IAAA,EAAMD,gBAAAA,CAAAA;AACpB,QAAA,CAAA,CAAA;AACF,IAAA,CAAA;AAEF,MAAMK,QAAAA,CAAAA;AA0EJ,IAAA,MAAMC,IAAAA,CAAK,EAAEC,MAAM,EAAuB,EAAE;QAC1C,IAAI,OAAO,IAAI,CAACC,MAAM,CAACC,UAAU,CAACA,UAAU,KAAK,UAAA,EAAY;AAC3D;;;;;;;;;AASC,UACD,IAAI,CAACC,MAAM,CAACC,KAAK,CAAC,4CAAA,CAAA;;YAGlB,IAAI,IAAI,CAACH,MAAM,CAACC,UAAU,CAACG,MAAM,KAAK,QAAA,EAAU;AAC9C,gBAAA,MAAM,IAAI,CAACH,UAAU,CAACI,GAAG,CAAC,UAAA,CAAA;YAC5B,CAAA,MAAO;AACL,gBAAA,MAAM,IAAI,CAACJ,UAAU,CAACG,MAAM,CAACE,iBAAiB,EAAA;AAChD,YAAA;AACF,QAAA;AAEA,QAAA,IAAI,CAACC,QAAQ,CAACC,UAAU,CAACT,MAAAA,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0B,IAAI,CAACzD,MAAM,CAACC,UAAU;;QAGpD,IAAI,OAAO,IAAI,CAACD,MAAM,CAACC,UAAU,CAACA,UAAU,KAAK,UAAA,EAAY;YAC3D,IAAI,CAACP,OAAO,CAACgE,SAAS,EAAA;QACxB,CAAA,MAEK;AACH,YAAA,IAAI,CAACxD,MAAM,CAACyD,IAAI,CACd,wJAAA,CAAA;YAGFF,UAAAA,GAAa;AACX,gBAAA,GAAG,IAAI,CAACzD,MAAM,CAACC,UAAU;gBACzBA,UAAAA,EAAY,UAAA;;oBAEV,MAAM2D,IAAAA,GAAO,MAAM,IAAI,CAAC5D,MAAM,CAACC,UAAU,CAACA,UAAU,EAAA;AACpD,oBAAA,IAAI,CAACP,OAAO,CAACgE,SAAS,CAACE,IAAAA,CAAAA;oBACvB,OAAOA,IAAAA;AACT,gBAAA;AACF,aAAA;AACF,QAAA;AAEA,QAAA,IAAI,CAACrD,QAAQ,GAAGsD,sBAAAA,CAAe,EAAE,CAAA;AAEjC,QAAA,IAAI,CAAC5D,UAAU,GAAG6D,2BAAAA,CAAiBL,UAAAA,EAAY;YAC7CM,IAAAA,EAAM;AAAEzE,gBAAAA,WAAAA,EAAaA,YAAY,IAAI;AAAE;AACzC,SAAA,CAAA;AAEA,QAAA,IAAI,CAAC2C,MAAM,GAAG+B,4BAAAA,CAAqB,IAAI,CAAA;AAEvC,QAAA,IAAI,CAACC,UAAU,GAAGC,gCAAAA,CAAyB,IAAI,CAAA;AAC/C,QAAA,IAAI,CAAChB,UAAU,GAAGiB,gCAAAA,CAAyB,IAAI,CAAA;AAE/C,QAAA,IAAI,CAACrD,aAAa,GAAGsD,2BAAAA,CAAoB,IAAI,CAAA;AAE7C,QAAA,IAAI,CAACC,MAAM,GAAGC,2BAAAA,CAAoB,IAAI,CAAA;AACxC,IAAA;AAkJF;;;;;;;"}
package/dist/index.mjs CHANGED
@@ -138,7 +138,7 @@ class Database {
138
138
  settings: {
139
139
  forceMigration: true,
140
140
  runMigrations: true,
141
- ...config.settings ?? {}
141
+ ...config.settings
142
142
  }
143
143
  };
144
144
  this.logger = config.logger ?? console;
@@ -1 +1 @@
1
- {"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, type Migration } from './migrations';\nimport { createLifecyclesProvider, LifecycleProvider } from './lifecycles';\nimport type { Event } from './lifecycles';\nimport { createConnection } from './connection';\nimport * as errors from './errors';\nimport { Callback, transactionCtx, TransactionObject } from './transaction-context';\nimport { validateDatabase } from './validations';\nimport type { Model, JoinTable } from './types';\nimport type { Identifiers } from './utils/identifiers';\nimport { createRepairManager, type RepairManager } from './repairs';\n\nexport { isKnexQuery } from './utils/knex';\nexport { isDatabaseClientKind } from './connection';\n\ninterface Settings {\n forceMigration?: boolean;\n runMigrations?: boolean;\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}\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 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 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(knexConfig, {\n pool: { afterCreate: afterCreate(this) },\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 await this.connection.client.acquireConnection();\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 * 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 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.connection.transaction()\n : (transactionCtx.get() as Knex.Transaction);\n\n async function commit() {\n if (notNestedTransaction) {\n await transactionCtx.commit(trx);\n }\n }\n\n async function rollback() {\n if (notNestedTransaction) {\n await transactionCtx.rollback(trx);\n }\n }\n\n if (!cb) {\n return { commit, rollback, get: () => trx };\n }\n\n return transactionCtx.run(trx, 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 }\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 async destroy() {\n await this.lifecycles.clear();\n await this.connection.destroy();\n }\n}\n\nexport { Database, errors };\nexport type { Model, JoinTable, Identifiers, Migration, Event };\n"],"names":["afterCreate","db","nativeConnection","done","dialect","initialize","then","Database","init","models","config","connection","logger","debug","client","raw","acquireConnection","metadata","loadModels","validateDatabase","query","uid","has","Error","entityManager","getRepository","inTransaction","transactionCtx","get","transaction","cb","notNestedTransaction","trx","commit","rollback","run","callbackParams","onCommit","onRollback","res","error","getSchemaName","connectionSettings","schema","getConnection","tableName","withSchema","getInfo","displayName","absolutePath","filename","path","relative","process","cwd","database","getSchemaConnection","queryBuilder","createQueryBuilder","destroy","lifecycles","clear","settings","forceMigration","runMigrations","console","getDialect","knexConfig","configure","warn","conn","createMetadata","createConnection","pool","createSchemaProvider","migrations","createMigrationsProvider","createLifecyclesProvider","createEntityManager","repair","createRepairManager"],"mappings":";;;;;;;;;;;;;;;;AA0CA,MAAMA,WAAAA,GACJ,CAACC,EAAAA,GACD,CACEC,gBAAAA,EACAC,IAAAA,GAAAA;;AAGAF,QAAAA,EAAAA,CAAGG,OAAO,CAACC,UAAU,CAACH,gBAAAA,CAAAA,CAAkBI,IAAI,CAAC,IAAA;AAC3C,YAAA,OAAOH,KAAK,IAAA,EAAMD,gBAAAA,CAAAA;AACpB,QAAA,CAAA,CAAA;AACF,IAAA,CAAA;AAEF,MAAMK,QAAAA,CAAAA;AA0EJ,IAAA,MAAMC,IAAAA,CAAK,EAAEC,MAAM,EAAuB,EAAE;QAC1C,IAAI,OAAO,IAAI,CAACC,MAAM,CAACC,UAAU,CAACA,UAAU,KAAK,UAAA,EAAY;AAC3D;;;;;;;;;AASC,UACD,IAAI,CAACC,MAAM,CAACC,KAAK,CAAC,4CAAA,CAAA;;YAGlB,IAAI,IAAI,CAACH,MAAM,CAACC,UAAU,CAACG,MAAM,KAAK,QAAA,E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AAA,IAAI,CAACrD,aAAa,GAAGsD,mBAAAA,CAAoB,IAAI,CAAA;AAE7C,QAAA,IAAI,CAACC,MAAM,GAAGC,mBAAAA,CAAoB,IAAI,CAAA;AACxC,IAAA;AAkJF;;;;"}
1
+ {"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, type Migration } from './migrations';\nimport { createLifecyclesProvider, LifecycleProvider } from './lifecycles';\nimport type { Event } from './lifecycles';\nimport { createConnection } from './connection';\nimport * as errors from './errors';\nimport { Callback, transactionCtx, TransactionObject } from './transaction-context';\nimport { validateDatabase } from './validations';\nimport type { Model, JoinTable } from './types';\nimport type { Identifiers } from './utils/identifiers';\nimport { createRepairManager, type RepairManager } from './repairs';\n\nexport { isKnexQuery } from './utils/knex';\nexport { isDatabaseClientKind } from './connection';\n\ninterface Settings {\n forceMigration?: boolean;\n runMigrations?: boolean;\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}\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 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 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(knexConfig, {\n pool: { afterCreate: afterCreate(this) },\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 await this.connection.client.acquireConnection();\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 * 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 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.connection.transaction()\n : (transactionCtx.get() as Knex.Transaction);\n\n async function commit() {\n if (notNestedTransaction) {\n await transactionCtx.commit(trx);\n }\n }\n\n async function rollback() {\n if (notNestedTransaction) {\n await transactionCtx.rollback(trx);\n }\n }\n\n if (!cb) {\n return { commit, rollback, get: () => trx };\n }\n\n return transactionCtx.run(trx, 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 }\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 async destroy() {\n await this.lifecycles.clear();\n await this.connection.destroy();\n }\n}\n\nexport { Database, errors };\nexport type { Model, JoinTable, Identifiers, Migration, Event };\n"],"names":["afterCreate","db","nativeConnection","done","dialect","initialize","then","Database","init","models","config","connection","logger","debug","client","raw","acquireConnection","metadata","loadModels","validateDatabase","query","uid","has","Error","entityManager","getRepository","inTransaction","transactionCtx","get","transaction","cb","notNestedTransaction","trx","commit","rollback","run","callbackParams","onCommit","onRollback","res","error","getSchemaName","connectionSettings","schema","getConnection","tableName","withSchema","getInfo","displayName","absolutePath","filename","path","relative","process","cwd","database","getSchemaConnection","queryBuilder","createQueryBuilder","destroy","lifecycles","clear","settings","forceMigration","runMigrations","console","getDialect","knexConfig","configure","warn","conn","createMetadata","createConnection","pool","createSchemaProvider","migrations","createMigrationsProvider","createLifecyclesProvider","createEntityManager","repair","createRepairManager"],"mappings":";;;;;;;;;;;;;;;;AA0CA,MAAMA,WAAAA,GACJ,CAACC,EAAAA,GACD,CACEC,gBAAAA,EACAC,IAAAA,GAAAA;;AAGAF,QAAAA,EAAAA,CAAGG,OAAO,CAACC,UAAU,CAACH,gBAAAA,CAAAA,CAAkBI,IAAI,CAAC,IAAA;AAC3C,YAAA,OAAOH,KAAK,IAAA,EAAMD,gBAAAA,CAAAA;AACpB,QAAA,CAAA,CAAA;AACF,IAAA,CAAA;AAEF,MAAMK,QAAAA,CAAAA;AA0EJ,IAAA,MAAMC,IAAAA,CAAK,EAAEC,MAAM,EAAuB,EAAE;QAC1C,IAAI,OAAO,IAAI,CAACC,MAAM,CAACC,UAAU,CAACA,UAAU,KAAK,UAAA,EAAY;AAC3D;;;;;;;;;AASC,UACD,IAAI,CAACC,MAAM,CAACC,KAAK,CAAC,4CAAA,CAAA;;YAGlB,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AGiB,wBAAAA,CAAyB,IAAI,CAAA;AAE/C,QAAA,IAAI,CAACrD,aAAa,GAAGsD,mBAAAA,CAAoB,IAAI,CAAA;AAE7C,QAAA,IAAI,CAACC,MAAM,GAAGC,mBAAAA,CAAoB,IAAI,CAAA;AACxC,IAAA;AAkJF;;;;"}
@@ -15,7 +15,7 @@
15
15
  columnName
16
16
  ], `${tableName}_${columnName}_unique`);
17
17
  });
18
- } catch (error) {
18
+ } catch {
19
19
  // If unique index does not exist, do nothing
20
20
  }
21
21
  };
@@ -1 +1 @@
1
- {"version":3,"file":"5.0.0-05-drop-slug-unique-index.js","sources":["../../../src/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.ts"],"sourcesContent":["/**\n * In V4 slug fields contained a unique index.\n * In V5 slug fields should not have a unique index.\n *\n * This migration drops existing unique indexes from slug fields so downstream migrations\n * can work on the data without violating the unique index.\n */\nimport type { Knex } from 'knex';\n\nimport type { Migration } from '../common';\n\nconst dropIndex = async (knex: Knex, tableName: string, columnName: string) => {\n try {\n await knex.schema.alterTable(tableName, (table) => {\n // NOTE: Can not use \"identifiers\" utility, as the 5.0.0-01 migration does not rename this particular index\n // to `tableName_columnName_uq`.\n table.dropUnique([columnName], `${tableName}_${columnName}_unique`);\n });\n } catch (error) {\n // If unique index does not exist, do nothing\n }\n};\n\nexport const dropSlugFieldsIndex: Migration = {\n name: '5.0.0-05-drop-slug-fields-index',\n async up(knex, db) {\n for (const meta of db.metadata.values()) {\n const hasTable = await knex.schema.hasTable(meta.tableName);\n if (!hasTable) {\n continue;\n }\n\n for (const attribute of Object.values(meta.attributes)) {\n if (attribute.type === 'uid' && attribute.columnName) {\n await dropIndex(knex, meta.tableName, attribute.columnName);\n }\n }\n }\n },\n async down() {\n throw new Error('not implemented');\n },\n};\n"],"names":["dropIndex","knex","tableName","columnName","schema","alterTable","table","dropUnique","error","dropSlugFieldsIndex","name","up","db","meta","metadata","values","hasTable","attribute","Object","attributes","type","down","Error"],"mappings":";;AAAA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.js","sources":["../../../src/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.ts"],"sourcesContent":["/**\n * In V4 slug fields contained a unique index.\n * In V5 slug fields should not have a unique index.\n *\n * This migration drops existing unique indexes from slug fields so downstream migrations\n * can work on the data without violating the unique index.\n */\nimport type { Knex } from 'knex';\n\nimport type { Migration } from '../common';\n\nconst dropIndex = async (knex: Knex, tableName: string, columnName: string) => {\n try {\n await knex.schema.alterTable(tableName, (table) => {\n // NOTE: Can not use \"identifiers\" utility, as the 5.0.0-01 migration does not rename this particular index\n // to `tableName_columnName_uq`.\n table.dropUnique([columnName], `${tableName}_${columnName}_unique`);\n });\n } catch {\n // If unique index does not exist, do nothing\n }\n};\n\nexport const dropSlugFieldsIndex: Migration = {\n name: '5.0.0-05-drop-slug-fields-index',\n async up(knex, db) {\n for (const meta of db.metadata.values()) {\n const hasTable = await knex.schema.hasTable(meta.tableName);\n if (!hasTable) {\n continue;\n }\n\n for (const attribute of Object.values(meta.attributes)) {\n if (attribute.type === 'uid' && attribute.columnName) {\n await dropIndex(knex, meta.tableName, attribute.columnName);\n }\n }\n }\n },\n async down() {\n throw new Error('not implemented');\n },\n};\n"],"names":["dropIndex","knex","tableName","columnName","schema","alterTable","table","dropUnique","dropSlugFieldsIndex","name","up","db","meta","metadata","values","hasTable","attribute","Object","attributes","type","down","Error"],"mappings":";;AAAA;;;;;;AAMC,IAKD,MAAMA,SAAAA,GAAY,OAAOC,IAAAA,EAAYC,SAAAA,EAAmBC,UAAAA,GAAAA;IACtD,IAAI;AACF,QAAA,MAAMF,KAAKG,MAAM,CAACC,UAAU,CAACH,WAAW,CAACI,KAAAA,GAAAA;;;AAGvCA,YAAAA,KAAAA,CAAMC,UAAU,CAAC;AAACJ,gBAAAA;AAAW,aAAA,EAAE,GAAGD,SAAAA,CAAU,CAAC,EAAEC,UAAAA,CAAW,OAAO,CAAC,CAAA;AACpE,QAAA,CAAA,CAAA;AACF,IAAA,CAAA,CAAE,OAAM;;AAER,IAAA;AACF,CAAA;MAEaK,mBAAAA,GAAiC;IAC5CC,IAAAA,EAAM,iCAAA;IACN,MAAMC,EAAAA,CAAAA,CAAGT,IAAI,EAAEU,EAAE,EAAA;AACf,QAAA,KAAK,MAAMC,IAAAA,IAAQD,EAAAA,CAAGE,QAAQ,CAACC,MAAM,EAAA,CAAI;YACvC,MAAMC,QAAAA,GAAW,MAAMd,IAAAA,CAAKG,MAAM,CAACW,QAAQ,CAACH,KAAKV,SAAS,CAAA;AAC1D,YAAA,IAAI,CAACa,QAAAA,EAAU;AACb,gBAAA;AACF,YAAA;AAEA,YAAA,KAAK,MAAMC,SAAAA,IAAaC,MAAAA,CAAOH,MAAM,CAACF,IAAAA,CAAKM,UAAU,CAAA,CAAG;AACtD,gBAAA,IAAIF,UAAUG,IAAI,KAAK,KAAA,IAASH,SAAAA,CAAUb,UAAU,EAAE;AACpD,oBAAA,MAAMH,UAAUC,IAAAA,EAAMW,IAAAA,CAAKV,SAAS,EAAEc,UAAUb,UAAU,CAAA;AAC5D,gBAAA;AACF,YAAA;AACF,QAAA;AACF,IAAA,CAAA;IACA,MAAMiB,IAAAA,CAAAA,GAAAA;AACJ,QAAA,MAAM,IAAIC,KAAAA,CAAM,iBAAA,CAAA;AAClB,IAAA;AACF;;;;"}
@@ -13,7 +13,7 @@
13
13
  columnName
14
14
  ], `${tableName}_${columnName}_unique`);
15
15
  });
16
- } catch (error) {
16
+ } catch {
17
17
  // If unique index does not exist, do nothing
18
18
  }
19
19
  };
@@ -1 +1 @@
1
- {"version":3,"file":"5.0.0-05-drop-slug-unique-index.mjs","sources":["../../../src/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.ts"],"sourcesContent":["/**\n * In V4 slug fields contained a unique index.\n * In V5 slug fields should not have a unique index.\n *\n * This migration drops existing unique indexes from slug fields so downstream migrations\n * can work on the data without violating the unique index.\n */\nimport type { Knex } from 'knex';\n\nimport type { Migration } from '../common';\n\nconst dropIndex = async (knex: Knex, tableName: string, columnName: string) => {\n try {\n await knex.schema.alterTable(tableName, (table) => {\n // NOTE: Can not use \"identifiers\" utility, as the 5.0.0-01 migration does not rename this particular index\n // to `tableName_columnName_uq`.\n table.dropUnique([columnName], `${tableName}_${columnName}_unique`);\n });\n } catch (error) {\n // If unique index does not exist, do nothing\n }\n};\n\nexport const dropSlugFieldsIndex: Migration = {\n name: '5.0.0-05-drop-slug-fields-index',\n async up(knex, db) {\n for (const meta of db.metadata.values()) {\n const hasTable = await knex.schema.hasTable(meta.tableName);\n if (!hasTable) {\n continue;\n }\n\n for (const attribute of Object.values(meta.attributes)) {\n if (attribute.type === 'uid' && attribute.columnName) {\n await dropIndex(knex, meta.tableName, attribute.columnName);\n }\n }\n }\n },\n async down() {\n throw new Error('not implemented');\n },\n};\n"],"names":["dropIndex","knex","tableName","columnName","schema","alterTable","table","dropUnique","error","dropSlugFieldsIndex","name","up","db","meta","metadata","values","hasTable","attribute","Object","attributes","type","down","Error"],"mappings":"AAAA;;;;;;AAMC,IAKD,MAAMA,SAAAA,GAAY,OAAOC,IAAAA,EAAYC,SAAAA,EAAmBC,UAAAA,GAAAA;IACtD,IAAI;AACF,QAAA,MAAMF,KAAKG,MAAM,CAACC,UAAU,CAACH,WAAW,CAACI,KAAAA,GAAAA;;;AAGvCA,YAAAA,KAAAA,CAAMC,UAAU,CAAC;AAACJ,gBAAAA;AAAW,aAAA,EAAE,GAAGD,SAAAA,CAAU,CAAC,EAAEC,UAAAA,CAAW,OAAO,CAAC,CAAA;AACpE,QAAA,CAAA,CAAA;AACF,IAAA,CAAA,CAAE,OAAOK,KAAAA,EAAO;;AAEhB,IAAA;AACF,CAAA;MAEaC,mBAAAA,GAAiC;IAC5CC,IAAAA,EAAM,iCAAA;IACN,MAAMC,EAAAA,CAAAA,CAAGV,IAAI,EAAEW,EAAE,EAAA;AACf,QAAA,KAAK,MAAMC,IAAAA,IAAQD,EAAAA,CAAGE,QAAQ,CAACC,MAAM,EAAA,CAAI;YACvC,MAAMC,QAAAA,GAAW,MAAMf,IAAAA,CAAKG,MAAM,CAACY,QAAQ,CAACH,KAAKX,SAAS,CAAA;AAC1D,YAAA,IAAI,CAACc,QAAAA,EAAU;AACb,gBAAA;AACF,YAAA;AAEA,YAAA,KAAK,MAAMC,SAAAA,IAAaC,MAAAA,CAAOH,MAAM,CAACF,IAAAA,CAAKM,UAAU,CAAA,CAAG;AACtD,gBAAA,IAAIF,UAAUG,IAAI,KAAK,KAAA,IAASH,SAAAA,CAAUd,UAAU,EAAE;AACpD,oBAAA,MAAMH,UAAUC,IAAAA,EAAMY,IAAAA,CAAKX,SAAS,EAAEe,UAAUd,UAAU,CAAA;AAC5D,gBAAA;AACF,YAAA;AACF,QAAA;AACF,IAAA,CAAA;IACA,MAAMkB,IAAAA,CAAAA,GAAAA;AACJ,QAAA,MAAM,IAAIC,KAAAA,CAAM,iBAAA,CAAA;AAClB,IAAA;AACF;;;;"}
1
+ {"version":3,"file":"5.0.0-05-drop-slug-unique-index.mjs","sources":["../../../src/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.ts"],"sourcesContent":["/**\n * In V4 slug fields contained a unique index.\n * In V5 slug fields should not have a unique index.\n *\n * This migration drops existing unique indexes from slug fields so downstream migrations\n * can work on the data without violating the unique index.\n */\nimport type { Knex } from 'knex';\n\nimport type { Migration } from '../common';\n\nconst dropIndex = async (knex: Knex, tableName: string, columnName: string) => {\n try {\n await knex.schema.alterTable(tableName, (table) => {\n // NOTE: Can not use \"identifiers\" utility, as the 5.0.0-01 migration does not rename this particular index\n // to `tableName_columnName_uq`.\n table.dropUnique([columnName], `${tableName}_${columnName}_unique`);\n });\n } catch {\n // If unique index does not exist, do nothing\n }\n};\n\nexport const dropSlugFieldsIndex: Migration = {\n name: '5.0.0-05-drop-slug-fields-index',\n async up(knex, db) {\n for (const meta of db.metadata.values()) {\n const hasTable = await knex.schema.hasTable(meta.tableName);\n if (!hasTable) {\n continue;\n }\n\n for (const attribute of Object.values(meta.attributes)) {\n if (attribute.type === 'uid' && attribute.columnName) {\n await dropIndex(knex, meta.tableName, attribute.columnName);\n }\n }\n }\n },\n async down() {\n throw new Error('not implemented');\n },\n};\n"],"names":["dropIndex","knex","tableName","columnName","schema","alterTable","table","dropUnique","dropSlugFieldsIndex","name","up","db","meta","metadata","values","hasTable","attribute","Object","attributes","type","down","Error"],"mappings":"AAAA;;;;;;AAMC,IAKD,MAAMA,SAAAA,GAAY,OAAOC,IAAAA,EAAYC,SAAAA,EAAmBC,UAAAA,GAAAA;IACtD,IAAI;AACF,QAAA,MAAMF,KAAKG,MAAM,CAACC,UAAU,CAACH,WAAW,CAACI,KAAAA,GAAAA;;;AAGvCA,YAAAA,KAAAA,CAAMC,UAAU,CAAC;AAACJ,gBAAAA;AAAW,aAAA,EAAE,GAAGD,SAAAA,CAAU,CAAC,EAAEC,UAAAA,CAAW,OAAO,CAAC,CAAA;AACpE,QAAA,CAAA,CAAA;AACF,IAAA,CAAA,CAAE,OAAM;;AAER,IAAA;AACF,CAAA;MAEaK,mBAAAA,GAAiC;IAC5CC,IAAAA,EAAM,iCAAA;IACN,MAAMC,EAAAA,CAAAA,CAAGT,IAAI,EAAEU,EAAE,EAAA;AACf,QAAA,KAAK,MAAMC,IAAAA,IAAQD,EAAAA,CAAGE,QAAQ,CAACC,MAAM,EAAA,CAAI;YACvC,MAAMC,QAAAA,GAAW,MAAMd,IAAAA,CAAKG,MAAM,CAACW,QAAQ,CAACH,KAAKV,SAAS,CAAA;AAC1D,YAAA,IAAI,CAACa,QAAAA,EAAU;AACb,gBAAA;AACF,YAAA;AAEA,YAAA,KAAK,MAAMC,SAAAA,IAAaC,MAAAA,CAAOH,MAAM,CAACF,IAAAA,CAAKM,UAAU,CAAA,CAAG;AACtD,gBAAA,IAAIF,UAAUG,IAAI,KAAK,KAAA,IAASH,SAAAA,CAAUb,UAAU,EAAE;AACpD,oBAAA,MAAMH,UAAUC,IAAAA,EAAMW,IAAAA,CAAKV,SAAS,EAAEc,UAAUb,UAAU,CAAA;AAC5D,gBAAA;AACF,YAAA;AACF,QAAA;AACF,IAAA,CAAA;IACA,MAAMiB,IAAAA,CAAAA,GAAAA;AACJ,QAAA,MAAM,IAAIC,KAAAA,CAAM,iBAAA,CAAA;AAClB,IAAA;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"apply.d.ts","sourceRoot":"","sources":["../../../../src/query/helpers/populate/apply.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AA2BzC,KAAK,OAAO,GAAG;IACb,EAAE,EAAE,QAAQ,CAAC;IACb,EAAE,EAAE,YAAY,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAoBF,KAAK,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAspBnC,QAAA,MAAM,aAAa,GAAU,SAAS,GAAG,EAAE,EAAE,UAAU,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,OAAO,+BA+DvF,CAAC;AAEF,eAAe,aAAa,CAAC"}
1
+ {"version":3,"file":"apply.d.ts","sourceRoot":"","sources":["../../../../src/query/helpers/populate/apply.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AA2BzC,KAAK,OAAO,GAAG;IACb,EAAE,EAAE,QAAQ,CAAC;IACb,EAAE,EAAE,YAAY,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAoBF,KAAK,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAwpBnC,QAAA,MAAM,aAAa,GAAU,SAAS,GAAG,EAAE,EAAE,UAAU,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,OAAO,+BA+DvF,CAAC;AAEF,eAAe,aAAa,CAAC"}
@@ -306,7 +306,7 @@ const morphX = async (input, ctx)=>{
306
306
  const referencedValues = ___default.default.uniq(results.map((r)=>r[idColumn.referencedColumn]).filter((value)=>!___default.default.isNil(value)));
307
307
  if (___default.default.isEmpty(referencedValues)) {
308
308
  results.forEach((result)=>{
309
- result[attributeName] = null;
309
+ result[attributeName] = attribute.relation === 'morphOne' ? null : [];
310
310
  });
311
311
  return;
312
312
  }
@@ -320,7 +320,8 @@ const morphX = async (input, ctx)=>{
320
320
  const map = ___default.default.groupBy(idColumn.name)(rows);
321
321
  results.forEach((result)=>{
322
322
  const matchingRows = map[result[idColumn.referencedColumn]];
323
- const matchingValue = attribute.relation === 'morphOne' ? ___default.default.first(matchingRows) : matchingRows;
323
+ // Match oneToMany/manyToMany: empty morphMany collections serialize as [], not null.
324
+ const matchingValue = attribute.relation === 'morphOne' ? ___default.default.first(matchingRows) : matchingRows || [];
324
325
  result[attributeName] = fromTargetRow(matchingValue);
325
326
  });
326
327
  } else if (targetAttribute.type === 'relation' && targetAttribute.relation === 'morphToMany') {
@@ -344,7 +345,7 @@ const morphX = async (input, ctx)=>{
344
345
  rootColumn: joinColumn.referencedColumn,
345
346
  rootTable: qb.alias,
346
347
  on: {
347
- ...joinTable.on || {},
348
+ ...joinTable.on,
348
349
  field: attributeName
349
350
  },
350
351
  orderBy: getJoinTableOrderBy(populateValue, joinTable)
@@ -360,7 +361,8 @@ const morphX = async (input, ctx)=>{
360
361
  const map = ___default.default.groupBy(idColumn.name)(rows);
361
362
  results.forEach((result)=>{
362
363
  const matchingRows = map[result[idColumn.referencedColumn]];
363
- const matchingValue = attribute.relation === 'morphOne' ? ___default.default.first(matchingRows) : matchingRows;
364
+ // Match oneToMany/manyToMany: empty morphMany collections serialize as [], not null.
365
+ const matchingValue = attribute.relation === 'morphOne' ? ___default.default.first(matchingRows) : matchingRows || [];
364
366
  result[attributeName] = fromTargetRow(matchingValue);
365
367
  });
366
368
  }
@@ -377,7 +379,7 @@ const morphToMany = async (input, ctx)=>{
377
379
  const qb = db.entityManager.createQueryBuilder(joinTable.name);
378
380
  const joinRowsRaw = await qb.where({
379
381
  [joinColumn.name]: referencedValues,
380
- ...joinTable.on || {}
382
+ ...joinTable.on
381
383
  }).orderBy([
382
384
  joinColumn.name,
383
385
  'order'