joist-core 2.5.0-next.11 → 2.5.0-next.13
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/build/InstanceData.cjs +7 -1
- package/build/InstanceData.cjs.map +1 -1
- package/build/InstanceData.d.cts +7 -1
- package/build/InstanceData.d.cts.map +1 -1
- package/build/InstanceData.d.mts +7 -1
- package/build/InstanceData.d.mts.map +1 -1
- package/build/InstanceData.js +7 -1
- package/build/InstanceData.js.map +1 -1
- package/build/PluginManager.cjs +10 -3
- package/build/PluginManager.cjs.map +1 -1
- package/build/PluginManager.d.cts +8 -3
- package/build/PluginManager.d.cts.map +1 -1
- package/build/PluginManager.d.mts +8 -3
- package/build/PluginManager.d.mts.map +1 -1
- package/build/PluginManager.js +10 -3
- package/build/PluginManager.js.map +1 -1
- package/build/fields.cjs +12 -6
- package/build/fields.cjs.map +1 -1
- package/build/fields.d.cts +3 -2
- package/build/fields.d.cts.map +1 -1
- package/build/fields.d.mts +3 -2
- package/build/fields.d.mts.map +1 -1
- package/build/fields.js +12 -6
- package/build/fields.js.map +1 -1
- package/build/flush/JoinRows.cjs +1 -1
- package/build/flush/JoinRows.cjs.map +1 -1
- package/build/flush/JoinRows.d.cts.map +1 -1
- package/build/flush/JoinRows.d.mts.map +1 -1
- package/build/flush/JoinRows.js +1 -1
- package/build/flush/JoinRows.js.map +1 -1
- package/build/relations/ReactiveManyToMany.cjs +18 -1
- package/build/relations/ReactiveManyToMany.cjs.map +1 -1
- package/build/relations/ReactiveManyToMany.d.cts +3 -0
- package/build/relations/ReactiveManyToMany.d.cts.map +1 -1
- package/build/relations/ReactiveManyToMany.d.mts +3 -0
- package/build/relations/ReactiveManyToMany.d.mts.map +1 -1
- package/build/relations/ReactiveManyToMany.js +18 -1
- package/build/relations/ReactiveManyToMany.js.map +1 -1
- package/build/relations/ReactiveManyToManyOtherSide.cjs +16 -2
- package/build/relations/ReactiveManyToManyOtherSide.cjs.map +1 -1
- package/build/relations/ReactiveManyToManyOtherSide.d.cts.map +1 -1
- package/build/relations/ReactiveManyToManyOtherSide.d.mts.map +1 -1
- package/build/relations/ReactiveManyToManyOtherSide.js +16 -2
- package/build/relations/ReactiveManyToManyOtherSide.js.map +1 -1
- package/package.json +2 -2
package/build/fields.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.cjs","names":["getInstanceData","getMetadata","getEmInternalApi","cleanStringValue","isEntity","maybeResolveReferenceToId","maybeRequireTemporal","fail"],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Plugins observe only the first read of each field, including internal reads. Install\n * plugins before reading entities; adding one later does not replay earlier reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs first-read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * The plugin bit is set before invoking hooks so a hook may read or change its own field,\n * reentering this function without invoking the hook again.\n * A throwing hook clears both bits for this field, allowing a later access to retry it.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n if (!hasReadField(instanceData.pluginReadFields, instanceData.pluginReadFieldsExtra, index)) {\n markPluginReadField(instanceData, index, true);\n try {\n getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName);\n } catch (error) {\n markPluginReadField(instanceData, index, false);\n markApplicationReadField(entity, index, false);\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n }\n }\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if ((fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes one cold-path plugin bit, preserving other reads completed inside the callback. */\nfunction markPluginReadField(data: InstanceData, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n if (index < 32) {\n data.pluginReadFields = read ? data.pluginReadFields | bit : data.pluginReadFields & ~bit;\n } else {\n const extra = (data.pluginReadFieldsExtra ??= []);\n const word = (index >>> 5) - 1;\n extra[word] = read ? (extra[word] ?? 0) | bit : (extra[word] ?? 0) & ~bit;\n }\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,SAAS,QAAgB,WAAmB,aAAa,OAAY;CACnF,MAAM,eAAeA,mBAAAA,gBAAgB,MAAM;CAC3C,MAAM,QAAQ,aAAa,SAAS,iBAAiB;CACrD,IAAI,OAAO,UAAU,UAAU,cAAA,KAAK,iBAAiB,aAAa,SAAS,KAAK,GAAG,WAAW;CAE9F,KAAK,iBAAiB,QAAQ,UAAU,CAAC,IAAK,MAAM,QAAQ,SAAU,GACpE,OAAO,aAAa,KAAK;CAE3B,OAAO,UAAU,QAAQ,cAAc,WAAW,YAAY,KAAK;AACrE;;AAGA,SAAgB,kBAAkB,QAAgB,WAA4B;CAC5E,OAAO,CAAC,CAACC,uBAAAA,YAAY,MAAM,CAAC,CAAC,UAAU,UAAU,EAAE;AACrD;;AAGA,SAAgB,WAAW,QAAgB,WAA4B;CACrE,MAAM,EAAE,SAASD,mBAAAA,gBAAgB,MAAM;CACvC,IAAI,aAAa,MAAM,OAAO;CAE9B,IAAI,OAAO,aAAa,OAAO;CAE/B,SAAS,QAAQ,WAAW,IAAI;CAChC,OAAO,aAAa;AACtB;;;;;;;;;;AAWA,SAAgB,SAAS,QAAgB,WAAmB,UAAwB;CAClF,cAAA,iBAAiB,QAAQ,SAAS;CAClC,MAAM,EA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AM,MAAM,QAAQ;CAC1B,IAAI,QAAQ,IACV,KAAK,mBAAmB,OAAO,KAAK,mBAAmB,MAAM,KAAK,mBAAmB,CAAC;MACjF;EACL,MAAM,QAAS,KAAK,0BAA0B,CAAC;EAC/C,MAAM,QAAQ,UAAU,KAAK;EAC7B,MAAM,QAAQ,QAAQ,MAAM,SAAS,KAAK,OAAO,MAAM,SAAS,KAAK,CAAC;CACxE;AACF;;AAGA,SAAS,yBAAyB,QAAgB,OAAe,MAAqB;CACpF,MAAM,MAAM,MAAM,QAAQ;CAC1B,MAAM,OAAO,UAAU;CACvB,MAAM,QAAQ,iBAAiB,QAAQ,IAAI;CAC3C,iBAAiB,QAAQ,MAAM,OAAO,QAAQ,MAAM,QAAQ,CAAC,GAAG;AAClE;;AAGA,SAAS,iBAAiB,QAAgB,MAAsB;CAC9D,OAAQ,OAA2B,aAAa,IAAI;AACtD;;AAGA,SAAS,iBAAiB,QAAgB,MAAc,OAAqB;CAC3E,OAA4B,aAAa,IAAI,KAAK;AACpD;;AAGA,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
|
|
1
|
+
{"version":3,"file":"fields.cjs","names":["getInstanceData","getMetadata","getEmInternalApi","cleanStringValue","isEntity","maybeResolveReferenceToId","maybeRequireTemporal","fail"],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Plugins observe the first read, including internal reads, and subsequent reads if any plugin returns `\"allow\"`.\n *\n * Install plugins before reading entities; adding one later does not replay cached reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * The plugin bit is set before invoking hooks so a hook may read or change its own field,\n * reentering this function without invoking the hook again.\n * A hook returning `\"allow\"` or throwing clears both bits, so later accesses check again.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n let canCache = true;\n if (!hasReadField(instanceData.pluginReadFields, instanceData.pluginReadFieldsExtra, index)) {\n markPluginReadField(instanceData, index, true);\n try {\n canCache = getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName) !== \"allow\";\n if (!canCache) {\n markPluginReadField(instanceData, index, false);\n // A reentrant getter may have published a warm bit before the hook vetoed caching.\n markApplicationReadField(entity, index, false);\n }\n } catch (error) {\n markPluginReadField(instanceData, index, false);\n markApplicationReadField(entity, index, false);\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n }\n }\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if (canCache && (fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes one cold-path plugin bit, preserving other reads completed inside the callback. */\nfunction markPluginReadField(data: InstanceData, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n if (index < 32) {\n data.pluginReadFields = read ? data.pluginReadFields | bit : data.pluginReadFields & ~bit;\n } else {\n const extra = (data.pluginReadFieldsExtra ??= []);\n const word = (index >>> 5) - 1;\n extra[word] = read ? (extra[word] ?? 0) | bit : (extra[word] ?? 0) & ~bit;\n }\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,SAAS,QAAgB,WAAmB,aAAa,OAAY;CACnF,MAAM,eAAeA,mBAAAA,gBAAgB,MAAM;CAC3C,MAAM,QAAQ,aAAa,SAAS,iBAAi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AAM,QAAQ,CAAC,GAAG;AAClE;;AAGA,SAAS,iBAAiB,QAAgB,MAAsB;CAC9D,OAAQ,OAA2B,aAAa,IAAI;AACtD;;AAGA,SAAS,iBAAiB,QAAgB,MAAc,OAAqB;CAC3E,OAA4B,aAAa,IAAI,KAAK;AACpD;;AAGA,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
|
package/build/fields.d.cts
CHANGED
|
@@ -2,8 +2,9 @@ import { Entity } from "./Entity.cjs";
|
|
|
2
2
|
/**
|
|
3
3
|
* Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.
|
|
4
4
|
*
|
|
5
|
-
* Plugins observe
|
|
6
|
-
*
|
|
5
|
+
* Plugins observe the first read, including internal reads, and subsequent reads if any plugin returns `"allow"`.
|
|
6
|
+
*
|
|
7
|
+
* Install plugins before reading entities; adding one later does not replay cached reads.
|
|
7
8
|
* Generated getters and direct application calls are protected by default. Only ORM
|
|
8
9
|
* housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.
|
|
9
10
|
* The field name is a string because generated getters and ORM internals know its type.
|
package/build/fields.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.d.cts","names":[],"sources":["../src/fields.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"fields.d.cts","names":[],"sources":["../src/fields.ts"],"mappings":";;;;;;;;;;;wBAsBgB,SAAS,QAAQ,QAAQ,mBAAmB;;wBAY5C,kBAAkB,QAAQ,QAAQ;;wBAKlC,WAAW,QAAQ,QAAQ;;;;;;;;;;wBAmB3B,SAAS,QAAQ,QAAQ,mBAAmB;wBAwH5C,YAAY,UAAU;wBAMtB,MAAM,QAAQ"}
|
package/build/fields.d.mts
CHANGED
|
@@ -2,8 +2,9 @@ import { Entity } from "./Entity.mjs";
|
|
|
2
2
|
/**
|
|
3
3
|
* Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.
|
|
4
4
|
*
|
|
5
|
-
* Plugins observe
|
|
6
|
-
*
|
|
5
|
+
* Plugins observe the first read, including internal reads, and subsequent reads if any plugin returns `"allow"`.
|
|
6
|
+
*
|
|
7
|
+
* Install plugins before reading entities; adding one later does not replay cached reads.
|
|
7
8
|
* Generated getters and direct application calls are protected by default. Only ORM
|
|
8
9
|
* housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.
|
|
9
10
|
* The field name is a string because generated getters and ORM internals know its type.
|
package/build/fields.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.d.mts","names":[],"sources":["../src/fields.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"fields.d.mts","names":[],"sources":["../src/fields.ts"],"mappings":";;;;;;;;;;;wBAsBgB,SAAS,QAAQ,QAAQ,mBAAmB;;wBAY5C,kBAAkB,QAAQ,QAAQ;;wBAKlC,WAAW,QAAQ,QAAQ;;;;;;;;;;wBAmB3B,SAAS,QAAQ,QAAQ,mBAAmB;wBAwH5C,YAAY,UAAU;wBAMtB,MAAM,QAAQ"}
|
package/build/fields.js
CHANGED
|
@@ -10,8 +10,9 @@ import { cleanStringValue, fail } from "./utils.js";
|
|
|
10
10
|
/**
|
|
11
11
|
* Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.
|
|
12
12
|
*
|
|
13
|
-
* Plugins observe
|
|
14
|
-
*
|
|
13
|
+
* Plugins observe the first read, including internal reads, and subsequent reads if any plugin returns `"allow"`.
|
|
14
|
+
*
|
|
15
|
+
* Install plugins before reading entities; adding one later does not replay cached reads.
|
|
15
16
|
* Generated getters and direct application calls are protected by default. Only ORM
|
|
16
17
|
* housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.
|
|
17
18
|
* The field name is a string because generated getters and ORM internals know its type.
|
|
@@ -115,18 +116,23 @@ function equal(a, b) {
|
|
|
115
116
|
return false;
|
|
116
117
|
}
|
|
117
118
|
/**
|
|
118
|
-
* Performs
|
|
119
|
+
* Performs read callbacks, protection, and lazy conversion before publishing the warm-read bit.
|
|
119
120
|
*
|
|
120
121
|
* The plugin bit is set before invoking hooks so a hook may read or change its own field,
|
|
121
122
|
* reentering this function without invoking the hook again.
|
|
122
|
-
* A throwing
|
|
123
|
+
* A hook returning `"allow"` or throwing clears both bits, so later accesses check again.
|
|
123
124
|
*/
|
|
124
125
|
function readField(entity, instanceData, fieldName, isInternal, index) {
|
|
125
126
|
const { em, metadata } = instanceData;
|
|
127
|
+
let canCache = true;
|
|
126
128
|
if (!hasReadField(instanceData.pluginReadFields, instanceData.pluginReadFieldsExtra, index)) {
|
|
127
129
|
markPluginReadField(instanceData, index, true);
|
|
128
130
|
try {
|
|
129
|
-
getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName);
|
|
131
|
+
canCache = getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName) !== "allow";
|
|
132
|
+
if (!canCache) {
|
|
133
|
+
markPluginReadField(instanceData, index, false);
|
|
134
|
+
markApplicationReadField(entity, index, false);
|
|
135
|
+
}
|
|
130
136
|
} catch (error) {
|
|
131
137
|
markPluginReadField(instanceData, index, false);
|
|
132
138
|
markApplicationReadField(entity, index, false);
|
|
@@ -138,7 +144,7 @@ function readField(entity, instanceData, fieldName, isInternal, index) {
|
|
|
138
144
|
if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);
|
|
139
145
|
const { data } = instanceData;
|
|
140
146
|
if (!(fieldName in data) && !instanceData.isNewEntity) data[fieldName] = (field?.serde ?? fail(`Missing serde for ${fieldName}`)).fromRow(instanceData.rowData, instanceData.rowIndex);
|
|
141
|
-
if ((fieldName === "id" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) markApplicationReadField(entity, index, true);
|
|
147
|
+
if (canCache && (fieldName === "id" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) markApplicationReadField(entity, index, true);
|
|
142
148
|
return data[fieldName];
|
|
143
149
|
}
|
|
144
150
|
/** Tests a field bit without allocating the extra words for small entity types. */
|
package/build/fields.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.js","names":[],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Plugins observe only the first read of each field, including internal reads. Install\n * plugins before reading entities; adding one later does not replay earlier reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs first-read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * The plugin bit is set before invoking hooks so a hook may read or change its own field,\n * reentering this function without invoking the hook again.\n * A throwing hook clears both bits for this field, allowing a later access to retry it.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n if (!hasReadField(instanceData.pluginReadFields, instanceData.pluginReadFieldsExtra, index)) {\n markPluginReadField(instanceData, index, true);\n try {\n getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName);\n } catch (error) {\n markPluginReadField(instanceData, index, false);\n markApplicationReadField(entity, index, false);\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n }\n }\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if ((fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes one cold-path plugin bit, preserving other reads completed inside the callback. */\nfunction markPluginReadField(data: InstanceData, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n if (index < 32) {\n data.pluginReadFields = read ? data.pluginReadFields | bit : data.pluginReadFields & ~bit;\n } else {\n const extra = (data.pluginReadFieldsExtra ??= []);\n const word = (index >>> 5) - 1;\n extra[word] = read ? (extra[word] ?? 0) | bit : (extra[word] ?? 0) & ~bit;\n }\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,SAAgB,SAAS,QAAgB,WAAmB,aAAa,OAAY;CACnF,MAAM,eAAe,gBAAgB,MAAM;CAC3C,MAAM,QAAQ,aAAa,SAAS,iBAAiB;CACrD,IAAI,OAAO,UAAU,UAAU,KAAK,iBAAiB,aAAa,SAAS,KAAK,GAAG,WAAW;CAE9F,KAAK,iBAAiB,QAAQ,UAAU,CAAC,IAAK,MAAM,QAAQ,SAAU,GACpE,OAAO,aAAa,KAAK;CAE3B,OAAO,UAAU,QAAQ,cAAc,WAAW,YAAY,KAAK;AACrE;;AAGA,SAAgB,kBAAkB,QAAgB,WAA4B;CAC5E,OAAO,CAAC,CAAC,YAAY,MAAM,CAAC,CAAC,UAAU,UAAU,EAAE;AACrD;;AAGA,SAAgB,WAAW,QAAgB,WAA4B;CACrE,MAAM,EAAE,SAAS,gBAAgB,MAAM;CACvC,IAAI,aAAa,MAAM,OAAO;CAE9B,IAAI,OAAO,aAAa,OAAO;CAE/B,SAAS,QAAQ,WAAW,IAAI;CAChC,OAAO,aAAa;AACtB;;;;;;;;;;AAWA,SAAgB,SAAS,QAAgB,WAAmB,UAAwB;CAClF,iBAAiB,QAAQ,SAAS;CAClC,MAAM,EAAE,OAAO;CACf,MAAM,MAAM,iBAAiB,EAAE;CAC/B,MAAM,EAAE,IAAI,eAAe,cAAc,aAAa,kBAAkB;CAGxE,IAAI,mBAAmB;CAEvB,MAAM,eAAe,gBAAgB,MAAM;CAC3C,MAAM,EAAE,MAAM,cAAc,gBAAgB;CAG5C,MAAM,QAAQ,YAAY,MAAM,CAAC,CAAC,UAAU;CAC5C,IAAI,MAAM,SAAS,eAAe,MAAM,SAAS,YAAY,MAAM,aAAa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,QAAQ,IAAI;CAC3C,iBAAiB,QAAQ,MAAM,OAAO,QAAQ,MAAM,QAAQ,CAAC,GAAG;AAClE;;AAGA,SAAS,iBAAiB,QAAgB,MAAsB;CAC9D,OAAQ,OAA2B,aAAa,IAAI;AACtD;;AAGA,SAAS,iBAAiB,QAAgB,MAAc,OAAqB;CAC3E,OAA4B,aAAa,IAAI,KAAK;AACpD;;AAGA,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
|
|
1
|
+
{"version":3,"file":"fields.js","names":[],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Plugins observe the first read, including internal reads, and subsequent reads if any plugin returns `\"allow\"`.\n *\n * Install plugins before reading entities; adding one later does not replay cached reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * The plugin bit is set before invoking hooks so a hook may read or change its own field,\n * reentering this function without invoking the hook again.\n * A hook returning `\"allow\"` or throwing clears both bits, so later accesses check again.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n let canCache = true;\n if (!hasReadField(instanceData.pluginReadFields, instanceData.pluginReadFieldsExtra, index)) {\n markPluginReadField(instanceData, index, true);\n try {\n canCache = getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName) !== \"allow\";\n if (!canCache) {\n markPluginReadField(instanceData, index, false);\n // A reentrant getter may have published a warm bit before the hook vetoed caching.\n markApplicationReadField(entity, index, false);\n }\n } catch (error) {\n markPluginReadField(instanceData, index, false);\n markApplicationReadField(entity, index, false);\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n }\n }\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if (canCache && (fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes one cold-path plugin bit, preserving other reads completed inside the callback. */\nfunction markPluginReadField(data: InstanceData, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n if (index < 32) {\n data.pluginReadFields = read ? data.pluginReadFields | bit : data.pluginReadFields & ~bit;\n } else {\n const extra = (data.pluginReadFieldsExtra ??= []);\n const word = (index >>> 5) - 1;\n extra[word] = read ? (extra[word] ?? 0) | bit : (extra[word] ?? 0) & ~bit;\n }\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,SAAS,QAAgB,WAAmB,aAAa,OAAY;CACnF,MAAM,eAAe,gBAAgB,MAAM;CAC3C,MAAM,QAAQ,aAAa,SAAS,iBAAiB;CACrD,IAAI,OAAO,UAAU,UAAU,KAAK,iBAAiB,aAAa,SAAS,KAAK,GAAG,WAAW;CAE9F,KAAK,iBAAiB,QAAQ,UAAU,CAAC,IAAK,MAAM,QAAQ,SAAU,GACpE,OAAO,aAAa,KAAK;CAE3B,OAAO,UAAU,QAAQ,cAAc,WAAW,YAAY,KAAK;AACrE;;AAGA,SAAgB,kBAAkB,QAAgB,WAA4B;CAC5E,OAAO,CAAC,CAAC,YAAY,MAAM,CAAC,CAAC,UAAU,UAAU,EAAE;AACrD;;AAGA,SAAgB,WAAW,QAAgB,WAA4B;CACrE,MAAM,EAAE,SAAS,gBAAgB,MAAM;CACvC,IAAI,aAAa,MAAM,OAAO;CAE9B,IAAI,OAAO,aAAa,OAAO;CAE/B,SA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A,SAAS,aAAa,OAAe,OAAsC,OAAwB;CAEjG,SADa,QAAQ,KAAK,QAAS,SAAS,UAAU,KAAK,MAAM,KACjD,MAAM,QAAQ,SAAU;AAC1C;;AAGA,SAAS,oBAAoB,MAAoB,OAAe,MAAqB;CACnF,MAAM,MAAM,MAAM,QAAQ;CAC1B,IAAI,QAAQ,IACV,KAAK,mBAAmB,OAAO,KAAK,mBAAmB,MAAM,KAAK,mBAAmB,CAAC;MACjF;EACL,MAAM,QAAS,KAAK,0BAA0B,CAAC;EAC/C,MAAM,QAAQ,UAAU,KAAK;EAC7B,MAAM,QAAQ,QAAQ,MAAM,SAAS,KAAK,OAAO,MAAM,SAAS,KAAK,CAAC;CACxE;AACF;;AAGA,SAAS,yBAAyB,QAAgB,OAAe,MAAqB;CACpF,MAAM,MAAM,MAAM,QAAQ;CAC1B,MAAM,OAAO,UAAU;CACvB,MAAM,QAAQ,iBAAiB,QAAQ,IAAI;CAC3C,iBAAiB,QAAQ,MAAM,OAAO,QAAQ,MAAM,QAAQ,CAAC,GAAG;AAClE;;AAGA,SAAS,iBAAiB,QAAgB,MAAsB;CAC9D,OAAQ,OAA2B,aAAa,IAAI;AACtD;;AAGA,SAAS,iBAAiB,QAAgB,MAAc,OAAqB;CAC3E,OAA4B,aAAa,IAAI,KAAK;AACpD;;AAGA,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
|
package/build/flush/JoinRows.cjs
CHANGED
|
@@ -139,7 +139,7 @@ var JoinRows = class {
|
|
|
139
139
|
const others = this.index.getOthers(columnName, entity);
|
|
140
140
|
if (others.length === 0) return [];
|
|
141
141
|
const [c1, c2] = Object.keys(others[0].columns);
|
|
142
|
-
const c =
|
|
142
|
+
const c = c1 === columnName ? c2 : c1;
|
|
143
143
|
return others.filter((o) => !o.deleted).map((row) => row.columns[c]);
|
|
144
144
|
}
|
|
145
145
|
/** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JoinRows.cjs","names":["keyToTaggedId","keyToNumber","getEmInternalApi","getBaseAndSelfMetas"],"sources":["../../src/flush/JoinRows.ts"],"sourcesContent":["import type { Entity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, getBaseAndSelfMetas } from \"src/EntityMetadata.ts\";\nimport type { EnumMetadata } from \"src/EnumMetadata.ts\";\nimport type { JoinRowTodo } from \"src/flush/Todo.ts\";\nimport { keyToNumber, keyToTaggedId } from \"src/keys.ts\";\nimport type { ReactionsManager } from \"src/reactivity/ReactionsManager.ts\";\nimport { remove } from \"src/utils.ts\";\n\n/**\n * A simplified interface for ManyToManyCollection-like relations.\n *\n * Specifically lets ReactiveManyToMany & ReactiveManyToManyOtherSide use JoinRows\n * as if they were full-fledged m2m relations.\n *\n * The \"other\" side of the join table is usually a second entity, but for `EnumCollection`s\n * (i.e. `Publisher.logoColors`) it is an enum table; in that case `otherEnum` is set and the\n * other column's value is the enum's numeric id rather than an `Entity` (there is also no\n * `otherMeta`/`otherFieldName`, since enums have no reverse collection to keep in sync).\n */\nexport type ManyToManyLike = {\n entity: Entity;\n joinTableName: string;\n columnName: string;\n otherColumnName: string;\n fieldName: string;\n meta: EntityMetadata;\n /** Undefined when the other side is an enum. */\n otherFieldName?: string;\n /** Undefined when the other side is an enum. */\n otherMeta?: EntityMetadata;\n /** Set when the other side is an enum table, for mapping enum codes <-> their numeric ids. */\n otherEnum?: EnumMetadata<any, any, number>;\n /** Whether the join table has a surrogate `id` PK; if false the FK pair is the composite PK. */\n hasJoinTableId: boolean;\n};\n\n/** The value of a join row's column: an `Entity`, or an enum's numeric id for `EnumCollection`s. */\nexport type JoinColumnValue = Entity | number;\n\n/** Whether a join column points at a not-yet-inserted entity (enum ids are never \"new\"). */\nfunction isNewColumn(value: JoinColumnValue): boolean {\n return typeof value !== \"number\" && value.isNewEntity;\n}\n\n/** A small holder around m2m join rows, which we treat as psuedo-entities. */\nexport class JoinRows {\n // The in-memory rows for our m2m table.\n private readonly rows: JoinRow[] = [];\n private readonly index: ManyToManyIndex;\n\n constructor(\n // This could be either side of the m2m relation, depending on which is accessed first.\n // Regardless of which m2m side, we still have a single `JoinRows` instance in memory per m2m table.\n readonly m2m: ManyToManyLike,\n private rm: ReactionsManager,\n ) {\n this.index = new ManyToManyIndex(m2m);\n }\n\n /** Adds a new join row to this table. */\n addNew(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n if (!e1) throw new Error(`Cannot add a m2m row with an entity that is ${e1}`);\n if (!e2) throw new Error(`Cannot add a m2m row with an entity that is ${e2}`);\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n existing.deleted = false;\n existing.op = JoinRowOperation.Pending;\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: false,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Adds a new remove to this table. */\n addRemove(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n if (!existing.persisted) {\n // It was only added in-memory and never persisted, so just drop it\n remove(this.rows, existing);\n this.index.remove(existing);\n } else {\n existing.deleted = true;\n }\n existing.op = JoinRowOperation.Pending;\n } else {\n // We're removing against an unloaded collection, so assume the row exists in the database\n // (persisted: true) and queue a delete; the delete keys off the (col1, col2) composite.\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n deleted: true,\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Return any \"old values\" for a m2m collection that might need reactivity checks. */\n removedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n // I.e. if we did `t1.books.remove(b1)` find all join rows that have\n // `tag_id=t1`, are marked for deletion, and then `.map` them to the removed book.\n const removedRows = this.index.getOthers(m2m.columnName, e1).filter((r) => r.deleted);\n return removedRows.map((r) => r.columns[otherColumnName]);\n }\n\n addedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n const addedRows = this.index\n .getOthers(m2m.columnName, e1)\n .filter(\n (r) =>\n ((!r.persisted && r.op === JoinRowOperation.Pending) || r.op === JoinRowOperation.Flushed) &&\n r.deleted !== true,\n );\n return addedRows.map((r) => r.columns[otherColumnName]);\n }\n\n /** Adds an existing join row to this table. */\n addPreloadedRow(m2m: ManyToManyLike, id: number | undefined, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n // Treat any existing WIP change as source-of-truth, so leave it alone\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n }\n\n /** Look up/create our internal JoinRow psuedo-entities for the db rows. */\n async loadRows(tuples: [string, string][], dbRows: any[]): Promise<void> {\n const { em } = this.m2m.entity;\n const { columnName: column1, otherColumnName: column2, meta: meta1, otherMeta: meta2, otherEnum } = this.m2m;\n\n const oneIds: string[] = [];\n // Tagged ids for an entity other-side, or raw enum ids for an enum other-side.\n const twoVals: JoinColumnValue[] = [];\n for (const dbRow of dbRows) {\n oneIds.push(keyToTaggedId(meta1, dbRow[column1])!);\n twoVals.push(\n otherEnum ? (dbRow[column2] as number) : (em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!) as any),\n );\n }\n\n // Make sure we have entities in memory for all the joined-to tables. The enum side has no\n // entities to load; the entity sides do (and `twoVals` is re-resolved to entities below).\n await Promise.all([\n em.loadAll(meta1.cstr, oneIds),\n otherEnum\n ? Promise.resolve([])\n : em.loadAll(\n meta2!.cstr,\n dbRows.map((dbRow) => keyToTaggedId(meta2!, dbRow[column2])!),\n ),\n ]);\n\n // If we're doing a em.refresh/reload, we need to watch for rows that are no longer here. For an\n // enum other-side, only persisted rows are delete-candidates (pending in-memory adds are kept,\n // since `EnumCollection` relies on `JoinRows` to hold them rather than re-asserting on load).\n const existingRows = new Set<JoinRow>();\n for (const [columnName, id] of tuples) {\n const others = this.index.getOthers(columnName, em.getEntity(id)!);\n for (const row of others) if (!otherEnum || row.persisted) existingRows.add(row);\n }\n\n let i = 0;\n for (const dbRow of dbRows) {\n const e1 = em.getEntity(oneIds[i])!;\n const e2 = otherEnum ? (dbRow[column2] as number) : em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!)!;\n i++;\n let row = this.index.get(this.m2m, e1, e2);\n if (!row) {\n row = {\n op: JoinRowOperation.Completed,\n id: dbRow.id,\n persisted: true,\n columns: { [column1]: e1, [column2]: e2 },\n created_at: dbRow.created_at,\n };\n this.rows.push(row);\n this.index.add(this.m2m, e1, e2, row);\n } else {\n // If a placeholder row was created while a ManyToManyCollection was unloaded, and we find it during\n // a subsequent load/query, update its id to be what is in the database and mark it persisted.\n row.id = dbRow.id;\n row.persisted = true;\n // Mark this row as still valid\n existingRows.delete(row);\n }\n }\n\n // Mark all no-longer-there rows as deleted\n for (const row of existingRows) row.deleted = true;\n }\n\n getOthers(columnName: string, entity: Entity): JoinColumnValue[] {\n const others = this.index.getOthers(columnName, entity);\n if (others.length === 0) return [];\n const [c1, c2] = Object.keys(others[0].columns);\n const c = others[0].columns[c1] === entity ? c2 : c1;\n return others.filter((o) => !o.deleted).map((row) => row.columns[c]);\n }\n\n /** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */\n removeAllFor(columnName: string, entity: Entity): void {\n for (const row of this.index.getOthers(columnName, entity)) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Drops a single `(e1, e2)` row without queuing a flush, e.g. when mirroring another em's removal. */\n removePreloadedRow(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const row = this.index.get(m2m, e1, e2);\n if (row) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Scans our `rows` for newly-added/newly-deleted rows that need `INSERT`s/`UPDATE`s. */\n toTodo(): JoinRowTodo | undefined {\n const newRows = this.rows.filter((r) => !r.persisted && r.deleted !== true && r.op === \"pending\");\n const deletedRows = this.rows.filter((r) => r.persisted && r.deleted === true && r.op === \"pending\");\n if (newRows.length === 0 && deletedRows.length === 0) {\n return undefined;\n }\n return {\n m2m: this.m2m,\n newRows,\n deletedRows,\n resetAfterFlushed: () => {\n for (const row of this.rows) {\n if (row.op === JoinRowOperation.Pending || row.op === JoinRowOperation.Flushed)\n row.op = JoinRowOperation.Completed;\n }\n },\n // The driver flushes pure (int, int) FK pairs; resolve them here so it never has to know\n // whether a column points at an entity (use its id) or an enum (its value is already the id).\n dbValue: (row, columnName) => this.#dbValue(row, columnName),\n isNew: (row, columnName) => isNewColumn(row.columns[columnName]),\n };\n }\n\n get hasChanges() {\n return this.rows.some(({ op }) => op === JoinRowOperation.Pending || op === JoinRowOperation.Flushed);\n }\n\n /** The db int value for `row`'s `columnName`: an entity's id, or (for enums) the enum's id itself. */\n #dbValue(row: JoinRow, columnName: string): number {\n const value = row.columns[columnName];\n if (typeof value === \"number\") return value;\n const meta = columnName === this.m2m.columnName ? this.m2m.meta : this.m2m.otherMeta!;\n return keyToNumber(meta, value.idTagged)!;\n }\n\n /**\n * Invalidates caches & queues reactivity for a join-row change.\n *\n * The owning entity (`e1`) always reacts; the \"other\" side only reacts when it is an entity,\n * since enum other-sides have no `em`/reverse-field to keep in sync.\n */\n #reactToChange(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const { em } = this.m2m.entity;\n const api = getEmInternalApi(e1.em);\n api.isLoadedCache.resetIsLoaded(e1, m2m.fieldName);\n this.rm.queueDownstreamReactables(e1, m2m.fieldName);\n if (getBaseAndSelfMetas(e1).some((meta) => meta.config.__data.touchOnChange.has(m2m.fieldName))) {\n em.touch(e1);\n }\n if (!m2m.otherEnum) {\n const other = e2 as Entity;\n const otherFieldName = m2m.otherFieldName!;\n api.isLoadedCache.resetIsLoaded(other, otherFieldName);\n this.rm.queueDownstreamReactables(other, otherFieldName);\n if (getBaseAndSelfMetas(other).some((meta) => meta.config.__data.touchOnChange.has(otherFieldName))) {\n em.touch(other);\n }\n }\n }\n}\n\n/**\n * A \"psuedo-entity\" for a join row.\n *\n * We treat this as a special entity, i.e. it has two \"relations\" to each entity for the current\n * row, an optional surrogate `id` primary key, and an optional `created_at` column.\n *\n * These rows are immutable, i.e. once created we don't change either FK, and instead make\n * collection changes only by inserting new rows and deleting old rows.\n *\n * This makes the column1+column2 combination a composite key. For id-less join tables, that\n * composite is the actual primary key and `id` is always undefined.\n */\nexport interface JoinRow {\n /**\n * Whether our relation has been processed or not.\n *\n * - `pending` means we've not flushed it to the Database\n * - `flushed` means we've flushed but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `completed` means we've been flushed and `em.flush` has completed\n */\n op: JoinRowOperation;\n /** The surrogate key for id-ful join tables; always undefined for id-less tables. */\n id: number | undefined;\n /**\n * Whether this row exists (or is assumed to exist) in the database.\n *\n * This is orthogonal to `op` (the flush lifecycle) and is what distinguishes a pending insert\n * from a pending delete: a `pending` row that is `!persisted` is a pending INSERT (added in\n * memory, not yet in the db), while a `pending` row that is `persisted` is a pending DELETE\n * (in the db, marked `deleted`). `op` alone cannot tell these apart, because both inserts and\n * deletes walk the same `pending -> flushed -> completed` progression.\n *\n * We track this as its own flag rather than inferring it from `id` being set/unset, because\n * id-less join tables (whose PK is just the composite of the two FKs) never have an `id` — so\n * `id === undefined` would be ambiguous. `persisted` is the id-agnostic generalization of the\n * `id`-is-set check that id-ful tables historically relied on.\n *\n * It must survive add/remove/re-add sequences: e.g. loading a row (persisted), removing it\n * (pending delete), then re-adding it (`deleted` flipped back to false, `op` back to `pending`)\n * leaves a `pending && !deleted` row that looks identical to a fresh insert — but it is still in\n * the db, so a subsequent remove must issue a DELETE, which only `persisted` can tell us.\n */\n persisted: boolean;\n /** Maps each FK column to its value: an `Entity`, or (for `EnumCollection`s) an enum's numeric id. */\n columns: Record<string, JoinColumnValue>;\n created_at?: Date;\n deleted?: boolean;\n}\n\n/** An enum to track our insert/delete state progression. */\nexport enum JoinRowOperation {\n Pending = \"pending\",\n Flushed = \"flushed\",\n Completed = \"completed\",\n}\n\n/** Keep an in-memory index to avoid sequentially scanning `rows`. */\nclass ManyToManyIndex {\n private indexes: Record<string, Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>> = {};\n\n constructor(private readonly m2m: ManyToManyLike) {\n this.indexes[m2m.columnName] = new Map();\n this.indexes[m2m.otherColumnName] = new Map();\n }\n\n add(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue, value: JoinRow): void {\n // Store both e1+e2 => value and e2+e1 => value so we can do lookups from either side\n this.#doAdd(this.indexes[m2m.columnName], e1, e2, value);\n this.#doAdd(this.indexes[m2m.otherColumnName], e2, e1, value);\n }\n\n remove(value: JoinRow): void {\n const [[column1, e1], [column2, e2]] = Object.entries(value.columns);\n this.#doRemove(this.indexes[column1], e1, e2);\n this.#doRemove(this.indexes[column2], e2, e1);\n }\n\n get(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue): JoinRow | undefined {\n return this.indexes[m2m.columnName].get(e1)?.get(e2);\n }\n\n /** Cheat and use the index to return \"the other entities\" for `entity`. */\n getOthers(columnName: string, entity: JoinColumnValue): JoinRow[] {\n // It's empty m2m collection won't have any other entities, and so no index entries\n const map = this.indexes[columnName].get(entity);\n if (!map) return [];\n // Sort for a stable order regardless of how many batches contributed rows — the underlying\n // Map preserves insertion order, which depends on DataLoader timing and is non-deterministic\n // across processes. New rows (no key yet) sort last.\n const rows = Array.from(map.values());\n if (this.m2m.hasJoinTableId) {\n // Sort by join-row id.\n return rows.sort((a, b) => (a.id ?? Infinity) - (b.id ?? Infinity));\n }\n // Id-less tables have no surrogate id, so sort by the other side's id.\n const otherColumn = columnName === this.m2m.columnName ? this.m2m.otherColumnName : this.m2m.columnName;\n if (this.m2m.otherEnum && otherColumn === this.m2m.otherColumnName) {\n // The other side is an enum, so its column value is already its numeric id.\n return rows.sort((a, b) => (a.columns[otherColumn] as number) - (b.columns[otherColumn] as number));\n }\n const otherMeta = columnName === this.m2m.columnName ? this.m2m.otherMeta! : this.m2m.meta;\n const key = (r: JoinRow) => {\n const other = r.columns[otherColumn] as Entity;\n return other.isNewEntity ? Infinity : keyToNumber(otherMeta, other.id)!;\n };\n return rows.sort((a, b) => key(a) - key(b));\n }\n\n #doAdd(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n value: JoinRow,\n ): void {\n const map = index.get(e1) ?? new Map();\n if (map.size === 0) index.set(e1, map);\n map.set(e2, value);\n }\n\n #doRemove(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n ): void {\n index.get(e1)?.delete(e2);\n }\n}\n"],"mappings":";;;;;;;AAyCA,SAAS,YAAY,OAAiC;CACpD,OAAO,OAAO,UAAU,YAAY,MAAM;AAC5C;;AAGA,IAAa,WAAb,MAAsB;CAQT;CACD;CAPV,OAAmC,CAAC;CACpC;CAEA,YAGE,KACA,IACA;EAFS,KAAA,MAAA;EACD,KAAA,KAAA;EAER,KAAK,QAAQ,IAAI,gBAAgB,GAAG;CACtC;;CAGA,OAAO,KAAqB,IAAY,IAA2B;EACjE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C,IAAI;EAC5E,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C,IAAI;EAC5E,MAAM,WAAW,KAAK,MAAM,IAAI,KAAK,IAAI,EAAE;EAC3C,IAA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K,IAAI,gBAEX,OAAO,KAAK,MAAM,GAAG,OAAO,EAAE,MAAM,aAAa,EAAE,MAAM,SAAS;EAGpE,MAAM,cAAc,eAAe,KAAK,IAAI,aAAa,KAAK,IAAI,kBAAkB,KAAK,IAAI;EAC7F,IAAI,KAAK,IAAI,aAAa,gBAAgB,KAAK,IAAI,iBAEjD,OAAO,KAAK,MAAM,GAAG,MAAO,EAAE,QAAQ,eAA2B,EAAE,QAAQ,YAAuB;EAEpG,MAAM,YAAY,eAAe,KAAK,IAAI,aAAa,KAAK,IAAI,YAAa,KAAK,IAAI;EACtF,MAAM,OAAO,MAAe;GAC1B,MAAM,QAAQ,EAAE,QAAQ;GACxB,OAAO,MAAM,cAAc,WAAWF,aAAAA,YAAY,WAAW,MAAM,EAAE;EACvE;EACA,OAAO,KAAK,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC;CAC5C;CAEA,OACE,OACA,IACA,IACA,OACM;EACN,MAAM,MAAM,MAAM,IAAI,EAAE,qBAAK,IAAI,IAAI;EACrC,IAAI,IAAI,SAAS,GAAG,MAAM,IAAI,IAAI,GAAG;EACrC,IAAI,IAAI,IAAI,KAAK;CACnB;CAEA,UACE,OACA,IACA,IACM;EACN,MAAM,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE;CAC1B;AACF"}
|
|
1
|
+
{"version":3,"file":"JoinRows.cjs","names":["keyToTaggedId","keyToNumber","getEmInternalApi","getBaseAndSelfMetas"],"sources":["../../src/flush/JoinRows.ts"],"sourcesContent":["import type { Entity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, getBaseAndSelfMetas } from \"src/EntityMetadata.ts\";\nimport type { EnumMetadata } from \"src/EnumMetadata.ts\";\nimport type { JoinRowTodo } from \"src/flush/Todo.ts\";\nimport { keyToNumber, keyToTaggedId } from \"src/keys.ts\";\nimport type { ReactionsManager } from \"src/reactivity/ReactionsManager.ts\";\nimport { remove } from \"src/utils.ts\";\n\n/**\n * A simplified interface for ManyToManyCollection-like relations.\n *\n * Specifically lets ReactiveManyToMany & ReactiveManyToManyOtherSide use JoinRows\n * as if they were full-fledged m2m relations.\n *\n * The \"other\" side of the join table is usually a second entity, but for `EnumCollection`s\n * (i.e. `Publisher.logoColors`) it is an enum table; in that case `otherEnum` is set and the\n * other column's value is the enum's numeric id rather than an `Entity` (there is also no\n * `otherMeta`/`otherFieldName`, since enums have no reverse collection to keep in sync).\n */\nexport type ManyToManyLike = {\n entity: Entity;\n joinTableName: string;\n columnName: string;\n otherColumnName: string;\n fieldName: string;\n meta: EntityMetadata;\n /** Undefined when the other side is an enum. */\n otherFieldName?: string;\n /** Undefined when the other side is an enum. */\n otherMeta?: EntityMetadata;\n /** Set when the other side is an enum table, for mapping enum codes <-> their numeric ids. */\n otherEnum?: EnumMetadata<any, any, number>;\n /** Whether the join table has a surrogate `id` PK; if false the FK pair is the composite PK. */\n hasJoinTableId: boolean;\n};\n\n/** The value of a join row's column: an `Entity`, or an enum's numeric id for `EnumCollection`s. */\nexport type JoinColumnValue = Entity | number;\n\n/** Whether a join column points at a not-yet-inserted entity (enum ids are never \"new\"). */\nfunction isNewColumn(value: JoinColumnValue): boolean {\n return typeof value !== \"number\" && value.isNewEntity;\n}\n\n/** A small holder around m2m join rows, which we treat as psuedo-entities. */\nexport class JoinRows {\n // The in-memory rows for our m2m table.\n private readonly rows: JoinRow[] = [];\n private readonly index: ManyToManyIndex;\n\n constructor(\n // This could be either side of the m2m relation, depending on which is accessed first.\n // Regardless of which m2m side, we still have a single `JoinRows` instance in memory per m2m table.\n readonly m2m: ManyToManyLike,\n private rm: ReactionsManager,\n ) {\n this.index = new ManyToManyIndex(m2m);\n }\n\n /** Adds a new join row to this table. */\n addNew(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n if (!e1) throw new Error(`Cannot add a m2m row with an entity that is ${e1}`);\n if (!e2) throw new Error(`Cannot add a m2m row with an entity that is ${e2}`);\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n existing.deleted = false;\n existing.op = JoinRowOperation.Pending;\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: false,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Adds a new remove to this table. */\n addRemove(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n if (!existing.persisted) {\n // It was only added in-memory and never persisted, so just drop it\n remove(this.rows, existing);\n this.index.remove(existing);\n } else {\n existing.deleted = true;\n }\n existing.op = JoinRowOperation.Pending;\n } else {\n // We're removing against an unloaded collection, so assume the row exists in the database\n // (persisted: true) and queue a delete; the delete keys off the (col1, col2) composite.\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n deleted: true,\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Return any \"old values\" for a m2m collection that might need reactivity checks. */\n removedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n // I.e. if we did `t1.books.remove(b1)` find all join rows that have\n // `tag_id=t1`, are marked for deletion, and then `.map` them to the removed book.\n const removedRows = this.index.getOthers(m2m.columnName, e1).filter((r) => r.deleted);\n return removedRows.map((r) => r.columns[otherColumnName]);\n }\n\n addedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n const addedRows = this.index\n .getOthers(m2m.columnName, e1)\n .filter(\n (r) =>\n ((!r.persisted && r.op === JoinRowOperation.Pending) || r.op === JoinRowOperation.Flushed) &&\n r.deleted !== true,\n );\n return addedRows.map((r) => r.columns[otherColumnName]);\n }\n\n /** Adds an existing join row to this table. */\n addPreloadedRow(m2m: ManyToManyLike, id: number | undefined, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n // Treat any existing WIP change as source-of-truth, so leave it alone\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n }\n\n /** Look up/create our internal JoinRow psuedo-entities for the db rows. */\n async loadRows(tuples: [string, string][], dbRows: any[]): Promise<void> {\n const { em } = this.m2m.entity;\n const { columnName: column1, otherColumnName: column2, meta: meta1, otherMeta: meta2, otherEnum } = this.m2m;\n\n const oneIds: string[] = [];\n // Tagged ids for an entity other-side, or raw enum ids for an enum other-side.\n const twoVals: JoinColumnValue[] = [];\n for (const dbRow of dbRows) {\n oneIds.push(keyToTaggedId(meta1, dbRow[column1])!);\n twoVals.push(\n otherEnum ? (dbRow[column2] as number) : (em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!) as any),\n );\n }\n\n // Make sure we have entities in memory for all the joined-to tables. The enum side has no\n // entities to load; the entity sides do (and `twoVals` is re-resolved to entities below).\n await Promise.all([\n em.loadAll(meta1.cstr, oneIds),\n otherEnum\n ? Promise.resolve([])\n : em.loadAll(\n meta2!.cstr,\n dbRows.map((dbRow) => keyToTaggedId(meta2!, dbRow[column2])!),\n ),\n ]);\n\n // If we're doing a em.refresh/reload, we need to watch for rows that are no longer here. For an\n // enum other-side, only persisted rows are delete-candidates (pending in-memory adds are kept,\n // since `EnumCollection` relies on `JoinRows` to hold them rather than re-asserting on load).\n const existingRows = new Set<JoinRow>();\n for (const [columnName, id] of tuples) {\n const others = this.index.getOthers(columnName, em.getEntity(id)!);\n for (const row of others) if (!otherEnum || row.persisted) existingRows.add(row);\n }\n\n let i = 0;\n for (const dbRow of dbRows) {\n const e1 = em.getEntity(oneIds[i])!;\n const e2 = otherEnum ? (dbRow[column2] as number) : em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!)!;\n i++;\n let row = this.index.get(this.m2m, e1, e2);\n if (!row) {\n row = {\n op: JoinRowOperation.Completed,\n id: dbRow.id,\n persisted: true,\n columns: { [column1]: e1, [column2]: e2 },\n created_at: dbRow.created_at,\n };\n this.rows.push(row);\n this.index.add(this.m2m, e1, e2, row);\n } else {\n // If a placeholder row was created while a ManyToManyCollection was unloaded, and we find it during\n // a subsequent load/query, update its id to be what is in the database and mark it persisted.\n row.id = dbRow.id;\n row.persisted = true;\n // Mark this row as still valid\n existingRows.delete(row);\n }\n }\n\n // Mark all no-longer-there rows as deleted\n for (const row of existingRows) row.deleted = true;\n }\n\n getOthers(columnName: string, entity: Entity): JoinColumnValue[] {\n const others = this.index.getOthers(columnName, entity);\n if (others.length === 0) return [];\n const [c1, c2] = Object.keys(others[0].columns);\n // Self-referencing rows can contain the same entity in both columns, so identity cannot tell the sides apart.\n const c = c1 === columnName ? c2 : c1;\n return others.filter((o) => !o.deleted).map((row) => row.columns[c]);\n }\n\n /** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */\n removeAllFor(columnName: string, entity: Entity): void {\n for (const row of this.index.getOthers(columnName, entity)) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Drops a single `(e1, e2)` row without queuing a flush, e.g. when mirroring another em's removal. */\n removePreloadedRow(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const row = this.index.get(m2m, e1, e2);\n if (row) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Scans our `rows` for newly-added/newly-deleted rows that need `INSERT`s/`UPDATE`s. */\n toTodo(): JoinRowTodo | undefined {\n const newRows = this.rows.filter((r) => !r.persisted && r.deleted !== true && r.op === \"pending\");\n const deletedRows = this.rows.filter((r) => r.persisted && r.deleted === true && r.op === \"pending\");\n if (newRows.length === 0 && deletedRows.length === 0) {\n return undefined;\n }\n return {\n m2m: this.m2m,\n newRows,\n deletedRows,\n resetAfterFlushed: () => {\n for (const row of this.rows) {\n if (row.op === JoinRowOperation.Pending || row.op === JoinRowOperation.Flushed)\n row.op = JoinRowOperation.Completed;\n }\n },\n // The driver flushes pure (int, int) FK pairs; resolve them here so it never has to know\n // whether a column points at an entity (use its id) or an enum (its value is already the id).\n dbValue: (row, columnName) => this.#dbValue(row, columnName),\n isNew: (row, columnName) => isNewColumn(row.columns[columnName]),\n };\n }\n\n get hasChanges() {\n return this.rows.some(({ op }) => op === JoinRowOperation.Pending || op === JoinRowOperation.Flushed);\n }\n\n /** The db int value for `row`'s `columnName`: an entity's id, or (for enums) the enum's id itself. */\n #dbValue(row: JoinRow, columnName: string): number {\n const value = row.columns[columnName];\n if (typeof value === \"number\") return value;\n const meta = columnName === this.m2m.columnName ? this.m2m.meta : this.m2m.otherMeta!;\n return keyToNumber(meta, value.idTagged)!;\n }\n\n /**\n * Invalidates caches & queues reactivity for a join-row change.\n *\n * The owning entity (`e1`) always reacts; the \"other\" side only reacts when it is an entity,\n * since enum other-sides have no `em`/reverse-field to keep in sync.\n */\n #reactToChange(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const { em } = this.m2m.entity;\n const api = getEmInternalApi(e1.em);\n api.isLoadedCache.resetIsLoaded(e1, m2m.fieldName);\n this.rm.queueDownstreamReactables(e1, m2m.fieldName);\n if (getBaseAndSelfMetas(e1).some((meta) => meta.config.__data.touchOnChange.has(m2m.fieldName))) {\n em.touch(e1);\n }\n if (!m2m.otherEnum) {\n const other = e2 as Entity;\n const otherFieldName = m2m.otherFieldName!;\n api.isLoadedCache.resetIsLoaded(other, otherFieldName);\n this.rm.queueDownstreamReactables(other, otherFieldName);\n if (getBaseAndSelfMetas(other).some((meta) => meta.config.__data.touchOnChange.has(otherFieldName))) {\n em.touch(other);\n }\n }\n }\n}\n\n/**\n * A \"psuedo-entity\" for a join row.\n *\n * We treat this as a special entity, i.e. it has two \"relations\" to each entity for the current\n * row, an optional surrogate `id` primary key, and an optional `created_at` column.\n *\n * These rows are immutable, i.e. once created we don't change either FK, and instead make\n * collection changes only by inserting new rows and deleting old rows.\n *\n * This makes the column1+column2 combination a composite key. For id-less join tables, that\n * composite is the actual primary key and `id` is always undefined.\n */\nexport interface JoinRow {\n /**\n * Whether our relation has been processed or not.\n *\n * - `pending` means we've not flushed it to the Database\n * - `flushed` means we've flushed but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `completed` means we've been flushed and `em.flush` has completed\n */\n op: JoinRowOperation;\n /** The surrogate key for id-ful join tables; always undefined for id-less tables. */\n id: number | undefined;\n /**\n * Whether this row exists (or is assumed to exist) in the database.\n *\n * This is orthogonal to `op` (the flush lifecycle) and is what distinguishes a pending insert\n * from a pending delete: a `pending` row that is `!persisted` is a pending INSERT (added in\n * memory, not yet in the db), while a `pending` row that is `persisted` is a pending DELETE\n * (in the db, marked `deleted`). `op` alone cannot tell these apart, because both inserts and\n * deletes walk the same `pending -> flushed -> completed` progression.\n *\n * We track this as its own flag rather than inferring it from `id` being set/unset, because\n * id-less join tables (whose PK is just the composite of the two FKs) never have an `id` — so\n * `id === undefined` would be ambiguous. `persisted` is the id-agnostic generalization of the\n * `id`-is-set check that id-ful tables historically relied on.\n *\n * It must survive add/remove/re-add sequences: e.g. loading a row (persisted), removing it\n * (pending delete), then re-adding it (`deleted` flipped back to false, `op` back to `pending`)\n * leaves a `pending && !deleted` row that looks identical to a fresh insert — but it is still in\n * the db, so a subsequent remove must issue a DELETE, which only `persisted` can tell us.\n */\n persisted: boolean;\n /** Maps each FK column to its value: an `Entity`, or (for `EnumCollection`s) an enum's numeric id. */\n columns: Record<string, JoinColumnValue>;\n created_at?: Date;\n deleted?: boolean;\n}\n\n/** An enum to track our insert/delete state progression. */\nexport enum JoinRowOperation {\n Pending = \"pending\",\n Flushed = \"flushed\",\n Completed = \"completed\",\n}\n\n/** Keep an in-memory index to avoid sequentially scanning `rows`. */\nclass ManyToManyIndex {\n private indexes: Record<string, Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>> = {};\n\n constructor(private readonly m2m: ManyToManyLike) {\n this.indexes[m2m.columnName] = new Map();\n this.indexes[m2m.otherColumnName] = new Map();\n }\n\n add(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue, value: JoinRow): void {\n // Store both e1+e2 => value and e2+e1 => value so we can do lookups from either side\n this.#doAdd(this.indexes[m2m.columnName], e1, e2, value);\n this.#doAdd(this.indexes[m2m.otherColumnName], e2, e1, value);\n }\n\n remove(value: JoinRow): void {\n const [[column1, e1], [column2, e2]] = Object.entries(value.columns);\n this.#doRemove(this.indexes[column1], e1, e2);\n this.#doRemove(this.indexes[column2], e2, e1);\n }\n\n get(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue): JoinRow | undefined {\n return this.indexes[m2m.columnName].get(e1)?.get(e2);\n }\n\n /** Cheat and use the index to return \"the other entities\" for `entity`. */\n getOthers(columnName: string, entity: JoinColumnValue): JoinRow[] {\n // It's empty m2m collection won't have any other entities, and so no index entries\n const map = this.indexes[columnName].get(entity);\n if (!map) return [];\n // Sort for a stable order regardless of how many batches contributed rows — the underlying\n // Map preserves insertion order, which depends on DataLoader timing and is non-deterministic\n // across processes. New rows (no key yet) sort last.\n const rows = Array.from(map.values());\n if (this.m2m.hasJoinTableId) {\n // Sort by join-row id.\n return rows.sort((a, b) => (a.id ?? Infinity) - (b.id ?? Infinity));\n }\n // Id-less tables have no surrogate id, so sort by the other side's id.\n const otherColumn = columnName === this.m2m.columnName ? this.m2m.otherColumnName : this.m2m.columnName;\n if (this.m2m.otherEnum && otherColumn === this.m2m.otherColumnName) {\n // The other side is an enum, so its column value is already its numeric id.\n return rows.sort((a, b) => (a.columns[otherColumn] as number) - (b.columns[otherColumn] as number));\n }\n const otherMeta = columnName === this.m2m.columnName ? this.m2m.otherMeta! : this.m2m.meta;\n const key = (r: JoinRow) => {\n const other = r.columns[otherColumn] as Entity;\n return other.isNewEntity ? Infinity : keyToNumber(otherMeta, other.id)!;\n };\n return rows.sort((a, b) => key(a) - key(b));\n }\n\n #doAdd(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n value: JoinRow,\n ): void {\n const map = index.get(e1) ?? new Map();\n if (map.size === 0) index.set(e1, map);\n map.set(e2, value);\n }\n\n #doRemove(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n ): void {\n index.get(e1)?.delete(e2);\n }\n}\n"],"mappings":";;;;;;;AAyCA,SAAS,YAAY,OAAiC;CACpD,OAAO,OAAO,UAAU,YAAY,MAAM;AAC5C;;AAGA,IAAa,WAAb,MAAsB;CAQT;CACD;CAPV,OAAmC,CAAC;CACpC;CAEA,YAGE,KACA,IACA;EAFS,KAAA,MAAA;EACD,KAAA,KAAA;EAER,KAAK,QAAQ,IAAI,gBAAgB,GAAG;CACtC;;CAGA,OAAO,KAAqB,IAAY,IAA2B;EACjE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C,IAAI;EAC5E,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C,IAAI;EAC5E,MAAM,WAAW,KAAK,MAAM,IAAI,KAAK,IAAI,EAAE;EAC3C,IAAI,UAAU;GACZ,SAAS,UAAU;GACnB,SAAS,KAAA;EACX,OAAO;GACL,MAAM,MAAM;IACV,IAAA;IACA,IAAI,KAAA;IACJ,WAAW;IACX,SAAS;MAAG,IAAI,aAAa;MAAK,IAAI,kBAAkB;IAAG;GAC7D;GACA,KAAK,KAAK,KAAK,GAAG;GAClB,KAAK,MAAM,IAAI,KAAK,IAAI,IAAI,GAAG;EACjC;EACA,KAAK,eAAe,KAAK,IAAI,EAAE;CACjC;;CAGA,UAAU,KAAqB,IAAY,IAA2B;EACpE,MAAM,WAAW,KAAK,MAAM,IAAI,KAAK,IAAI,EAAE;EA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AQ;GACxB,OAAO,MAAM,cAAc,WAAWF,aAAAA,YAAY,WAAW,MAAM,EAAE;EACvE;EACA,OAAO,KAAK,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC;CAC5C;CAEA,OACE,OACA,IACA,IACA,OACM;EACN,MAAM,MAAM,MAAM,IAAI,EAAE,qBAAK,IAAI,IAAI;EACrC,IAAI,IAAI,SAAS,GAAG,MAAM,IAAI,IAAI,GAAG;EACrC,IAAI,IAAI,IAAI,KAAK;CACnB;CAEA,UACE,OACA,IACA,IACM;EACN,MAAM,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE;CAC1B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JoinRows.d.cts","names":[],"sources":["../../src/flush/JoinRows.ts"],"mappings":";;;;;;;;;;;;;;;;YAoBY;EACV,QAAQ;EACR;EACA;EACA;EACA;EACA,MAAM;;EAEN;;EAEA,YAAY;;EAEZ,YAAY;;EAEZ;;;YAIU,kBAAkB;;qBAQjB;;WAQA,KAAK;UACN;mBAPO;mBACA;EAEjB,YAGW,KAAK,gBACN,IAAI;;EAMd,OAAO,KAAK,gBAAgB,IAAI,QAAQ,IAAI;;EAqB5C,UAAU,KAAK,gBAAgB,IAAI,QAAQ,IAAI;;EA4B/C,WAAW,KAAK,gBAAgB,IAAI,SAAS;EAQ7C,SAAS,KAAK,gBAAgB,IAAI,SAAS;;EAa3C,gBAAgB,KAAK,gBAAgB,wBAAwB,IAAI,QAAQ,IAAI;;EAiBvE,SAAS,4BAA4B,gBAAgB;EAiE3D,UAAU,oBAAoB,QAAQ,SAAS;;
|
|
1
|
+
{"version":3,"file":"JoinRows.d.cts","names":[],"sources":["../../src/flush/JoinRows.ts"],"mappings":";;;;;;;;;;;;;;;;YAoBY;EACV,QAAQ;EACR;EACA;EACA;EACA;EACA,MAAM;;EAEN;;EAEA,YAAY;;EAEZ,YAAY;;EAEZ;;;YAIU,kBAAkB;;qBAQjB;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+
{"version":3,"file":"JoinRows.d.mts","names":[],"sources":["../../src/flush/JoinRows.ts"],"mappings":";;;;;;;;;;;;;;;;YAoBY;EACV,QAAQ;EACR;EACA;EACA;EACA;EACA,MAAM;;EAEN;;EAEA,YAAY;;EAEZ,YAAY;;EAEZ;;;YAIU,kBAAkB;;qBAQjB;;WAQA,KAAK;UACN;mBAPO;mBACA;EAEjB,YAGW,KAAK,gBACN,IAAI;;EAMd,OAAO,KAAK,gBAAgB,IAAI,QAAQ,IAAI;;EAqB5C,UAAU,KAAK,gBAAgB,IAAI,QAAQ,IAAI;;EA4B/C,WAAW,KAAK,gBAAgB,IAAI,SAAS;EAQ7C,SAAS,KAAK,gBAAgB,IAAI,SAAS;;EAa3C,gBAAgB,KAAK,gBAAgB,wBAAwB,IAAI,QAAQ,IAAI;;EAiBvE,SAAS,4BAA4B,gBAAgB;EAiE3D,UAAU,oBAAoB,QAAQ,SAAS;;EAU/C,aAAa,oBAAoB,QAAQ;;EAQzC,mBAAmB,KAAK,gBAAgB,IAAI,QAAQ,IAAI;;EASxD,UAAU;MAuBN;;;;;;;;;;;;;;iBAkDW;;;;;;;;EAQf,IAAI;;EAEJ;;;;;;;;;;;;;;;;;;;;EAoBA;;EAEA,SAAS,eAAe;EACxB,aAAa;EACb;;;oBAIU;EACV;EACA;EACA"}
|
package/build/flush/JoinRows.js
CHANGED
|
@@ -138,7 +138,7 @@ var JoinRows = class {
|
|
|
138
138
|
const others = this.index.getOthers(columnName, entity);
|
|
139
139
|
if (others.length === 0) return [];
|
|
140
140
|
const [c1, c2] = Object.keys(others[0].columns);
|
|
141
|
-
const c =
|
|
141
|
+
const c = c1 === columnName ? c2 : c1;
|
|
142
142
|
return others.filter((o) => !o.deleted).map((row) => row.columns[c]);
|
|
143
143
|
}
|
|
144
144
|
/** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JoinRows.js","names":[],"sources":["../../src/flush/JoinRows.ts"],"sourcesContent":["import type { Entity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, getBaseAndSelfMetas } from \"src/EntityMetadata.ts\";\nimport type { EnumMetadata } from \"src/EnumMetadata.ts\";\nimport type { JoinRowTodo } from \"src/flush/Todo.ts\";\nimport { keyToNumber, keyToTaggedId } from \"src/keys.ts\";\nimport type { ReactionsManager } from \"src/reactivity/ReactionsManager.ts\";\nimport { remove } from \"src/utils.ts\";\n\n/**\n * A simplified interface for ManyToManyCollection-like relations.\n *\n * Specifically lets ReactiveManyToMany & ReactiveManyToManyOtherSide use JoinRows\n * as if they were full-fledged m2m relations.\n *\n * The \"other\" side of the join table is usually a second entity, but for `EnumCollection`s\n * (i.e. `Publisher.logoColors`) it is an enum table; in that case `otherEnum` is set and the\n * other column's value is the enum's numeric id rather than an `Entity` (there is also no\n * `otherMeta`/`otherFieldName`, since enums have no reverse collection to keep in sync).\n */\nexport type ManyToManyLike = {\n entity: Entity;\n joinTableName: string;\n columnName: string;\n otherColumnName: string;\n fieldName: string;\n meta: EntityMetadata;\n /** Undefined when the other side is an enum. */\n otherFieldName?: string;\n /** Undefined when the other side is an enum. */\n otherMeta?: EntityMetadata;\n /** Set when the other side is an enum table, for mapping enum codes <-> their numeric ids. */\n otherEnum?: EnumMetadata<any, any, number>;\n /** Whether the join table has a surrogate `id` PK; if false the FK pair is the composite PK. */\n hasJoinTableId: boolean;\n};\n\n/** The value of a join row's column: an `Entity`, or an enum's numeric id for `EnumCollection`s. */\nexport type JoinColumnValue = Entity | number;\n\n/** Whether a join column points at a not-yet-inserted entity (enum ids are never \"new\"). */\nfunction isNewColumn(value: JoinColumnValue): boolean {\n return typeof value !== \"number\" && value.isNewEntity;\n}\n\n/** A small holder around m2m join rows, which we treat as psuedo-entities. */\nexport class JoinRows {\n // The in-memory rows for our m2m table.\n private readonly rows: JoinRow[] = [];\n private readonly index: ManyToManyIndex;\n\n constructor(\n // This could be either side of the m2m relation, depending on which is accessed first.\n // Regardless of which m2m side, we still have a single `JoinRows` instance in memory per m2m table.\n readonly m2m: ManyToManyLike,\n private rm: ReactionsManager,\n ) {\n this.index = new ManyToManyIndex(m2m);\n }\n\n /** Adds a new join row to this table. */\n addNew(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n if (!e1) throw new Error(`Cannot add a m2m row with an entity that is ${e1}`);\n if (!e2) throw new Error(`Cannot add a m2m row with an entity that is ${e2}`);\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n existing.deleted = false;\n existing.op = JoinRowOperation.Pending;\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: false,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Adds a new remove to this table. */\n addRemove(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n if (!existing.persisted) {\n // It was only added in-memory and never persisted, so just drop it\n remove(this.rows, existing);\n this.index.remove(existing);\n } else {\n existing.deleted = true;\n }\n existing.op = JoinRowOperation.Pending;\n } else {\n // We're removing against an unloaded collection, so assume the row exists in the database\n // (persisted: true) and queue a delete; the delete keys off the (col1, col2) composite.\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n deleted: true,\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Return any \"old values\" for a m2m collection that might need reactivity checks. */\n removedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n // I.e. if we did `t1.books.remove(b1)` find all join rows that have\n // `tag_id=t1`, are marked for deletion, and then `.map` them to the removed book.\n const removedRows = this.index.getOthers(m2m.columnName, e1).filter((r) => r.deleted);\n return removedRows.map((r) => r.columns[otherColumnName]);\n }\n\n addedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n const addedRows = this.index\n .getOthers(m2m.columnName, e1)\n .filter(\n (r) =>\n ((!r.persisted && r.op === JoinRowOperation.Pending) || r.op === JoinRowOperation.Flushed) &&\n r.deleted !== true,\n );\n return addedRows.map((r) => r.columns[otherColumnName]);\n }\n\n /** Adds an existing join row to this table. */\n addPreloadedRow(m2m: ManyToManyLike, id: number | undefined, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n // Treat any existing WIP change as source-of-truth, so leave it alone\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n }\n\n /** Look up/create our internal JoinRow psuedo-entities for the db rows. */\n async loadRows(tuples: [string, string][], dbRows: any[]): Promise<void> {\n const { em } = this.m2m.entity;\n const { columnName: column1, otherColumnName: column2, meta: meta1, otherMeta: meta2, otherEnum } = this.m2m;\n\n const oneIds: string[] = [];\n // Tagged ids for an entity other-side, or raw enum ids for an enum other-side.\n const twoVals: JoinColumnValue[] = [];\n for (const dbRow of dbRows) {\n oneIds.push(keyToTaggedId(meta1, dbRow[column1])!);\n twoVals.push(\n otherEnum ? (dbRow[column2] as number) : (em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!) as any),\n );\n }\n\n // Make sure we have entities in memory for all the joined-to tables. The enum side has no\n // entities to load; the entity sides do (and `twoVals` is re-resolved to entities below).\n await Promise.all([\n em.loadAll(meta1.cstr, oneIds),\n otherEnum\n ? Promise.resolve([])\n : em.loadAll(\n meta2!.cstr,\n dbRows.map((dbRow) => keyToTaggedId(meta2!, dbRow[column2])!),\n ),\n ]);\n\n // If we're doing a em.refresh/reload, we need to watch for rows that are no longer here. For an\n // enum other-side, only persisted rows are delete-candidates (pending in-memory adds are kept,\n // since `EnumCollection` relies on `JoinRows` to hold them rather than re-asserting on load).\n const existingRows = new Set<JoinRow>();\n for (const [columnName, id] of tuples) {\n const others = this.index.getOthers(columnName, em.getEntity(id)!);\n for (const row of others) if (!otherEnum || row.persisted) existingRows.add(row);\n }\n\n let i = 0;\n for (const dbRow of dbRows) {\n const e1 = em.getEntity(oneIds[i])!;\n const e2 = otherEnum ? (dbRow[column2] as number) : em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!)!;\n i++;\n let row = this.index.get(this.m2m, e1, e2);\n if (!row) {\n row = {\n op: JoinRowOperation.Completed,\n id: dbRow.id,\n persisted: true,\n columns: { [column1]: e1, [column2]: e2 },\n created_at: dbRow.created_at,\n };\n this.rows.push(row);\n this.index.add(this.m2m, e1, e2, row);\n } else {\n // If a placeholder row was created while a ManyToManyCollection was unloaded, and we find it during\n // a subsequent load/query, update its id to be what is in the database and mark it persisted.\n row.id = dbRow.id;\n row.persisted = true;\n // Mark this row as still valid\n existingRows.delete(row);\n }\n }\n\n // Mark all no-longer-there rows as deleted\n for (const row of existingRows) row.deleted = true;\n }\n\n getOthers(columnName: string, entity: Entity): JoinColumnValue[] {\n const others = this.index.getOthers(columnName, entity);\n if (others.length === 0) return [];\n const [c1, c2] = Object.keys(others[0].columns);\n const c = others[0].columns[c1] === entity ? c2 : c1;\n return others.filter((o) => !o.deleted).map((row) => row.columns[c]);\n }\n\n /** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */\n removeAllFor(columnName: string, entity: Entity): void {\n for (const row of this.index.getOthers(columnName, entity)) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Drops a single `(e1, e2)` row without queuing a flush, e.g. when mirroring another em's removal. */\n removePreloadedRow(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const row = this.index.get(m2m, e1, e2);\n if (row) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Scans our `rows` for newly-added/newly-deleted rows that need `INSERT`s/`UPDATE`s. */\n toTodo(): JoinRowTodo | undefined {\n const newRows = this.rows.filter((r) => !r.persisted && r.deleted !== true && r.op === \"pending\");\n const deletedRows = this.rows.filter((r) => r.persisted && r.deleted === true && r.op === \"pending\");\n if (newRows.length === 0 && deletedRows.length === 0) {\n return undefined;\n }\n return {\n m2m: this.m2m,\n newRows,\n deletedRows,\n resetAfterFlushed: () => {\n for (const row of this.rows) {\n if (row.op === JoinRowOperation.Pending || row.op === JoinRowOperation.Flushed)\n row.op = JoinRowOperation.Completed;\n }\n },\n // The driver flushes pure (int, int) FK pairs; resolve them here so it never has to know\n // whether a column points at an entity (use its id) or an enum (its value is already the id).\n dbValue: (row, columnName) => this.#dbValue(row, columnName),\n isNew: (row, columnName) => isNewColumn(row.columns[columnName]),\n };\n }\n\n get hasChanges() {\n return this.rows.some(({ op }) => op === JoinRowOperation.Pending || op === JoinRowOperation.Flushed);\n }\n\n /** The db int value for `row`'s `columnName`: an entity's id, or (for enums) the enum's id itself. */\n #dbValue(row: JoinRow, columnName: string): number {\n const value = row.columns[columnName];\n if (typeof value === \"number\") return value;\n const meta = columnName === this.m2m.columnName ? this.m2m.meta : this.m2m.otherMeta!;\n return keyToNumber(meta, value.idTagged)!;\n }\n\n /**\n * Invalidates caches & queues reactivity for a join-row change.\n *\n * The owning entity (`e1`) always reacts; the \"other\" side only reacts when it is an entity,\n * since enum other-sides have no `em`/reverse-field to keep in sync.\n */\n #reactToChange(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const { em } = this.m2m.entity;\n const api = getEmInternalApi(e1.em);\n api.isLoadedCache.resetIsLoaded(e1, m2m.fieldName);\n this.rm.queueDownstreamReactables(e1, m2m.fieldName);\n if (getBaseAndSelfMetas(e1).some((meta) => meta.config.__data.touchOnChange.has(m2m.fieldName))) {\n em.touch(e1);\n }\n if (!m2m.otherEnum) {\n const other = e2 as Entity;\n const otherFieldName = m2m.otherFieldName!;\n api.isLoadedCache.resetIsLoaded(other, otherFieldName);\n this.rm.queueDownstreamReactables(other, otherFieldName);\n if (getBaseAndSelfMetas(other).some((meta) => meta.config.__data.touchOnChange.has(otherFieldName))) {\n em.touch(other);\n }\n }\n }\n}\n\n/**\n * A \"psuedo-entity\" for a join row.\n *\n * We treat this as a special entity, i.e. it has two \"relations\" to each entity for the current\n * row, an optional surrogate `id` primary key, and an optional `created_at` column.\n *\n * These rows are immutable, i.e. once created we don't change either FK, and instead make\n * collection changes only by inserting new rows and deleting old rows.\n *\n * This makes the column1+column2 combination a composite key. For id-less join tables, that\n * composite is the actual primary key and `id` is always undefined.\n */\nexport interface JoinRow {\n /**\n * Whether our relation has been processed or not.\n *\n * - `pending` means we've not flushed it to the Database\n * - `flushed` means we've flushed but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `completed` means we've been flushed and `em.flush` has completed\n */\n op: JoinRowOperation;\n /** The surrogate key for id-ful join tables; always undefined for id-less tables. */\n id: number | undefined;\n /**\n * Whether this row exists (or is assumed to exist) in the database.\n *\n * This is orthogonal to `op` (the flush lifecycle) and is what distinguishes a pending insert\n * from a pending delete: a `pending` row that is `!persisted` is a pending INSERT (added in\n * memory, not yet in the db), while a `pending` row that is `persisted` is a pending DELETE\n * (in the db, marked `deleted`). `op` alone cannot tell these apart, because both inserts and\n * deletes walk the same `pending -> flushed -> completed` progression.\n *\n * We track this as its own flag rather than inferring it from `id` being set/unset, because\n * id-less join tables (whose PK is just the composite of the two FKs) never have an `id` — so\n * `id === undefined` would be ambiguous. `persisted` is the id-agnostic generalization of the\n * `id`-is-set check that id-ful tables historically relied on.\n *\n * It must survive add/remove/re-add sequences: e.g. loading a row (persisted), removing it\n * (pending delete), then re-adding it (`deleted` flipped back to false, `op` back to `pending`)\n * leaves a `pending && !deleted` row that looks identical to a fresh insert — but it is still in\n * the db, so a subsequent remove must issue a DELETE, which only `persisted` can tell us.\n */\n persisted: boolean;\n /** Maps each FK column to its value: an `Entity`, or (for `EnumCollection`s) an enum's numeric id. */\n columns: Record<string, JoinColumnValue>;\n created_at?: Date;\n deleted?: boolean;\n}\n\n/** An enum to track our insert/delete state progression. */\nexport enum JoinRowOperation {\n Pending = \"pending\",\n Flushed = \"flushed\",\n Completed = \"completed\",\n}\n\n/** Keep an in-memory index to avoid sequentially scanning `rows`. */\nclass ManyToManyIndex {\n private indexes: Record<string, Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>> = {};\n\n constructor(private readonly m2m: ManyToManyLike) {\n this.indexes[m2m.columnName] = new Map();\n this.indexes[m2m.otherColumnName] = new Map();\n }\n\n add(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue, value: JoinRow): void {\n // Store both e1+e2 => value and e2+e1 => value so we can do lookups from either side\n this.#doAdd(this.indexes[m2m.columnName], e1, e2, value);\n this.#doAdd(this.indexes[m2m.otherColumnName], e2, e1, value);\n }\n\n remove(value: JoinRow): void {\n const [[column1, e1], [column2, e2]] = Object.entries(value.columns);\n this.#doRemove(this.indexes[column1], e1, e2);\n this.#doRemove(this.indexes[column2], e2, e1);\n }\n\n get(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue): JoinRow | undefined {\n return this.indexes[m2m.columnName].get(e1)?.get(e2);\n }\n\n /** Cheat and use the index to return \"the other entities\" for `entity`. */\n getOthers(columnName: string, entity: JoinColumnValue): JoinRow[] {\n // It's empty m2m collection won't have any other entities, and so no index entries\n const map = this.indexes[columnName].get(entity);\n if (!map) return [];\n // Sort for a stable order regardless of how many batches contributed rows — the underlying\n // Map preserves insertion order, which depends on DataLoader timing and is non-deterministic\n // across processes. New rows (no key yet) sort last.\n const rows = Array.from(map.values());\n if (this.m2m.hasJoinTableId) {\n // Sort by join-row id.\n return rows.sort((a, b) => (a.id ?? Infinity) - (b.id ?? Infinity));\n }\n // Id-less tables have no surrogate id, so sort by the other side's id.\n const otherColumn = columnName === this.m2m.columnName ? this.m2m.otherColumnName : this.m2m.columnName;\n if (this.m2m.otherEnum && otherColumn === this.m2m.otherColumnName) {\n // The other side is an enum, so its column value is already its numeric id.\n return rows.sort((a, b) => (a.columns[otherColumn] as number) - (b.columns[otherColumn] as number));\n }\n const otherMeta = columnName === this.m2m.columnName ? this.m2m.otherMeta! : this.m2m.meta;\n const key = (r: JoinRow) => {\n const other = r.columns[otherColumn] as Entity;\n return other.isNewEntity ? Infinity : keyToNumber(otherMeta, other.id)!;\n };\n return rows.sort((a, b) => key(a) - key(b));\n }\n\n #doAdd(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n value: JoinRow,\n ): void {\n const map = index.get(e1) ?? new Map();\n if (map.size === 0) index.set(e1, map);\n map.set(e2, value);\n }\n\n #doRemove(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n ): void {\n index.get(e1)?.delete(e2);\n }\n}\n"],"mappings":";;;;;;AAyCA,SAAS,YAAY,OAAiC;CACpD,OAAO,OAAO,UAAU,YAAY,MAAM;AAC5C;;AAGA,IAAa,WAAb,MAAsB;CAQT;CACD;CAPV,OAAmC,CAAC;CACpC;CAEA,YAGE,KACA,IACA;EAFS,KAAA,MAAA;EACD,KAAA,KAAA;EAER,KAAK,QAAQ,IAAI,gBAAgB,GAAG;CACtC;;CAGA,OAAO,KAAqB,IAAY,IAA2B;EACjE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C,IAAI;EAC5E,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C,IAAI;EAC5E,MAAM,WAAW,KAAK,MAAM,IAAI,KAAK,IAAI,EAAE;EAC3C,IAAI,UAAU;GACZ,SAAS,UAAU;GACnB,SAAS,KAAA;EACX,OAAO;GACL,MAAM,MAAM;IACV,IAAA;IACA,IAAI,KAAA;IACJ,WAAW;IACX,SAA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iBAEjD,OAAO,KAAK,MAAM,GAAG,MAAO,EAAE,QAAQ,eAA2B,EAAE,QAAQ,YAAuB;EAEpG,MAAM,YAAY,eAAe,KAAK,IAAI,aAAa,KAAK,IAAI,YAAa,KAAK,IAAI;EACtF,MAAM,OAAO,MAAe;GAC1B,MAAM,QAAQ,EAAE,QAAQ;GACxB,OAAO,MAAM,cAAc,WAAW,YAAY,WAAW,MAAM,EAAE;EACvE;EACA,OAAO,KAAK,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC;CAC5C;CAEA,OACE,OACA,IACA,IACA,OACM;EACN,MAAM,MAAM,MAAM,IAAI,EAAE,qBAAK,IAAI,IAAI;EACrC,IAAI,IAAI,SAAS,GAAG,MAAM,IAAI,IAAI,GAAG;EACrC,IAAI,IAAI,IAAI,KAAK;CACnB;CAEA,UACE,OACA,IACA,IACM;EACN,MAAM,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE;CAC1B;AACF"}
|
|
1
|
+
{"version":3,"file":"JoinRows.js","names":[],"sources":["../../src/flush/JoinRows.ts"],"sourcesContent":["import type { Entity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, getBaseAndSelfMetas } from \"src/EntityMetadata.ts\";\nimport type { EnumMetadata } from \"src/EnumMetadata.ts\";\nimport type { JoinRowTodo } from \"src/flush/Todo.ts\";\nimport { keyToNumber, keyToTaggedId } from \"src/keys.ts\";\nimport type { ReactionsManager } from \"src/reactivity/ReactionsManager.ts\";\nimport { remove } from \"src/utils.ts\";\n\n/**\n * A simplified interface for ManyToManyCollection-like relations.\n *\n * Specifically lets ReactiveManyToMany & ReactiveManyToManyOtherSide use JoinRows\n * as if they were full-fledged m2m relations.\n *\n * The \"other\" side of the join table is usually a second entity, but for `EnumCollection`s\n * (i.e. `Publisher.logoColors`) it is an enum table; in that case `otherEnum` is set and the\n * other column's value is the enum's numeric id rather than an `Entity` (there is also no\n * `otherMeta`/`otherFieldName`, since enums have no reverse collection to keep in sync).\n */\nexport type ManyToManyLike = {\n entity: Entity;\n joinTableName: string;\n columnName: string;\n otherColumnName: string;\n fieldName: string;\n meta: EntityMetadata;\n /** Undefined when the other side is an enum. */\n otherFieldName?: string;\n /** Undefined when the other side is an enum. */\n otherMeta?: EntityMetadata;\n /** Set when the other side is an enum table, for mapping enum codes <-> their numeric ids. */\n otherEnum?: EnumMetadata<any, any, number>;\n /** Whether the join table has a surrogate `id` PK; if false the FK pair is the composite PK. */\n hasJoinTableId: boolean;\n};\n\n/** The value of a join row's column: an `Entity`, or an enum's numeric id for `EnumCollection`s. */\nexport type JoinColumnValue = Entity | number;\n\n/** Whether a join column points at a not-yet-inserted entity (enum ids are never \"new\"). */\nfunction isNewColumn(value: JoinColumnValue): boolean {\n return typeof value !== \"number\" && value.isNewEntity;\n}\n\n/** A small holder around m2m join rows, which we treat as psuedo-entities. */\nexport class JoinRows {\n // The in-memory rows for our m2m table.\n private readonly rows: JoinRow[] = [];\n private readonly index: ManyToManyIndex;\n\n constructor(\n // This could be either side of the m2m relation, depending on which is accessed first.\n // Regardless of which m2m side, we still have a single `JoinRows` instance in memory per m2m table.\n readonly m2m: ManyToManyLike,\n private rm: ReactionsManager,\n ) {\n this.index = new ManyToManyIndex(m2m);\n }\n\n /** Adds a new join row to this table. */\n addNew(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n if (!e1) throw new Error(`Cannot add a m2m row with an entity that is ${e1}`);\n if (!e2) throw new Error(`Cannot add a m2m row with an entity that is ${e2}`);\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n existing.deleted = false;\n existing.op = JoinRowOperation.Pending;\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: false,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Adds a new remove to this table. */\n addRemove(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n if (!existing.persisted) {\n // It was only added in-memory and never persisted, so just drop it\n remove(this.rows, existing);\n this.index.remove(existing);\n } else {\n existing.deleted = true;\n }\n existing.op = JoinRowOperation.Pending;\n } else {\n // We're removing against an unloaded collection, so assume the row exists in the database\n // (persisted: true) and queue a delete; the delete keys off the (col1, col2) composite.\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n deleted: true,\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Return any \"old values\" for a m2m collection that might need reactivity checks. */\n removedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n // I.e. if we did `t1.books.remove(b1)` find all join rows that have\n // `tag_id=t1`, are marked for deletion, and then `.map` them to the removed book.\n const removedRows = this.index.getOthers(m2m.columnName, e1).filter((r) => r.deleted);\n return removedRows.map((r) => r.columns[otherColumnName]);\n }\n\n addedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n const addedRows = this.index\n .getOthers(m2m.columnName, e1)\n .filter(\n (r) =>\n ((!r.persisted && r.op === JoinRowOperation.Pending) || r.op === JoinRowOperation.Flushed) &&\n r.deleted !== true,\n );\n return addedRows.map((r) => r.columns[otherColumnName]);\n }\n\n /** Adds an existing join row to this table. */\n addPreloadedRow(m2m: ManyToManyLike, id: number | undefined, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n // Treat any existing WIP change as source-of-truth, so leave it alone\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n }\n\n /** Look up/create our internal JoinRow psuedo-entities for the db rows. */\n async loadRows(tuples: [string, string][], dbRows: any[]): Promise<void> {\n const { em } = this.m2m.entity;\n const { columnName: column1, otherColumnName: column2, meta: meta1, otherMeta: meta2, otherEnum } = this.m2m;\n\n const oneIds: string[] = [];\n // Tagged ids for an entity other-side, or raw enum ids for an enum other-side.\n const twoVals: JoinColumnValue[] = [];\n for (const dbRow of dbRows) {\n oneIds.push(keyToTaggedId(meta1, dbRow[column1])!);\n twoVals.push(\n otherEnum ? (dbRow[column2] as number) : (em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!) as any),\n );\n }\n\n // Make sure we have entities in memory for all the joined-to tables. The enum side has no\n // entities to load; the entity sides do (and `twoVals` is re-resolved to entities below).\n await Promise.all([\n em.loadAll(meta1.cstr, oneIds),\n otherEnum\n ? Promise.resolve([])\n : em.loadAll(\n meta2!.cstr,\n dbRows.map((dbRow) => keyToTaggedId(meta2!, dbRow[column2])!),\n ),\n ]);\n\n // If we're doing a em.refresh/reload, we need to watch for rows that are no longer here. For an\n // enum other-side, only persisted rows are delete-candidates (pending in-memory adds are kept,\n // since `EnumCollection` relies on `JoinRows` to hold them rather than re-asserting on load).\n const existingRows = new Set<JoinRow>();\n for (const [columnName, id] of tuples) {\n const others = this.index.getOthers(columnName, em.getEntity(id)!);\n for (const row of others) if (!otherEnum || row.persisted) existingRows.add(row);\n }\n\n let i = 0;\n for (const dbRow of dbRows) {\n const e1 = em.getEntity(oneIds[i])!;\n const e2 = otherEnum ? (dbRow[column2] as number) : em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!)!;\n i++;\n let row = this.index.get(this.m2m, e1, e2);\n if (!row) {\n row = {\n op: JoinRowOperation.Completed,\n id: dbRow.id,\n persisted: true,\n columns: { [column1]: e1, [column2]: e2 },\n created_at: dbRow.created_at,\n };\n this.rows.push(row);\n this.index.add(this.m2m, e1, e2, row);\n } else {\n // If a placeholder row was created while a ManyToManyCollection was unloaded, and we find it during\n // a subsequent load/query, update its id to be what is in the database and mark it persisted.\n row.id = dbRow.id;\n row.persisted = true;\n // Mark this row as still valid\n existingRows.delete(row);\n }\n }\n\n // Mark all no-longer-there rows as deleted\n for (const row of existingRows) row.deleted = true;\n }\n\n getOthers(columnName: string, entity: Entity): JoinColumnValue[] {\n const others = this.index.getOthers(columnName, entity);\n if (others.length === 0) return [];\n const [c1, c2] = Object.keys(others[0].columns);\n // Self-referencing rows can contain the same entity in both columns, so identity cannot tell the sides apart.\n const c = c1 === columnName ? c2 : c1;\n return others.filter((o) => !o.deleted).map((row) => row.columns[c]);\n }\n\n /** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */\n removeAllFor(columnName: string, entity: Entity): void {\n for (const row of this.index.getOthers(columnName, entity)) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Drops a single `(e1, e2)` row without queuing a flush, e.g. when mirroring another em's removal. */\n removePreloadedRow(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const row = this.index.get(m2m, e1, e2);\n if (row) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Scans our `rows` for newly-added/newly-deleted rows that need `INSERT`s/`UPDATE`s. */\n toTodo(): JoinRowTodo | undefined {\n const newRows = this.rows.filter((r) => !r.persisted && r.deleted !== true && r.op === \"pending\");\n const deletedRows = this.rows.filter((r) => r.persisted && r.deleted === true && r.op === \"pending\");\n if (newRows.length === 0 && deletedRows.length === 0) {\n return undefined;\n }\n return {\n m2m: this.m2m,\n newRows,\n deletedRows,\n resetAfterFlushed: () => {\n for (const row of this.rows) {\n if (row.op === JoinRowOperation.Pending || row.op === JoinRowOperation.Flushed)\n row.op = JoinRowOperation.Completed;\n }\n },\n // The driver flushes pure (int, int) FK pairs; resolve them here so it never has to know\n // whether a column points at an entity (use its id) or an enum (its value is already the id).\n dbValue: (row, columnName) => this.#dbValue(row, columnName),\n isNew: (row, columnName) => isNewColumn(row.columns[columnName]),\n };\n }\n\n get hasChanges() {\n return this.rows.some(({ op }) => op === JoinRowOperation.Pending || op === JoinRowOperation.Flushed);\n }\n\n /** The db int value for `row`'s `columnName`: an entity's id, or (for enums) the enum's id itself. */\n #dbValue(row: JoinRow, columnName: string): number {\n const value = row.columns[columnName];\n if (typeof value === \"number\") return value;\n const meta = columnName === this.m2m.columnName ? this.m2m.meta : this.m2m.otherMeta!;\n return keyToNumber(meta, value.idTagged)!;\n }\n\n /**\n * Invalidates caches & queues reactivity for a join-row change.\n *\n * The owning entity (`e1`) always reacts; the \"other\" side only reacts when it is an entity,\n * since enum other-sides have no `em`/reverse-field to keep in sync.\n */\n #reactToChange(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const { em } = this.m2m.entity;\n const api = getEmInternalApi(e1.em);\n api.isLoadedCache.resetIsLoaded(e1, m2m.fieldName);\n this.rm.queueDownstreamReactables(e1, m2m.fieldName);\n if (getBaseAndSelfMetas(e1).some((meta) => meta.config.__data.touchOnChange.has(m2m.fieldName))) {\n em.touch(e1);\n }\n if (!m2m.otherEnum) {\n const other = e2 as Entity;\n const otherFieldName = m2m.otherFieldName!;\n api.isLoadedCache.resetIsLoaded(other, otherFieldName);\n this.rm.queueDownstreamReactables(other, otherFieldName);\n if (getBaseAndSelfMetas(other).some((meta) => meta.config.__data.touchOnChange.has(otherFieldName))) {\n em.touch(other);\n }\n }\n }\n}\n\n/**\n * A \"psuedo-entity\" for a join row.\n *\n * We treat this as a special entity, i.e. it has two \"relations\" to each entity for the current\n * row, an optional surrogate `id` primary key, and an optional `created_at` column.\n *\n * These rows are immutable, i.e. once created we don't change either FK, and instead make\n * collection changes only by inserting new rows and deleting old rows.\n *\n * This makes the column1+column2 combination a composite key. For id-less join tables, that\n * composite is the actual primary key and `id` is always undefined.\n */\nexport interface JoinRow {\n /**\n * Whether our relation has been processed or not.\n *\n * - `pending` means we've not flushed it to the Database\n * - `flushed` means we've flushed but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `completed` means we've been flushed and `em.flush` has completed\n */\n op: JoinRowOperation;\n /** The surrogate key for id-ful join tables; always undefined for id-less tables. */\n id: number | undefined;\n /**\n * Whether this row exists (or is assumed to exist) in the database.\n *\n * This is orthogonal to `op` (the flush lifecycle) and is what distinguishes a pending insert\n * from a pending delete: a `pending` row that is `!persisted` is a pending INSERT (added in\n * memory, not yet in the db), while a `pending` row that is `persisted` is a pending DELETE\n * (in the db, marked `deleted`). `op` alone cannot tell these apart, because both inserts and\n * deletes walk the same `pending -> flushed -> completed` progression.\n *\n * We track this as its own flag rather than inferring it from `id` being set/unset, because\n * id-less join tables (whose PK is just the composite of the two FKs) never have an `id` — so\n * `id === undefined` would be ambiguous. `persisted` is the id-agnostic generalization of the\n * `id`-is-set check that id-ful tables historically relied on.\n *\n * It must survive add/remove/re-add sequences: e.g. loading a row (persisted), removing it\n * (pending delete), then re-adding it (`deleted` flipped back to false, `op` back to `pending`)\n * leaves a `pending && !deleted` row that looks identical to a fresh insert — but it is still in\n * the db, so a subsequent remove must issue a DELETE, which only `persisted` can tell us.\n */\n persisted: boolean;\n /** Maps each FK column to its value: an `Entity`, or (for `EnumCollection`s) an enum's numeric id. */\n columns: Record<string, JoinColumnValue>;\n created_at?: Date;\n deleted?: boolean;\n}\n\n/** An enum to track our insert/delete state progression. */\nexport enum JoinRowOperation {\n Pending = \"pending\",\n Flushed = \"flushed\",\n Completed = \"completed\",\n}\n\n/** Keep an in-memory index to avoid sequentially scanning `rows`. */\nclass ManyToManyIndex {\n private indexes: Record<string, Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>> = {};\n\n constructor(private readonly m2m: ManyToManyLike) {\n this.indexes[m2m.columnName] = new Map();\n this.indexes[m2m.otherColumnName] = new Map();\n }\n\n add(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue, value: JoinRow): void {\n // Store both e1+e2 => value and e2+e1 => value so we can do lookups from either side\n this.#doAdd(this.indexes[m2m.columnName], e1, e2, value);\n this.#doAdd(this.indexes[m2m.otherColumnName], e2, e1, value);\n }\n\n remove(value: JoinRow): void {\n const [[column1, e1], [column2, e2]] = Object.entries(value.columns);\n this.#doRemove(this.indexes[column1], e1, e2);\n this.#doRemove(this.indexes[column2], e2, e1);\n }\n\n get(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue): JoinRow | undefined {\n return this.indexes[m2m.columnName].get(e1)?.get(e2);\n }\n\n /** Cheat and use the index to return \"the other entities\" for `entity`. */\n getOthers(columnName: string, entity: JoinColumnValue): JoinRow[] {\n // It's empty m2m collection won't have any other entities, and so no index entries\n const map = this.indexes[columnName].get(entity);\n if (!map) return [];\n // Sort for a stable order regardless of how many batches contributed rows — the underlying\n // Map preserves insertion order, which depends on DataLoader timing and is non-deterministic\n // across processes. New rows (no key yet) sort last.\n const rows = Array.from(map.values());\n if (this.m2m.hasJoinTableId) {\n // Sort by join-row id.\n return rows.sort((a, b) => (a.id ?? Infinity) - (b.id ?? Infinity));\n }\n // Id-less tables have no surrogate id, so sort by the other side's id.\n const otherColumn = columnName === this.m2m.columnName ? this.m2m.otherColumnName : this.m2m.columnName;\n if (this.m2m.otherEnum && otherColumn === this.m2m.otherColumnName) {\n // The other side is an enum, so its column value is already its numeric id.\n return rows.sort((a, b) => (a.columns[otherColumn] as number) - (b.columns[otherColumn] as number));\n }\n const otherMeta = columnName === this.m2m.columnName ? this.m2m.otherMeta! : this.m2m.meta;\n const key = (r: JoinRow) => {\n const other = r.columns[otherColumn] as Entity;\n return other.isNewEntity ? Infinity : keyToNumber(otherMeta, other.id)!;\n };\n return rows.sort((a, b) => key(a) - key(b));\n }\n\n #doAdd(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n value: JoinRow,\n ): void {\n const map = index.get(e1) ?? new Map();\n if (map.size === 0) index.set(e1, map);\n map.set(e2, value);\n }\n\n #doRemove(\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AI,EAAE,CAAC,EAAE,OAAO,EAAE;CAC1B;AACF"}
|
|
@@ -107,6 +107,10 @@ var ReactiveManyToManyImpl = class extends require_relations_AbstractRelationImp
|
|
|
107
107
|
get get() {
|
|
108
108
|
return this.#doGet({ withDeleted: false });
|
|
109
109
|
}
|
|
110
|
+
/** Returns the stored membership without deriving or queuing join-row changes. */
|
|
111
|
+
current() {
|
|
112
|
+
return this.#loaded ?? require_EntityManager.getEmInternalApi(this.entity.em).joinRows(this).getOthers(this.columnName, this.entity);
|
|
113
|
+
}
|
|
110
114
|
set() {
|
|
111
115
|
require_utils.fail(`Cannot set ${this.entity}.${this.fieldName} ReactiveManyToMany directly.`);
|
|
112
116
|
}
|
|
@@ -158,7 +162,20 @@ var ReactiveManyToManyImpl = class extends require_relations_AbstractRelationImp
|
|
|
158
162
|
get isPreloaded() {
|
|
159
163
|
return false;
|
|
160
164
|
}
|
|
161
|
-
|
|
165
|
+
/** Installs materialized membership without deriving, e.g. when RunPlugin mirrors a flush. */
|
|
166
|
+
preload() {
|
|
167
|
+
if (this.entity.isNewEntity) return;
|
|
168
|
+
const api = require_EntityManager.getEmInternalApi(this.entity.em);
|
|
169
|
+
const preloaded = api.getPreloadedRelation(this.entity.idTagged, this.fieldName);
|
|
170
|
+
if (preloaded) {
|
|
171
|
+
this.#loaded = preloaded;
|
|
172
|
+
this.#loadedMode = "ref";
|
|
173
|
+
this.#isJoinTableLoaded = true;
|
|
174
|
+
this.#isLoaded = true;
|
|
175
|
+
this.#isCached = false;
|
|
176
|
+
api.isLoadedCache.add(this);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
162
179
|
import(other, _, mapEntities) {
|
|
163
180
|
this.#loaded = mapEntities(other.#loaded);
|
|
164
181
|
this.#isJoinTableLoaded = this.entity.isNewEntity;
|