@strapi/database 5.61.1 → 5.62.0
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/entity-manager/entity-repository.js +26 -26
- package/dist/entity-manager/entity-repository.js.map +1 -1
- package/dist/entity-manager/entity-repository.mjs +26 -26
- package/dist/entity-manager/entity-repository.mjs.map +1 -1
- package/dist/errors/index.d.ts +3 -1
- package/dist/errors/index.d.ts.map +1 -1
- package/dist/errors/index.js +4 -0
- package/dist/errors/index.js.map +1 -1
- package/dist/errors/index.mjs +2 -0
- package/dist/errors/index.mjs.map +1 -1
- package/dist/errors/invalid-boolean.d.ts +5 -0
- package/dist/errors/invalid-boolean.d.ts.map +1 -0
- package/dist/errors/invalid-boolean.js +13 -0
- package/dist/errors/invalid-boolean.js.map +1 -0
- package/dist/errors/invalid-boolean.mjs +11 -0
- package/dist/errors/invalid-boolean.mjs.map +1 -0
- package/dist/errors/savepoint.d.ts +14 -0
- package/dist/errors/savepoint.d.ts.map +1 -0
- package/dist/errors/savepoint.js +16 -0
- package/dist/errors/savepoint.js.map +1 -0
- package/dist/errors/savepoint.mjs +14 -0
- package/dist/errors/savepoint.mjs.map +1 -0
- package/dist/fields/boolean.d.ts +5 -0
- package/dist/fields/boolean.d.ts.map +1 -1
- package/dist/fields/boolean.js +61 -24
- package/dist/fields/boolean.js.map +1 -1
- package/dist/fields/boolean.mjs +61 -24
- package/dist/fields/boolean.mjs.map +1 -1
- package/dist/fields/field.d.ts +5 -0
- package/dist/fields/field.d.ts.map +1 -1
- package/dist/fields/field.js +6 -0
- package/dist/fields/field.js.map +1 -1
- package/dist/fields/field.mjs +6 -0
- package/dist/fields/field.mjs.map +1 -1
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +24 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +24 -2
- package/dist/index.mjs.map +1 -1
- package/dist/query/helpers/where.js +1 -1
- package/dist/query/helpers/where.js.map +1 -1
- package/dist/query/helpers/where.mjs +1 -1
- package/dist/query/helpers/where.mjs.map +1 -1
- package/dist/transaction-context.d.ts +9 -0
- package/dist/transaction-context.d.ts.map +1 -1
- package/dist/transaction-context.js +66 -0
- package/dist/transaction-context.js.map +1 -1
- package/dist/transaction-context.mjs +66 -0
- package/dist/transaction-context.mjs.map +1 -1
- package/dist/utils/async-stack.d.ts +8 -0
- package/dist/utils/async-stack.d.ts.map +1 -0
- package/dist/utils/async-stack.js +39 -0
- package/dist/utils/async-stack.js.map +1 -0
- package/dist/utils/async-stack.mjs +37 -0
- package/dist/utils/async-stack.mjs.map +1 -0
- package/package.json +6 -6
package/dist/fields/boolean.mjs
CHANGED
|
@@ -1,36 +1,73 @@
|
|
|
1
1
|
import { toString } from 'lodash';
|
|
2
2
|
import Field from './field.mjs';
|
|
3
|
+
import InvalidBooleanError from '../errors/invalid-boolean.mjs';
|
|
3
4
|
|
|
4
|
-
function
|
|
5
|
-
|
|
5
|
+
function toRecognisedNumber(value) {
|
|
6
|
+
if (value === 1) {
|
|
7
|
+
return true;
|
|
8
|
+
}
|
|
9
|
+
if (value === 0) {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
// Case-insensitive, so `'FALSE'` is read as false rather than `Boolean('FALSE')`.
|
|
15
|
+
function toRecognisedString(value) {
|
|
16
|
+
const lowerCased = value.toLowerCase();
|
|
17
|
+
if ([
|
|
18
|
+
'true',
|
|
19
|
+
't',
|
|
20
|
+
'1'
|
|
21
|
+
].includes(lowerCased)) {
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
if ([
|
|
25
|
+
'false',
|
|
26
|
+
'f',
|
|
27
|
+
'0'
|
|
28
|
+
].includes(lowerCased)) {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Casts the values both `toDB` and `toFilterValue` accept. Returns `undefined` for any other
|
|
35
|
+
* value, so each caller decides how to handle it.
|
|
36
|
+
*/ function toRecognisedBoolean(value) {
|
|
37
|
+
if (typeof value === 'boolean') {
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
// Handle null/undefined values explicitly
|
|
41
|
+
if (value === null || value === undefined) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
if (typeof value === 'number') {
|
|
45
|
+
return toRecognisedNumber(value);
|
|
46
|
+
}
|
|
47
|
+
if (typeof value === 'string') {
|
|
48
|
+
return toRecognisedString(value);
|
|
49
|
+
}
|
|
50
|
+
return undefined;
|
|
6
51
|
}
|
|
7
52
|
class BooleanField extends Field {
|
|
8
53
|
toDB(value) {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
// Handle null/undefined values explicitly
|
|
13
|
-
if (value === null || value === undefined) {
|
|
14
|
-
return null;
|
|
15
|
-
}
|
|
16
|
-
if (isStringOrNumber(value) && [
|
|
17
|
-
'true',
|
|
18
|
-
't',
|
|
19
|
-
'1',
|
|
20
|
-
1
|
|
21
|
-
].includes(value)) {
|
|
22
|
-
return true;
|
|
23
|
-
}
|
|
24
|
-
if (isStringOrNumber(value) && [
|
|
25
|
-
'false',
|
|
26
|
-
'f',
|
|
27
|
-
'0',
|
|
28
|
-
0
|
|
29
|
-
].includes(value)) {
|
|
30
|
-
return false;
|
|
54
|
+
const recognised = toRecognisedBoolean(value);
|
|
55
|
+
if (recognised !== undefined) {
|
|
56
|
+
return recognised;
|
|
31
57
|
}
|
|
58
|
+
// Lenient on writes, kept for backward compatibility of direct `db.query` callers.
|
|
32
59
|
return Boolean(value);
|
|
33
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Strict on filters: the `Boolean(value)` fallback of `toDB` reads `'no'` as `true`, so
|
|
63
|
+
* `filters[flag][$eq]=no` would silently match the true rows.
|
|
64
|
+
*/ toFilterValue(value) {
|
|
65
|
+
const recognised = toRecognisedBoolean(value);
|
|
66
|
+
if (recognised === undefined) {
|
|
67
|
+
throw new InvalidBooleanError();
|
|
68
|
+
}
|
|
69
|
+
return recognised;
|
|
70
|
+
}
|
|
34
71
|
fromDB(value) {
|
|
35
72
|
if (typeof value === 'boolean') {
|
|
36
73
|
return value;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boolean.mjs","sources":["../../src/fields/boolean.ts"],"sourcesContent":["import { toString } from 'lodash';\nimport Field from './field';\n\nfunction
|
|
1
|
+
{"version":3,"file":"boolean.mjs","sources":["../../src/fields/boolean.ts"],"sourcesContent":["import { toString } from 'lodash';\nimport Field from './field';\nimport { InvalidBooleanError } from '../errors';\n\nfunction toRecognisedNumber(value: number): boolean | undefined {\n if (value === 1) {\n return true;\n }\n\n if (value === 0) {\n return false;\n }\n\n return undefined;\n}\n\n// Case-insensitive, so `'FALSE'` is read as false rather than `Boolean('FALSE')`.\nfunction toRecognisedString(value: string): boolean | undefined {\n const lowerCased = value.toLowerCase();\n\n if (['true', 't', '1'].includes(lowerCased)) {\n return true;\n }\n\n if (['false', 'f', '0'].includes(lowerCased)) {\n return false;\n }\n\n return undefined;\n}\n\n/**\n * Casts the values both `toDB` and `toFilterValue` accept. Returns `undefined` for any other\n * value, so each caller decides how to handle it.\n */\nfunction toRecognisedBoolean(value: unknown): boolean | null | undefined {\n if (typeof value === 'boolean') {\n return value;\n }\n\n // Handle null/undefined values explicitly\n if (value === null || value === undefined) {\n return null;\n }\n\n if (typeof value === 'number') {\n return toRecognisedNumber(value);\n }\n\n if (typeof value === 'string') {\n return toRecognisedString(value);\n }\n\n return undefined;\n}\n\nexport default class BooleanField extends Field {\n toDB(value: unknown) {\n const recognised = toRecognisedBoolean(value);\n\n if (recognised !== undefined) {\n return recognised;\n }\n\n // Lenient on writes, kept for backward compatibility of direct `db.query` callers.\n return Boolean(value);\n }\n\n /**\n * Strict on filters: the `Boolean(value)` fallback of `toDB` reads `'no'` as `true`, so\n * `filters[flag][$eq]=no` would silently match the true rows.\n */\n toFilterValue(value: unknown) {\n const recognised = toRecognisedBoolean(value);\n\n if (recognised === undefined) {\n throw new InvalidBooleanError();\n }\n\n return recognised;\n }\n\n fromDB(value: unknown) {\n if (typeof value === 'boolean') {\n return value;\n }\n\n const strVal = toString(value);\n\n if (strVal === '1') {\n return true;\n }\n if (strVal === '0') {\n return false;\n }\n return null;\n }\n}\n"],"names":["toRecognisedNumber","value","undefined","toRecognisedString","lowerCased","toLowerCase","includes","toRecognisedBoolean","BooleanField","Field","toDB","recognised","Boolean","toFilterValue","InvalidBooleanError","fromDB","strVal","toString"],"mappings":";;;;AAIA,SAASA,mBAAmBC,KAAa,EAAA;AACvC,IAAA,IAAIA,UAAU,CAAA,EAAG;QACf,OAAO,IAAA;AACT,IAAA;AAEA,IAAA,IAAIA,UAAU,CAAA,EAAG;QACf,OAAO,KAAA;AACT,IAAA;IAEA,OAAOC,SAAAA;AACT;AAEA;AACA,SAASC,mBAAmBF,KAAa,EAAA;IACvC,MAAMG,UAAAA,GAAaH,MAAMI,WAAW,EAAA;IAEpC,IAAI;AAAC,QAAA,MAAA;AAAQ,QAAA,GAAA;AAAK,QAAA;KAAI,CAACC,QAAQ,CAACF,UAAAA,CAAAA,EAAa;QAC3C,OAAO,IAAA;AACT,IAAA;IAEA,IAAI;AAAC,QAAA,OAAA;AAAS,QAAA,GAAA;AAAK,QAAA;KAAI,CAACE,QAAQ,CAACF,UAAAA,CAAAA,EAAa;QAC5C,OAAO,KAAA;AACT,IAAA;IAEA,OAAOF,SAAAA;AACT;AAEA;;;IAIA,SAASK,oBAAoBN,KAAc,EAAA;IACzC,IAAI,OAAOA,UAAU,SAAA,EAAW;QAC9B,OAAOA,KAAAA;AACT,IAAA;;IAGA,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,EAAW;QACzC,OAAO,IAAA;AACT,IAAA;IAEA,IAAI,OAAOD,UAAU,QAAA,EAAU;AAC7B,QAAA,OAAOD,kBAAAA,CAAmBC,KAAAA,CAAAA;AAC5B,IAAA;IAEA,IAAI,OAAOA,UAAU,QAAA,EAAU;AAC7B,QAAA,OAAOE,kBAAAA,CAAmBF,KAAAA,CAAAA;AAC5B,IAAA;IAEA,OAAOC,SAAAA;AACT;AAEe,MAAMM,YAAAA,SAAqBC,KAAAA,CAAAA;AACxCC,IAAAA,IAAAA,CAAKT,KAAc,EAAE;AACnB,QAAA,MAAMU,aAAaJ,mBAAAA,CAAoBN,KAAAA,CAAAA;AAEvC,QAAA,IAAIU,eAAeT,SAAAA,EAAW;YAC5B,OAAOS,UAAAA;AACT,QAAA;;AAGA,QAAA,OAAOC,OAAAA,CAAQX,KAAAA,CAAAA;AACjB,IAAA;AAEA;;;MAIAY,aAAAA,CAAcZ,KAAc,EAAE;AAC5B,QAAA,MAAMU,aAAaJ,mBAAAA,CAAoBN,KAAAA,CAAAA;AAEvC,QAAA,IAAIU,eAAeT,SAAAA,EAAW;AAC5B,YAAA,MAAM,IAAIY,mBAAAA,EAAAA;AACZ,QAAA;QAEA,OAAOH,UAAAA;AACT,IAAA;AAEAI,IAAAA,MAAAA,CAAOd,KAAc,EAAE;QACrB,IAAI,OAAOA,UAAU,SAAA,EAAW;YAC9B,OAAOA,KAAAA;AACT,QAAA;AAEA,QAAA,MAAMe,SAASC,QAAAA,CAAShB,KAAAA,CAAAA;AAExB,QAAA,IAAIe,WAAW,GAAA,EAAK;YAClB,OAAO,IAAA;AACT,QAAA;AACA,QAAA,IAAIA,WAAW,GAAA,EAAK;YAClB,OAAO,KAAA;AACT,QAAA;QACA,OAAO,IAAA;AACT,IAAA;AACF;;;;"}
|
package/dist/fields/field.d.ts
CHANGED
|
@@ -2,6 +2,11 @@ export default class Field {
|
|
|
2
2
|
config: unknown;
|
|
3
3
|
constructor(config: unknown);
|
|
4
4
|
toDB(value: unknown): unknown;
|
|
5
|
+
/**
|
|
6
|
+
* Casts a filter value. Defaults to `toDB`; override when filters must be stricter than
|
|
7
|
+
* writes, so an unrecognised value fails instead of matching the wrong rows.
|
|
8
|
+
*/
|
|
9
|
+
toFilterValue(value: unknown): unknown;
|
|
5
10
|
fromDB(value: unknown): unknown;
|
|
6
11
|
}
|
|
7
12
|
//# sourceMappingURL=field.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"field.d.ts","sourceRoot":"","sources":["../../src/fields/field.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,OAAO,OAAO,KAAK;IACxB,MAAM,EAAE,OAAO,CAAC;gBAEJ,MAAM,EAAE,OAAO;IAI3B,IAAI,CAAC,KAAK,EAAE,OAAO;IAInB,MAAM,CAAC,KAAK,EAAE,OAAO;CAGtB"}
|
|
1
|
+
{"version":3,"file":"field.d.ts","sourceRoot":"","sources":["../../src/fields/field.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,OAAO,OAAO,KAAK;IACxB,MAAM,EAAE,OAAO,CAAC;gBAEJ,MAAM,EAAE,OAAO;IAI3B,IAAI,CAAC,KAAK,EAAE,OAAO;IAInB;;;OAGG;IACH,aAAa,CAAC,KAAK,EAAE,OAAO;IAI5B,MAAM,CAAC,KAAK,EAAE,OAAO;CAGtB"}
|
package/dist/fields/field.js
CHANGED
|
@@ -4,6 +4,12 @@ class Field {
|
|
|
4
4
|
toDB(value) {
|
|
5
5
|
return value;
|
|
6
6
|
}
|
|
7
|
+
/**
|
|
8
|
+
* Casts a filter value. Defaults to `toDB`; override when filters must be stricter than
|
|
9
|
+
* writes, so an unrecognised value fails instead of matching the wrong rows.
|
|
10
|
+
*/ toFilterValue(value) {
|
|
11
|
+
return this.toDB(value);
|
|
12
|
+
}
|
|
7
13
|
fromDB(value) {
|
|
8
14
|
return value;
|
|
9
15
|
}
|
package/dist/fields/field.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"field.js","sources":["../../src/fields/field.ts"],"sourcesContent":["export default class Field {\n config: unknown;\n\n constructor(config: unknown) {\n this.config = config;\n }\n\n toDB(value: unknown) {\n return value;\n }\n\n fromDB(value: unknown) {\n return value;\n }\n}\n"],"names":["Field","toDB","value","fromDB","config"],"mappings":";;AAAe,MAAMA,KAAAA,CAAAA;AAOnBC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;QACnB,OAAOA,KAAAA;AACT,IAAA;
|
|
1
|
+
{"version":3,"file":"field.js","sources":["../../src/fields/field.ts"],"sourcesContent":["export default class Field {\n config: unknown;\n\n constructor(config: unknown) {\n this.config = config;\n }\n\n toDB(value: unknown) {\n return value;\n }\n\n /**\n * Casts a filter value. Defaults to `toDB`; override when filters must be stricter than\n * writes, so an unrecognised value fails instead of matching the wrong rows.\n */\n toFilterValue(value: unknown) {\n return this.toDB(value);\n }\n\n fromDB(value: unknown) {\n return value;\n }\n}\n"],"names":["Field","toDB","value","toFilterValue","fromDB","config"],"mappings":";;AAAe,MAAMA,KAAAA,CAAAA;AAOnBC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;QACnB,OAAOA,KAAAA;AACT,IAAA;AAEA;;;MAIAC,aAAAA,CAAcD,KAAc,EAAE;QAC5B,OAAO,IAAI,CAACD,IAAI,CAACC,KAAAA,CAAAA;AACnB,IAAA;AAEAE,IAAAA,MAAAA,CAAOF,KAAc,EAAE;QACrB,OAAOA,KAAAA;AACT,IAAA;AAlBA,IAAA,WAAA,CAAYG,MAAe,CAAE;QAC3B,IAAI,CAACA,MAAM,GAAGA,MAAAA;AAChB,IAAA;AAiBF;;;;"}
|
package/dist/fields/field.mjs
CHANGED
|
@@ -2,6 +2,12 @@ class Field {
|
|
|
2
2
|
toDB(value) {
|
|
3
3
|
return value;
|
|
4
4
|
}
|
|
5
|
+
/**
|
|
6
|
+
* Casts a filter value. Defaults to `toDB`; override when filters must be stricter than
|
|
7
|
+
* writes, so an unrecognised value fails instead of matching the wrong rows.
|
|
8
|
+
*/ toFilterValue(value) {
|
|
9
|
+
return this.toDB(value);
|
|
10
|
+
}
|
|
5
11
|
fromDB(value) {
|
|
6
12
|
return value;
|
|
7
13
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"field.mjs","sources":["../../src/fields/field.ts"],"sourcesContent":["export default class Field {\n config: unknown;\n\n constructor(config: unknown) {\n this.config = config;\n }\n\n toDB(value: unknown) {\n return value;\n }\n\n fromDB(value: unknown) {\n return value;\n }\n}\n"],"names":["Field","toDB","value","fromDB","config"],"mappings":"AAAe,MAAMA,KAAAA,CAAAA;AAOnBC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;QACnB,OAAOA,KAAAA;AACT,IAAA;
|
|
1
|
+
{"version":3,"file":"field.mjs","sources":["../../src/fields/field.ts"],"sourcesContent":["export default class Field {\n config: unknown;\n\n constructor(config: unknown) {\n this.config = config;\n }\n\n toDB(value: unknown) {\n return value;\n }\n\n /**\n * Casts a filter value. Defaults to `toDB`; override when filters must be stricter than\n * writes, so an unrecognised value fails instead of matching the wrong rows.\n */\n toFilterValue(value: unknown) {\n return this.toDB(value);\n }\n\n fromDB(value: unknown) {\n return value;\n }\n}\n"],"names":["Field","toDB","value","toFilterValue","fromDB","config"],"mappings":"AAAe,MAAMA,KAAAA,CAAAA;AAOnBC,IAAAA,IAAAA,CAAKC,KAAc,EAAE;QACnB,OAAOA,KAAAA;AACT,IAAA;AAEA;;;MAIAC,aAAAA,CAAcD,KAAc,EAAE;QAC5B,OAAO,IAAI,CAACD,IAAI,CAACC,KAAAA,CAAAA;AACnB,IAAA;AAEAE,IAAAA,MAAAA,CAAOF,KAAc,EAAE;QACrB,OAAOA,KAAAA;AACT,IAAA;AAlBA,IAAA,WAAA,CAAYG,MAAe,CAAE;QAC3B,IAAI,CAACA,MAAM,GAAGA,MAAAA;AAChB,IAAA;AAiBF;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -84,6 +84,20 @@ declare class Database {
|
|
|
84
84
|
*/
|
|
85
85
|
transaction(): Promise<TransactionObject>;
|
|
86
86
|
transaction<TCallback extends Callback>(c: TCallback): Promise<ReturnType<TCallback>>;
|
|
87
|
+
/**
|
|
88
|
+
* Runs `cb` in a savepoint of the current transaction, so a failure undoes only `cb`'s writes.
|
|
89
|
+
* If `cb` throws, its writes are rolled back, the `onCommit` callbacks registered in it are
|
|
90
|
+
* dropped, its `onRollback` callbacks run, and the error is rethrown. The transaction stays
|
|
91
|
+
* usable, on Postgres also after a database error, but not after a MySQL deadlock, which rolls
|
|
92
|
+
* back the whole transaction: the savepoint then can't be rolled back to, and it throws an
|
|
93
|
+
* `errors.SavepointError`, as when it can't be released. Throws if called outside a transaction.
|
|
94
|
+
*/
|
|
95
|
+
savepoint<T>(cb: () => Promise<T> | T): Promise<T>;
|
|
96
|
+
/**
|
|
97
|
+
* Starts a top-level knex transaction. knex resolves it through a promise chain that async stack
|
|
98
|
+
* traces cannot follow, so on failure the stack is extended with the frames of our callers.
|
|
99
|
+
*/
|
|
100
|
+
private startTransaction;
|
|
87
101
|
getSchemaName(): string | undefined;
|
|
88
102
|
getConnection(): Knex;
|
|
89
103
|
getConnection(tableName?: string): Knex.QueryBuilder;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAIjC,OAAO,EAAE,OAAO,EAAc,MAAM,YAAY,CAAC;AACjD,OAAO,EAAwB,cAAc,EAAE,MAAM,UAAU,CAAC;AAChE,OAAO,EAAkB,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAuB,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EAA4B,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAA4B,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAE3E,OAAO,KAAK,MAAM,MAAM,UAAU,CAAC;AACnC,OAAO,EAAE,QAAQ,EAAkB,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;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KAAK,CAAC,CAAS;gBAEX,MAAM,EAAE,cAAc;IAkE5B,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE;QAAE,MAAM,EAAE,KAAK,EAAE,CAAA;KAAE;IA6B1C,KAAK,CAAC,GAAG,EAAE,MAAM;IAQjB,aAAa;IAIb;;;;;;;;;OASG;IACG,UAAU,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAWpE;;;;;;OAMG;IACH,WAAW,IAAI,OAAO,CAAC,iBAAiB,CAAC;IACzC,WAAW,CAAC,SAAS,SAAS,QAAQ,EAAE,CAAC,EAAE,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC;IA4CrF;;;;;;;OAOG;IACH,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAIlD;;;OAGG;YACW,gBAAgB;IAS9B,aAAa,IAAI,MAAM,GAAG,SAAS;IAInC,aAAa,IAAI,IAAI;IACrB,aAAa,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC,YAAY;IAQpD,OAAO;;;;;IA2BP,mBAAmB,CAAC,GAAG,mBAAkB;IAKzC,YAAY,CAAC,GAAG,EAAE,MAAM;IAIlB,OAAO;CASd;AAED,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -11,6 +11,7 @@ var connection = require('./connection.js');
|
|
|
11
11
|
var index$1 = require('./errors/index.js');
|
|
12
12
|
var transactionContext = require('./transaction-context.js');
|
|
13
13
|
var index$2 = require('./validations/index.js');
|
|
14
|
+
var asyncStack = require('./utils/async-stack.js');
|
|
14
15
|
var index$a = require('./repairs/index.js');
|
|
15
16
|
var index$5 = require('./pool-diagnostics/index.js');
|
|
16
17
|
var knexLog = require('./utils/knex-log.js');
|
|
@@ -84,7 +85,7 @@ class Database {
|
|
|
84
85
|
}
|
|
85
86
|
async transaction(cb) {
|
|
86
87
|
const notNestedTransaction = !transactionContext.transactionCtx.get();
|
|
87
|
-
const trx = notNestedTransaction ? await this.
|
|
88
|
+
const trx = notNestedTransaction ? await this.startTransaction() : transactionContext.transactionCtx.get();
|
|
88
89
|
async function commit() {
|
|
89
90
|
if (notNestedTransaction) {
|
|
90
91
|
await transactionContext.transactionCtx.commit(trx);
|
|
@@ -102,7 +103,7 @@ class Database {
|
|
|
102
103
|
get: ()=>trx
|
|
103
104
|
};
|
|
104
105
|
}
|
|
105
|
-
return transactionContext.transactionCtx.run(trx, async ()=>{
|
|
106
|
+
return await transactionContext.transactionCtx.run(trx, async ()=>{
|
|
106
107
|
try {
|
|
107
108
|
const callbackParams = {
|
|
108
109
|
trx,
|
|
@@ -120,6 +121,27 @@ class Database {
|
|
|
120
121
|
}
|
|
121
122
|
});
|
|
122
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* Runs `cb` in a savepoint of the current transaction, so a failure undoes only `cb`'s writes.
|
|
126
|
+
* If `cb` throws, its writes are rolled back, the `onCommit` callbacks registered in it are
|
|
127
|
+
* dropped, its `onRollback` callbacks run, and the error is rethrown. The transaction stays
|
|
128
|
+
* usable, on Postgres also after a database error, but not after a MySQL deadlock, which rolls
|
|
129
|
+
* back the whole transaction: the savepoint then can't be rolled back to, and it throws an
|
|
130
|
+
* `errors.SavepointError`, as when it can't be released. Throws if called outside a transaction.
|
|
131
|
+
*/ savepoint(cb) {
|
|
132
|
+
return transactionContext.transactionCtx.savepoint(cb);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Starts a top-level knex transaction. knex resolves it through a promise chain that async stack
|
|
136
|
+
* traces cannot follow, so on failure the stack is extended with the frames of our callers.
|
|
137
|
+
*/ async startTransaction() {
|
|
138
|
+
try {
|
|
139
|
+
return await this.connection.transaction();
|
|
140
|
+
} catch (error) {
|
|
141
|
+
asyncStack.appendCallerStack(error);
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
123
145
|
getSchemaName() {
|
|
124
146
|
return this.connection.client.connectionSettings.schema;
|
|
125
147
|
}
|
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 } from './migrations';\nimport { createLifecyclesProvider, LifecycleProvider } from './lifecycles';\nimport { createConnection } from './connection';\nimport * as errors from './errors';\nimport { Callback, transactionCtx, TransactionObject } from './transaction-context';\nimport { validateDatabase } from './validations';\nimport type { Model } from './types';\nimport { createRepairManager, type RepairManager } from './repairs';\nimport { installPoolDiagnostics, type PoolDiagnostics } from './pool-diagnostics';\nimport { withStrapiKnexLog } from './utils/knex-log';\n\nexport { isKnexQuery } from './utils/knex';\nexport { isDatabaseClientKind } from './connection';\nexport { attributeNaming } from './metadata';\nexport { createField } from './fields';\nexport type { AttributeNaming, Meta } from './metadata';\nexport type {\n AttributeRenamesOperation,\n Migration,\n BuiltMigrationFile,\n MigrationFileBuilder,\n MigrationFileFormat,\n MigrationFileOperation,\n} from './migrations';\nexport type { Event } from './lifecycles';\nexport type { Attribute, Model, JoinTable } from './types';\nexport type { AttributeRenameHandler, AttributeRenames } from './schema';\nexport type { Identifiers } from './utils/identifiers';\nexport { POOL_TIMEOUT_CODE } from './pool-diagnostics';\nexport type {\n EventLoopDelay,\n PoolDiagnostics,\n PoolState,\n PoolTimeoutDetails,\n} from './pool-diagnostics';\n\ninterface Settings {\n forceMigration?: boolean;\n runMigrations?: boolean;\n /**\n * Describe the pool on knex connection pool timeouts (details on the error, a docs link, one\n * warning block per 30 s). Defaults to true; false leaves knex's error untouched. Must be a\n * boolean (for example `env.bool('DATABASE_POOL_TIMEOUT_DIAGNOSTICS', true)`): a string is not\n * read as false.\n */\n poolTimeoutDiagnostics?: boolean;\n migrations: {\n dir: string;\n };\n [key: string]: unknown;\n}\n\nexport type Logger = Record<\n 'info' | 'warn' | 'error' | 'debug',\n (message: string | Record<string, unknown>) => void\n>;\n\nexport interface DatabaseConfig {\n connection: Knex.Config;\n settings: Settings;\n logger?: Logger;\n /** Lifecycle phase of the host application, e.g. \"boot\" or \"runtime\", for pool timeout reports. */\n getPhase?: () => string | undefined;\n}\n\nconst afterCreate =\n (db: Database) =>\n (\n nativeConnection: unknown,\n done: (error: Error | null, nativeConnection: unknown) => Promise<void>\n ) => {\n // run initialize for it since commands such as postgres SET and sqlite PRAGMA are per-connection\n db.dialect.initialize(nativeConnection).then(() => {\n return done(null, nativeConnection);\n });\n };\n\nclass Database {\n connection: Knex;\n\n dialect: Dialect;\n\n config: DatabaseConfig;\n\n metadata: Metadata;\n\n schema: SchemaProvider;\n\n migrations: MigrationProvider;\n\n lifecycles: LifecycleProvider;\n\n entityManager: EntityManager;\n\n repair: RepairManager;\n\n logger: Logger;\n\n /** Set unless `settings.poolTimeoutDiagnostics` is false or the install failed. */\n private poolDiagnostics?: PoolDiagnostics;\n\n private phase?: string;\n\n constructor(config: DatabaseConfig) {\n this.config = {\n ...config,\n settings: {\n forceMigration: true,\n runMigrations: true,\n ...config.settings,\n },\n };\n\n this.logger = config.logger ?? console;\n\n this.dialect = getDialect(this);\n\n let knexConfig: Knex.Config = this.config.connection;\n\n // for object connections, we can configure the dialect synchronously\n if (typeof this.config.connection.connection !== 'function') {\n this.dialect.configure();\n }\n // for connection functions, we wrap it so that we can modify it with dialect configure before it reaches knex\n else {\n this.logger.warn(\n 'Knex connection functions are currently experimental. Attempting to access the connection object before database initialization will result in errors.'\n );\n\n knexConfig = {\n ...this.config.connection,\n connection: async () => {\n // @ts-expect-error confirmed it was a function above\n const conn = await this.config.connection.connection();\n this.dialect.configure(conn);\n return conn;\n },\n };\n }\n\n this.metadata = createMetadata([]);\n\n this.connection = createConnection(withStrapiKnexLog(knexConfig, this.logger), {\n pool: { afterCreate: afterCreate(this) },\n });\n\n if (this.config.settings.poolTimeoutDiagnostics !== false) {\n try {\n this.poolDiagnostics = installPoolDiagnostics(this.connection, {\n logger: { warn: (message) => this.logger.warn(message) },\n getPhase: () => this.phase ?? this.config.getPhase?.(),\n });\n } catch (error) {\n // Diagnostics are optional: failing to install them must not stop the application booting\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.debug(`[database] pool timeout diagnostics not installed: ${reason}`);\n }\n }\n\n this.schema = createSchemaProvider(this);\n\n this.migrations = createMigrationsProvider(this);\n this.lifecycles = createLifecyclesProvider(this);\n\n this.entityManager = createEntityManager(this);\n\n this.repair = createRepairManager(this);\n }\n\n async init({ models }: { models: Model[] }) {\n if (typeof this.config.connection.connection === 'function') {\n /*\n * User code needs to be able to access `connection.connection` directly as if\n * it were always an object. For a connection function, that doesn't happen\n * until the pool is created, so we need to do that here\n *\n * TODO: In the next major version, we need to replace all internal code that\n * directly references `connection.connection` prior to init, and make a breaking\n * change that it cannot be relied on to exist before init so that we can call\n * this feature stable.\n */\n this.logger.debug('Forcing Knex to make real connection to db');\n\n // sqlite does not support connection pooling so acquireConnection doesn't work\n if (this.config.connection.client === 'sqlite') {\n await this.connection.raw('SELECT 1');\n } else {\n // release it straight away, otherwise it holds a pool slot for the life of the process\n const conn = await this.connection.client.acquireConnection();\n await this.connection.client.releaseConnection(conn);\n }\n }\n\n this.metadata.loadModels(models);\n await validateDatabase(this);\n return this;\n }\n\n query(uid: string) {\n if (!this.metadata.has(uid)) {\n throw new Error(`Model ${uid} not found`);\n }\n\n return this.entityManager.getRepository(uid);\n }\n\n inTransaction() {\n return !!transactionCtx.get();\n }\n\n /**\n * Labels pool timeout reports raised while `fn` runs, for example \"schema sync\". Nested calls\n * restore the outer label. Calls that overlap without nesting can restore the wrong label; core\n * only nests them (schema sync, then a migration).\n *\n * The label is process-wide, not per call: a call made at runtime relabels every concurrent\n * timeout report until it returns. It is meant for boot-time work (schema sync, migrations).\n *\n * @internal\n */\n async runInPhase<T>(phase: string, fn: () => Promise<T>): Promise<T> {\n const previous = this.phase;\n this.phase = phase;\n\n try {\n return await fn();\n } finally {\n this.phase = previous;\n }\n }\n\n /**\n * Run work inside a DB transaction. On a fulfilled callback, the transaction\n * is committed; on rejection, it is rolled back. The callback receives Knex\n * `commit` and `rollback` helpers: if you call `rollback` and return without\n * throwing, the implementation avoids attempting a second `commit` on an\n * already-finalised transactor.\n */\n 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 try {\n await this.lifecycles.clear();\n } finally {\n this.poolDiagnostics?.dispose();\n }\n\n await this.connection.destroy();\n }\n}\n\nexport { Database, errors };\n"],"names":["afterCreate","db","nativeConnection","done","dialect","initialize","then","Database","init","models","config","connection","logger","debug","client","raw","conn","acquireConnection","releaseConnection","metadata","loadModels","validateDatabase","query","uid","has","Error","entityManager","getRepository","inTransaction","transactionCtx","get","runInPhase","phase","fn","previous","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","poolDiagnostics","dispose","settings","forceMigration","runMigrations","console","getDialect","knexConfig","configure","warn","createMetadata","createConnection","withStrapiKnexLog","pool","poolTimeoutDiagnostics","installPoolDiagnostics","message","getPhase","reason","String","createSchemaProvider","migrations","createMigrationsProvider","createLifecyclesProvider","createEntityManager","repair","createRepairManager"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,MAAMA,WAAAA,GACJ,CAACC,EAAAA,GACD,CACEC,gBAAAA,EACAC,IAAAA,GAAAA;;AAGAF,QAAAA,EAAAA,CAAGG,OAAO,CAACC,UAAU,CAACH,gBAAAA,CAAAA,CAAkBI,IAAI,CAAC,I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G,MAAAA,CAAOzC,KAAAA,CAAAA;gBAC/D,IAAI,CAAClC,MAAM,CAACC,KAAK,CAAC,CAAC,mDAAmD,EAAEyE,MAAAA,CAAAA,CAAQ,CAAA;AAClF,YAAA;AACF,QAAA;AAEA,QAAA,IAAI,CAACrC,MAAM,GAAGuC,4BAAAA,CAAqB,IAAI,CAAA;AAEvC,QAAA,IAAI,CAACC,UAAU,GAAGC,gCAAAA,CAAyB,IAAI,CAAA;AAC/C,QAAA,IAAI,CAACxB,UAAU,GAAGyB,gCAAAA,CAAyB,IAAI,CAAA;AAE/C,QAAA,IAAI,CAACjE,aAAa,GAAGkE,2BAAAA,CAAoB,IAAI,CAAA;AAE7C,QAAA,IAAI,CAACC,MAAM,GAAGC,2BAAAA,CAAoB,IAAI,CAAA;AACxC,IAAA;AA8KF;;;;;;;;;;"}
|
|
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 } from './migrations';\nimport { createLifecyclesProvider, LifecycleProvider } from './lifecycles';\nimport { createConnection } from './connection';\nimport * as errors from './errors';\nimport { Callback, transactionCtx, TransactionObject } from './transaction-context';\nimport { validateDatabase } from './validations';\nimport { appendCallerStack } from './utils/async-stack';\nimport type { Model } from './types';\nimport { createRepairManager, type RepairManager } from './repairs';\nimport { installPoolDiagnostics, type PoolDiagnostics } from './pool-diagnostics';\nimport { withStrapiKnexLog } from './utils/knex-log';\n\nexport { isKnexQuery } from './utils/knex';\nexport { isDatabaseClientKind } from './connection';\nexport { attributeNaming } from './metadata';\nexport { createField } from './fields';\nexport type { AttributeNaming, Meta } from './metadata';\nexport type {\n AttributeRenamesOperation,\n Migration,\n BuiltMigrationFile,\n MigrationFileBuilder,\n MigrationFileFormat,\n MigrationFileOperation,\n} from './migrations';\nexport type { Event } from './lifecycles';\nexport type { Attribute, Model, JoinTable } from './types';\nexport type { AttributeRenameHandler, AttributeRenames } from './schema';\nexport type { Identifiers } from './utils/identifiers';\nexport { POOL_TIMEOUT_CODE } from './pool-diagnostics';\nexport type {\n EventLoopDelay,\n PoolDiagnostics,\n PoolState,\n PoolTimeoutDetails,\n} from './pool-diagnostics';\n\ninterface Settings {\n forceMigration?: boolean;\n runMigrations?: boolean;\n /**\n * Describe the pool on knex connection pool timeouts (details on the error, a docs link, one\n * warning block per 30 s). Defaults to true; false leaves knex's error untouched. Must be a\n * boolean (for example `env.bool('DATABASE_POOL_TIMEOUT_DIAGNOSTICS', true)`): a string is not\n * read as false.\n */\n poolTimeoutDiagnostics?: boolean;\n migrations: {\n dir: string;\n };\n [key: string]: unknown;\n}\n\nexport type Logger = Record<\n 'info' | 'warn' | 'error' | 'debug',\n (message: string | Record<string, unknown>) => void\n>;\n\nexport interface DatabaseConfig {\n connection: Knex.Config;\n settings: Settings;\n logger?: Logger;\n /** Lifecycle phase of the host application, e.g. \"boot\" or \"runtime\", for pool timeout reports. */\n getPhase?: () => string | undefined;\n}\n\nconst afterCreate =\n (db: Database) =>\n (\n nativeConnection: unknown,\n done: (error: Error | null, nativeConnection: unknown) => Promise<void>\n ) => {\n // run initialize for it since commands such as postgres SET and sqlite PRAGMA are per-connection\n db.dialect.initialize(nativeConnection).then(() => {\n return done(null, nativeConnection);\n });\n };\n\nclass Database {\n connection: Knex;\n\n dialect: Dialect;\n\n config: DatabaseConfig;\n\n metadata: Metadata;\n\n schema: SchemaProvider;\n\n migrations: MigrationProvider;\n\n lifecycles: LifecycleProvider;\n\n entityManager: EntityManager;\n\n repair: RepairManager;\n\n logger: Logger;\n\n /** Set unless `settings.poolTimeoutDiagnostics` is false or the install failed. */\n private poolDiagnostics?: PoolDiagnostics;\n\n private phase?: string;\n\n constructor(config: DatabaseConfig) {\n this.config = {\n ...config,\n settings: {\n forceMigration: true,\n runMigrations: true,\n ...config.settings,\n },\n };\n\n this.logger = config.logger ?? console;\n\n this.dialect = getDialect(this);\n\n let knexConfig: Knex.Config = this.config.connection;\n\n // for object connections, we can configure the dialect synchronously\n if (typeof this.config.connection.connection !== 'function') {\n this.dialect.configure();\n }\n // for connection functions, we wrap it so that we can modify it with dialect configure before it reaches knex\n else {\n this.logger.warn(\n 'Knex connection functions are currently experimental. Attempting to access the connection object before database initialization will result in errors.'\n );\n\n knexConfig = {\n ...this.config.connection,\n connection: async () => {\n // @ts-expect-error confirmed it was a function above\n const conn = await this.config.connection.connection();\n this.dialect.configure(conn);\n return conn;\n },\n };\n }\n\n this.metadata = createMetadata([]);\n\n this.connection = createConnection(withStrapiKnexLog(knexConfig, this.logger), {\n pool: { afterCreate: afterCreate(this) },\n });\n\n if (this.config.settings.poolTimeoutDiagnostics !== false) {\n try {\n this.poolDiagnostics = installPoolDiagnostics(this.connection, {\n logger: { warn: (message) => this.logger.warn(message) },\n getPhase: () => this.phase ?? this.config.getPhase?.(),\n });\n } catch (error) {\n // Diagnostics are optional: failing to install them must not stop the application booting\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.debug(`[database] pool timeout diagnostics not installed: ${reason}`);\n }\n }\n\n this.schema = createSchemaProvider(this);\n\n this.migrations = createMigrationsProvider(this);\n this.lifecycles = createLifecyclesProvider(this);\n\n this.entityManager = createEntityManager(this);\n\n this.repair = createRepairManager(this);\n }\n\n async init({ models }: { models: Model[] }) {\n if (typeof this.config.connection.connection === 'function') {\n /*\n * User code needs to be able to access `connection.connection` directly as if\n * it were always an object. For a connection function, that doesn't happen\n * until the pool is created, so we need to do that here\n *\n * TODO: In the next major version, we need to replace all internal code that\n * directly references `connection.connection` prior to init, and make a breaking\n * change that it cannot be relied on to exist before init so that we can call\n * this feature stable.\n */\n this.logger.debug('Forcing Knex to make real connection to db');\n\n // sqlite does not support connection pooling so acquireConnection doesn't work\n if (this.config.connection.client === 'sqlite') {\n await this.connection.raw('SELECT 1');\n } else {\n // release it straight away, otherwise it holds a pool slot for the life of the process\n const conn = await this.connection.client.acquireConnection();\n await this.connection.client.releaseConnection(conn);\n }\n }\n\n this.metadata.loadModels(models);\n await validateDatabase(this);\n return this;\n }\n\n query(uid: string) {\n if (!this.metadata.has(uid)) {\n throw new Error(`Model ${uid} not found`);\n }\n\n return this.entityManager.getRepository(uid);\n }\n\n inTransaction() {\n return !!transactionCtx.get();\n }\n\n /**\n * Labels pool timeout reports raised while `fn` runs, for example \"schema sync\". Nested calls\n * restore the outer label. Calls that overlap without nesting can restore the wrong label; core\n * only nests them (schema sync, then a migration).\n *\n * The label is process-wide, not per call: a call made at runtime relabels every concurrent\n * timeout report until it returns. It is meant for boot-time work (schema sync, migrations).\n *\n * @internal\n */\n async runInPhase<T>(phase: string, fn: () => Promise<T>): Promise<T> {\n const previous = this.phase;\n this.phase = phase;\n\n try {\n return await fn();\n } finally {\n this.phase = previous;\n }\n }\n\n /**\n * Run work inside a DB transaction. On a fulfilled callback, the transaction\n * is committed; on rejection, it is rolled back. The callback receives Knex\n * `commit` and `rollback` helpers: if you call `rollback` and return without\n * throwing, the implementation avoids attempting a second `commit` on an\n * already-finalised transactor.\n */\n transaction(): Promise<TransactionObject>;\n transaction<TCallback extends Callback>(c: TCallback): Promise<ReturnType<TCallback>>;\n async transaction<TCallback extends Callback>(\n cb?: TCallback\n ): Promise<ReturnType<TCallback> | TransactionObject> {\n const notNestedTransaction = !transactionCtx.get();\n const trx = notNestedTransaction\n ? await this.startTransaction()\n : (transactionCtx.get() as Knex.Transaction);\n\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 await 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 /**\n * Runs `cb` in a savepoint of the current transaction, so a failure undoes only `cb`'s writes.\n * If `cb` throws, its writes are rolled back, the `onCommit` callbacks registered in it are\n * dropped, its `onRollback` callbacks run, and the error is rethrown. The transaction stays\n * usable, on Postgres also after a database error, but not after a MySQL deadlock, which rolls\n * back the whole transaction: the savepoint then can't be rolled back to, and it throws an\n * `errors.SavepointError`, as when it can't be released. Throws if called outside a transaction.\n */\n savepoint<T>(cb: () => Promise<T> | T): Promise<T> {\n return transactionCtx.savepoint(cb);\n }\n\n /**\n * Starts a top-level knex transaction. knex resolves it through a promise chain that async stack\n * traces cannot follow, so on failure the stack is extended with the frames of our callers.\n */\n private async startTransaction(): Promise<Knex.Transaction> {\n try {\n return await this.connection.transaction();\n } catch (error) {\n appendCallerStack(error);\n throw error;\n }\n }\n\n getSchemaName(): string | undefined {\n return this.connection.client.connectionSettings.schema;\n }\n\n getConnection(): Knex;\n getConnection(tableName?: string): Knex.QueryBuilder;\n getConnection(tableName?: string): Knex | Knex.QueryBuilder {\n const schema = this.getSchemaName();\n const connection = tableName ? this.connection(tableName) : this.connection;\n return schema ? connection.withSchema(schema) : connection;\n }\n\n // Returns basic info about the database connection\n getInfo() {\n const connectionSettings = this.connection?.client?.connectionSettings || {};\n const client = this.dialect?.client || '';\n\n let displayName = '';\n let schema;\n\n // For SQLite, get the relative filename\n if (client === 'sqlite') {\n const absolutePath = connectionSettings?.filename;\n if (absolutePath) {\n displayName = path.relative(process.cwd(), absolutePath);\n }\n }\n // For other dialects, get the database name\n else {\n displayName = connectionSettings?.database;\n schema = connectionSettings?.schema;\n }\n\n return {\n displayName,\n schema,\n client,\n };\n }\n\n getSchemaConnection(trx = this.connection) {\n const schema = this.getSchemaName();\n return schema ? trx.schema.withSchema(schema) : trx.schema;\n }\n\n queryBuilder(uid: string) {\n return this.entityManager.createQueryBuilder(uid);\n }\n\n async destroy() {\n try {\n await this.lifecycles.clear();\n } finally {\n this.poolDiagnostics?.dispose();\n }\n\n await this.connection.destroy();\n }\n}\n\nexport { Database, errors };\n"],"names":["afterCreate","db","nativeConnection","done","dialect","initialize","then","Database","init","models","config","connection","logger","debug","client","raw","conn","acquireConnection","releaseConnection","metadata","loadModels","validateDatabase","query","uid","has","Error","entityManager","getRepository","inTransaction","transactionCtx","get","runInPhase","phase","fn","previous","transaction","cb","notNestedTransaction","trx","startTransaction","commit","rollback","run","callbackParams","onCommit","onRollback","res","error","savepoint","appendCallerStack","getSchemaName","connectionSettings","schema","getConnection","tableName","withSchema","getInfo","displayName","absolutePath","filename","path","relative","process","cwd","database","getSchemaConnection","queryBuilder","createQueryBuilder","destroy","lifecycles","clear","poolDiagnostics","dispose","settings","forceMigration","runMigrations","console","getDialect","knexConfig","configure","warn","createMetadata","createConnection","withStrapiKnexLog","pool","poolTimeoutDiagnostics","installPoolDiagnostics","message","getPhase","reason","String","createSchemaProvider","migrations","createMigrationsProvider","createLifecyclesProvider","createEntityManager","repair","createRepairManager"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,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;AA4FJ,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,IAA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GG,MAAAA,CAAO3C,KAAAA,CAAAA;gBAC/D,IAAI,CAACnC,MAAM,CAACC,KAAK,CAAC,CAAC,mDAAmD,EAAE4E,MAAAA,CAAAA,CAAQ,CAAA;AAClF,YAAA;AACF,QAAA;AAEA,QAAA,IAAI,CAACrC,MAAM,GAAGuC,4BAAAA,CAAqB,IAAI,CAAA;AAEvC,QAAA,IAAI,CAACC,UAAU,GAAGC,gCAAAA,CAAyB,IAAI,CAAA;AAC/C,QAAA,IAAI,CAACxB,UAAU,GAAGyB,gCAAAA,CAAyB,IAAI,CAAA;AAE/C,QAAA,IAAI,CAACpE,aAAa,GAAGqE,2BAAAA,CAAoB,IAAI,CAAA;AAE7C,QAAA,IAAI,CAACC,MAAM,GAAGC,2BAAAA,CAAoB,IAAI,CAAA;AACxC,IAAA;AAuMF;;;;;;;;;;"}
|
package/dist/index.mjs
CHANGED
|
@@ -11,6 +11,7 @@ import * as index from './errors/index.mjs';
|
|
|
11
11
|
export { index as errors };
|
|
12
12
|
import { transactionCtx } from './transaction-context.mjs';
|
|
13
13
|
import { validateDatabase } from './validations/index.mjs';
|
|
14
|
+
import { appendCallerStack } from './utils/async-stack.mjs';
|
|
14
15
|
import { createRepairManager } from './repairs/index.mjs';
|
|
15
16
|
import { installPoolDiagnostics } from './pool-diagnostics/index.mjs';
|
|
16
17
|
import { withStrapiKnexLog } from './utils/knex-log.mjs';
|
|
@@ -80,7 +81,7 @@ class Database {
|
|
|
80
81
|
}
|
|
81
82
|
async transaction(cb) {
|
|
82
83
|
const notNestedTransaction = !transactionCtx.get();
|
|
83
|
-
const trx = notNestedTransaction ? await this.
|
|
84
|
+
const trx = notNestedTransaction ? await this.startTransaction() : transactionCtx.get();
|
|
84
85
|
async function commit() {
|
|
85
86
|
if (notNestedTransaction) {
|
|
86
87
|
await transactionCtx.commit(trx);
|
|
@@ -98,7 +99,7 @@ class Database {
|
|
|
98
99
|
get: ()=>trx
|
|
99
100
|
};
|
|
100
101
|
}
|
|
101
|
-
return transactionCtx.run(trx, async ()=>{
|
|
102
|
+
return await transactionCtx.run(trx, async ()=>{
|
|
102
103
|
try {
|
|
103
104
|
const callbackParams = {
|
|
104
105
|
trx,
|
|
@@ -116,6 +117,27 @@ class Database {
|
|
|
116
117
|
}
|
|
117
118
|
});
|
|
118
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Runs `cb` in a savepoint of the current transaction, so a failure undoes only `cb`'s writes.
|
|
122
|
+
* If `cb` throws, its writes are rolled back, the `onCommit` callbacks registered in it are
|
|
123
|
+
* dropped, its `onRollback` callbacks run, and the error is rethrown. The transaction stays
|
|
124
|
+
* usable, on Postgres also after a database error, but not after a MySQL deadlock, which rolls
|
|
125
|
+
* back the whole transaction: the savepoint then can't be rolled back to, and it throws an
|
|
126
|
+
* `errors.SavepointError`, as when it can't be released. Throws if called outside a transaction.
|
|
127
|
+
*/ savepoint(cb) {
|
|
128
|
+
return transactionCtx.savepoint(cb);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Starts a top-level knex transaction. knex resolves it through a promise chain that async stack
|
|
132
|
+
* traces cannot follow, so on failure the stack is extended with the frames of our callers.
|
|
133
|
+
*/ async startTransaction() {
|
|
134
|
+
try {
|
|
135
|
+
return await this.connection.transaction();
|
|
136
|
+
} catch (error) {
|
|
137
|
+
appendCallerStack(error);
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
119
141
|
getSchemaName() {
|
|
120
142
|
return this.connection.client.connectionSettings.schema;
|
|
121
143
|
}
|
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 } from './migrations';\nimport { createLifecyclesProvider, LifecycleProvider } from './lifecycles';\nimport { createConnection } from './connection';\nimport * as errors from './errors';\nimport { Callback, transactionCtx, TransactionObject } from './transaction-context';\nimport { validateDatabase } from './validations';\nimport type { Model } from './types';\nimport { createRepairManager, type RepairManager } from './repairs';\nimport { installPoolDiagnostics, type PoolDiagnostics } from './pool-diagnostics';\nimport { withStrapiKnexLog } from './utils/knex-log';\n\nexport { isKnexQuery } from './utils/knex';\nexport { isDatabaseClientKind } from './connection';\nexport { attributeNaming } from './metadata';\nexport { createField } from './fields';\nexport type { AttributeNaming, Meta } from './metadata';\nexport type {\n AttributeRenamesOperation,\n Migration,\n BuiltMigrationFile,\n MigrationFileBuilder,\n MigrationFileFormat,\n MigrationFileOperation,\n} from './migrations';\nexport type { Event } from './lifecycles';\nexport type { Attribute, Model, JoinTable } from './types';\nexport type { AttributeRenameHandler, AttributeRenames } from './schema';\nexport type { Identifiers } from './utils/identifiers';\nexport { POOL_TIMEOUT_CODE } from './pool-diagnostics';\nexport type {\n EventLoopDelay,\n PoolDiagnostics,\n PoolState,\n PoolTimeoutDetails,\n} from './pool-diagnostics';\n\ninterface Settings {\n forceMigration?: boolean;\n runMigrations?: boolean;\n /**\n * Describe the pool on knex connection pool timeouts (details on the error, a docs link, one\n * warning block per 30 s). Defaults to true; false leaves knex's error untouched. Must be a\n * boolean (for example `env.bool('DATABASE_POOL_TIMEOUT_DIAGNOSTICS', true)`): a string is not\n * read as false.\n */\n poolTimeoutDiagnostics?: boolean;\n migrations: {\n dir: string;\n };\n [key: string]: unknown;\n}\n\nexport type Logger = Record<\n 'info' | 'warn' | 'error' | 'debug',\n (message: string | Record<string, unknown>) => void\n>;\n\nexport interface DatabaseConfig {\n connection: Knex.Config;\n settings: Settings;\n logger?: Logger;\n /** Lifecycle phase of the host application, e.g. \"boot\" or \"runtime\", for pool timeout reports. */\n getPhase?: () => string | undefined;\n}\n\nconst afterCreate =\n (db: Database) =>\n (\n nativeConnection: unknown,\n done: (error: Error | null, nativeConnection: unknown) => Promise<void>\n ) => {\n // run initialize for it since commands such as postgres SET and sqlite PRAGMA are per-connection\n db.dialect.initialize(nativeConnection).then(() => {\n return done(null, nativeConnection);\n });\n };\n\nclass Database {\n connection: Knex;\n\n dialect: Dialect;\n\n config: DatabaseConfig;\n\n metadata: Metadata;\n\n schema: SchemaProvider;\n\n migrations: MigrationProvider;\n\n lifecycles: LifecycleProvider;\n\n entityManager: EntityManager;\n\n repair: RepairManager;\n\n logger: Logger;\n\n /** Set unless `settings.poolTimeoutDiagnostics` is false or the install failed. */\n private poolDiagnostics?: PoolDiagnostics;\n\n private phase?: string;\n\n constructor(config: DatabaseConfig) {\n this.config = {\n ...config,\n settings: {\n forceMigration: true,\n runMigrations: true,\n ...config.settings,\n },\n };\n\n this.logger = config.logger ?? console;\n\n this.dialect = getDialect(this);\n\n let knexConfig: Knex.Config = this.config.connection;\n\n // for object connections, we can configure the dialect synchronously\n if (typeof this.config.connection.connection !== 'function') {\n this.dialect.configure();\n }\n // for connection functions, we wrap it so that we can modify it with dialect configure before it reaches knex\n else {\n this.logger.warn(\n 'Knex connection functions are currently experimental. Attempting to access the connection object before database initialization will result in errors.'\n );\n\n knexConfig = {\n ...this.config.connection,\n connection: async () => {\n // @ts-expect-error confirmed it was a function above\n const conn = await this.config.connection.connection();\n this.dialect.configure(conn);\n return conn;\n },\n };\n }\n\n this.metadata = createMetadata([]);\n\n this.connection = createConnection(withStrapiKnexLog(knexConfig, this.logger), {\n pool: { afterCreate: afterCreate(this) },\n });\n\n if (this.config.settings.poolTimeoutDiagnostics !== false) {\n try {\n this.poolDiagnostics = installPoolDiagnostics(this.connection, {\n logger: { warn: (message) => this.logger.warn(message) },\n getPhase: () => this.phase ?? this.config.getPhase?.(),\n });\n } catch (error) {\n // Diagnostics are optional: failing to install them must not stop the application booting\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.debug(`[database] pool timeout diagnostics not installed: ${reason}`);\n }\n }\n\n this.schema = createSchemaProvider(this);\n\n this.migrations = createMigrationsProvider(this);\n this.lifecycles = createLifecyclesProvider(this);\n\n this.entityManager = createEntityManager(this);\n\n this.repair = createRepairManager(this);\n }\n\n async init({ models }: { models: Model[] }) {\n if (typeof this.config.connection.connection === 'function') {\n /*\n * User code needs to be able to access `connection.connection` directly as if\n * it were always an object. For a connection function, that doesn't happen\n * until the pool is created, so we need to do that here\n *\n * TODO: In the next major version, we need to replace all internal code that\n * directly references `connection.connection` prior to init, and make a breaking\n * change that it cannot be relied on to exist before init so that we can call\n * this feature stable.\n */\n this.logger.debug('Forcing Knex to make real connection to db');\n\n // sqlite does not support connection pooling so acquireConnection doesn't work\n if (this.config.connection.client === 'sqlite') {\n await this.connection.raw('SELECT 1');\n } else {\n // release it straight away, otherwise it holds a pool slot for the life of the process\n const conn = await this.connection.client.acquireConnection();\n await this.connection.client.releaseConnection(conn);\n }\n }\n\n this.metadata.loadModels(models);\n await validateDatabase(this);\n return this;\n }\n\n query(uid: string) {\n if (!this.metadata.has(uid)) {\n throw new Error(`Model ${uid} not found`);\n }\n\n return this.entityManager.getRepository(uid);\n }\n\n inTransaction() {\n return !!transactionCtx.get();\n }\n\n /**\n * Labels pool timeout reports raised while `fn` runs, for example \"schema sync\". Nested calls\n * restore the outer label. Calls that overlap without nesting can restore the wrong label; core\n * only nests them (schema sync, then a migration).\n *\n * The label is process-wide, not per call: a call made at runtime relabels every concurrent\n * timeout report until it returns. It is meant for boot-time work (schema sync, migrations).\n *\n * @internal\n */\n async runInPhase<T>(phase: string, fn: () => Promise<T>): Promise<T> {\n const previous = this.phase;\n this.phase = phase;\n\n try {\n return await fn();\n } finally {\n this.phase = previous;\n }\n }\n\n /**\n * Run work inside a DB transaction. On a fulfilled callback, the transaction\n * is committed; on rejection, it is rolled back. The callback receives Knex\n * `commit` and `rollback` helpers: if you call `rollback` and return without\n * throwing, the implementation avoids attempting a second `commit` on an\n * already-finalised transactor.\n */\n 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 try {\n await this.lifecycles.clear();\n } finally {\n this.poolDiagnostics?.dispose();\n }\n\n await this.connection.destroy();\n }\n}\n\nexport { Database, errors };\n"],"names":["afterCreate","db","nativeConnection","done","dialect","initialize","then","Database","init","models","config","connection","logger","debug","client","raw","conn","acquireConnection","releaseConnection","metadata","loadModels","validateDatabase","query","uid","has","Error","entityManager","getRepository","inTransaction","transactionCtx","get","runInPhase","phase","fn","previous","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","poolDiagnostics","dispose","settings","forceMigration","runMigrations","console","getDialect","knexConfig","configure","warn","createMetadata","createConnection","withStrapiKnexLog","pool","poolTimeoutDiagnostics","installPoolDiagnostics","message","getPhase","reason","String","createSchemaProvider","migrations","createMigrationsProvider","createLifecyclesProvider","createEntityManager","repair","createRepairManager"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyEA,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;AA4FJ,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,IAA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GC,mBAAAA,CAAoB,IAAI,CAAA;AACxC,IAAA;AA8KF;;;;"}
|
|
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 } from './migrations';\nimport { createLifecyclesProvider, LifecycleProvider } from './lifecycles';\nimport { createConnection } from './connection';\nimport * as errors from './errors';\nimport { Callback, transactionCtx, TransactionObject } from './transaction-context';\nimport { validateDatabase } from './validations';\nimport { appendCallerStack } from './utils/async-stack';\nimport type { Model } from './types';\nimport { createRepairManager, type RepairManager } from './repairs';\nimport { installPoolDiagnostics, type PoolDiagnostics } from './pool-diagnostics';\nimport { withStrapiKnexLog } from './utils/knex-log';\n\nexport { isKnexQuery } from './utils/knex';\nexport { isDatabaseClientKind } from './connection';\nexport { attributeNaming } from './metadata';\nexport { createField } from './fields';\nexport type { AttributeNaming, Meta } from './metadata';\nexport type {\n AttributeRenamesOperation,\n Migration,\n BuiltMigrationFile,\n MigrationFileBuilder,\n MigrationFileFormat,\n MigrationFileOperation,\n} from './migrations';\nexport type { Event } from './lifecycles';\nexport type { Attribute, Model, JoinTable } from './types';\nexport type { AttributeRenameHandler, AttributeRenames } from './schema';\nexport type { Identifiers } from './utils/identifiers';\nexport { POOL_TIMEOUT_CODE } from './pool-diagnostics';\nexport type {\n EventLoopDelay,\n PoolDiagnostics,\n PoolState,\n PoolTimeoutDetails,\n} from './pool-diagnostics';\n\ninterface Settings {\n forceMigration?: boolean;\n runMigrations?: boolean;\n /**\n * Describe the pool on knex connection pool timeouts (details on the error, a docs link, one\n * warning block per 30 s). Defaults to true; false leaves knex's error untouched. Must be a\n * boolean (for example `env.bool('DATABASE_POOL_TIMEOUT_DIAGNOSTICS', true)`): a string is not\n * read as false.\n */\n poolTimeoutDiagnostics?: boolean;\n migrations: {\n dir: string;\n };\n [key: string]: unknown;\n}\n\nexport type Logger = Record<\n 'info' | 'warn' | 'error' | 'debug',\n (message: string | Record<string, unknown>) => void\n>;\n\nexport interface DatabaseConfig {\n connection: Knex.Config;\n settings: Settings;\n logger?: Logger;\n /** Lifecycle phase of the host application, e.g. \"boot\" or \"runtime\", for pool timeout reports. */\n getPhase?: () => string | undefined;\n}\n\nconst afterCreate =\n (db: Database) =>\n (\n nativeConnection: unknown,\n done: (error: Error | null, nativeConnection: unknown) => Promise<void>\n ) => {\n // run initialize for it since commands such as postgres SET and sqlite PRAGMA are per-connection\n db.dialect.initialize(nativeConnection).then(() => {\n return done(null, nativeConnection);\n });\n };\n\nclass Database {\n connection: Knex;\n\n dialect: Dialect;\n\n config: DatabaseConfig;\n\n metadata: Metadata;\n\n schema: SchemaProvider;\n\n migrations: MigrationProvider;\n\n lifecycles: LifecycleProvider;\n\n entityManager: EntityManager;\n\n repair: RepairManager;\n\n logger: Logger;\n\n /** Set unless `settings.poolTimeoutDiagnostics` is false or the install failed. */\n private poolDiagnostics?: PoolDiagnostics;\n\n private phase?: string;\n\n constructor(config: DatabaseConfig) {\n this.config = {\n ...config,\n settings: {\n forceMigration: true,\n runMigrations: true,\n ...config.settings,\n },\n };\n\n this.logger = config.logger ?? console;\n\n this.dialect = getDialect(this);\n\n let knexConfig: Knex.Config = this.config.connection;\n\n // for object connections, we can configure the dialect synchronously\n if (typeof this.config.connection.connection !== 'function') {\n this.dialect.configure();\n }\n // for connection functions, we wrap it so that we can modify it with dialect configure before it reaches knex\n else {\n this.logger.warn(\n 'Knex connection functions are currently experimental. Attempting to access the connection object before database initialization will result in errors.'\n );\n\n knexConfig = {\n ...this.config.connection,\n connection: async () => {\n // @ts-expect-error confirmed it was a function above\n const conn = await this.config.connection.connection();\n this.dialect.configure(conn);\n return conn;\n },\n };\n }\n\n this.metadata = createMetadata([]);\n\n this.connection = createConnection(withStrapiKnexLog(knexConfig, this.logger), {\n pool: { afterCreate: afterCreate(this) },\n });\n\n if (this.config.settings.poolTimeoutDiagnostics !== false) {\n try {\n this.poolDiagnostics = installPoolDiagnostics(this.connection, {\n logger: { warn: (message) => this.logger.warn(message) },\n getPhase: () => this.phase ?? this.config.getPhase?.(),\n });\n } catch (error) {\n // Diagnostics are optional: failing to install them must not stop the application booting\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.debug(`[database] pool timeout diagnostics not installed: ${reason}`);\n }\n }\n\n this.schema = createSchemaProvider(this);\n\n this.migrations = createMigrationsProvider(this);\n this.lifecycles = createLifecyclesProvider(this);\n\n this.entityManager = createEntityManager(this);\n\n this.repair = createRepairManager(this);\n }\n\n async init({ models }: { models: Model[] }) {\n if (typeof this.config.connection.connection === 'function') {\n /*\n * User code needs to be able to access `connection.connection` directly as if\n * it were always an object. For a connection function, that doesn't happen\n * until the pool is created, so we need to do that here\n *\n * TODO: In the next major version, we need to replace all internal code that\n * directly references `connection.connection` prior to init, and make a breaking\n * change that it cannot be relied on to exist before init so that we can call\n * this feature stable.\n */\n this.logger.debug('Forcing Knex to make real connection to db');\n\n // sqlite does not support connection pooling so acquireConnection doesn't work\n if (this.config.connection.client === 'sqlite') {\n await this.connection.raw('SELECT 1');\n } else {\n // release it straight away, otherwise it holds a pool slot for the life of the process\n const conn = await this.connection.client.acquireConnection();\n await this.connection.client.releaseConnection(conn);\n }\n }\n\n this.metadata.loadModels(models);\n await validateDatabase(this);\n return this;\n }\n\n query(uid: string) {\n if (!this.metadata.has(uid)) {\n throw new Error(`Model ${uid} not found`);\n }\n\n return this.entityManager.getRepository(uid);\n }\n\n inTransaction() {\n return !!transactionCtx.get();\n }\n\n /**\n * Labels pool timeout reports raised while `fn` runs, for example \"schema sync\". Nested calls\n * restore the outer label. Calls that overlap without nesting can restore the wrong label; core\n * only nests them (schema sync, then a migration).\n *\n * The label is process-wide, not per call: a call made at runtime relabels every concurrent\n * timeout report until it returns. It is meant for boot-time work (schema sync, migrations).\n *\n * @internal\n */\n async runInPhase<T>(phase: string, fn: () => Promise<T>): Promise<T> {\n const previous = this.phase;\n this.phase = phase;\n\n try {\n return await fn();\n } finally {\n this.phase = previous;\n }\n }\n\n /**\n * Run work inside a DB transaction. On a fulfilled callback, the transaction\n * is committed; on rejection, it is rolled back. The callback receives Knex\n * `commit` and `rollback` helpers: if you call `rollback` and return without\n * throwing, the implementation avoids attempting a second `commit` on an\n * already-finalised transactor.\n */\n transaction(): Promise<TransactionObject>;\n transaction<TCallback extends Callback>(c: TCallback): Promise<ReturnType<TCallback>>;\n async transaction<TCallback extends Callback>(\n cb?: TCallback\n ): Promise<ReturnType<TCallback> | TransactionObject> {\n const notNestedTransaction = !transactionCtx.get();\n const trx = notNestedTransaction\n ? await this.startTransaction()\n : (transactionCtx.get() as Knex.Transaction);\n\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 await 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 /**\n * Runs `cb` in a savepoint of the current transaction, so a failure undoes only `cb`'s writes.\n * If `cb` throws, its writes are rolled back, the `onCommit` callbacks registered in it are\n * dropped, its `onRollback` callbacks run, and the error is rethrown. The transaction stays\n * usable, on Postgres also after a database error, but not after a MySQL deadlock, which rolls\n * back the whole transaction: the savepoint then can't be rolled back to, and it throws an\n * `errors.SavepointError`, as when it can't be released. Throws if called outside a transaction.\n */\n savepoint<T>(cb: () => Promise<T> | T): Promise<T> {\n return transactionCtx.savepoint(cb);\n }\n\n /**\n * Starts a top-level knex transaction. knex resolves it through a promise chain that async stack\n * traces cannot follow, so on failure the stack is extended with the frames of our callers.\n */\n private async startTransaction(): Promise<Knex.Transaction> {\n try {\n return await this.connection.transaction();\n } catch (error) {\n appendCallerStack(error);\n throw error;\n }\n }\n\n getSchemaName(): string | undefined {\n return this.connection.client.connectionSettings.schema;\n }\n\n getConnection(): Knex;\n getConnection(tableName?: string): Knex.QueryBuilder;\n getConnection(tableName?: string): Knex | Knex.QueryBuilder {\n const schema = this.getSchemaName();\n const connection = tableName ? this.connection(tableName) : this.connection;\n return schema ? connection.withSchema(schema) : connection;\n }\n\n // Returns basic info about the database connection\n getInfo() {\n const connectionSettings = this.connection?.client?.connectionSettings || {};\n const client = this.dialect?.client || '';\n\n let displayName = '';\n let schema;\n\n // For SQLite, get the relative filename\n if (client === 'sqlite') {\n const absolutePath = connectionSettings?.filename;\n if (absolutePath) {\n displayName = path.relative(process.cwd(), absolutePath);\n }\n }\n // For other dialects, get the database name\n else {\n displayName = connectionSettings?.database;\n schema = connectionSettings?.schema;\n }\n\n return {\n displayName,\n schema,\n client,\n };\n }\n\n getSchemaConnection(trx = this.connection) {\n const schema = this.getSchemaName();\n return schema ? trx.schema.withSchema(schema) : trx.schema;\n }\n\n queryBuilder(uid: string) {\n return this.entityManager.createQueryBuilder(uid);\n }\n\n async destroy() {\n try {\n await this.lifecycles.clear();\n } finally {\n this.poolDiagnostics?.dispose();\n }\n\n await this.connection.destroy();\n }\n}\n\nexport { Database, errors };\n"],"names":["afterCreate","db","nativeConnection","done","dialect","initialize","then","Database","init","models","config","connection","logger","debug","client","raw","conn","acquireConnection","releaseConnection","metadata","loadModels","validateDatabase","query","uid","has","Error","entityManager","getRepository","inTransaction","transactionCtx","get","runInPhase","phase","fn","previous","transaction","cb","notNestedTransaction","trx","startTransaction","commit","rollback","run","callbackParams","onCommit","onRollback","res","error","savepoint","appendCallerStack","getSchemaName","connectionSettings","schema","getConnection","tableName","withSchema","getInfo","displayName","absolutePath","filename","path","relative","process","cwd","database","getSchemaConnection","queryBuilder","createQueryBuilder","destroy","lifecycles","clear","poolDiagnostics","dispose","settings","forceMigration","runMigrations","console","getDialect","knexConfig","configure","warn","createMetadata","createConnection","withStrapiKnexLog","pool","poolTimeoutDiagnostics","installPoolDiagnostics","message","getPhase","reason","String","createSchemaProvider","migrations","createMigrationsProvider","createLifecyclesProvider","createEntityManager","repair","createRepairManager"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0EA,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;AA4FJ,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;;gBAEL,MAAMC,IAAAA,GAAO,MAAM,IAAI,CAACL,UAAU,CAACG,MAAM,CAACG,iBAAiB,EAAA;AAC3D,gBAAA,MAAM,IAAI,CAACN,UAAU,CAACG,MAAM,CAACI,iBAAiB,CAACF,IAAAA,CAAAA;AACjD,YAAA;AACF,QAAA;AAEA,QAAA,IAAI,CAACG,QAAQ,CAACC,UAAU,CAACX,MAAAA,CAAAA;AACzB,QAAA,MAAMY,iBAAiB,IAAI,CAAA;AAC3B,QAAA,OAAO,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I,CAAA;AACxC,IAAA;AAuMF;;;;"}
|
|
@@ -16,7 +16,7 @@ const castValue = (value, attribute)=>{
|
|
|
16
16
|
}
|
|
17
17
|
if (types.isScalar(attribute.type) && !knex.isKnexQuery(value)) {
|
|
18
18
|
const field = index.createField(attribute);
|
|
19
|
-
return value === null ? null : field.
|
|
19
|
+
return value === null ? null : field.toFilterValue(value);
|
|
20
20
|
}
|
|
21
21
|
return value;
|
|
22
22
|
};
|