import invariant from 'invariant'; import type { IEntityClass } from './Entity.ts'; import type { CacheAdapterFlavor, DatabaseAdapterFlavor } from './EntityCompanionProvider.ts'; import { RESERVED_ENTITY_COUNT_QUERY_ALIAS } from './EntityDatabaseAdapter.ts'; import type { EntityFieldDefinition } from './EntityFieldDefinition.ts'; import type { SerializedCompositeFieldHolder } from './internal/CompositeFieldHolder.ts'; import { CompositeFieldHolder } from './internal/CompositeFieldHolder.ts'; import { invertMap, mapMap, reduceMap } from './utils/collections/maps.ts'; /** * A composite field is an unordered set of fields by which entities can be loaded in a batched * and (optionally) cached manner akin to how normal fieldName loads are batched and (optionally) cached. */ export type EntityCompositeField> = readonly (keyof TFields)[]; /** * Specification of composite field for an entity and whether it can be cached. */ export type EntityCompositeFieldDefinition> = { /** * The composite field. */ compositeField: EntityCompositeField; /** * Whether or not to cache loaded instances of the entity by this composite field. The column names in * the composite field are used to derive a cache key for the cache entry. If true, the set of columns * must be able uniquely identify the entity and the database must have a unique constraint on the * set of columns. */ cache: boolean; }; /** * A composite field value is a mapping of fields to values for a composite field. */ export type EntityCompositeFieldValue< TFields extends Record, TCompositeField extends EntityCompositeField, > = Record>; /** * Helper class to validate and store composite field information. */ export class CompositeFieldInfo< TFields extends Record, TIDField extends keyof TFields, > { private readonly compositeFieldInfoMap: ReadonlyMap< SerializedCompositeFieldHolder, { compositeFieldHolder: CompositeFieldHolder; cache: boolean; } >; constructor(compositeFieldsDefinitions: EntityCompositeFieldDefinition[]) { this.compositeFieldInfoMap = new Map( compositeFieldsDefinitions.map((keyDefinition) => { invariant( keyDefinition.compositeField.length >= 2, 'Composite field must have at least two sub-fields', ); invariant( keyDefinition.compositeField.length === new Set(keyDefinition.compositeField).size, 'Composite field must have unique sub-fields', ); const compositeFieldHolder = new CompositeFieldHolder( keyDefinition.compositeField, ); return [ compositeFieldHolder.serialize(), { compositeFieldHolder, cache: keyDefinition.cache ?? false }, ]; }), ); } public getCompositeFieldHolderForCompositeField( compositeField: EntityCompositeField, ): CompositeFieldHolder | undefined { return this.compositeFieldInfoMap.get( new CompositeFieldHolder(compositeField).serialize(), )?.compositeFieldHolder; } public getAllCompositeFieldHolders(): readonly CompositeFieldHolder[] { return Array.from(this.compositeFieldInfoMap.values()).map((v) => v.compositeFieldHolder); } public canCacheCompositeField(compositeField: EntityCompositeField): boolean { const compositeFieldInfo = this.compositeFieldInfoMap.get( new CompositeFieldHolder(compositeField).serialize(), ); invariant( compositeFieldInfo, `Composite field (${compositeField.join(',')}) not found in entity configuration`, ); return compositeFieldInfo.cache; } } /** * The data storage configuration for a type of Entity. Contains information relating to IDs, * cachable fields, field mappings, and types of cache and database adapter. */ export class EntityConfiguration< TFields extends Record, TIDField extends keyof TFields, > { readonly idField: TIDField; readonly tableName: string; readonly cacheableKeys: ReadonlySet; readonly compositeFieldInfo: CompositeFieldInfo; readonly cacheKeyVersion: number; readonly inboundEdges: IEntityClass[]; readonly schema: ReadonlyMap>; readonly entityToDBFieldsKeyMapping: ReadonlyMap; readonly dbToEntityFieldsKeyMapping: ReadonlyMap; readonly databaseAdapterFlavor: DatabaseAdapterFlavor; readonly cacheAdapterFlavor: CacheAdapterFlavor; constructor({ idField, tableName, schema, inboundEdges = [], cacheKeyVersion = 0, compositeFieldDefinitions, databaseAdapterFlavor, cacheAdapterFlavor, }: { /** * The field used to identify this entity. Must be a unique field in the table. */ idField: TIDField; /** * The name of the table where entities of this type are stored. */ tableName: string; /** * Map from each entity field to an EntityFieldDefinition specifying information about the field. */ schema: Omit>, TIDField> & Record>; /** * List of other entity types that reference this type in EntityFieldDefinition associations. */ inboundEdges?: IEntityClass[]; /** * Cache key version for this entity type. Should be bumped when a field is added to, removed from, or changed * in this entity and the underlying database table. */ cacheKeyVersion?: number; /** * Composite field definitions for this entity. */ compositeFieldDefinitions?: EntityCompositeFieldDefinition[]; /** * Backing database and transaction type for this entity. */ databaseAdapterFlavor: DatabaseAdapterFlavor; /** * Cache system for this entity. */ cacheAdapterFlavor: CacheAdapterFlavor; }) { this.idField = idField; this.tableName = tableName; this.cacheKeyVersion = cacheKeyVersion; this.databaseAdapterFlavor = databaseAdapterFlavor; this.cacheAdapterFlavor = cacheAdapterFlavor; this.inboundEdges = inboundEdges; // external schema is a Record to typecheck that all fields have FieldDefinitions, // but internally the most useful representation is a map for lookups this.schema = this.validateSchemaMap(new Map(Object.entries(schema))); this.cacheableKeys = EntityConfiguration.computeCacheableKeys(this.schema); this.compositeFieldInfo = new CompositeFieldInfo(compositeFieldDefinitions ?? []); this.entityToDBFieldsKeyMapping = EntityConfiguration.computeEntityToDBFieldsKeyMapping( this.schema, ); this.dbToEntityFieldsKeyMapping = invertMap(this.entityToDBFieldsKeyMapping); } private validateSchemaMap( schemaMap: ReadonlyMap>, ): ReadonlyMap> { for (const disallowedFieldName of Object.getOwnPropertyNames(Object.prototype)) { if (schemaMap.has(disallowedFieldName)) { throw new Error( `Entity field name not allowed to prevent conflicts with standard Object prototype fields: ${disallowedFieldName}`, ); } } // check for column named RESERVED_ENTITY_COUNT_QUERY_ALIAS which is used for count queries and would cause issues if used as a column name for an entity field for (const [fieldName, fieldDefinition] of schemaMap) { if (fieldDefinition.columnName === RESERVED_ENTITY_COUNT_QUERY_ALIAS) { throw new Error( `Entity field "${String(fieldName)}" has disallowed column name "${RESERVED_ENTITY_COUNT_QUERY_ALIAS}" which is reserved for count queries. Choose a different column name.`, ); } } return schemaMap; } private static computeCacheableKeys>( schema: ReadonlyMap>, ): ReadonlySet { return reduceMap( schema, (acc, v, k) => { if (v.cache) { acc.add(k); } return acc; }, new Set(), ); } private static computeEntityToDBFieldsKeyMapping( schema: ReadonlyMap>, ): ReadonlyMap { return mapMap(schema, (v) => v.columnName); } }