@strapi/database 5.50.1 → 5.51.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/connection.d.ts +8 -0
- package/dist/connection.d.ts.map +1 -1
- package/dist/connection.js +4 -3
- package/dist/connection.js.map +1 -1
- package/dist/connection.mjs +4 -4
- package/dist/connection.mjs.map +1 -1
- package/dist/dialects/mysql/index.d.ts +2 -1
- package/dist/dialects/mysql/index.d.ts.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.d.ts.map +1 -1
- package/dist/entity-manager/index.js +14 -2
- package/dist/entity-manager/index.js.map +1 -1
- package/dist/entity-manager/index.mjs +14 -2
- package/dist/entity-manager/index.mjs.map +1 -1
- package/dist/entity-manager/relations-orderer.d.ts.map +1 -1
- package/dist/entity-manager/relations-orderer.js +36 -22
- package/dist/entity-manager/relations-orderer.js.map +1 -1
- package/dist/entity-manager/relations-orderer.mjs +30 -16
- package/dist/entity-manager/relations-orderer.mjs.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -0
- package/dist/index.mjs.map +1 -1
- package/dist/query/query-builder.d.ts +3 -1
- package/dist/query/query-builder.d.ts.map +1 -1
- package/dist/query/query-builder.js +25 -1
- package/dist/query/query-builder.js.map +1 -1
- package/dist/query/query-builder.mjs +26 -2
- package/dist/query/query-builder.mjs.map +1 -1
- package/package.json +10 -6
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var _ = require('lodash/fp');
|
|
4
|
-
var _
|
|
3
|
+
var _$1 = require('lodash/fp');
|
|
4
|
+
var _ = require('lodash');
|
|
5
5
|
var invalidRelation = require('../errors/invalid-relation.js');
|
|
6
6
|
|
|
7
7
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
8
8
|
|
|
9
|
-
var ___default = /*#__PURE__*/_interopDefault(_
|
|
9
|
+
var ___default = /*#__PURE__*/_interopDefault(_);
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* When connecting relations, the order you connect them matters.
|
|
@@ -138,12 +138,12 @@ var ___default = /*#__PURE__*/_interopDefault(_$1);
|
|
|
138
138
|
* another one that does not exist
|
|
139
139
|
* @return {*}
|
|
140
140
|
*/ const relationsOrderer = (initArr, idColumn, orderColumn, strict)=>{
|
|
141
|
-
const computedRelations = _.castArray(initArr ?? []).map((r)=>({
|
|
141
|
+
const computedRelations = ___default.default.sortBy(_$1.castArray(initArr ?? []).map((r)=>({
|
|
142
142
|
init: true,
|
|
143
143
|
id: r[idColumn],
|
|
144
|
-
order: Number(r[orderColumn])
|
|
145
|
-
}));
|
|
146
|
-
const maxOrder = _.maxBy('order', computedRelations)?.order || 0;
|
|
144
|
+
order: r[orderColumn] !== null && r[orderColumn] !== undefined ? Number(r[orderColumn]) : 1
|
|
145
|
+
})), 'order');
|
|
146
|
+
const maxOrder = _$1.maxBy('order', computedRelations)?.order || 0;
|
|
147
147
|
const findRelation = (id)=>{
|
|
148
148
|
const idx = computedRelations.findIndex((r)=>r.id === id);
|
|
149
149
|
return {
|
|
@@ -160,23 +160,30 @@ var ___default = /*#__PURE__*/_interopDefault(_$1);
|
|
|
160
160
|
const insertRelation = (r)=>{
|
|
161
161
|
let idx;
|
|
162
162
|
if (r.position?.before) {
|
|
163
|
-
const { idx:
|
|
163
|
+
const { idx: beforeIdx, relation } = findRelation(r.position.before);
|
|
164
164
|
if (relation.init) {
|
|
165
|
-
|
|
165
|
+
const prevRelation = beforeIdx > 0 ? computedRelations[beforeIdx - 1] : null;
|
|
166
|
+
r.order = prevRelation && prevRelation.order < relation.order ? (prevRelation.order + relation.order) / 2 : relation.order - 0.5;
|
|
166
167
|
} else {
|
|
167
168
|
r.order = relation.order;
|
|
168
169
|
}
|
|
169
|
-
idx =
|
|
170
|
+
idx = beforeIdx;
|
|
170
171
|
} else if (r.position?.after) {
|
|
171
|
-
const { idx:
|
|
172
|
+
const { idx: afterIdx, relation } = findRelation(r.position.after);
|
|
172
173
|
if (relation.init) {
|
|
173
|
-
|
|
174
|
+
const nextRelation = afterIdx < computedRelations.length - 1 ? computedRelations[afterIdx + 1] : null;
|
|
175
|
+
r.order = nextRelation && nextRelation.order > relation.order ? (relation.order + nextRelation.order) / 2 : relation.order + 0.5;
|
|
174
176
|
} else {
|
|
175
177
|
r.order = relation.order;
|
|
176
178
|
}
|
|
177
|
-
idx =
|
|
179
|
+
idx = afterIdx + 1;
|
|
178
180
|
} else if (r.position?.start) {
|
|
179
|
-
|
|
181
|
+
if (computedRelations.length > 0) {
|
|
182
|
+
const firstRelation = computedRelations[0];
|
|
183
|
+
r.order = firstRelation.init ? firstRelation.order - 0.5 : firstRelation.order;
|
|
184
|
+
} else {
|
|
185
|
+
r.order = 0.5;
|
|
186
|
+
}
|
|
180
187
|
idx = 0;
|
|
181
188
|
} else {
|
|
182
189
|
r.order = maxOrder + 0.5;
|
|
@@ -187,13 +194,13 @@ var ___default = /*#__PURE__*/_interopDefault(_$1);
|
|
|
187
194
|
};
|
|
188
195
|
return {
|
|
189
196
|
disconnect (relations) {
|
|
190
|
-
_.castArray(relations).forEach((relation)=>{
|
|
197
|
+
_$1.castArray(relations).forEach((relation)=>{
|
|
191
198
|
removeRelation(relation);
|
|
192
199
|
});
|
|
193
200
|
return this;
|
|
194
201
|
},
|
|
195
202
|
connect (relations) {
|
|
196
|
-
sortConnectArray(_.castArray(relations), computedRelations, strict).forEach((relation)=>{
|
|
203
|
+
sortConnectArray(_$1.castArray(relations), computedRelations, strict).forEach((relation)=>{
|
|
197
204
|
this.disconnect(relation);
|
|
198
205
|
try {
|
|
199
206
|
insertRelation(relation);
|
|
@@ -209,13 +216,20 @@ var ___default = /*#__PURE__*/_interopDefault(_$1);
|
|
|
209
216
|
/**
|
|
210
217
|
* Get a map between the relation id and its order
|
|
211
218
|
*/ getOrderMap () {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
219
|
+
const map = {};
|
|
220
|
+
const chunks = ___default.default(computedRelations).groupBy('order').value();
|
|
221
|
+
const sortedKeys = Object.keys(chunks).sort((a, b)=>parseFloat(a) - parseFloat(b));
|
|
222
|
+
for (const orderStr of sortedKeys){
|
|
223
|
+
const relations = chunks[orderStr];
|
|
224
|
+
let offset = 1;
|
|
225
|
+
relations.forEach((relation)=>{
|
|
226
|
+
if (!relation.init) {
|
|
227
|
+
map[relation.id] = parseFloat(orderStr) + offset / (relations.length + 1) * 0.49;
|
|
228
|
+
offset += 1;
|
|
229
|
+
}
|
|
216
230
|
});
|
|
217
|
-
|
|
218
|
-
|
|
231
|
+
}
|
|
232
|
+
return map;
|
|
219
233
|
}
|
|
220
234
|
};
|
|
221
235
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relations-orderer.js","sources":["../../src/entity-manager/relations-orderer.ts"],"sourcesContent":["import { castArray, maxBy } from 'lodash/fp';\nimport _ from 'lodash';\n\nimport { InvalidRelationError } from '../errors';\nimport type { ID } from '../types';\n\ninterface Link {\n id: ID;\n position?: { before?: ID; after?: ID; start?: true; end?: true };\n order?: number;\n __component?: string;\n}\n\ninterface OrderedLink extends Link {\n init?: boolean;\n order: number;\n}\n\n/**\n * When connecting relations, the order you connect them matters.\n *\n * Example, if you connect the following relations:\n * { id: 5, position: { before: 1 } }\n * { id: 1, position: { before: 2 } }\n * { id: 2, position: { end: true } }\n *\n * Going through the connect array, id 5 has to be connected before id 1,\n * so the order of id5 = id1 - 1. But the order value of id 1 is unknown.\n * The only way to know the order of id 1 is to connect it first.\n *\n * This function makes sure the relations are connected in the right order:\n * { id: 2, position: { end: true } }\n * { id: 1, position: { before: 2 } }\n * { id: 5, position: { before: 1 } }\n *\n */\nconst sortConnectArray = (connectArr: Link[], initialArr: Link[] = [], strictSort = true) => {\n const sortedConnect: Link[] = [];\n // Boolean to know if we have to recalculate the order of the relations\n let needsSorting = false;\n // Map to validate if relation is already in sortedConnect or DB.\n const relationInInitialArray = initialArr.reduce(\n (acc, rel) => ({ ...acc, [rel.id]: true }),\n {} as Record<ID, boolean>\n );\n // Map to store the first index where a relation id is connected\n const mappedRelations = connectArr.reduce(\n (mapper, relation: Link) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n\n if (!adjacentRelId || (!relationInInitialArray[adjacentRelId] && !mapper[adjacentRelId])) {\n needsSorting = true;\n }\n\n /**\n * We do not allow duplicate relations to be connected, so we need to check for uniqueness with components\n * Note that the id here includes the uid for polymorphic relations\n *\n * So for normal relations, the same id means the same relation\n * For component relations, it means the unique combo of (id, component name)\n */\n\n // Check if there's an existing relation with this id\n const existingRelation = mapper[relation.id];\n\n // Check if existing relation has a component or not\n const hasNoComponent = existingRelation && !('__component' in existingRelation);\n\n // Check if the existing relation has the same component as the new relation\n const hasSameComponent =\n existingRelation && existingRelation.__component === relation.__component;\n\n // If we have an existing relation that is not unique (no component or same component) we won't accept it\n if (existingRelation && (hasNoComponent || hasSameComponent)) {\n throw new InvalidRelationError(\n `The relation with id ${relation.id} is already connected. ` +\n 'You cannot connect the same relation twice.'\n );\n }\n\n return {\n [relation.id]: { ...relation, computed: false },\n ...mapper,\n };\n },\n {} as Record<ID, Link & { computed: boolean }>\n );\n\n // If we don't need to sort the connect array, we can return it as is\n if (!needsSorting) return connectArr;\n\n // Recursively compute in which order the relation should be connected\n const computeRelation = (relation: Link, relationsSeenInBranch: Record<ID, boolean>) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n const adjacentRelation = mappedRelations[adjacentRelId as ID];\n\n // If the relation has already been seen in the current branch,\n // it means there is a circular reference\n if (adjacentRelId && relationsSeenInBranch[adjacentRelId]) {\n throw new InvalidRelationError(\n 'A circular reference was found in the connect array. ' +\n 'One relation is trying to connect before/after another one that is trying to connect before/after it'\n );\n }\n\n // This relation has already been computed\n if (mappedRelations[relation.id]?.computed) {\n return;\n }\n\n mappedRelations[relation.id].computed = true;\n\n // Relation does not have a before or after attribute or is in the initial array\n if (!adjacentRelId || relationInInitialArray[adjacentRelId]) {\n sortedConnect.push(relation);\n return;\n }\n\n // Look if id is referenced elsewhere in the array\n if (mappedRelations[adjacentRelId]) {\n computeRelation(adjacentRelation, { ...relationsSeenInBranch, [relation.id]: true });\n sortedConnect.push(relation);\n } else if (strictSort) {\n // If we reach this point, it means that the adjacent relation is not in the connect array\n // and it is not in the database.\n throw new InvalidRelationError(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The relation with id ${adjacentRelId} needs to be connected first.`\n );\n } else {\n // We are in non-strict mode so we can push the relation.\n sortedConnect.push({ id: relation.id, position: { end: true } });\n }\n };\n\n // Iterate over connectArr and populate sortedConnect\n connectArr.forEach((relation) => computeRelation(relation, {}));\n\n return sortedConnect;\n};\n\n/**\n * Responsible for calculating the relations order when connecting them.\n *\n * The connect method takes an array of relations with positional attributes:\n * - before: the id of the relation to connect before\n * - after: the id of the relation to connect after\n * - end: it should be at the end\n * - start: it should be at the start\n *\n * Example:\n * - Having a connect array like:\n * [ { id: 4, before: 2 }, { id: 4, before: 3}, {id: 5, before: 4} ]\n * - With the initial relations:\n * [ { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * - Step by step, going through the connect array, the array of relations would be:\n * [ { id: 4, order: 3.5 }, { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 5, order: 3.5 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * - The final step would be to recalculate fractional order values.\n * [ { id: 2, order: 4 }, { id: 5, order: 3.33 }, { id: 4, order: 3.66 }, { id: 3, order: 10 } ]\n *\n * @param {Array<*>} initArr - array of relations to initialize the class with\n * @param {string} idColumn - the column name of the id\n * @param {string} orderColumn - the column name of the order\n * @param {boolean} strict - if true, will throw an error if a relation is connected adjacent to\n * another one that does not exist\n * @return {*}\n */\nconst relationsOrderer = <TRelation extends Record<string, ID | number | null>>(\n initArr: TRelation[],\n idColumn: keyof TRelation,\n orderColumn: keyof TRelation,\n strict?: boolean\n) => {\n const computedRelations: OrderedLink[] = castArray(initArr ?? []).map((r) => ({\n init: true,\n id: r[idColumn] as ID,\n order: Number(r[orderColumn]) || 1,\n }));\n\n const maxOrder = maxBy('order', computedRelations)?.order || 0;\n\n const findRelation = (id: ID) => {\n const idx = computedRelations.findIndex((r) => r.id === id);\n return { idx, relation: computedRelations[idx] };\n };\n\n const removeRelation = (r: Link) => {\n const { idx } = findRelation(r.id);\n if (idx >= 0) {\n computedRelations.splice(idx, 1);\n }\n };\n\n const insertRelation = (r: Link) => {\n let idx;\n\n if (r.position?.before) {\n const { idx: relationIndex, relation } = findRelation(r.position.before);\n if (relation.init) {\n r.order = relation.order - 0.5;\n } else {\n r.order = relation.order;\n }\n idx = relationIndex;\n } else if (r.position?.after) {\n const { idx: relationIndex, relation } = findRelation(r.position.after);\n if (relation.init) {\n r.order = relation.order + 0.5;\n } else {\n r.order = relation.order;\n }\n\n idx = relationIndex + 1;\n } else if (r.position?.start) {\n r.order = 0.5;\n idx = 0;\n } else {\n r.order = maxOrder + 0.5;\n idx = computedRelations.length;\n }\n\n // Insert the relation in the array\n computedRelations.splice(idx, 0, r as OrderedLink);\n };\n\n return {\n disconnect(relations: Link | Link[]) {\n castArray(relations).forEach((relation) => {\n removeRelation(relation);\n });\n return this;\n },\n connect(relations: Link | Link[]) {\n sortConnectArray(castArray(relations), computedRelations, strict).forEach((relation) => {\n this.disconnect(relation);\n\n try {\n insertRelation(relation);\n } catch (err) {\n throw new Error(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The list of connect relations is not valid`\n );\n }\n });\n return this;\n },\n get() {\n return computedRelations;\n },\n /**\n * Get a map between the relation id and its order\n */\n getOrderMap() {\n return _(computedRelations)\n .groupBy('order')\n .reduce(\n (acc, relations) => {\n if (relations[0]?.init) return acc;\n relations.forEach((relation, idx) => {\n acc[relation.id] = Math.floor(relation.order) + (idx + 1) / (relations.length + 1);\n });\n return acc;\n },\n {} as Record<ID, number>\n );\n },\n };\n};\n\nexport { relationsOrderer, sortConnectArray };\n"],"names":["sortConnectArray","connectArr","initialArr","strictSort","sortedConnect","needsSorting","relationInInitialArray","reduce","acc","rel","id","mappedRelations","mapper","relation","adjacentRelId","position","before","after","existingRelation","hasNoComponent","hasSameComponent","__component","InvalidRelationError","computed","computeRelation","relationsSeenInBranch","adjacentRelation","push","JSON","stringify","end","forEach","relationsOrderer","initArr","idColumn","orderColumn","strict","computedRelations","castArray","map","r","init","order","Number","maxOrder","maxBy","findRelation","idx","findIndex","removeRelation","splice","insertRelation","relationIndex","start","length","disconnect","relations","connect","err","Error","get","getOrderMap","_","groupBy","Math","floor"],"mappings":";;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;IAkBA,MAAMA,mBAAmB,CAACC,UAAAA,EAAoBC,aAAqB,EAAE,EAAEC,aAAa,IAAI,GAAA;AACtF,IAAA,MAAMC,gBAAwB,EAAE;;AAEhC,IAAA,IAAIC,YAAAA,GAAe,KAAA;;AAEnB,IAAA,MAAMC,yBAAyBJ,UAAAA,CAAWK,MAAM,CAC9C,CAACC,GAAAA,EAAKC,OAAS;AAAE,YAAA,GAAGD,GAAG;YAAE,CAACC,GAAAA,CAAIC,EAAE,GAAG;AAAK,SAAA,GACxC,EAAC,CAAA;;AAGH,IAAA,MAAMC,eAAAA,GAAkBV,UAAAA,CAAWM,MAAM,CACvC,CAACK,MAAAA,EAAQC,QAAAA,GAAAA;AACP,QAAA,MAAMC,gBAAgBD,QAAAA,CAASE,QAAQ,EAAEC,MAAAA,IAAUH,QAAAA,CAASE,QAAQ,EAAEE,KAAAA;QAEtE,IAA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er.js","sources":["../../src/entity-manager/relations-orderer.ts"],"sourcesContent":["import { castArray, maxBy } from 'lodash/fp';\nimport _ from 'lodash';\n\nimport { InvalidRelationError } from '../errors';\nimport type { ID } from '../types';\n\ninterface Link {\n id: ID;\n position?: { before?: ID; after?: ID; start?: true; end?: true };\n order?: number;\n __component?: string;\n}\n\ninterface OrderedLink extends Link {\n init?: boolean;\n order: number;\n}\n\n/**\n * When connecting relations, the order you connect them matters.\n *\n * Example, if you connect the following relations:\n * { id: 5, position: { before: 1 } }\n * { id: 1, position: { before: 2 } }\n * { id: 2, position: { end: true } }\n *\n * Going through the connect array, id 5 has to be connected before id 1,\n * so the order of id5 = id1 - 1. But the order value of id 1 is unknown.\n * The only way to know the order of id 1 is to connect it first.\n *\n * This function makes sure the relations are connected in the right order:\n * { id: 2, position: { end: true } }\n * { id: 1, position: { before: 2 } }\n * { id: 5, position: { before: 1 } }\n *\n */\nconst sortConnectArray = (connectArr: Link[], initialArr: Link[] = [], strictSort = true) => {\n const sortedConnect: Link[] = [];\n // Boolean to know if we have to recalculate the order of the relations\n let needsSorting = false;\n // Map to validate if relation is already in sortedConnect or DB.\n const relationInInitialArray = initialArr.reduce(\n (acc, rel) => ({ ...acc, [rel.id]: true }),\n {} as Record<ID, boolean>\n );\n // Map to store the first index where a relation id is connected\n const mappedRelations = connectArr.reduce(\n (mapper, relation: Link) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n\n if (!adjacentRelId || (!relationInInitialArray[adjacentRelId] && !mapper[adjacentRelId])) {\n needsSorting = true;\n }\n\n /**\n * We do not allow duplicate relations to be connected, so we need to check for uniqueness with components\n * Note that the id here includes the uid for polymorphic relations\n *\n * So for normal relations, the same id means the same relation\n * For component relations, it means the unique combo of (id, component name)\n */\n\n // Check if there's an existing relation with this id\n const existingRelation = mapper[relation.id];\n\n // Check if existing relation has a component or not\n const hasNoComponent = existingRelation && !('__component' in existingRelation);\n\n // Check if the existing relation has the same component as the new relation\n const hasSameComponent =\n existingRelation && existingRelation.__component === relation.__component;\n\n // If we have an existing relation that is not unique (no component or same component) we won't accept it\n if (existingRelation && (hasNoComponent || hasSameComponent)) {\n throw new InvalidRelationError(\n `The relation with id ${relation.id} is already connected. ` +\n 'You cannot connect the same relation twice.'\n );\n }\n\n return {\n [relation.id]: { ...relation, computed: false },\n ...mapper,\n };\n },\n {} as Record<ID, Link & { computed: boolean }>\n );\n\n // If we don't need to sort the connect array, we can return it as is\n if (!needsSorting) return connectArr;\n\n // Recursively compute in which order the relation should be connected\n const computeRelation = (relation: Link, relationsSeenInBranch: Record<ID, boolean>) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n const adjacentRelation = mappedRelations[adjacentRelId as ID];\n\n // If the relation has already been seen in the current branch,\n // it means there is a circular reference\n if (adjacentRelId && relationsSeenInBranch[adjacentRelId]) {\n throw new InvalidRelationError(\n 'A circular reference was found in the connect array. ' +\n 'One relation is trying to connect before/after another one that is trying to connect before/after it'\n );\n }\n\n // This relation has already been computed\n if (mappedRelations[relation.id]?.computed) {\n return;\n }\n\n mappedRelations[relation.id].computed = true;\n\n // Relation does not have a before or after attribute or is in the initial array\n if (!adjacentRelId || relationInInitialArray[adjacentRelId]) {\n sortedConnect.push(relation);\n return;\n }\n\n // Look if id is referenced elsewhere in the array\n if (mappedRelations[adjacentRelId]) {\n computeRelation(adjacentRelation, { ...relationsSeenInBranch, [relation.id]: true });\n sortedConnect.push(relation);\n } else if (strictSort) {\n // If we reach this point, it means that the adjacent relation is not in the connect array\n // and it is not in the database.\n throw new InvalidRelationError(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The relation with id ${adjacentRelId} needs to be connected first.`\n );\n } else {\n // We are in non-strict mode so we can push the relation.\n sortedConnect.push({ id: relation.id, position: { end: true } });\n }\n };\n\n // Iterate over connectArr and populate sortedConnect\n connectArr.forEach((relation) => computeRelation(relation, {}));\n\n return sortedConnect;\n};\n\n/**\n * Responsible for calculating the relations order when connecting them.\n *\n * The connect method takes an array of relations with positional attributes:\n * - before: the id of the relation to connect before\n * - after: the id of the relation to connect after\n * - end: it should be at the end\n * - start: it should be at the start\n *\n * Example:\n * - Having a connect array like:\n * [ { id: 4, before: 2 }, { id: 4, before: 3}, {id: 5, before: 4} ]\n * - With the initial relations:\n * [ { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * - Step by step, going through the connect array, the array of relations would be:\n * [ { id: 4, order: 3.5 }, { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 5, order: 3.5 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * - The final step would be to recalculate fractional order values.\n * [ { id: 2, order: 4 }, { id: 5, order: 3.33 }, { id: 4, order: 3.66 }, { id: 3, order: 10 } ]\n *\n * @param {Array<*>} initArr - array of relations to initialize the class with\n * @param {string} idColumn - the column name of the id\n * @param {string} orderColumn - the column name of the order\n * @param {boolean} strict - if true, will throw an error if a relation is connected adjacent to\n * another one that does not exist\n * @return {*}\n */\nconst relationsOrderer = <TRelation extends Record<string, ID | number | null>>(\n initArr: TRelation[],\n idColumn: keyof TRelation,\n orderColumn: keyof TRelation,\n strict?: boolean\n) => {\n const computedRelations: OrderedLink[] = _.sortBy(\n castArray(initArr ?? []).map((r) => ({\n init: true,\n id: r[idColumn] as ID,\n order: r[orderColumn] !== null && r[orderColumn] !== undefined ? Number(r[orderColumn]) : 1,\n })),\n 'order'\n );\n\n const maxOrder = maxBy('order', computedRelations)?.order || 0;\n\n const findRelation = (id: ID) => {\n const idx = computedRelations.findIndex((r) => r.id === id);\n return { idx, relation: computedRelations[idx] };\n };\n\n const removeRelation = (r: Link) => {\n const { idx } = findRelation(r.id);\n if (idx >= 0) {\n computedRelations.splice(idx, 1);\n }\n };\n\n const insertRelation = (r: Link) => {\n let idx;\n\n if (r.position?.before) {\n const { idx: beforeIdx, relation } = findRelation(r.position.before);\n if (relation.init) {\n const prevRelation = beforeIdx > 0 ? computedRelations[beforeIdx - 1] : null;\n r.order =\n prevRelation && prevRelation.order < relation.order\n ? (prevRelation.order + relation.order) / 2\n : relation.order - 0.5;\n } else {\n r.order = relation.order;\n }\n idx = beforeIdx;\n } else if (r.position?.after) {\n const { idx: afterIdx, relation } = findRelation(r.position.after);\n if (relation.init) {\n const nextRelation =\n afterIdx < computedRelations.length - 1 ? computedRelations[afterIdx + 1] : null;\n r.order =\n nextRelation && nextRelation.order > relation.order\n ? (relation.order + nextRelation.order) / 2\n : relation.order + 0.5;\n } else {\n r.order = relation.order;\n }\n idx = afterIdx + 1;\n } else if (r.position?.start) {\n if (computedRelations.length > 0) {\n const firstRelation = computedRelations[0];\n r.order = firstRelation.init ? firstRelation.order - 0.5 : firstRelation.order;\n } else {\n r.order = 0.5;\n }\n idx = 0;\n } else {\n r.order = maxOrder + 0.5;\n idx = computedRelations.length;\n }\n\n // Insert the relation in the array\n computedRelations.splice(idx, 0, r as OrderedLink);\n };\n\n return {\n disconnect(relations: Link | Link[]) {\n castArray(relations).forEach((relation) => {\n removeRelation(relation);\n });\n return this;\n },\n connect(relations: Link | Link[]) {\n sortConnectArray(castArray(relations), computedRelations, strict).forEach((relation) => {\n this.disconnect(relation);\n\n try {\n insertRelation(relation);\n } catch (err) {\n throw new Error(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The list of connect relations is not valid`\n );\n }\n });\n return this;\n },\n get() {\n return computedRelations;\n },\n /**\n * Get a map between the relation id and its order\n */\n getOrderMap() {\n const map: Record<ID, number> = {};\n const chunks = _(computedRelations).groupBy('order').value();\n const sortedKeys = Object.keys(chunks).sort((a, b) => parseFloat(a) - parseFloat(b));\n\n for (const orderStr of sortedKeys) {\n const relations = chunks[orderStr];\n let offset = 1;\n relations.forEach((relation) => {\n if (!relation.init) {\n map[relation.id] = parseFloat(orderStr) + (offset / (relations.length + 1)) * 0.49;\n offset += 1;\n }\n });\n }\n\n return map;\n },\n };\n};\n\nexport { relationsOrderer, sortConnectArray };\n"],"names":["sortConnectArray","connectArr","initialArr","strictSort","sortedConnect","needsSorting","relationInInitialArray","reduce","acc","rel","id","mappedRelations","mapper","relation","adjacentRelId","position","before","after","existingRelation","hasNoComponent","hasSameComponent","__component","InvalidRelationError","computed","computeRelation","relationsSeenInBranch","adjacentRelation","push","JSON","stringify","end","forEach","relationsOrderer","initArr","idColumn","orderColumn","strict","computedRelations","_","sortBy","castArray","map","r","init","order","undefined","Number","maxOrder","maxBy","findRelation","idx","findIndex","removeRelation","splice","insertRelation","beforeIdx","prevRelation","afterIdx","nextRelation","length","start","firstRelation","disconnect","relations","connect","err","Error","get","getOrderMap","chunks","groupBy","value","sortedKeys","Object","keys","sort","a","b","parseFloat","orderStr","offset"],"mappings":";;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;IAkBA,MAAMA,mBAAmB,CAACC,UAAAA,EAAoBC,aAAqB,EAAE,EAAEC,aAAa,IAAI,GAAA;AACtF,IAAA,MAAMC,gBAAwB,EAAE;;AAEhC,IAAA,IAAIC,YAAAA,GAAe,KAAA;;AAEnB,IAAA,MAAMC,yBAAyBJ,UAAAA,CAAWK,MAAM,CAC9C,CAACC,GAAAA,EAAKC,OAAS;AAAE,YAAA,GAAGD,GAAG;YAAE,CAACC,GAAAA,CAAIC,EAAE,GAAG;AAAK,SAAA,GACxC,EAAC,CAAA;;AAGH,IAAA,MAAMC,eAAAA,GAAkBV,UAAAA,CAAWM,MAAM,CACvC,CAACK,MAAAA,EAAQC,QAAAA,GAAAA;AACP,QAAA,MAAMC,gBAAgBD,QAAAA,CAASE,QAAQ,EAAEC,MAAAA,IAAUH,QAAAA,CAASE,QAAQ,EAAEE,KAAAA;QAEtE,IAAI,CAACH,aAAAA,IAAkB,CAACR,sBAAsB,CAACQ,aAAAA,CAAc,IAAI,CAACF,MAAM,CAACE,aAAAA,CAAc,EAAG;YACxFT,YAAAA,GAAe,IAAA;AACj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CAC5BhB,SAASE,QAAQ,CAAA,CACjB,4CAA4C,CAAC,CAAA;AAEnD,gBAAA;AACF,YAAA,CAAA,CAAA;AACA,YAAA,OAAO,IAAI;AACb,QAAA,CAAA;AACAoD,QAAAA,GAAAA,CAAAA,GAAAA;YACE,OAAO9B,iBAAAA;AACT,QAAA,CAAA;AACA;;QAGA+B,WAAAA,CAAAA,GAAAA;AACE,YAAA,MAAM3B,MAA0B,EAAC;AACjC,YAAA,MAAM4B,SAAS/B,kBAAAA,CAAED,iBAAAA,CAAAA,CAAmBiC,OAAO,CAAC,SAASC,KAAK,EAAA;AAC1D,YAAA,MAAMC,UAAAA,GAAaC,MAAAA,CAAOC,IAAI,CAACL,MAAAA,CAAAA,CAAQM,IAAI,CAAC,CAACC,CAAAA,EAAGC,CAAAA,GAAMC,UAAAA,CAAWF,CAAAA,CAAAA,GAAKE,UAAAA,CAAWD,CAAAA,CAAAA,CAAAA;YAEjF,KAAK,MAAME,YAAYP,UAAAA,CAAY;gBACjC,MAAMT,SAAAA,GAAYM,MAAM,CAACU,QAAAA,CAAS;AAClC,gBAAA,IAAIC,MAAAA,GAAS,CAAA;gBACbjB,SAAAA,CAAUhC,OAAO,CAAC,CAAClB,QAAAA,GAAAA;oBACjB,IAAI,CAACA,QAAAA,CAAS8B,IAAI,EAAE;AAClBF,wBAAAA,GAAG,CAAC5B,QAAAA,CAASH,EAAE,CAAC,GAAGoE,UAAAA,CAAWC,QAAAA,CAAAA,GAAY,MAACC,IAAUjB,SAAAA,CAAUJ,MAAM,GAAG,CAAA,CAAA,GAAM,IAAA;wBAC9EqB,MAAAA,IAAU,CAAA;AACZ,oBAAA;AACF,gBAAA,CAAA,CAAA;AACF,YAAA;YAEA,OAAOvC,GAAAA;AACT,QAAA;AACF,KAAA;AACF;;;;;"}
|
|
@@ -132,11 +132,11 @@ import InvalidRelationError from '../errors/invalid-relation.mjs';
|
|
|
132
132
|
* another one that does not exist
|
|
133
133
|
* @return {*}
|
|
134
134
|
*/ const relationsOrderer = (initArr, idColumn, orderColumn, strict)=>{
|
|
135
|
-
const computedRelations = castArray(initArr ?? []).map((r)=>({
|
|
135
|
+
const computedRelations = _.sortBy(castArray(initArr ?? []).map((r)=>({
|
|
136
136
|
init: true,
|
|
137
137
|
id: r[idColumn],
|
|
138
|
-
order: Number(r[orderColumn])
|
|
139
|
-
}));
|
|
138
|
+
order: r[orderColumn] !== null && r[orderColumn] !== undefined ? Number(r[orderColumn]) : 1
|
|
139
|
+
})), 'order');
|
|
140
140
|
const maxOrder = maxBy('order', computedRelations)?.order || 0;
|
|
141
141
|
const findRelation = (id)=>{
|
|
142
142
|
const idx = computedRelations.findIndex((r)=>r.id === id);
|
|
@@ -154,23 +154,30 @@ import InvalidRelationError from '../errors/invalid-relation.mjs';
|
|
|
154
154
|
const insertRelation = (r)=>{
|
|
155
155
|
let idx;
|
|
156
156
|
if (r.position?.before) {
|
|
157
|
-
const { idx:
|
|
157
|
+
const { idx: beforeIdx, relation } = findRelation(r.position.before);
|
|
158
158
|
if (relation.init) {
|
|
159
|
-
|
|
159
|
+
const prevRelation = beforeIdx > 0 ? computedRelations[beforeIdx - 1] : null;
|
|
160
|
+
r.order = prevRelation && prevRelation.order < relation.order ? (prevRelation.order + relation.order) / 2 : relation.order - 0.5;
|
|
160
161
|
} else {
|
|
161
162
|
r.order = relation.order;
|
|
162
163
|
}
|
|
163
|
-
idx =
|
|
164
|
+
idx = beforeIdx;
|
|
164
165
|
} else if (r.position?.after) {
|
|
165
|
-
const { idx:
|
|
166
|
+
const { idx: afterIdx, relation } = findRelation(r.position.after);
|
|
166
167
|
if (relation.init) {
|
|
167
|
-
|
|
168
|
+
const nextRelation = afterIdx < computedRelations.length - 1 ? computedRelations[afterIdx + 1] : null;
|
|
169
|
+
r.order = nextRelation && nextRelation.order > relation.order ? (relation.order + nextRelation.order) / 2 : relation.order + 0.5;
|
|
168
170
|
} else {
|
|
169
171
|
r.order = relation.order;
|
|
170
172
|
}
|
|
171
|
-
idx =
|
|
173
|
+
idx = afterIdx + 1;
|
|
172
174
|
} else if (r.position?.start) {
|
|
173
|
-
|
|
175
|
+
if (computedRelations.length > 0) {
|
|
176
|
+
const firstRelation = computedRelations[0];
|
|
177
|
+
r.order = firstRelation.init ? firstRelation.order - 0.5 : firstRelation.order;
|
|
178
|
+
} else {
|
|
179
|
+
r.order = 0.5;
|
|
180
|
+
}
|
|
174
181
|
idx = 0;
|
|
175
182
|
} else {
|
|
176
183
|
r.order = maxOrder + 0.5;
|
|
@@ -203,13 +210,20 @@ import InvalidRelationError from '../errors/invalid-relation.mjs';
|
|
|
203
210
|
/**
|
|
204
211
|
* Get a map between the relation id and its order
|
|
205
212
|
*/ getOrderMap () {
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
213
|
+
const map = {};
|
|
214
|
+
const chunks = _(computedRelations).groupBy('order').value();
|
|
215
|
+
const sortedKeys = Object.keys(chunks).sort((a, b)=>parseFloat(a) - parseFloat(b));
|
|
216
|
+
for (const orderStr of sortedKeys){
|
|
217
|
+
const relations = chunks[orderStr];
|
|
218
|
+
let offset = 1;
|
|
219
|
+
relations.forEach((relation)=>{
|
|
220
|
+
if (!relation.init) {
|
|
221
|
+
map[relation.id] = parseFloat(orderStr) + offset / (relations.length + 1) * 0.49;
|
|
222
|
+
offset += 1;
|
|
223
|
+
}
|
|
210
224
|
});
|
|
211
|
-
|
|
212
|
-
|
|
225
|
+
}
|
|
226
|
+
return map;
|
|
213
227
|
}
|
|
214
228
|
};
|
|
215
229
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relations-orderer.mjs","sources":["../../src/entity-manager/relations-orderer.ts"],"sourcesContent":["import { castArray, maxBy } from 'lodash/fp';\nimport _ from 'lodash';\n\nimport { InvalidRelationError } from '../errors';\nimport type { ID } from '../types';\n\ninterface Link {\n id: ID;\n position?: { before?: ID; after?: ID; start?: true; end?: true };\n order?: number;\n __component?: string;\n}\n\ninterface OrderedLink extends Link {\n init?: boolean;\n order: number;\n}\n\n/**\n * When connecting relations, the order you connect them matters.\n *\n * Example, if you connect the following relations:\n * { id: 5, position: { before: 1 } }\n * { id: 1, position: { before: 2 } }\n * { id: 2, position: { end: true } }\n *\n * Going through the connect array, id 5 has to be connected before id 1,\n * so the order of id5 = id1 - 1. But the order value of id 1 is unknown.\n * The only way to know the order of id 1 is to connect it first.\n *\n * This function makes sure the relations are connected in the right order:\n * { id: 2, position: { end: true } }\n * { id: 1, position: { before: 2 } }\n * { id: 5, position: { before: 1 } }\n *\n */\nconst sortConnectArray = (connectArr: Link[], initialArr: Link[] = [], strictSort = true) => {\n const sortedConnect: Link[] = [];\n // Boolean to know if we have to recalculate the order of the relations\n let needsSorting = false;\n // Map to validate if relation is already in sortedConnect or DB.\n const relationInInitialArray = initialArr.reduce(\n (acc, rel) => ({ ...acc, [rel.id]: true }),\n {} as Record<ID, boolean>\n );\n // Map to store the first index where a relation id is connected\n const mappedRelations = connectArr.reduce(\n (mapper, relation: Link) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n\n if (!adjacentRelId || (!relationInInitialArray[adjacentRelId] && !mapper[adjacentRelId])) {\n needsSorting = true;\n }\n\n /**\n * We do not allow duplicate relations to be connected, so we need to check for uniqueness with components\n * Note that the id here includes the uid for polymorphic relations\n *\n * So for normal relations, the same id means the same relation\n * For component relations, it means the unique combo of (id, component name)\n */\n\n // Check if there's an existing relation with this id\n const existingRelation = mapper[relation.id];\n\n // Check if existing relation has a component or not\n const hasNoComponent = existingRelation && !('__component' in existingRelation);\n\n // Check if the existing relation has the same component as the new relation\n const hasSameComponent =\n existingRelation && existingRelation.__component === relation.__component;\n\n // If we have an existing relation that is not unique (no component or same component) we won't accept it\n if (existingRelation && (hasNoComponent || hasSameComponent)) {\n throw new InvalidRelationError(\n `The relation with id ${relation.id} is already connected. ` +\n 'You cannot connect the same relation twice.'\n );\n }\n\n return {\n [relation.id]: { ...relation, computed: false },\n ...mapper,\n };\n },\n {} as Record<ID, Link & { computed: boolean }>\n );\n\n // If we don't need to sort the connect array, we can return it as is\n if (!needsSorting) return connectArr;\n\n // Recursively compute in which order the relation should be connected\n const computeRelation = (relation: Link, relationsSeenInBranch: Record<ID, boolean>) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n const adjacentRelation = mappedRelations[adjacentRelId as ID];\n\n // If the relation has already been seen in the current branch,\n // it means there is a circular reference\n if (adjacentRelId && relationsSeenInBranch[adjacentRelId]) {\n throw new InvalidRelationError(\n 'A circular reference was found in the connect array. ' +\n 'One relation is trying to connect before/after another one that is trying to connect before/after it'\n );\n }\n\n // This relation has already been computed\n if (mappedRelations[relation.id]?.computed) {\n return;\n }\n\n mappedRelations[relation.id].computed = true;\n\n // Relation does not have a before or after attribute or is in the initial array\n if (!adjacentRelId || relationInInitialArray[adjacentRelId]) {\n sortedConnect.push(relation);\n return;\n }\n\n // Look if id is referenced elsewhere in the array\n if (mappedRelations[adjacentRelId]) {\n computeRelation(adjacentRelation, { ...relationsSeenInBranch, [relation.id]: true });\n sortedConnect.push(relation);\n } else if (strictSort) {\n // If we reach this point, it means that the adjacent relation is not in the connect array\n // and it is not in the database.\n throw new InvalidRelationError(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The relation with id ${adjacentRelId} needs to be connected first.`\n );\n } else {\n // We are in non-strict mode so we can push the relation.\n sortedConnect.push({ id: relation.id, position: { end: true } });\n }\n };\n\n // Iterate over connectArr and populate sortedConnect\n connectArr.forEach((relation) => computeRelation(relation, {}));\n\n return sortedConnect;\n};\n\n/**\n * Responsible for calculating the relations order when connecting them.\n *\n * The connect method takes an array of relations with positional attributes:\n * - before: the id of the relation to connect before\n * - after: the id of the relation to connect after\n * - end: it should be at the end\n * - start: it should be at the start\n *\n * Example:\n * - Having a connect array like:\n * [ { id: 4, before: 2 }, { id: 4, before: 3}, {id: 5, before: 4} ]\n * - With the initial relations:\n * [ { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * - Step by step, going through the connect array, the array of relations would be:\n * [ { id: 4, order: 3.5 }, { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 5, order: 3.5 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * - The final step would be to recalculate fractional order values.\n * [ { id: 2, order: 4 }, { id: 5, order: 3.33 }, { id: 4, order: 3.66 }, { id: 3, order: 10 } ]\n *\n * @param {Array<*>} initArr - array of relations to initialize the class with\n * @param {string} idColumn - the column name of the id\n * @param {string} orderColumn - the column name of the order\n * @param {boolean} strict - if true, will throw an error if a relation is connected adjacent to\n * another one that does not exist\n * @return {*}\n */\nconst relationsOrderer = <TRelation extends Record<string, ID | number | null>>(\n initArr: TRelation[],\n idColumn: keyof TRelation,\n orderColumn: keyof TRelation,\n strict?: boolean\n) => {\n const computedRelations: OrderedLink[] = castArray(initArr ?? []).map((r) => ({\n init: true,\n id: r[idColumn] as ID,\n order: Number(r[orderColumn]) || 1,\n }));\n\n const maxOrder = maxBy('order', computedRelations)?.order || 0;\n\n const findRelation = (id: ID) => {\n const idx = computedRelations.findIndex((r) => r.id === id);\n return { idx, relation: computedRelations[idx] };\n };\n\n const removeRelation = (r: Link) => {\n const { idx } = findRelation(r.id);\n if (idx >= 0) {\n computedRelations.splice(idx, 1);\n }\n };\n\n const insertRelation = (r: Link) => {\n let idx;\n\n if (r.position?.before) {\n const { idx: relationIndex, relation } = findRelation(r.position.before);\n if (relation.init) {\n r.order = relation.order - 0.5;\n } else {\n r.order = relation.order;\n }\n idx = relationIndex;\n } else if (r.position?.after) {\n const { idx: relationIndex, relation } = findRelation(r.position.after);\n if (relation.init) {\n r.order = relation.order + 0.5;\n } else {\n r.order = relation.order;\n }\n\n idx = relationIndex + 1;\n } else if (r.position?.start) {\n r.order = 0.5;\n idx = 0;\n } else {\n r.order = maxOrder + 0.5;\n idx = computedRelations.length;\n }\n\n // Insert the relation in the array\n computedRelations.splice(idx, 0, r as OrderedLink);\n };\n\n return {\n disconnect(relations: Link | Link[]) {\n castArray(relations).forEach((relation) => {\n removeRelation(relation);\n });\n return this;\n },\n connect(relations: Link | Link[]) {\n sortConnectArray(castArray(relations), computedRelations, strict).forEach((relation) => {\n this.disconnect(relation);\n\n try {\n insertRelation(relation);\n } catch (err) {\n throw new Error(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The list of connect relations is not valid`\n );\n }\n });\n return this;\n },\n get() {\n return computedRelations;\n },\n /**\n * Get a map between the relation id and its order\n */\n getOrderMap() {\n return _(computedRelations)\n .groupBy('order')\n .reduce(\n (acc, relations) => {\n if (relations[0]?.init) return acc;\n relations.forEach((relation, idx) => {\n acc[relation.id] = Math.floor(relation.order) + (idx + 1) / (relations.length + 1);\n });\n return acc;\n },\n {} as Record<ID, number>\n );\n },\n };\n};\n\nexport { relationsOrderer, sortConnectArray };\n"],"names":["sortConnectArray","connectArr","initialArr","strictSort","sortedConnect","needsSorting","relationInInitialArray","reduce","acc","rel","id","mappedRelations","mapper","relation","adjacentRelId","position","before","after","existingRelation","hasNoComponent","hasSameComponent","__component","InvalidRelationError","computed","computeRelation","relationsSeenInBranch","adjacentRelation","push","JSON","stringify","end","forEach","relationsOrderer","initArr","idColumn","orderColumn","strict","computedRelations","castArray","map","r","init","order","Number","maxOrder","maxBy","findRelation","idx","findIndex","removeRelation","splice","insertRelation","relationIndex","start","length","disconnect","relations","connect","err","Error","get","getOrderMap","_","groupBy","Math","floor"],"mappings":";;;;AAkBA;;;;;;;;;;;;;;;;;IAkBA,MAAMA,mBAAmB,CAACC,UAAAA,EAAoBC,aAAqB,EAAE,EAAEC,aAAa,IAAI,GAAA;AACtF,IAAA,MAAMC,gBAAwB,EAAE;;AAEhC,IAAA,IAAIC,YAAAA,GAAe,KAAA;;AAEnB,IAAA,MAAMC,yBAAyBJ,UAAAA,CAAWK,MAAM,CAC9C,C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C,GAAAA,GAAAA;oBAC3BvC,GAAG,CAACK,SAASH,EAAE,CAAC,GAAGsD,IAAAA,CAAKC,KAAK,CAACpD,QAAAA,CAAS6B,KAAK,IAAI,CAACK,MAAM,CAAA,KAAMS,SAAAA,CAAUF,MAAM,GAAG,CAAA,CAAA;AAClF,gBAAA,CAAA,CAAA;gBACA,OAAO9C,GAAAA;AACT,YAAA,CAAA,EACA,EAAC,CAAA;AAEP,QAAA;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"relations-orderer.mjs","sources":["../../src/entity-manager/relations-orderer.ts"],"sourcesContent":["import { castArray, maxBy } from 'lodash/fp';\nimport _ from 'lodash';\n\nimport { InvalidRelationError } from '../errors';\nimport type { ID } from '../types';\n\ninterface Link {\n id: ID;\n position?: { before?: ID; after?: ID; start?: true; end?: true };\n order?: number;\n __component?: string;\n}\n\ninterface OrderedLink extends Link {\n init?: boolean;\n order: number;\n}\n\n/**\n * When connecting relations, the order you connect them matters.\n *\n * Example, if you connect the following relations:\n * { id: 5, position: { before: 1 } }\n * { id: 1, position: { before: 2 } }\n * { id: 2, position: { end: true } }\n *\n * Going through the connect array, id 5 has to be connected before id 1,\n * so the order of id5 = id1 - 1. But the order value of id 1 is unknown.\n * The only way to know the order of id 1 is to connect it first.\n *\n * This function makes sure the relations are connected in the right order:\n * { id: 2, position: { end: true } }\n * { id: 1, position: { before: 2 } }\n * { id: 5, position: { before: 1 } }\n *\n */\nconst sortConnectArray = (connectArr: Link[], initialArr: Link[] = [], strictSort = true) => {\n const sortedConnect: Link[] = [];\n // Boolean to know if we have to recalculate the order of the relations\n let needsSorting = false;\n // Map to validate if relation is already in sortedConnect or DB.\n const relationInInitialArray = initialArr.reduce(\n (acc, rel) => ({ ...acc, [rel.id]: true }),\n {} as Record<ID, boolean>\n );\n // Map to store the first index where a relation id is connected\n const mappedRelations = connectArr.reduce(\n (mapper, relation: Link) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n\n if (!adjacentRelId || (!relationInInitialArray[adjacentRelId] && !mapper[adjacentRelId])) {\n needsSorting = true;\n }\n\n /**\n * We do not allow duplicate relations to be connected, so we need to check for uniqueness with components\n * Note that the id here includes the uid for polymorphic relations\n *\n * So for normal relations, the same id means the same relation\n * For component relations, it means the unique combo of (id, component name)\n */\n\n // Check if there's an existing relation with this id\n const existingRelation = mapper[relation.id];\n\n // Check if existing relation has a component or not\n const hasNoComponent = existingRelation && !('__component' in existingRelation);\n\n // Check if the existing relation has the same component as the new relation\n const hasSameComponent =\n existingRelation && existingRelation.__component === relation.__component;\n\n // If we have an existing relation that is not unique (no component or same component) we won't accept it\n if (existingRelation && (hasNoComponent || hasSameComponent)) {\n throw new InvalidRelationError(\n `The relation with id ${relation.id} is already connected. ` +\n 'You cannot connect the same relation twice.'\n );\n }\n\n return {\n [relation.id]: { ...relation, computed: false },\n ...mapper,\n };\n },\n {} as Record<ID, Link & { computed: boolean }>\n );\n\n // If we don't need to sort the connect array, we can return it as is\n if (!needsSorting) return connectArr;\n\n // Recursively compute in which order the relation should be connected\n const computeRelation = (relation: Link, relationsSeenInBranch: Record<ID, boolean>) => {\n const adjacentRelId = relation.position?.before || relation.position?.after;\n const adjacentRelation = mappedRelations[adjacentRelId as ID];\n\n // If the relation has already been seen in the current branch,\n // it means there is a circular reference\n if (adjacentRelId && relationsSeenInBranch[adjacentRelId]) {\n throw new InvalidRelationError(\n 'A circular reference was found in the connect array. ' +\n 'One relation is trying to connect before/after another one that is trying to connect before/after it'\n );\n }\n\n // This relation has already been computed\n if (mappedRelations[relation.id]?.computed) {\n return;\n }\n\n mappedRelations[relation.id].computed = true;\n\n // Relation does not have a before or after attribute or is in the initial array\n if (!adjacentRelId || relationInInitialArray[adjacentRelId]) {\n sortedConnect.push(relation);\n return;\n }\n\n // Look if id is referenced elsewhere in the array\n if (mappedRelations[adjacentRelId]) {\n computeRelation(adjacentRelation, { ...relationsSeenInBranch, [relation.id]: true });\n sortedConnect.push(relation);\n } else if (strictSort) {\n // If we reach this point, it means that the adjacent relation is not in the connect array\n // and it is not in the database.\n throw new InvalidRelationError(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The relation with id ${adjacentRelId} needs to be connected first.`\n );\n } else {\n // We are in non-strict mode so we can push the relation.\n sortedConnect.push({ id: relation.id, position: { end: true } });\n }\n };\n\n // Iterate over connectArr and populate sortedConnect\n connectArr.forEach((relation) => computeRelation(relation, {}));\n\n return sortedConnect;\n};\n\n/**\n * Responsible for calculating the relations order when connecting them.\n *\n * The connect method takes an array of relations with positional attributes:\n * - before: the id of the relation to connect before\n * - after: the id of the relation to connect after\n * - end: it should be at the end\n * - start: it should be at the start\n *\n * Example:\n * - Having a connect array like:\n * [ { id: 4, before: 2 }, { id: 4, before: 3}, {id: 5, before: 4} ]\n * - With the initial relations:\n * [ { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * - Step by step, going through the connect array, the array of relations would be:\n * [ { id: 4, order: 3.5 }, { id: 2, order: 4 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * [ { id: 2, order: 4 }, { id: 5, order: 3.5 }, { id: 4, order: 3.5 }, { id: 3, order: 10 } ]\n * - The final step would be to recalculate fractional order values.\n * [ { id: 2, order: 4 }, { id: 5, order: 3.33 }, { id: 4, order: 3.66 }, { id: 3, order: 10 } ]\n *\n * @param {Array<*>} initArr - array of relations to initialize the class with\n * @param {string} idColumn - the column name of the id\n * @param {string} orderColumn - the column name of the order\n * @param {boolean} strict - if true, will throw an error if a relation is connected adjacent to\n * another one that does not exist\n * @return {*}\n */\nconst relationsOrderer = <TRelation extends Record<string, ID | number | null>>(\n initArr: TRelation[],\n idColumn: keyof TRelation,\n orderColumn: keyof TRelation,\n strict?: boolean\n) => {\n const computedRelations: OrderedLink[] = _.sortBy(\n castArray(initArr ?? []).map((r) => ({\n init: true,\n id: r[idColumn] as ID,\n order: r[orderColumn] !== null && r[orderColumn] !== undefined ? Number(r[orderColumn]) : 1,\n })),\n 'order'\n );\n\n const maxOrder = maxBy('order', computedRelations)?.order || 0;\n\n const findRelation = (id: ID) => {\n const idx = computedRelations.findIndex((r) => r.id === id);\n return { idx, relation: computedRelations[idx] };\n };\n\n const removeRelation = (r: Link) => {\n const { idx } = findRelation(r.id);\n if (idx >= 0) {\n computedRelations.splice(idx, 1);\n }\n };\n\n const insertRelation = (r: Link) => {\n let idx;\n\n if (r.position?.before) {\n const { idx: beforeIdx, relation } = findRelation(r.position.before);\n if (relation.init) {\n const prevRelation = beforeIdx > 0 ? computedRelations[beforeIdx - 1] : null;\n r.order =\n prevRelation && prevRelation.order < relation.order\n ? (prevRelation.order + relation.order) / 2\n : relation.order - 0.5;\n } else {\n r.order = relation.order;\n }\n idx = beforeIdx;\n } else if (r.position?.after) {\n const { idx: afterIdx, relation } = findRelation(r.position.after);\n if (relation.init) {\n const nextRelation =\n afterIdx < computedRelations.length - 1 ? computedRelations[afterIdx + 1] : null;\n r.order =\n nextRelation && nextRelation.order > relation.order\n ? (relation.order + nextRelation.order) / 2\n : relation.order + 0.5;\n } else {\n r.order = relation.order;\n }\n idx = afterIdx + 1;\n } else if (r.position?.start) {\n if (computedRelations.length > 0) {\n const firstRelation = computedRelations[0];\n r.order = firstRelation.init ? firstRelation.order - 0.5 : firstRelation.order;\n } else {\n r.order = 0.5;\n }\n idx = 0;\n } else {\n r.order = maxOrder + 0.5;\n idx = computedRelations.length;\n }\n\n // Insert the relation in the array\n computedRelations.splice(idx, 0, r as OrderedLink);\n };\n\n return {\n disconnect(relations: Link | Link[]) {\n castArray(relations).forEach((relation) => {\n removeRelation(relation);\n });\n return this;\n },\n connect(relations: Link | Link[]) {\n sortConnectArray(castArray(relations), computedRelations, strict).forEach((relation) => {\n this.disconnect(relation);\n\n try {\n insertRelation(relation);\n } catch (err) {\n throw new Error(\n `There was a problem connecting relation with id ${\n relation.id\n } at position ${JSON.stringify(\n relation.position\n )}. The list of connect relations is not valid`\n );\n }\n });\n return this;\n },\n get() {\n return computedRelations;\n },\n /**\n * Get a map between the relation id and its order\n */\n getOrderMap() {\n const map: Record<ID, number> = {};\n const chunks = _(computedRelations).groupBy('order').value();\n const sortedKeys = Object.keys(chunks).sort((a, b) => parseFloat(a) - parseFloat(b));\n\n for (const orderStr of sortedKeys) {\n const relations = chunks[orderStr];\n let offset = 1;\n relations.forEach((relation) => {\n if (!relation.init) {\n map[relation.id] = parseFloat(orderStr) + (offset / (relations.length + 1)) * 0.49;\n offset += 1;\n }\n });\n }\n\n return map;\n },\n };\n};\n\nexport { relationsOrderer, sortConnectArray };\n"],"names":["sortConnectArray","connectArr","initialArr","strictSort","sortedConnect","needsSorting","relationInInitialArray","reduce","acc","rel","id","mappedRelations","mapper","relation","adjacentRelId","position","before","after","existingRelation","hasNoComponent","hasSameComponent","__component","InvalidRelationError","computed","computeRelation","relationsSeenInBranch","adjacentRelation","push","JSON","stringify","end","forEach","relationsOrderer","initArr","idColumn","orderColumn","strict","computedRelations","_","sortBy","castArray","map","r","init","order","undefined","Number","maxOrder","maxBy","findRelation","idx","findIndex","removeRelation","splice","insertRelation","beforeIdx","prevRelation","afterIdx","nextRelation","length","start","firstRelation","disconnect","relations","connect","err","Error","get","getOrderMap","chunks","groupBy","value","sortedKeys","Object","keys","sort","a","b","parseFloat","orderStr","offset"],"mappings":";;;;AAkBA;;;;;;;;;;;;;;;;;IAkBA,MAAMA,mBAAmB,CAACC,UAAAA,EAAoBC,aAAqB,EAAE,EAAEC,aAAa,IAAI,GAAA;AACtF,IAAA,MAAMC,gBAAwB,EAAE;;AAEhC,IAAA,IAAIC,YAAAA,GAAe,KAAA;;AAEnB,IAAA,MAAMC,yBAAyBJ,UAAAA,CAAWK,MAAM,CAC9C,CAACC,GAAAA,EAAKC,OAAS;AAAE,YAAA,GAAGD,GAAG;YAAE,CAACC,GAAAA,CAAIC,EAAE,GAAG;AAAK,SAAA,GACxC,EAAC,CAAA;;AAGH,IAAA,MAAM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GAAY,MAACC,IAAUjB,SAAAA,CAAUJ,MAAM,GAAG,CAAA,CAAA,GAAM,IAAA;wBAC9EqB,MAAAA,IAAU,CAAA;AACZ,oBAAA;AACF,gBAAA,CAAA,CAAA;AACF,YAAA;YAEA,OAAOvC,GAAAA;AACT,QAAA;AACF,KAAA;AACF;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ import type { Model, JoinTable } from './types';
|
|
|
12
12
|
import type { Identifiers } from './utils/identifiers';
|
|
13
13
|
import { type RepairManager } from './repairs';
|
|
14
14
|
export { isKnexQuery } from './utils/knex';
|
|
15
|
+
export { isDatabaseClientKind } from './connection';
|
|
15
16
|
interface Settings {
|
|
16
17
|
forceMigration?: boolean;
|
|
17
18
|
runMigrations?: boolean;
|
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,KAAK,SAAS,EAAE,MAAM,cAAc,CAAC;AAC3F,OAAO,EAA4B,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAE1C,OAAO,KAAK,MAAM,MAAM,UAAU,CAAC;AACnC,OAAO,EAAE,QAAQ,EAAkB,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAEpF,OAAO,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,KAAK,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,OAAO;CAId;AAED,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;AAC5B,YAAY,EAAE,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC"}
|
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';\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":";;;;;;;;;;;;;;;;;;;;AAyCA,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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ACC,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,IAA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AA;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
|
@@ -6,6 +6,7 @@ import { createEntityManager } from './entity-manager/index.mjs';
|
|
|
6
6
|
import { createMigrationsProvider } from './migrations/index.mjs';
|
|
7
7
|
import { createLifecyclesProvider } from './lifecycles/index.mjs';
|
|
8
8
|
import { createConnection } from './connection.mjs';
|
|
9
|
+
export { isDatabaseClientKind } from './connection.mjs';
|
|
9
10
|
import * as index from './errors/index.mjs';
|
|
10
11
|
export { index as errors };
|
|
11
12
|
import { transactionCtx } from './transaction-context.mjs';
|
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';\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","createLifecy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V,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,cAAAA,CAAe,EAAE,CAAA;AAEjC,QAAA,IAAI,CAAC5D,UAAU,GAAG6D,gBAAAA,CAAiBL,UAAAA,EAAY;YAC7CM,IAAAA,EAAM;AAAEzE,gBAAAA,WAAAA,EAAaA,YAAY,IAAI;AAAE;AACzC,SAAA,CAAA;AAEA,QAAA,IAAI,CAAC2C,MAAM,GAAG+B,oBAAAA,CAAqB,IAAI,CAAA;AAEvC,QAAA,IAAI,CAACC,UAAU,GAAGC,wBAAAA,CAAyB,IAAI,CAAA;AAC/C,QAAA,IAAI,CAAChB,UAAU,GAAGiB,wBAAAA,CAAyB,IAAI,CAAA;AAE/C,QAAA,IAAI,CAACrD,aAAa,GAAGsD,mBAAAA,CAAoB,IAAI,CAAA;AAE7C,QAAA,IAAI,CAACC,MAAM,GAAGC,mBAAAA,CAAoB,IAAI,CAAA;AACxC,IAAA;AAkJF;;;;"}
|
|
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;AAEA,QAAA,IAAI,CAACC,QAAQ,CAACC,UAAU,CAACT,MAAAA,CAAAA;AACzB,QAAA,MAAMU,iBAAiB,IAAI,CAAA;AAC3B,QAAA,OAAO,IAAI;AACb,IAAA;AAEAC,IAAAA,KAAAA,CAAMC,GAAW,EAAE;AACjB,QAAA,IAAI,CAAC,IAAI,CAACJ,QAAQ,CAACK,GAAG,CAACD,GAAAA,CAAAA,EAAM;AAC3B,YAAA,MAAM,IAAIE,KAAAA,CAAM,CAAC,MAAM,EAAEF,GAAAA,C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AAA,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,cAAAA,CAAe,EAAE,CAAA;AAEjC,QAAA,IAAI,CAAC5D,UAAU,GAAG6D,gBAAAA,CAAiBL,UAAAA,EAAY;YAC7CM,IAAAA,EAAM;AAAEzE,gBAAAA,WAAAA,EAAaA,YAAY,IAAI;AAAE;AACzC,SAAA,CAAA;AAEA,QAAA,IAAI,CAAC2C,MAAM,GAAG+B,oBAAAA,CAAqB,IAAI,CAAA;AAEvC,QAAA,IAAI,CAACC,UAAU,GAAGC,wBAAAA,CAAyB,IAAI,CAAA;AAC/C,QAAA,IAAI,CAAChB,UAAU,GAAGiB,wBAAAA,CAAyB,IAAI,CAAA;AAE/C,QAAA,IAAI,CAACrD,aAAa,GAAGsD,mBAAAA,CAAoB,IAAI,CAAA;AAE7C,QAAA,IAAI,CAACC,MAAM,GAAGC,mBAAAA,CAAoB,IAAI,CAAA;AACxC,IAAA;AAkJF;;;;"}
|
|
@@ -3,10 +3,11 @@ import type { Database } from '..';
|
|
|
3
3
|
import * as helpers from './helpers';
|
|
4
4
|
import type { Join } from './helpers/join';
|
|
5
5
|
interface State {
|
|
6
|
-
type: 'select' | 'insert' | 'update' | 'delete' | 'count' | 'max' | 'truncate';
|
|
6
|
+
type: 'select' | 'insert' | 'update' | 'delete' | 'count' | 'max' | 'min' | 'truncate';
|
|
7
7
|
select: Array<string | Knex.Raw>;
|
|
8
8
|
count: string | null;
|
|
9
9
|
max: string | null;
|
|
10
|
+
min: string | null;
|
|
10
11
|
first: boolean;
|
|
11
12
|
data: Record<string, unknown> | (null | Record<string, unknown>)[] | null;
|
|
12
13
|
where: Record<string, unknown>[];
|
|
@@ -47,6 +48,7 @@ export interface QueryBuilder {
|
|
|
47
48
|
decrement(column: string, amount?: number): QueryBuilder;
|
|
48
49
|
count(count?: string): QueryBuilder;
|
|
49
50
|
max(column: string): QueryBuilder;
|
|
51
|
+
min(column: string): QueryBuilder;
|
|
50
52
|
where(where?: object): QueryBuilder;
|
|
51
53
|
limit(limit: number): QueryBuilder;
|
|
52
54
|
offset(offset: number): QueryBuilder;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-builder.d.ts","sourceRoot":"","sources":["../../src/query/query-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAGjC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAKnC,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;AACrC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAG3C,UAAU,KAAK;IACb,IAAI,EAAE,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,OAAO,GAAG,KAAK,GAAG,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"query-builder.d.ts","sourceRoot":"","sources":["../../src/query/query-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAGjC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAKnC,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;AACrC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAG3C,UAAU,KAAK;IACb,IAAI,EAAE,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,OAAO,GAAG,KAAK,GAAG,KAAK,GAAG,UAAU,CAAC;IACvF,MAAM,EAAE,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