@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.
- package/dist/dialects/mysql/database-inspector.js +1 -1
- package/dist/dialects/mysql/database-inspector.js.map +1 -1
- package/dist/dialects/mysql/database-inspector.mjs +1 -1
- package/dist/dialects/mysql/database-inspector.mjs.map +1 -1
- package/dist/dialects/mysql/index.js +2 -2
- package/dist/dialects/mysql/index.js.map +1 -1
- package/dist/dialects/mysql/index.mjs +2 -2
- package/dist/dialects/mysql/index.mjs.map +1 -1
- package/dist/entity-manager/index.js +30 -30
- package/dist/entity-manager/index.js.map +1 -1
- package/dist/entity-manager/index.mjs +30 -30
- package/dist/entity-manager/index.mjs.map +1 -1
- package/dist/entity-manager/relations-orderer.js +1 -1
- package/dist/entity-manager/relations-orderer.js.map +1 -1
- package/dist/entity-manager/relations-orderer.mjs +1 -1
- package/dist/entity-manager/relations-orderer.mjs.map +1 -1
- package/dist/fields/datetime.d.ts.map +1 -1
- package/dist/fields/datetime.js +6 -23
- package/dist/fields/datetime.js.map +1 -1
- package/dist/fields/datetime.mjs +6 -3
- package/dist/fields/datetime.mjs.map +1 -1
- package/dist/fields/index.d.ts.map +1 -1
- package/dist/fields/index.js +21 -8
- package/dist/fields/index.js.map +1 -1
- package/dist/fields/index.mjs +21 -4
- package/dist/fields/index.mjs.map +1 -1
- package/dist/fields/json.js +1 -1
- package/dist/fields/json.js.map +1 -1
- package/dist/fields/json.mjs +1 -1
- package/dist/fields/json.mjs.map +1 -1
- package/dist/fields/shared/parsers.js +1 -1
- package/dist/fields/shared/parsers.js.map +1 -1
- package/dist/fields/shared/parsers.mjs +1 -1
- package/dist/fields/shared/parsers.mjs.map +1 -1
- package/dist/fields/timestamp.d.ts.map +1 -1
- package/dist/fields/timestamp.js +5 -23
- package/dist/fields/timestamp.js.map +1 -1
- package/dist/fields/timestamp.mjs +5 -3
- package/dist/fields/timestamp.mjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.js +1 -1
- package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.js.map +1 -1
- package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.mjs +1 -1
- package/dist/migrations/internal-migrations/5.0.0-05-drop-slug-unique-index.mjs.map +1 -1
- package/dist/query/helpers/populate/apply.d.ts.map +1 -1
- package/dist/query/helpers/populate/apply.js +7 -5
- package/dist/query/helpers/populate/apply.js.map +1 -1
- package/dist/query/helpers/populate/apply.mjs +7 -5
- package/dist/query/helpers/populate/apply.mjs.map +1 -1
- package/dist/query/helpers/search.d.ts +1 -0
- package/dist/query/helpers/search.d.ts.map +1 -1
- package/dist/query/helpers/search.js +1 -0
- package/dist/query/helpers/search.js.map +1 -1
- package/dist/query/helpers/search.mjs +1 -1
- package/dist/query/helpers/search.mjs.map +1 -1
- package/dist/query/helpers/transform.d.ts.map +1 -1
- package/dist/query/helpers/transform.js +4 -1
- package/dist/query/helpers/transform.js.map +1 -1
- package/dist/query/helpers/transform.mjs +4 -1
- package/dist/query/helpers/transform.mjs.map +1 -1
- package/dist/query/helpers/where.d.ts.map +1 -1
- package/dist/query/helpers/where.js +34 -14
- package/dist/query/helpers/where.js.map +1 -1
- package/dist/query/helpers/where.mjs +34 -14
- package/dist/query/helpers/where.mjs.map +1 -1
- package/package.json +5 -5
package/dist/fields/timestamp.js
CHANGED
|
@@ -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
|
-
|
|
33
|
-
|
|
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
|
|
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
|
-
|
|
11
|
-
|
|
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
|
|
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
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,IAAA;AAEAC,IAAAA,KAAAA,CAAMC,GAAW,EAAE;AACjB,QAAA,IAAI,CAAC,IAAI,CAACJ,QAAQ,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AAS,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,CAAAA;AACzB,QAAA,MAAMU,yBAAiB,IAAI,CAAA;AAC3B,QAAA,OAAO,IAAI;AACb,IAA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AAU,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
package/dist/index.mjs.map
CHANGED
|
@@ -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,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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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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AA;AAkJF;;;;"}
|
|
@@ -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
|
|
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 {\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":"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
|
|
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;
|
|
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
|
-
|
|
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
|
-
|
|
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'
|