@exogee/graphweaver-mikroorm 2.3.0 → 2.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/introspection/generate.ts"],
4
- "sourcesContent": ["import { DatabaseSchema, AbstractSqlPlatform, DatabaseTable } from '@mikro-orm/knex';\nimport {\n\tEntityMetadata,\n\tEntityProperty,\n\tNamingStrategy,\n\tReferenceKind,\n\tUtils,\n} from '@mikro-orm/core';\nimport pluralize from 'pluralize';\n\nimport { ConnectionManager, ConnectionOptions, DatabaseType } from '../database';\nimport {\n\tDataEntityFile,\n\tDataEntityIndexFile,\n\tDataSourceIndexFile,\n\tSchemaEntityFile,\n\tSchemaIndexFile,\n\tDatabaseFile,\n} from './files';\nimport { pascalToCamelCaseString } from './utils';\n\nconst CONNECTION_MANAGER_ID = 'generate';\n\nexport class IntrospectionError extends Error {\n\tprotected type: string;\n\tconstructor(\n\t\tprotected title = '',\n\t\tmessage = ''\n\t) {\n\t\tsuper(message);\n\t\tthis.type = 'IntrospectionError';\n\t\tthis.title = title;\n\t\tthis.message = message;\n\t}\n}\n\nconst hasErrorMessage = (error: any): error is { message: string } => error.message;\n\nconst generateBidirectionalRelations = (metadata: EntityMetadata[]): void => {\n\tconst nonPrimaryKeyReferenceErrors: string[] = [];\n\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tfor (const prop of meta.relations) {\n\t\t\tif (!prop.name.includes('Inverse')) {\n\t\t\t\tconst targetMeta = metadata.find((m) => m.className === prop.type);\n\t\t\t\tconst referencedTablePrimaryKeys = Utils.flatten(\n\t\t\t\t\t(targetMeta?.getPrimaryProps() ?? []).map((pk) => pk.fieldNames)\n\t\t\t\t);\n\n\t\t\t\t// Check any props that actually have fields in the database to store keys in for references to non-primary keys.\n\t\t\t\tif (prop.fieldNames?.length) {\n\t\t\t\t\tfor (const referencedColumn of prop.referencedColumnNames) {\n\t\t\t\t\t\tif (!referencedTablePrimaryKeys.includes(referencedColumn)) {\n\t\t\t\t\t\t\tnonPrimaryKeyReferenceErrors.push(\n\t\t\t\t\t\t\t\t` - Relationship between ${meta.className}.${prop.fieldNames.join(', ')} and ${targetMeta?.className}.${referencedColumn} is not supported.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst newProp = {\n\t\t\t\t\tname: prop.name + 'Inverse',\n\t\t\t\t\ttype: meta.className,\n\t\t\t\t\tjoinColumns: prop.fieldNames,\n\t\t\t\t\treferencedTableName: meta.tableName,\n\t\t\t\t\treferencedColumnNames: referencedTablePrimaryKeys,\n\t\t\t\t\tmappedBy: prop.name,\n\t\t\t\t} as EntityProperty;\n\n\t\t\t\t// Add reference to the inverse entity\n\t\t\t\tconst inverseMeta = metadata.find((m) => m.className === meta.className);\n\t\t\t\tconst inverseProp = inverseMeta?.props.find((p) => p.name === newProp.mappedBy);\n\t\t\t\tif (inverseProp) inverseProp.inversedBy = newProp.name;\n\n\t\t\t\tif (prop.kind === ReferenceKind.MANY_TO_ONE) {\n\t\t\t\t\tconst name = pascalToCamelCaseString(meta.className);\n\t\t\t\t\tnewProp.name = pluralize(name);\n\t\t\t\t\tnewProp.kind = ReferenceKind.ONE_TO_MANY;\n\t\t\t\t} else if (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.mappedBy) {\n\t\t\t\t\tnewProp.kind = ReferenceKind.ONE_TO_ONE;\n\t\t\t\t\tnewProp.nullable = true;\n\t\t\t\t} else if (prop.kind === ReferenceKind.MANY_TO_MANY && !prop.mappedBy) {\n\t\t\t\t\tconst name = pascalToCamelCaseString(meta.className);\n\t\t\t\t\tnewProp.name = pluralize(name);\n\t\t\t\t\tnewProp.kind = ReferenceKind.MANY_TO_MANY;\n\t\t\t\t} else {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\ttargetMeta?.addProperty(newProp);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (nonPrimaryKeyReferenceErrors.length) {\n\t\tthrow new IntrospectionError(\n\t\t\t`Unsupported Relationship${nonPrimaryKeyReferenceErrors.length === 1 ? '' : 's'} Detected`,\n\t\t\t`\\n${nonPrimaryKeyReferenceErrors.join('\\n')}\\n\\nForeign keys in Graphweaver currently need to reference the primary key of the other table.`\n\t\t);\n\t}\n};\n\nconst detectManyToManyRelations = (metadata: EntityMetadata[]) => {\n\tfor (const meta of metadata) {\n\t\tif (\n\t\t\tmeta.compositePK && // needs to have composite PK\n\t\t\tmeta.primaryKeys.length === meta.relations.length && // all relations are PKs\n\t\t\tmeta.relations.length === 2 && // there are exactly two relation properties\n\t\t\tmeta.relations.length === meta.props.length && // all properties are relations\n\t\t\tmeta.relations.every((prop) => prop.kind === ReferenceKind.MANY_TO_ONE) // all relations are m:1\n\t\t) {\n\t\t\tmeta.pivotTable = true;\n\t\t\tconst owner = metadata.find((m) => m.className === meta.relations[0].type);\n\t\t\tif (!owner) throw new Error('No Owner');\n\t\t\tconst name = pascalToCamelCaseString(meta.relations?.[1]?.type);\n\t\t\towner.addProperty({\n\t\t\t\tname: pluralize(name),\n\t\t\t\tkind: ReferenceKind.MANY_TO_MANY,\n\t\t\t\tpivotTable: meta.tableName,\n\t\t\t\ttype: meta.relations[1].type,\n\t\t\t\tjoinColumns: meta.relations[0].fieldNames,\n\t\t\t\tinverseJoinColumns: meta.relations[1].fieldNames,\n\t\t\t} as EntityProperty);\n\t\t}\n\t}\n};\n\nconst generateIdentifiedReferences = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tfor (const prop of meta.relations) {\n\t\t\tif ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {\n\t\t\t\tconst name = pascalToCamelCaseString(prop.type);\n\t\t\t\tprop.name = pluralize.singular(name);\n\t\t\t\tprop.ref = true;\n\t\t\t}\n\t\t}\n\t}\n};\n\nconst generateSingularTypeReferences = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tmeta.className = pluralize.singular(meta.className);\n\t\tfor (const prop of meta.relations) {\n\t\t\tprop.type = pluralize.singular(prop.type);\n\t\t}\n\t}\n};\n\n// Convert properties like FirstName to firstName\nconst convertToCamelCasePropertyNames = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tconst props = Object.values(meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tprop.name = pascalToCamelCaseString(prop.name);\n\t\t});\n\t}\n};\n\nconst assertUniqueForeignKeys = (table: DatabaseTable): void => {\n\tconst uniqueForeignKeys = new Set();\n\tconst definedForeignKeys = Object.values(table.getForeignKeys());\n\n\tfor (const foreignKey of definedForeignKeys) {\n\t\tconst { localTableName, referencedTableName, columnNames, referencedColumnNames } = foreignKey;\n\t\tconst serializedValue = JSON.stringify({\n\t\t\tlocalTableName,\n\t\t\tcolumnNames: columnNames.sort(),\n\t\t\treferencedTableName,\n\t\t\treferencedColumnNames: referencedColumnNames.sort(),\n\t\t});\n\n\t\tif (uniqueForeignKeys.has(serializedValue)) {\n\t\t\tthrow new Error(\n\t\t\t\t`\\n\\nImport Failed: Duplicate foreign keys detected on column/s (${columnNames.toString()}) in table \"${\n\t\t\t\t\ttable.name\n\t\t\t\t}\".`\n\t\t\t);\n\t\t}\n\n\t\tuniqueForeignKeys.add(serializedValue);\n\t}\n};\n\nconst convertSchemaToMetadata = async (\n\tschema: DatabaseSchema,\n\tplatform: AbstractSqlPlatform,\n\tnamingStrategy: NamingStrategy\n) => {\n\tconst helper = platform.getSchemaHelper();\n\n\tif (!helper) throw new Error('cannot connect to database');\n\n\tconst metadata = schema\n\t\t.getTables()\n\t\t.sort((a, b) => a.name.localeCompare(b.name))\n\t\t.map((table) => {\n\t\t\tassertUniqueForeignKeys(table);\n\t\t\treturn table.getEntityDeclaration(namingStrategy, helper, 'never');\n\t\t});\n\n\tif (metadata.length === 0) {\n\t\tthrow new IntrospectionError(\n\t\t\t`Warning: No tables found, this database is empty.`,\n\t\t\t`Make sure you have tables in this database and then try again.`\n\t\t);\n\t}\n\n\tconvertToCamelCasePropertyNames(metadata);\n\tdetectManyToManyRelations(metadata);\n\tgenerateIdentifiedReferences(metadata);\n\tgenerateBidirectionalRelations(metadata);\n\tgenerateSingularTypeReferences(metadata);\n\n\treturn metadata;\n};\n\nconst openConnection = async (type: DatabaseType, options: ConnectionOptions) => {\n\t// eslint-disable-next-line @typescript-eslint/no-var-requires\n\tconst module = require(`@mikro-orm/${type}`);\n\tconst PLATFORMS = {\n\t\tmysql: 'MySqlDriver',\n\t\tpostgresql: 'PostgreSqlDriver',\n\t\tsqlite: 'SqliteDriver',\n\t};\n\tawait ConnectionManager.connect(CONNECTION_MANAGER_ID, {\n\t\tmikroOrmConfig: {\n\t\t\tdriver: module[PLATFORMS[type]],\n\t\t\t...options.mikroOrmConfig,\n\t\t},\n\t});\n};\n\nconst closeConnection = async () => {\n\tconsole.log('Closing database connection...');\n\tawait ConnectionManager.close(CONNECTION_MANAGER_ID);\n\tconsole.log('Database connection closed.');\n};\n\ntype File =\n\t| DataEntityFile\n\t| SchemaEntityFile\n\t| SchemaIndexFile\n\t| DataEntityIndexFile\n\t| DataSourceIndexFile\n\t| DatabaseFile;\n\nexport const generate = async (databaseType: DatabaseType, options: ConnectionOptions) => {\n\ttry {\n\t\tawait openConnection(databaseType, options);\n\n\t\tconst database = ConnectionManager.database(CONNECTION_MANAGER_ID);\n\t\tif (!database)\n\t\t\tthrow new IntrospectionError(\n\t\t\t\t`Warning: Unable to connect to database.`,\n\t\t\t\t'Please check the connection settings and try again'\n\t\t\t);\n\n\t\tconst config = database.em.config;\n\t\tconst driver = database.em.getDriver();\n\t\tconst platform = driver.getPlatform();\n\t\tconst namingStrategy = config.getNamingStrategy();\n\t\tconst connection = driver.getConnection();\n\n\t\tconsole.log('Fetching database schema...');\n\t\tconst schema = await DatabaseSchema.create(connection, platform, config);\n\t\tconsole.log('Building metadata...');\n\t\tconst metadata = await convertSchemaToMetadata(schema, platform, namingStrategy);\n\n\t\t// Build a lookup for efficient cross-referencing later.\n\t\tconst entityLookup = new Map<string, EntityMetadata<any>>();\n\t\tfor (const meta of metadata) {\n\t\t\tentityLookup.set(meta.className, meta);\n\t\t}\n\n\t\tconst source: File[] = [];\n\n\t\tconst summaryOfEntities: { name: string; entityFilePath: string; schemaFilePath: string }[] =\n\t\t\t[];\n\n\t\tfor (const meta of metadata) {\n\t\t\tif (!meta.pivotTable) {\n\t\t\t\tconst dataEntityFile = new DataEntityFile(meta, namingStrategy, platform, databaseType);\n\t\t\t\tconst schemaEntityFile = new SchemaEntityFile(meta, namingStrategy, platform, entityLookup);\n\t\t\t\tsource.push(dataEntityFile, schemaEntityFile);\n\t\t\t\tsummaryOfEntities.push({\n\t\t\t\t\tname: meta.className,\n\t\t\t\t\tentityFilePath: `${dataEntityFile.getBasePath()}${dataEntityFile.getBaseName()}`,\n\t\t\t\t\tschemaFilePath: `${schemaEntityFile.getBasePath()}${schemaEntityFile.getBaseName()}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Export all the entities from the data source directory\n\t\tsource.push(new DataEntityIndexFile(metadata, databaseType));\n\t\t// Export the data source from the entities directory\n\t\tsource.push(new DataSourceIndexFile(databaseType));\n\t\t// Export the data source from the entities directory\n\t\tsource.push(new SchemaIndexFile(metadata));\n\t\t// Export the database connection to its own file\n\t\tsource.push(new DatabaseFile(databaseType, options));\n\n\t\tconst files = source.map((file) => {\n\t\t\treturn {\n\t\t\t\tpath: file.getBasePath(),\n\t\t\t\tname: file.getBaseName(),\n\t\t\t\tcontents: file.generate(),\n\t\t\t\tneedOverwriteWarning: !![DatabaseFile, SchemaIndexFile].some((cls) => file instanceof cls),\n\t\t\t};\n\t\t});\n\n\t\tawait closeConnection();\n\n\t\tconsole.log('\\nImport Summary:');\n\t\tconsole.table(summaryOfEntities);\n\t\tconsole.log(\n\t\t\t`\\nImported ${summaryOfEntities.length} entities, creating the above files in your Graphweaver project. \\n`\n\t\t);\n\n\t\treturn files;\n\t} catch (err) {\n\t\tif (err instanceof IntrospectionError) throw err;\n\n\t\tconsole.error('Got error during introspection:');\n\t\tconsole.error(err);\n\n\t\tthrow new IntrospectionError(\n\t\t\t`Warning: Unable to connect to database.`,\n\t\t\thasErrorMessage(err) ? err.message : 'Please check the connection settings and try again'\n\t\t);\n\t}\n};\n"],
4
+ "sourcesContent": ["import { DatabaseSchema, AbstractSqlPlatform, DatabaseTable } from '@mikro-orm/knex';\nimport {\n\tEntityMetadata,\n\tEntityProperty,\n\tNamingStrategy,\n\tReferenceKind,\n\tUtils,\n} from '@mikro-orm/core';\nimport pluralize from 'pluralize';\n\nimport { ConnectionManager, ConnectionOptions, DatabaseType } from '../database';\nimport {\n\tDataEntityFile,\n\tDataEntityIndexFile,\n\tDataSourceIndexFile,\n\tSchemaEntityFile,\n\tSchemaIndexFile,\n\tDatabaseFile,\n} from './files';\nimport { pascalToCamelCaseString } from './utils';\n\nconst CONNECTION_MANAGER_ID = 'generate';\n\nexport class IntrospectionError extends Error {\n\tprotected type: string;\n\tconstructor(\n\t\tprotected title = '',\n\t\tmessage = ''\n\t) {\n\t\tsuper(message);\n\t\tthis.type = 'IntrospectionError';\n\t\tthis.title = title;\n\t\tthis.message = message;\n\t}\n}\n\nconst hasErrorMessage = (error: any): error is { message: string } => error.message;\n\nconst generateBidirectionalRelations = (metadata: EntityMetadata[]): void => {\n\tconst nonPrimaryKeyReferenceErrors: string[] = [];\n\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tfor (const prop of meta.relations) {\n\t\t\tif (!prop.name.includes('Inverse')) {\n\t\t\t\tconst targetMeta = metadata.find((m) => m.className === prop.type);\n\t\t\t\tconst referencedTablePrimaryKeys = Utils.flatten(\n\t\t\t\t\t(targetMeta?.getPrimaryProps() ?? []).map((pk) => pk.fieldNames)\n\t\t\t\t);\n\n\t\t\t\t// Check any props that actually have fields in the database to store keys in for references to non-primary keys.\n\t\t\t\tif (prop.fieldNames?.length) {\n\t\t\t\t\tfor (const referencedColumn of prop.referencedColumnNames) {\n\t\t\t\t\t\tif (!referencedTablePrimaryKeys.includes(referencedColumn)) {\n\t\t\t\t\t\t\tnonPrimaryKeyReferenceErrors.push(\n\t\t\t\t\t\t\t\t` - Relationship between ${meta.className}.${prop.fieldNames.join(', ')} and ${targetMeta?.className}.${referencedColumn} is not supported.`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst newProp = {\n\t\t\t\t\tname: prop.name + 'Inverse',\n\t\t\t\t\ttype: meta.className,\n\t\t\t\t\tjoinColumns: prop.fieldNames,\n\t\t\t\t\treferencedTableName: meta.tableName,\n\t\t\t\t\treferencedColumnNames: referencedTablePrimaryKeys,\n\t\t\t\t\tmappedBy: prop.name,\n\t\t\t\t} as EntityProperty;\n\n\t\t\t\t// Add reference to the inverse entity\n\t\t\t\tconst inverseMeta = metadata.find((m) => m.className === meta.className);\n\t\t\t\tconst inverseProp = inverseMeta?.props.find((p) => p.name === newProp.mappedBy);\n\t\t\t\tif (inverseProp) inverseProp.inversedBy = newProp.name;\n\n\t\t\t\tif (prop.kind === ReferenceKind.MANY_TO_ONE) {\n\t\t\t\t\tconst name = pascalToCamelCaseString(meta.className);\n\t\t\t\t\tnewProp.name = pluralize(name);\n\t\t\t\t\tnewProp.kind = ReferenceKind.ONE_TO_MANY;\n\t\t\t\t} else if (prop.kind === ReferenceKind.ONE_TO_ONE && !prop.mappedBy) {\n\t\t\t\t\tnewProp.kind = ReferenceKind.ONE_TO_ONE;\n\t\t\t\t\tnewProp.nullable = true;\n\t\t\t\t} else if (prop.kind === ReferenceKind.MANY_TO_MANY && !prop.mappedBy) {\n\t\t\t\t\tconst name = pascalToCamelCaseString(meta.className);\n\t\t\t\t\tnewProp.name = pluralize(name);\n\t\t\t\t\tnewProp.kind = ReferenceKind.MANY_TO_MANY;\n\t\t\t\t} else {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\ttargetMeta?.addProperty(newProp);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (nonPrimaryKeyReferenceErrors.length) {\n\t\tthrow new IntrospectionError(\n\t\t\t`Unsupported Relationship${nonPrimaryKeyReferenceErrors.length === 1 ? '' : 's'} Detected`,\n\t\t\t`\\n${nonPrimaryKeyReferenceErrors.join('\\n')}\\n\\nForeign keys in Graphweaver currently need to reference the primary key of the other table.`\n\t\t);\n\t}\n};\n\nconst detectManyToManyRelations = (metadata: EntityMetadata[]) => {\n\tfor (const meta of metadata) {\n\t\tif (\n\t\t\tmeta.compositePK && // needs to have composite PK\n\t\t\tmeta.primaryKeys.length === meta.relations.length && // all relations are PKs\n\t\t\tmeta.relations.length === 2 && // there are exactly two relation properties\n\t\t\tmeta.relations.length === meta.props.length && // all properties are relations\n\t\t\tmeta.relations.every((prop) => prop.kind === ReferenceKind.MANY_TO_ONE) // all relations are m:1\n\t\t) {\n\t\t\tmeta.pivotTable = true;\n\t\t\tconst owner = metadata.find((m) => m.className === meta.relations[0].type);\n\t\t\tif (!owner) throw new Error('No Owner');\n\t\t\tconst name = pascalToCamelCaseString(meta.relations?.[1]?.type);\n\t\t\towner.addProperty({\n\t\t\t\tname: pluralize(name),\n\t\t\t\tkind: ReferenceKind.MANY_TO_MANY,\n\t\t\t\tpivotTable: meta.tableName,\n\t\t\t\ttype: meta.relations[1].type,\n\t\t\t\tjoinColumns: meta.relations[0].fieldNames,\n\t\t\t\tinverseJoinColumns: meta.relations[1].fieldNames,\n\t\t\t} as EntityProperty);\n\t\t}\n\t}\n};\n\nconst generateIdentifiedReferences = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tfor (const prop of meta.relations) {\n\t\t\tif ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {\n\t\t\t\tconst name = pascalToCamelCaseString(prop.type);\n\t\t\t\tprop.name = pluralize.singular(name);\n\t\t\t\tprop.ref = true;\n\t\t\t}\n\t\t}\n\t}\n};\n\nconst generateSingularTypeReferences = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tmeta.className = pluralize.singular(meta.className);\n\t\tfor (const prop of meta.relations) {\n\t\t\tprop.type = pluralize.singular(prop.type);\n\t\t}\n\t}\n};\n\n// Convert properties like FirstName to firstName\nconst convertToCamelCasePropertyNames = (metadata: EntityMetadata[]): void => {\n\tfor (const meta of metadata.filter((m) => !m.pivotTable)) {\n\t\tconst props = Object.values(meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tprop.name = pascalToCamelCaseString(prop.name);\n\t\t});\n\t}\n};\n\nconst assertUniqueForeignKeys = (table: DatabaseTable): void => {\n\tconst uniqueForeignKeys = new Set();\n\tconst definedForeignKeys = Object.values(table.getForeignKeys());\n\n\tfor (const foreignKey of definedForeignKeys) {\n\t\tconst { localTableName, referencedTableName, columnNames, referencedColumnNames } = foreignKey;\n\t\tconst serializedValue = JSON.stringify({\n\t\t\tlocalTableName,\n\t\t\tcolumnNames: columnNames.sort(),\n\t\t\treferencedTableName,\n\t\t\treferencedColumnNames: referencedColumnNames.sort(),\n\t\t});\n\n\t\tif (uniqueForeignKeys.has(serializedValue)) {\n\t\t\tthrow new Error(\n\t\t\t\t`\\n\\nImport Failed: Duplicate foreign keys detected on column/s (${columnNames.toString()}) in table \"${\n\t\t\t\t\ttable.name\n\t\t\t\t}\".`\n\t\t\t);\n\t\t}\n\n\t\tuniqueForeignKeys.add(serializedValue);\n\t}\n};\n\nconst convertSchemaToMetadata = async (\n\tschema: DatabaseSchema,\n\tplatform: AbstractSqlPlatform,\n\tnamingStrategy: NamingStrategy\n) => {\n\tconst helper = platform.getSchemaHelper();\n\n\tif (!helper) throw new Error('cannot connect to database');\n\n\tconst metadata = schema\n\t\t.getTables()\n\t\t.sort((a, b) => a.name.localeCompare(b.name))\n\t\t.map((table) => {\n\t\t\tassertUniqueForeignKeys(table);\n\t\t\treturn table.getEntityDeclaration(namingStrategy, helper, 'never');\n\t\t});\n\n\tif (metadata.length === 0) {\n\t\tthrow new IntrospectionError(\n\t\t\t`Warning: No tables found, this database is empty.`,\n\t\t\t`Make sure you have tables in this database and then try again.`\n\t\t);\n\t}\n\n\tconvertToCamelCasePropertyNames(metadata);\n\tdetectManyToManyRelations(metadata);\n\tgenerateIdentifiedReferences(metadata);\n\tgenerateBidirectionalRelations(metadata);\n\tgenerateSingularTypeReferences(metadata);\n\n\treturn metadata;\n};\n\nconst openConnection = async (type: DatabaseType, options: ConnectionOptions) => {\n\t// eslint-disable-next-line @typescript-eslint/no-require-imports\n\tconst module = require(`@mikro-orm/${type}`);\n\tconst PLATFORMS = {\n\t\tmysql: 'MySqlDriver',\n\t\tpostgresql: 'PostgreSqlDriver',\n\t\tsqlite: 'SqliteDriver',\n\t};\n\tawait ConnectionManager.connect(CONNECTION_MANAGER_ID, {\n\t\tmikroOrmConfig: {\n\t\t\tdriver: module[PLATFORMS[type]],\n\t\t\t...options.mikroOrmConfig,\n\t\t},\n\t});\n};\n\nconst closeConnection = async () => {\n\tconsole.log('Closing database connection...');\n\tawait ConnectionManager.close(CONNECTION_MANAGER_ID);\n\tconsole.log('Database connection closed.');\n};\n\ntype File =\n\t| DataEntityFile\n\t| SchemaEntityFile\n\t| SchemaIndexFile\n\t| DataEntityIndexFile\n\t| DataSourceIndexFile\n\t| DatabaseFile;\n\nexport const generate = async (databaseType: DatabaseType, options: ConnectionOptions) => {\n\ttry {\n\t\tawait openConnection(databaseType, options);\n\n\t\tconst database = ConnectionManager.database(CONNECTION_MANAGER_ID);\n\t\tif (!database)\n\t\t\tthrow new IntrospectionError(\n\t\t\t\t`Warning: Unable to connect to database.`,\n\t\t\t\t'Please check the connection settings and try again'\n\t\t\t);\n\n\t\tconst config = database.em.config;\n\t\tconst driver = database.em.getDriver();\n\t\tconst platform = driver.getPlatform();\n\t\tconst namingStrategy = config.getNamingStrategy();\n\t\tconst connection = driver.getConnection();\n\n\t\tconsole.log('Fetching database schema...');\n\t\tconst schema = await DatabaseSchema.create(connection, platform, config);\n\t\tconsole.log('Building metadata...');\n\t\tconst metadata = await convertSchemaToMetadata(schema, platform, namingStrategy);\n\n\t\t// Build a lookup for efficient cross-referencing later.\n\t\tconst entityLookup = new Map<string, EntityMetadata<any>>();\n\t\tfor (const meta of metadata) {\n\t\t\tentityLookup.set(meta.className, meta);\n\t\t}\n\n\t\tconst source: File[] = [];\n\n\t\tconst summaryOfEntities: { name: string; entityFilePath: string; schemaFilePath: string }[] =\n\t\t\t[];\n\n\t\tfor (const meta of metadata) {\n\t\t\tif (!meta.pivotTable) {\n\t\t\t\tconst dataEntityFile = new DataEntityFile(meta, namingStrategy, platform, databaseType);\n\t\t\t\tconst schemaEntityFile = new SchemaEntityFile(meta, namingStrategy, platform, entityLookup);\n\t\t\t\tsource.push(dataEntityFile, schemaEntityFile);\n\t\t\t\tsummaryOfEntities.push({\n\t\t\t\t\tname: meta.className,\n\t\t\t\t\tentityFilePath: `${dataEntityFile.getBasePath()}${dataEntityFile.getBaseName()}`,\n\t\t\t\t\tschemaFilePath: `${schemaEntityFile.getBasePath()}${schemaEntityFile.getBaseName()}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Export all the entities from the data source directory\n\t\tsource.push(new DataEntityIndexFile(metadata, databaseType));\n\t\t// Export the data source from the entities directory\n\t\tsource.push(new DataSourceIndexFile(databaseType));\n\t\t// Export the data source from the entities directory\n\t\tsource.push(new SchemaIndexFile(metadata));\n\t\t// Export the database connection to its own file\n\t\tsource.push(new DatabaseFile(databaseType, options));\n\n\t\tconst files = source.map((file) => {\n\t\t\treturn {\n\t\t\t\tpath: file.getBasePath(),\n\t\t\t\tname: file.getBaseName(),\n\t\t\t\tcontents: file.generate(),\n\t\t\t\tneedOverwriteWarning: !![DatabaseFile, SchemaIndexFile].some((cls) => file instanceof cls),\n\t\t\t};\n\t\t});\n\n\t\tawait closeConnection();\n\n\t\tconsole.log('\\nImport Summary:');\n\t\tconsole.table(summaryOfEntities);\n\t\tconsole.log(\n\t\t\t`\\nImported ${summaryOfEntities.length} entities, creating the above files in your Graphweaver project. \\n`\n\t\t);\n\n\t\treturn files;\n\t} catch (err) {\n\t\tif (err instanceof IntrospectionError) throw err;\n\n\t\tconsole.error('Got error during introspection:');\n\t\tconsole.error(err);\n\n\t\tthrow new IntrospectionError(\n\t\t\t`Warning: Unable to connect to database.`,\n\t\t\thasErrorMessage(err) ? err.message : 'Please check the connection settings and try again'\n\t\t);\n\t}\n};\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAmE;AACnE,kBAMO;AACP,uBAAsB;AAEtB,sBAAmE;AACnE,mBAOO;AACP,mBAAwC;AAExC,MAAM,wBAAwB;AAEvB,MAAM,2BAA2B,MAAM;AAAA,EAE7C,YACW,QAAQ,IAClB,UAAU,IACT;AACD,UAAM,OAAO;AAHH;AAIV,SAAK,OAAO;AACZ,SAAK,QAAQ;AACb,SAAK,UAAU;AAAA,EAChB;AACD;AAEA,MAAM,kBAAkB,CAAC,UAA6C,MAAM;AAE5E,MAAM,iCAAiC,CAAC,aAAqC;AAC5E,QAAM,+BAAyC,CAAC;AAEhD,aAAW,QAAQ,SAAS,OAAO,CAAC,MAAM,CAAC,EAAE,UAAU,GAAG;AACzD,eAAW,QAAQ,KAAK,WAAW;AAClC,UAAI,CAAC,KAAK,KAAK,SAAS,SAAS,GAAG;AACnC,cAAM,aAAa,SAAS,KAAK,CAAC,MAAM,EAAE,cAAc,KAAK,IAAI;AACjE,cAAM,6BAA6B,kBAAM;AAAA,WACvC,YAAY,gBAAgB,KAAK,CAAC,GAAG,IAAI,CAAC,OAAO,GAAG,UAAU;AA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Q,MAAM,iBAAiB;AAC/B,YAAQ;AAAA,MACP;AAAA,WAAc,kBAAkB,MAAM;AAAA;AAAA,IACvC;AAEA,WAAO;AAAA,EACR,SAAS,KAAK;AACb,QAAI,eAAe,mBAAoB,OAAM;AAE7C,YAAQ,MAAM,iCAAiC;AAC/C,YAAQ,MAAM,GAAG;AAEjB,UAAM,IAAI;AAAA,MACT;AAAA,MACA,gBAAgB,GAAG,IAAI,IAAI,UAAU;AAAA,IACtC;AAAA,EACD;AACD;",
6
6
  "names": ["pluralize", "module"]
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/provider/assign.ts"],
4
- "sourcesContent": ["import {\n\tAnyEntity,\n\tEntityData,\n\tEntityManager,\n\tEntityProperty,\n\tReference,\n\tReferenceKind,\n\tUtils,\n\twrap,\n} from '@mikro-orm/core';\nimport { logger } from '@exogee/logger';\n\nimport { ConnectionManager } from '../database';\n\n// This is how Mikro ORM does it within their own code, so in this file we're ok with non-null assertions.\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\n\ninterface AssignOptions {\n\t// Whether this assign should be allowed to create new entities.\n\t// If false and a create is attempted, assign will throw.\n\t// Defaults to true if not specified.\n\tcreate?: boolean;\n\n\t// Whether this assign should be allowed update existing entities.\n\t// If false and an update is attempted, assign will throw.\n\t// Defaults to true if not specified.\n\tupdate?: boolean;\n}\n\nexport const assign = async <T extends AnyEntity<T>>(\n\tentity: T,\n\tdata: EntityData<T>,\n\toptions?: AssignOptions,\n\tvisited = new Set<AnyEntity<any>>(),\n\tem = ConnectionManager.default.em\n) => {\n\tif (visited.has(entity)) return entity;\n\tvisited.add(entity);\n\n\t// We'll need the metadata for this entity to be able to traverse the properties later.\n\tconst metadata = wrap(entity, true).__meta!;\n\n\tfor (const [property, value] of Object.entries(data)) {\n\t\tconst entityPropertyValue = entity[property as keyof T];\n\n\t\t// We're going to need the metadata for this property so we can ensure it exists and so that we can\n\t\t// navigate to related entities.\n\t\tconst propertyMetadata = (metadata.properties as any)[property] as\n\t\t\t| EntityProperty<T>\n\t\t\t| undefined;\n\n\t\tif (\n\t\t\tpropertyMetadata?.kind === ReferenceKind.MANY_TO_MANY ||\n\t\t\tpropertyMetadata?.kind === ReferenceKind.ONE_TO_MANY\n\t\t) {\n\t\t\tif (!Array.isArray(value))\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Value is not an array while trying to assign to collection property ${property} on entity ${metadata.name}`\n\t\t\t\t);\n\n\t\t\t// Ensure the entity has a loaded collection at the same place.\n\t\t\tif (!Utils.isCollection<T, any>(entityPropertyValue)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Tried to merge array into non-collection property ${property} on entity ${metadata.name}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst relatedEntity = em.getMetadata().find(propertyMetadata.entity());\n\t\t\tif (relatedEntity?.primaryKeys.length !== 1) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Entity ${propertyMetadata.entity()} has multiple primary keys, which is not yet supported.`\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst [relatedPrimaryKeyField] = relatedEntity.primaryKeys;\n\n\t\t\tconst visitedEntities = new Set<T>();\n\n\t\t\tfor (const subvalue of value) {\n\t\t\t\tlet entity: T | undefined;\n\n\t\t\t\tif (subvalue[relatedPrimaryKeyField]) {\n\t\t\t\t\t// Get the current entity from the ORM if there's an ID.\n\t\t\t\t\tentity = em\n\t\t\t\t\t\t.getUnitOfWork()\n\t\t\t\t\t\t.getById(propertyMetadata.type, subvalue[relatedPrimaryKeyField]);\n\n\t\t\t\t\tif (!entity) {\n\t\t\t\t\t\t// There are two cases here: either the user is trying to assign properties to the entity as well as changing members of a collection,\n\t\t\t\t\t\t// or they're just changing members of a collection.\n\t\t\t\t\t\t// For the former we actually need the entity from the DB, while for the latter we can let it slide and just pass an ID entity on down.\n\t\t\t\t\t\tconst subvalueKeys = Object.keys(subvalue);\n\t\t\t\t\t\tif (subvalueKeys.length === 1 && subvalueKeys[0] === relatedPrimaryKeyField) {\n\t\t\t\t\t\t\t// It's just the ID.\n\t\t\t\t\t\t\tentity = em.getReference(\n\t\t\t\t\t\t\t\tpropertyMetadata.type,\n\t\t\t\t\t\t\t\tsubvalue[relatedPrimaryKeyField]\n\t\t\t\t\t\t\t) as T;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t\t`Doing a full database fetch for ${propertyMetadata.type} with id ${subvalue[relatedPrimaryKeyField]}, this should ideally be prefetched into the Unit of Work before calling assign() for performance`\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t// We should be prefetching for performance in most cases here but if we don't have it we can load it now.\n\t\t\t\t\t\t\t// From base resolver a reason this would be needed is when you're switching collection values from one entity to another, e.g.\n\t\t\t\t\t\t\t// Business unit 1 -> Business unit 2. In this scenario we prefetch the one that's currently on the entity, but the one we're changing\n\t\t\t\t\t\t\t// to is not in the unit of work.\n\t\t\t\t\t\t\tentity =\n\t\t\t\t\t\t\t\t((await em.findOne<any>(propertyMetadata.type, {\n\t\t\t\t\t\t\t\t\t[relatedPrimaryKeyField]: subvalue[relatedPrimaryKeyField],\n\t\t\t\t\t\t\t\t})) as T | null) ?? undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!entity) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Attempted to assign as an update to '${propertyMetadata.name}' property of ${metadata.name} Entity, but even after a full fetch to the database ${propertyMetadata.type} with ID of ${subvalue.id} could not be found.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst newEntity = await createOrAssignEntity<T>({\n\t\t\t\t\tentity,\n\t\t\t\t\tentityType: propertyMetadata.type,\n\t\t\t\t\tprimaryKeyField: relatedPrimaryKeyField,\n\t\t\t\t\tdata: subvalue,\n\t\t\t\t\toptions,\n\t\t\t\t\tvisited,\n\t\t\t\t\tem,\n\t\t\t\t});\n\n\t\t\t\t// Ok, now we've got the created or updated entity, ensure it's in the collection\n\t\t\t\t// so its foreign keys are set correctly. If it's already in the collection this is a noop.\n\t\t\t\tentityPropertyValue.add(newEntity);\n\n\t\t\t\t// We need to keep track of the fact that this entity belongs here so it doesn't get removed in the cleanup step down below.\n\t\t\t\tvisitedEntities.add(newEntity);\n\t\t\t}\n\n\t\t\t// Ok, at this point we know what IDs we visited. If anything is left in the collection that has an ID and has not been visited\n\t\t\t// it needs to be removed from the collection, because this is the canonical list of everything that's in the collection now.\n\t\t\t// ------------\n\t\t\t// \u2757\uD83D\uDC3B WARNING BEAR TRAP \uD83D\uDC3B\u2757: If you're looking at this going, \"But I just want to pass in the items I want to update and for it not to\n\t\t\t// mess with the rest of the collection\", this is here because without this behaviour, there's no way to remove items from\n\t\t\t// Many to Many properties. Consider the case of tags on an entity, when we pass ['a', 'b', 'c'] as the list of tags, that\n\t\t\t// means we need to remove anything that isn't 'a', 'b', or 'c' because it's not in the array.\n\t\t\tentityPropertyValue.remove(\n\t\t\t\tentityPropertyValue.getItems().filter((entity) => !visitedEntities.has(entity))\n\t\t\t);\n\t\t} else if (\n\t\t\tpropertyMetadata?.kind == ReferenceKind.MANY_TO_ONE ||\n\t\t\tpropertyMetadata?.kind === ReferenceKind.ONE_TO_ONE\n\t\t) {\n\t\t\tif (value === null) {\n\t\t\t\t// If the value is null, unset the reference\n\t\t\t\t(entity as any)[property] = null;\n\t\t\t} else {\n\t\t\t\tconst valueKeys = Object.keys(value as any);\n\t\t\t\tconst relatedEntity = em.getMetadata().find(propertyMetadata.entity());\n\t\t\t\tif (!relatedEntity) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Could not find entity ${propertyMetadata.entity()} in MikroORM metadata.`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (relatedEntity.primaryKeys.length !== 1) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Entity ${propertyMetadata.entity()} has ${relatedEntity.primaryKeys.length} primary keys, but we only support 1.`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst relatedPrimaryKeyField = relatedEntity.primaryKeys[0];\n\n\t\t\t\tif (valueKeys.length === 1 && valueKeys[0] === relatedPrimaryKeyField) {\n\t\t\t\t\t// Ok, this is just the ID, set the reference and move on.\n\t\t\t\t\tentity[property as keyof T] = em.getReference(\n\t\t\t\t\t\tpropertyMetadata.type,\n\t\t\t\t\t\t(value as any)[relatedPrimaryKeyField]\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tif (entityPropertyValue && !Reference.isReference(entityPropertyValue)) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Trying to merge to related property ${property} on entity ${metadata.name} which is not a reference.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (Reference.isReference(entityPropertyValue) && !entityPropertyValue.isInitialized()) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Trying to merge to related property ${property} on entity ${metadata.name} which is not initialised.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst newEntity = await createOrAssignEntity<T>({\n\t\t\t\t\t\tentity: (entityPropertyValue as Reference<T>)?.unwrap(),\n\t\t\t\t\t\tentityType: propertyMetadata.type,\n\t\t\t\t\t\tprimaryKeyField: relatedPrimaryKeyField,\n\t\t\t\t\t\tdata: value as EntityData<T>,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\tvisited,\n\t\t\t\t\t\tem,\n\t\t\t\t\t});\n\n\t\t\t\t\t(relatedEntity as any)[property] = Reference.create(newEntity);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Ok, we're a simple scalar.\n\t\t\t(entity as any)[property] = value;\n\t\t}\n\t}\n\n\treturn entity;\n};\n\nconst createOrAssignEntity = <T extends AnyEntity<T>>({\n\tentity,\n\tentityType,\n\tprimaryKeyField,\n\tdata,\n\toptions,\n\tvisited,\n\tem,\n}: {\n\tentity?: T;\n\tentityType: string;\n\tprimaryKeyField: string;\n\tdata: EntityData<T>;\n\toptions?: AssignOptions;\n\tvisited: Set<AnyEntity<any>>;\n\tem: EntityManager;\n}) => {\n\tconst create = options?.create ?? true;\n\tconst update = options?.update ?? true;\n\n\tif ((data as any)[primaryKeyField]) {\n\t\tif (!update) {\n\t\t\tthrow new Error(\n\t\t\t\t`Updates are disabled, but update value ${JSON.stringify(\n\t\t\t\t\tdata\n\t\t\t\t)} was passed which has an ID property.`\n\t\t\t);\n\t\t}\n\n\t\tif (!entity) {\n\t\t\tthrow new Error(\n\t\t\t\t`Tried to update with data ${JSON.stringify(\n\t\t\t\t\tdata\n\t\t\t\t)} but entity could not be located to update.`\n\t\t\t);\n\t\t}\n\n\t\t// Ok, we need to recurse here.\n\t\treturn assign(entity, data, options, visited);\n\t} else {\n\t\tif (!create) {\n\t\t\tthrow new Error(\n\t\t\t\t`Creates are disabled, but update value ${JSON.stringify(\n\t\t\t\t\tdata\n\t\t\t\t)} was passed which does not have an ID property.`\n\t\t\t);\n\t\t}\n\n\t\t// We don't want Mikro to manage the data merging here, we'll do it in the next line.\n\t\tconst entity = em.create<T>(entityType, {} as any);\n\t\treturn assign(entity, data, options, visited);\n\t}\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBASO;AACP,oBAAuB;AAEvB,sBAAkC;AAiB3B,MAAM,SAAS,OACrB,QACA,MACA,SACA,UAAU,oBAAI,IAAoB,GAClC,KAAK,kCAAkB,QAAQ,OAC3B;AACJ,MAAI,QAAQ,IAAI,MAAM,EAAG,QAAO;AAChC,UAAQ,IAAI,MAAM;AAGlB,QAAM,eAAW,kBAAK,QAAQ,IAAI,EAAE;AAEpC,aAAW,CAAC,UAAU,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AACrD,UAAM,sBAAsB,OAAO,QAAmB;AAItD,UAAM,mBAAoB,SAAS,WAAmB,Q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AAU,YAAY,CAAC,CAAQ;AACjD,WAAO,OAAOA,SAAQ,MAAM,SAAS,OAAO;AAAA,EAC7C;AACD;",
4
+ "sourcesContent": ["import {\n\tAnyEntity,\n\tEntityData,\n\tEntityManager,\n\tEntityProperty,\n\tReference,\n\tReferenceKind,\n\tUtils,\n\twrap,\n} from '@mikro-orm/core';\nimport { logger } from '@exogee/logger';\n\nimport { ConnectionManager } from '../database';\n\ninterface AssignOptions {\n\t// Whether this assign should be allowed to create new entities.\n\t// If false and a create is attempted, assign will throw.\n\t// Defaults to true if not specified.\n\tcreate?: boolean;\n\n\t// Whether this assign should be allowed update existing entities.\n\t// If false and an update is attempted, assign will throw.\n\t// Defaults to true if not specified.\n\tupdate?: boolean;\n}\n\nexport const assign = async <T extends AnyEntity<T>>(\n\tentity: T,\n\tdata: EntityData<T>,\n\toptions?: AssignOptions,\n\tvisited = new Set<AnyEntity<any>>(),\n\tem = ConnectionManager.default.em\n) => {\n\tif (visited.has(entity)) return entity;\n\tvisited.add(entity);\n\n\t// We'll need the metadata for this entity to be able to traverse the properties later.\n\tconst metadata = wrap(entity, true).__meta!;\n\n\tfor (const [property, value] of Object.entries(data)) {\n\t\tconst entityPropertyValue = entity[property as keyof T];\n\n\t\t// We're going to need the metadata for this property so we can ensure it exists and so that we can\n\t\t// navigate to related entities.\n\t\tconst propertyMetadata = (metadata.properties as any)[property] as\n\t\t\t| EntityProperty<T>\n\t\t\t| undefined;\n\n\t\tif (\n\t\t\tpropertyMetadata?.kind === ReferenceKind.MANY_TO_MANY ||\n\t\t\tpropertyMetadata?.kind === ReferenceKind.ONE_TO_MANY\n\t\t) {\n\t\t\tif (!Array.isArray(value))\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Value is not an array while trying to assign to collection property ${property} on entity ${metadata.name}`\n\t\t\t\t);\n\n\t\t\t// Ensure the entity has a loaded collection at the same place.\n\t\t\tif (!Utils.isCollection<T, any>(entityPropertyValue)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Tried to merge array into non-collection property ${property} on entity ${metadata.name}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst relatedEntity = em.getMetadata().find(propertyMetadata.entity());\n\t\t\tif (relatedEntity?.primaryKeys.length !== 1) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Entity ${propertyMetadata.entity()} has multiple primary keys, which is not yet supported.`\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst [relatedPrimaryKeyField] = relatedEntity.primaryKeys;\n\n\t\t\tconst visitedEntities = new Set<T>();\n\n\t\t\tfor (const subvalue of value) {\n\t\t\t\tlet entity: T | undefined;\n\n\t\t\t\tif (subvalue[relatedPrimaryKeyField]) {\n\t\t\t\t\t// Get the current entity from the ORM if there's an ID.\n\t\t\t\t\tentity = em\n\t\t\t\t\t\t.getUnitOfWork()\n\t\t\t\t\t\t.getById(propertyMetadata.type, subvalue[relatedPrimaryKeyField]);\n\n\t\t\t\t\tif (!entity) {\n\t\t\t\t\t\t// There are two cases here: either the user is trying to assign properties to the entity as well as changing members of a collection,\n\t\t\t\t\t\t// or they're just changing members of a collection.\n\t\t\t\t\t\t// For the former we actually need the entity from the DB, while for the latter we can let it slide and just pass an ID entity on down.\n\t\t\t\t\t\tconst subvalueKeys = Object.keys(subvalue);\n\t\t\t\t\t\tif (subvalueKeys.length === 1 && subvalueKeys[0] === relatedPrimaryKeyField) {\n\t\t\t\t\t\t\t// It's just the ID.\n\t\t\t\t\t\t\tentity = em.getReference(\n\t\t\t\t\t\t\t\tpropertyMetadata.type,\n\t\t\t\t\t\t\t\tsubvalue[relatedPrimaryKeyField]\n\t\t\t\t\t\t\t) as T;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t\t`Doing a full database fetch for ${propertyMetadata.type} with id ${subvalue[relatedPrimaryKeyField]}, this should ideally be prefetched into the Unit of Work before calling assign() for performance`\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t// We should be prefetching for performance in most cases here but if we don't have it we can load it now.\n\t\t\t\t\t\t\t// From base resolver a reason this would be needed is when you're switching collection values from one entity to another, e.g.\n\t\t\t\t\t\t\t// Business unit 1 -> Business unit 2. In this scenario we prefetch the one that's currently on the entity, but the one we're changing\n\t\t\t\t\t\t\t// to is not in the unit of work.\n\t\t\t\t\t\t\tentity =\n\t\t\t\t\t\t\t\t((await em.findOne<any>(propertyMetadata.type, {\n\t\t\t\t\t\t\t\t\t[relatedPrimaryKeyField]: subvalue[relatedPrimaryKeyField],\n\t\t\t\t\t\t\t\t})) as T | null) ?? undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!entity) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Attempted to assign as an update to '${propertyMetadata.name}' property of ${metadata.name} Entity, but even after a full fetch to the database ${propertyMetadata.type} with ID of ${subvalue.id} could not be found.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst newEntity = await createOrAssignEntity<T>({\n\t\t\t\t\tentity,\n\t\t\t\t\tentityType: propertyMetadata.type,\n\t\t\t\t\tprimaryKeyField: relatedPrimaryKeyField,\n\t\t\t\t\tdata: subvalue,\n\t\t\t\t\toptions,\n\t\t\t\t\tvisited,\n\t\t\t\t\tem,\n\t\t\t\t});\n\n\t\t\t\t// Ok, now we've got the created or updated entity, ensure it's in the collection\n\t\t\t\t// so its foreign keys are set correctly. If it's already in the collection this is a noop.\n\t\t\t\tentityPropertyValue.add(newEntity);\n\n\t\t\t\t// We need to keep track of the fact that this entity belongs here so it doesn't get removed in the cleanup step down below.\n\t\t\t\tvisitedEntities.add(newEntity);\n\t\t\t}\n\n\t\t\t// Ok, at this point we know what IDs we visited. If anything is left in the collection that has an ID and has not been visited\n\t\t\t// it needs to be removed from the collection, because this is the canonical list of everything that's in the collection now.\n\t\t\t// ------------\n\t\t\t// \u2757\uD83D\uDC3B WARNING BEAR TRAP \uD83D\uDC3B\u2757: If you're looking at this going, \"But I just want to pass in the items I want to update and for it not to\n\t\t\t// mess with the rest of the collection\", this is here because without this behaviour, there's no way to remove items from\n\t\t\t// Many to Many properties. Consider the case of tags on an entity, when we pass ['a', 'b', 'c'] as the list of tags, that\n\t\t\t// means we need to remove anything that isn't 'a', 'b', or 'c' because it's not in the array.\n\t\t\tentityPropertyValue.remove(\n\t\t\t\tentityPropertyValue.getItems().filter((entity) => !visitedEntities.has(entity))\n\t\t\t);\n\t\t} else if (\n\t\t\tpropertyMetadata?.kind == ReferenceKind.MANY_TO_ONE ||\n\t\t\tpropertyMetadata?.kind === ReferenceKind.ONE_TO_ONE\n\t\t) {\n\t\t\tif (value === null) {\n\t\t\t\t// If the value is null, unset the reference\n\t\t\t\t(entity as any)[property] = null;\n\t\t\t} else {\n\t\t\t\tconst valueKeys = Object.keys(value as any);\n\t\t\t\tconst relatedEntity = em.getMetadata().find(propertyMetadata.entity());\n\t\t\t\tif (!relatedEntity) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Could not find entity ${propertyMetadata.entity()} in MikroORM metadata.`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (relatedEntity.primaryKeys.length !== 1) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Entity ${propertyMetadata.entity()} has ${relatedEntity.primaryKeys.length} primary keys, but we only support 1.`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst relatedPrimaryKeyField = relatedEntity.primaryKeys[0];\n\n\t\t\t\tif (valueKeys.length === 1 && valueKeys[0] === relatedPrimaryKeyField) {\n\t\t\t\t\t// Ok, this is just the ID, set the reference and move on.\n\t\t\t\t\tentity[property as keyof T] = em.getReference(\n\t\t\t\t\t\tpropertyMetadata.type,\n\t\t\t\t\t\t(value as any)[relatedPrimaryKeyField]\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tif (entityPropertyValue && !Reference.isReference(entityPropertyValue)) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Trying to merge to related property ${property} on entity ${metadata.name} which is not a reference.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (Reference.isReference(entityPropertyValue) && !entityPropertyValue.isInitialized()) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Trying to merge to related property ${property} on entity ${metadata.name} which is not initialised.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst newEntity = await createOrAssignEntity<T>({\n\t\t\t\t\t\tentity: (entityPropertyValue as Reference<T>)?.unwrap(),\n\t\t\t\t\t\tentityType: propertyMetadata.type,\n\t\t\t\t\t\tprimaryKeyField: relatedPrimaryKeyField,\n\t\t\t\t\t\tdata: value as EntityData<T>,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\tvisited,\n\t\t\t\t\t\tem,\n\t\t\t\t\t});\n\n\t\t\t\t\t(relatedEntity as any)[property] = Reference.create(newEntity);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Ok, we're a simple scalar.\n\t\t\t(entity as any)[property] = value;\n\t\t}\n\t}\n\n\treturn entity;\n};\n\nconst createOrAssignEntity = <T extends AnyEntity<T>>({\n\tentity,\n\tentityType,\n\tprimaryKeyField,\n\tdata,\n\toptions,\n\tvisited,\n\tem,\n}: {\n\tentity?: T;\n\tentityType: string;\n\tprimaryKeyField: string;\n\tdata: EntityData<T>;\n\toptions?: AssignOptions;\n\tvisited: Set<AnyEntity<any>>;\n\tem: EntityManager;\n}) => {\n\tconst create = options?.create ?? true;\n\tconst update = options?.update ?? true;\n\n\tif ((data as any)[primaryKeyField]) {\n\t\tif (!update) {\n\t\t\tthrow new Error(\n\t\t\t\t`Updates are disabled, but update value ${JSON.stringify(\n\t\t\t\t\tdata\n\t\t\t\t)} was passed which has an ID property.`\n\t\t\t);\n\t\t}\n\n\t\tif (!entity) {\n\t\t\tthrow new Error(\n\t\t\t\t`Tried to update with data ${JSON.stringify(\n\t\t\t\t\tdata\n\t\t\t\t)} but entity could not be located to update.`\n\t\t\t);\n\t\t}\n\n\t\t// Ok, we need to recurse here.\n\t\treturn assign(entity, data, options, visited);\n\t} else {\n\t\tif (!create) {\n\t\t\tthrow new Error(\n\t\t\t\t`Creates are disabled, but update value ${JSON.stringify(\n\t\t\t\t\tdata\n\t\t\t\t)} was passed which does not have an ID property.`\n\t\t\t);\n\t\t}\n\n\t\t// We don't want Mikro to manage the data merging here, we'll do it in the next line.\n\t\tconst entity = em.create<T>(entityType, {} as any);\n\t\treturn assign(entity, data, options, visited);\n\t}\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBASO;AACP,oBAAuB;AAEvB,sBAAkC;AAc3B,MAAM,SAAS,OACrB,QACA,MACA,SACA,UAAU,oBAAI,IAAoB,GAClC,KAAK,kCAAkB,QAAQ,OAC3B;AACJ,MAAI,QAAQ,IAAI,MAAM,EAAG,QAAO;AAChC,UAAQ,IAAI,MAAM;AAGlB,QAAM,eAAW,kBAAK,QAAQ,IAAI,EAAE;AAEpC,aAAW,CAAC,UAAU,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AACrD,UAAM,sBAAsB,OAAO,QAAmB;AAItD,UAAM,mBAAoB,SAAS,WAAmB,QAAQ;AAI9D,QACC,kBAAkB,SAAS,0BAAc,gBACzC,kBAAkB,SAAS,0BAAc,aACxC;AACD,UAAI,CAAC,MAAM,QAAQ,KAAK;AACvB,cAAM,IAAI;AAAA,UACT,uEAAuE,QAAQ,cAAc,SAAS,IAAI;AAAA,QAC3G;AAGD,UAAI,CAAC,kBAAM,aAAqB,mBAAmB,GAAG;AACrD,cAAM,IAAI;AAAA,UACT,qDAAqD,QAAQ,cAAc,SAAS,IAAI;AAAA,QACzF;AAAA,MACD;AAEA,YAAM,gBAAgB,GAAG,YAAY,EAAE,KAAK,iBAAiB,OAAO,CAAC;AACrE,UAAI,eAAe,YAAY,W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,CAAC;AAED,UAAC,cAAsB,QAAQ,IAAI,sBAAU,OAAO,SAAS;AAAA,QAC9D;AAAA,MACD;AAAA,IACD,OAAO;AAEN,MAAC,OAAe,QAAQ,IAAI;AAAA,IAC7B;AAAA,EACD;AAEA,SAAO;AACR;AAEA,MAAM,uBAAuB,CAAyB;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,MAQM;AACL,QAAM,SAAS,SAAS,UAAU;AAClC,QAAM,SAAS,SAAS,UAAU;AAElC,MAAK,KAAa,eAAe,GAAG;AACnC,QAAI,CAAC,QAAQ;AACZ,YAAM,IAAI;AAAA,QACT,0CAA0C,KAAK;AAAA,UAC9C;AAAA,QACD,CAAC;AAAA,MACF;AAAA,IACD;AAEA,QAAI,CAAC,QAAQ;AACZ,YAAM,IAAI;AAAA,QACT,6BAA6B,KAAK;AAAA,UACjC;AAAA,QACD,CAAC;AAAA,MACF;AAAA,IACD;AAGA,WAAO,OAAO,QAAQ,MAAM,SAAS,OAAO;AAAA,EAC7C,OAAO;AACN,QAAI,CAAC,QAAQ;AACZ,YAAM,IAAI;AAAA,QACT,0CAA0C,KAAK;AAAA,UAC9C;AAAA,QACD,CAAC;AAAA,MACF;AAAA,IACD;AAGA,UAAMA,UAAS,GAAG,OAAU,YAAY,CAAC,CAAQ;AACjD,WAAO,OAAOA,SAAQ,MAAM,SAAS,OAAO;AAAA,EAC7C;AACD;",
6
6
  "names": ["entity"]
7
7
  }
@@ -108,17 +108,18 @@ class MikroBackendProvider {
108
108
  const map = import__.externalIdFieldMap.get(targetName);
109
109
  const mapFieldNames = (partialFilterObj) => {
110
110
  for (const [from, to] of Object.entries(map || {})) {
111
- if (partialFilterObj[from] && typeof partialFilterObj[from].id !== "undefined") {
112
- if (Object.keys(partialFilterObj[from]).length > 1) {
111
+ if (partialFilterObj[from]) {
112
+ const keys = Object.keys(partialFilterObj[from]);
113
+ if (keys.length > 1) {
113
114
  throw new Error(
114
- `Expected precisely 1 key called 'id' in queryObj.${from} on ${target}, got ${JSON.stringify(
115
+ `Expected precisely 1 key in queryObj.${from} on ${target}, got ${JSON.stringify(
115
116
  partialFilterObj[from],
116
117
  null,
117
118
  4
118
119
  )}`
119
120
  );
120
121
  }
121
- partialFilterObj[to] = partialFilterObj[from].id;
122
+ partialFilterObj[to] = partialFilterObj[from][keys[0]];
122
123
  delete partialFilterObj[from];
123
124
  }
124
125
  }
@@ -214,9 +215,9 @@ class MikroBackendProvider {
214
215
  if (Object.keys(whereWithAppliedExternalIdFields).length > 0) {
215
216
  query.andWhere(whereWithAppliedExternalIdFields);
216
217
  }
217
- pagination?.limit && query.limit(pagination.limit);
218
- pagination?.offset && query.offset(pagination.offset);
219
- pagination?.orderBy && query.orderBy({ ...pagination.orderBy });
218
+ if (pagination?.limit) query.limit(pagination.limit);
219
+ if (pagination?.offset) query.offset(pagination.offset);
220
+ if (pagination?.orderBy) query.orderBy({ ...pagination.orderBy });
220
221
  query.setFlag(import__.QueryFlag.DISTINCT);
221
222
  const driver = this.database.em.getDriver();
222
223
  const meta = this.database.em.getMetadata().get(this.entityType.name);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/provider/provider.ts"],
4
- "sourcesContent": ["import {\n\tBackendProvider,\n\tPaginationOptions,\n\tSort,\n\tFilter,\n\tBackendProviderConfig,\n\tFieldMetadata,\n\tAggregationResult,\n\tAggregationType,\n\tTraceMethod,\n\tTraceOptions,\n\ttraceSync,\n\ttrace as startTrace,\n\tGraphweaverRequestEvent,\n\tGraphweaverPluginNextFunction,\n\tEntityMetadata,\n\tgraphweaverMetadata,\n} from '@exogee/graphweaver';\nimport { logger } from '@exogee/logger';\nimport { Reference, RequestContext, sql } from '@mikro-orm/core';\nimport { AutoPath, PopulateHint } from '@mikro-orm/postgresql';\nimport { pluginManager, apolloPluginManager } from '@exogee/graphweaver-server';\n\nimport {\n\tLockMode,\n\tQueryFlag,\n\tReferenceKind,\n\tConnectionManager,\n\texternalIdFieldMap,\n\tAnyEntity,\n\tIsolationLevel,\n\tConnectionOptions,\n\tconnectToDatabase,\n} from '..';\n\nimport { OptimisticLockError } from '../utils/errors';\nimport { assign } from './assign';\n\ntype PostgresError = {\n\tcode: string;\n\troutine: string;\n};\n\nconst objectOperations = new Set(['_and', '_or', '_not']);\nconst mikroObjectOperations = new Set(['$and', '$or', '$not']);\n\nconst appendPath = (path: string, newPath: string) =>\n\tpath.length ? `${path}.${newPath}` : newPath;\n\nexport const gqlToMikro: (filter: any) => any = (filter: any) => {\n\tif (Array.isArray(filter)) {\n\t\treturn filter.map((element) => gqlToMikro(element));\n\t} else if (typeof filter === 'object') {\n\t\tfor (const key of Object.keys(filter)) {\n\t\t\t// A null here is a user-specified value and is valid to filter on\n\t\t\tif (filter[key] === null) continue;\n\n\t\t\tif (objectOperations.has(key)) {\n\t\t\t\t// { _not: '1' } => { $not: '1' }\n\t\t\t\tfilter[key.replace('_', '$')] = gqlToMikro(filter[key]);\n\t\t\t\tdelete filter[key];\n\t\t\t} else if (typeof filter[key] === 'object' && !Array.isArray(filter[key])) {\n\t\t\t\t// Recurse over nested filters only (arrays are an argument to a filter, not a nested filter)\n\t\t\t\tfilter[key] = gqlToMikro(filter[key]);\n\t\t\t} else if (key.indexOf('_') >= 0) {\n\t\t\t\t// { firstName_in: ['k', 'b'] } => { firstName: { $in: ['k', 'b'] } }\n\t\t\t\tconst [newKey, operator] = key.split('_');\n\t\t\t\tconst newValue = { [`$${operator}`]: gqlToMikro(filter[key]) };\n\n\t\t\t\t// They can construct multiple filters for the same key. In that case we need\n\t\t\t\t// to append them all into an object.\n\t\t\t\tif (typeof filter[newKey] !== 'undefined') {\n\t\t\t\t\tfilter[newKey] = { ...filter[newKey], ...newValue };\n\t\t\t\t} else {\n\t\t\t\t\tfilter[newKey] = newValue;\n\t\t\t\t}\n\n\t\t\t\tdelete filter[key];\n\t\t\t}\n\t\t}\n\t}\n\treturn filter;\n};\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport class MikroBackendProvider<D> implements BackendProvider<D> {\n\tprivate _backendId: string;\n\n\tprivate connection: ConnectionOptions;\n\n\tpublic entityType: new () => D;\n\tpublic connectionManagerId?: string;\n\tprivate transactionIsolationLevel!: IsolationLevel;\n\n\tpublic readonly supportsInFilter = true;\n\n\t// Default backend provider config\n\tpublic readonly backendProviderConfig: BackendProviderConfig = {\n\t\tfilter: true,\n\t\tpagination: false,\n\t\torderBy: false,\n\t\tsupportedAggregationTypes: new Set<AggregationType>([AggregationType.COUNT]),\n\t};\n\n\tget backendId() {\n\t\treturn this._backendId;\n\t}\n\n\tprivate get database() {\n\t\t// If we have a connection manager ID then use that else fallback to the Database\n\t\tif (!this.connectionManagerId) return ConnectionManager.default;\n\t\treturn ConnectionManager.database(this.connectionManagerId) || ConnectionManager.default;\n\t}\n\n\t// This is exposed for use in the RLS package\n\tpublic get transactional() {\n\t\treturn this.database.transactional;\n\t}\n\n\tpublic async withTransaction<T>(callback: () => Promise<T>) {\n\t\treturn this.database.transactional<T>(callback, this.transactionIsolationLevel);\n\t}\n\n\t// This is exposed for use in the RLS package\n\tpublic get em() {\n\t\treturn this.database.em;\n\t}\n\n\tpublic constructor(\n\t\tmikroType: new () => D,\n\t\tconnection: ConnectionOptions,\n\t\ttransactionIsolationLevel: IsolationLevel = IsolationLevel.REPEATABLE_READ\n\t) {\n\t\tthis.entityType = mikroType;\n\t\tthis.connectionManagerId = connection.connectionManagerId;\n\t\tthis._backendId = `mikro-orm-${connection.connectionManagerId || ''}`;\n\t\tthis.transactionIsolationLevel = transactionIsolationLevel;\n\t\tthis.connection = connection;\n\t\tthis.addRequestContext();\n\t\tthis.connectToDatabase();\n\t}\n\n\tprivate connectToDatabase = async () => {\n\t\tconst connectionManagerId = this.connectionManagerId;\n\t\tif (!connectionManagerId) {\n\t\t\tthrow new Error('Expected connectionManagerId to be defined when calling addRequestContext.');\n\t\t}\n\n\t\tapolloPluginManager.addPlugin(connectionManagerId, connectToDatabase(this.connection));\n\t};\n\n\tprivate addRequestContext = () => {\n\t\tconst connectionManagerId = this.connectionManagerId;\n\t\tif (!connectionManagerId) {\n\t\t\tthrow new Error('Expected connectionManagerId to be defined when calling addRequestContext.');\n\t\t}\n\n\t\tconst connectionPlugin = {\n\t\t\tname: connectionManagerId,\n\t\t\tevent: GraphweaverRequestEvent.OnRequest,\n\t\t\tnext: (_: GraphweaverRequestEvent, _next: GraphweaverPluginNextFunction) => {\n\t\t\t\tlogger.trace(`Graphweaver OnRequest plugin called`);\n\n\t\t\t\tconst connection = ConnectionManager.database(connectionManagerId);\n\t\t\t\tif (!connection) throw new Error('No database connection found');\n\n\t\t\t\treturn RequestContext.create(connection.orm.em, _next, {});\n\t\t\t},\n\t\t};\n\t\tpluginManager.addPlugin(connectionPlugin);\n\t};\n\n\tprivate mapAndAssignKeys = (result: D, entityType: new () => D, inputArgs: Partial<D>) => {\n\t\t// Clean the input and remove any GraphQL classes from the object\n\t\tconst assignmentObj = this.applyExternalIdFields(entityType, inputArgs);\n\t\treturn assign(result, assignmentObj, undefined, undefined, this.database.em);\n\t};\n\n\tprivate applyExternalIdFields = (target: AnyEntity | string, values: any) => {\n\t\tconst targetName = typeof target === 'string' ? target : target.name;\n\t\tconst map = externalIdFieldMap.get(targetName);\n\n\t\tconst mapFieldNames = (partialFilterObj: any) => {\n\t\t\tfor (const [from, to] of Object.entries(map || {})) {\n\t\t\t\tif (partialFilterObj[from] && typeof partialFilterObj[from].id !== 'undefined') {\n\t\t\t\t\tif (Object.keys(partialFilterObj[from]).length > 1) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Expected precisely 1 key called 'id' in queryObj.${from} on ${target}, got ${JSON.stringify(\n\t\t\t\t\t\t\t\tpartialFilterObj[from],\n\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\t4\n\t\t\t\t\t\t\t)}`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tpartialFilterObj[to] = partialFilterObj[from].id;\n\t\t\t\t\tdelete partialFilterObj[from];\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Check for and/or/etc at the root level and handle correctly\n\t\tfor (const rootLevelKey of Object.keys(values)) {\n\t\t\tif (mikroObjectOperations.has(rootLevelKey)) {\n\t\t\t\tfor (const field of values[rootLevelKey]) {\n\t\t\t\t\tmapFieldNames(field);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Map the rest of the field names as well\n\t\tmapFieldNames(values);\n\n\t\t// Traverse the nested entities\n\t\tconst { properties } = this.database.em.getMetadata().get(targetName);\n\t\tObject.values(properties)\n\t\t\t.filter((property) => typeof property.entity !== 'undefined' && values[property.name])\n\t\t\t.forEach((property) => {\n\t\t\t\tif (Array.isArray(values[property.name])) {\n\t\t\t\t\tvalues[property.name].forEach((value: any) =>\n\t\t\t\t\t\tthis.applyExternalIdFields(property.type, value)\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tvalues[property.name] = this.applyExternalIdFields(property.type, values[property.name]);\n\t\t\t\t}\n\t\t\t});\n\n\t\treturn values;\n\t};\n\n\t// Check if we have any keys that are a collection of entities\n\tpublic visitPathForPopulate = (entityName: string, updateArgBranch: any, populateBranch = '') => {\n\t\tconst { properties } = this.database.em.getMetadata().get(entityName);\n\t\tconst collectedPaths = populateBranch ? new Set<string>([populateBranch]) : new Set<string>([]);\n\n\t\tfor (const [key, value] of Object.entries(updateArgBranch ?? {})) {\n\t\t\tif (\n\t\t\t\t// If it's a relationship, go ahead and and '.' it in, recurse.\n\t\t\t\tproperties[key]?.kind === ReferenceKind.ONE_TO_ONE ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.ONE_TO_MANY ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.MANY_TO_ONE ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.MANY_TO_MANY\n\t\t\t) {\n\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\t// In the case where the array is empty we also need to make sure we load the collection.\n\t\t\t\t\tcollectedPaths.add(appendPath(populateBranch, key));\n\n\t\t\t\t\tfor (const entry of value) {\n\t\t\t\t\t\t// Recurse\n\t\t\t\t\t\tconst newPaths = this.visitPathForPopulate(\n\t\t\t\t\t\t\tproperties[key].type,\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t\tappendPath(populateBranch, key)\n\t\t\t\t\t\t);\n\t\t\t\t\t\tnewPaths.forEach((path) => collectedPaths.add(path));\n\t\t\t\t\t}\n\t\t\t\t} else if (typeof value === 'object') {\n\t\t\t\t\t// Recurse\n\t\t\t\t\tconst newPaths = this.visitPathForPopulate(\n\t\t\t\t\t\tproperties[key].type,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t\tappendPath(populateBranch, key)\n\t\t\t\t\t);\n\t\t\t\t\tnewPaths.forEach((path) => collectedPaths.add(path));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn collectedPaths;\n\t};\n\n\t@TraceMethod()\n\tpublic async find(\n\t\tfilter: Filter<D>,\n\t\tpagination?: PaginationOptions,\n\t\tentityMetadata?: EntityMetadata,\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\t// If we have a span, update the name\n\t\ttrace?.span.updateName(`Mikro-Orm - Find ${this.entityType.name}`);\n\n\t\tlogger.trace(`Running find ${this.entityType.name} with filter`, {\n\t\t\tfilter: JSON.stringify(filter),\n\t\t});\n\n\t\t// Strip custom types out of the equation.\n\t\t// This query only works if we JSON.parse(JSON.stringify(filter)):\n\t\t//\n\t\t// query {\n\t\t// drivers (filter: { region: { name: \"North Shore\" }}) {\n\t\t// id\n\t\t// }\n\t\t// }\n\t\tconst where = traceSync((trace?: TraceOptions) => {\n\t\t\ttrace?.span.updateName('Convert filter to Mikro-Orm format');\n\t\t\treturn filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\t\t})();\n\n\t\t// Convert from: { account: {id: '6' }}\n\t\t// to { accountId: '6' }\n\t\t// This conversion only works on root level objects\n\t\tconst whereWithAppliedExternalIdFields = where\n\t\t\t? this.applyExternalIdFields(this.entityType, where)\n\t\t\t: {};\n\n\t\t// Regions need some fancy handling with Query Builder. Process the where further\n\t\t// and return a Query Builder instance.\n\t\tconst query = this.em.createQueryBuilder(this.entityType);\n\t\tif (Object.keys(whereWithAppliedExternalIdFields).length > 0) {\n\t\t\tquery.andWhere(whereWithAppliedExternalIdFields);\n\t\t}\n\n\t\t// If we have specified a limit, offset or order then update the query\n\t\tpagination?.limit && query.limit(pagination.limit);\n\t\tpagination?.offset && query.offset(pagination.offset);\n\t\tpagination?.orderBy && query.orderBy({ ...pagination.orderBy });\n\n\t\t// Certain query filters can result in duplicate records once all joins are resolved\n\t\t// These duplicates can be discarded as related entities are returned to the\n\t\t// API consumer via field resolvers\n\t\tquery.setFlag(QueryFlag.DISTINCT);\n\n\t\t// 1:1 relations that aren't on the owning side need to get populated so the references get set.\n\t\t// This method is protected, but we need to use it from here, hence the `as any`.\n\t\tconst driver = this.database.em.getDriver();\n\t\tconst meta = this.database.em.getMetadata().get(this.entityType.name);\n\t\tquery.populate((driver as any).autoJoinOneToOneOwner(meta, []));\n\n\t\ttry {\n\t\t\tconst result = await startTrace(async (trace?: TraceOptions) => {\n\t\t\t\ttrace?.span.updateName('Mikro-Orm - Fetch Data');\n\t\t\t\treturn query.getResult();\n\t\t\t})();\n\n\t\t\tlogger.trace(`find ${this.entityType.name} result: ${result.length} rows`);\n\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tlogger.error(`find ${this.entityType.name} error: ${JSON.stringify(err)}`);\n\n\t\t\tif ((err as PostgresError)?.routine === 'InitializeSessionUserId') {\n\t\t\t\t// Throw if the user credentials are incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct user credentials for the database.'\n\t\t\t\t);\n\t\t\t} else if ((err as PostgresError)?.code === 'ECONNREFUSED') {\n\t\t\t\t// Throw if the database address or port is incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct address and port for the database.'\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t}\n\n\t@TraceMethod()\n\tpublic async findOne(\n\t\tfilter: Filter<D>,\n\t\tentityMetadata?: EntityMetadata,\n\t\ttrace?: TraceOptions\n\t): Promise<D | null> {\n\t\ttrace?.span.updateName(`Mikro-Orm - FindOne ${this.entityType.name}`);\n\t\tlogger.trace(`Running findOne ${this.entityType.name} with filter ${filter}`);\n\n\t\tconst metadata = this.em.getMetadata().get(this.entityType.name);\n\t\tlet primaryKeyField = metadata.primaryKeys[0];\n\n\t\tif (!primaryKeyField && entityMetadata) {\n\t\t\t// When using virtual entities, MikroORM will have no primary keys.\n\t\t\t// In this scenario we actually know what the primary key is from\n\t\t\t// the GraphQL metadata, so we can go ahead and use it.\n\t\t\tprimaryKeyField = graphweaverMetadata.primaryKeyFieldForEntity(entityMetadata);\n\t\t}\n\n\t\tif (!primaryKeyField || metadata.primaryKeys.length > 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`Entity ${this.entityType.name} has ${metadata.primaryKeys.length} primary keys. We only support entities with a single primary key at this stage.`\n\t\t\t);\n\t\t}\n\n\t\tconst [result] = await this.find(filter, {\n\t\t\torderBy: { [primaryKeyField]: Sort.DESC },\n\t\t\toffset: 0,\n\t\t\tlimit: 1,\n\t\t});\n\n\t\tlogger.trace(`findOne ${this.entityType.name} result`, { result });\n\n\t\treturn result;\n\t}\n\n\t@TraceMethod()\n\tpublic async findByRelatedId(\n\t\tentity: any,\n\t\trelatedField: string,\n\t\trelatedFieldIds: string[],\n\t\tfilter?: any,\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - findByRelatedId ${this.entityType.name}`);\n\t\tconst queryFilter = {\n\t\t\t$and: [{ [relatedField]: { $in: relatedFieldIds } }, ...[gqlToMikro(filter) ?? []]],\n\t\t};\n\n\t\tconst populate = [relatedField as AutoPath<typeof entity, PopulateHint>];\n\t\tconst result = await this.database.em.find(entity, queryFilter, {\n\t\t\tpopulate,\n\t\t});\n\n\t\treturn result as D[];\n\t}\n\n\t@TraceMethod()\n\tpublic async updateOne(\n\t\tid: string | number,\n\t\tupdateArgs: Partial<D & { version?: number }>,\n\t\ttrace?: TraceOptions\n\t): Promise<D> {\n\t\ttrace?.span.updateName(`Mikro-Orm - updateOne ${this.entityType.name}`);\n\n\t\tlogger.trace(`Running update ${this.entityType.name} with args`, {\n\t\t\tid,\n\t\t\tupdateArgs: JSON.stringify(updateArgs),\n\t\t});\n\n\t\tconst entity = await this.database.em.findOne(this.entityType, id, {\n\t\t\t// This is an optimisation so that assign() doesn't have to go fetch everything one at a time.\n\t\t\tpopulate: [...this.visitPathForPopulate(this.entityType.name, updateArgs)] as `${string}.`[],\n\t\t});\n\n\t\tif (entity === null) {\n\t\t\tthrow new Error(`Unable to locate ${this.entityType.name} with ID: '${id}' for updating.`);\n\t\t}\n\n\t\tconst { version, ...updateArgsWithoutVersion } = updateArgs;\n\n\t\t// If a version has been sent, let's check it\n\t\tif (version) {\n\t\t\ttry {\n\t\t\t\tawait this.database.em.lock(entity, LockMode.OPTIMISTIC, version);\n\t\t\t} catch (err) {\n\t\t\t\tthrow new OptimisticLockError((err as Error)?.message, { entity });\n\t\t\t}\n\t\t}\n\n\t\tawait this.mapAndAssignKeys(entity, this.entityType, updateArgsWithoutVersion as Partial<D>);\n\t\tawait this.database.em.persistAndFlush(entity);\n\n\t\tlogger.trace(`update ${this.entityType.name} entity`, entity);\n\n\t\treturn entity;\n\t}\n\n\t@TraceMethod()\n\tpublic async updateMany(\n\t\tupdateItems: (Partial<D> & { id: string })[],\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - updateMany ${this.entityType.name}`);\n\t\tlogger.trace(`Running update many ${this.entityType.name} with args`, {\n\t\t\tupdateItems: JSON.stringify(updateItems),\n\t\t});\n\n\t\tconst entities = await this.database.transactional<D[]>(async () => {\n\t\t\treturn Promise.all<D>(\n\t\t\t\tupdateItems.map(async (item) => {\n\t\t\t\t\tif (!item?.id) throw new Error('You must pass an ID for this entity to update it.');\n\n\t\t\t\t\t// Find the entity in the database\n\t\t\t\t\tconst entity = await this.database.em.findOneOrFail(this.entityType, item.id, {\n\t\t\t\t\t\tpopulate: [...this.visitPathForPopulate(this.entityType.name, item)] as `${string}.`[],\n\t\t\t\t\t});\n\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\tthis.database.em.persist(entity);\n\t\t\t\t\treturn entity;\n\t\t\t\t})\n\t\t\t);\n\t\t});\n\n\t\tlogger.trace(`updated ${this.entityType.name} items `, entities);\n\n\t\treturn entities;\n\t}\n\n\t@TraceMethod()\n\tpublic async createOrUpdateMany(items: Partial<D>[], trace?: TraceOptions): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createOrUpdateMany ${this.entityType.name}`);\n\t\tlogger.trace(`Running create or update many for ${this.entityType.name} with args`, {\n\t\t\titems: JSON.stringify(items),\n\t\t});\n\n\t\tconst entities = await this.database.transactional<D[]>(async () => {\n\t\t\treturn Promise.all<D>(\n\t\t\t\titems.map(async (item) => {\n\t\t\t\t\tlet entity;\n\t\t\t\t\tconst { id } = item as any;\n\t\t\t\t\tif (id) {\n\t\t\t\t\t\tentity = await this.database.em.findOneOrFail(this.entityType, id, {\n\t\t\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t\t\t...this.visitPathForPopulate(this.entityType.name, item),\n\t\t\t\t\t\t\t] as `${string}.`[],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tlogger.trace(`Running update on ${this.entityType.name} with item`, {\n\t\t\t\t\t\t\titem: JSON.stringify(item),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tentity = new this.entityType();\n\t\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\t\tlogger.trace(`Running create on ${this.entityType.name} with item`, {\n\t\t\t\t\t\t\titem: JSON.stringify(item),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tthis.database.em.persist(entity);\n\t\t\t\t\treturn entity;\n\t\t\t\t})\n\t\t\t);\n\t\t});\n\n\t\tlogger.trace(`created or updated ${this.entityType.name} items `, entities);\n\n\t\treturn entities;\n\t}\n\n\t@TraceMethod()\n\tpublic async createOne(createArgs: Partial<D>, trace?: TraceOptions): Promise<D> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createOne ${this.entityType.name}`);\n\t\tlogger.trace(`Running create ${this.entityType.name} with args`, {\n\t\t\tcreateArgs: JSON.stringify(createArgs),\n\t\t});\n\n\t\tconst entity = new this.entityType();\n\t\tawait this.mapAndAssignKeys(entity, this.entityType, createArgs);\n\t\tawait this.database.em.persistAndFlush(entity as Partial<D>);\n\n\t\tlogger.trace(`create ${this.entityType.name} result`, entity);\n\n\t\treturn entity;\n\t}\n\n\t@TraceMethod()\n\tpublic async createMany(createItems: Partial<D>[], trace?: TraceOptions): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createMany ${this.entityType.name}`);\n\t\treturn this._createMany(createItems);\n\t}\n\n\tpublic async createTraces(createItems: Partial<D>[]): Promise<D[]> {\n\t\treturn this._createMany(createItems);\n\t}\n\n\tprivate async _createMany(createItems: Partial<D>[]) {\n\t\tlogger.trace(`Running create ${this.entityType.name} with args`, {\n\t\t\tcreateArgs: JSON.stringify(createItems),\n\t\t});\n\n\t\tconst entities = await this.database.transactional<D[]>(async () => {\n\t\t\treturn Promise.all<D>(\n\t\t\t\tcreateItems.map(async (item) => {\n\t\t\t\t\tconst entity = new this.entityType();\n\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\tthis.database.em.persist(entity as Partial<D>);\n\t\t\t\t\treturn entity;\n\t\t\t\t})\n\t\t\t);\n\t\t});\n\n\t\tlogger.trace(`created ${this.entityType.name} items `, entities);\n\n\t\treturn entities;\n\t}\n\n\t@TraceMethod()\n\tpublic async deleteOne(filter: Filter<D>, trace?: TraceOptions): Promise<boolean> {\n\t\ttrace?.span.updateName(`Mikro-Orm - deleteOne ${this.entityType.name}`);\n\t\tlogger.trace(filter, `Running delete ${this.entityType.name} with filter.`);\n\t\tconst where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\t\tconst whereWithAppliedExternalIdFields =\n\t\t\twhere && this.applyExternalIdFields(this.entityType, where);\n\n\t\tconst deletedRows = await this.database.em.nativeDelete(\n\t\t\tthis.entityType,\n\t\t\twhereWithAppliedExternalIdFields\n\t\t);\n\n\t\tif (deletedRows > 1) {\n\t\t\tthrow new Error('Multiple deleted rows');\n\t\t}\n\n\t\tlogger.trace(`delete ${this.entityType.name} result: deleted ${deletedRows} row(s)`);\n\n\t\treturn deletedRows === 1;\n\t}\n\n\t@TraceMethod()\n\tpublic async deleteMany(filter: Filter<D>, trace?: TraceOptions): Promise<boolean> {\n\t\ttrace?.span.updateName(`Mikro-Orm - deleteMany ${this.entityType.name}`);\n\t\tlogger.trace(`Running delete ${this.entityType.name}`);\n\n\t\tconst deletedRows = await this.database.transactional<number>(async () => {\n\t\t\tconst where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\t\t\tconst whereWithAppliedExternalIdFields =\n\t\t\t\twhere && this.applyExternalIdFields(this.entityType, where);\n\n\t\t\tconst toDelete = await this.database.em.count(\n\t\t\t\tthis.entityType,\n\t\t\t\twhereWithAppliedExternalIdFields\n\t\t\t);\n\t\t\tconst deletedCount = await this.database.em.nativeDelete(\n\t\t\t\tthis.entityType,\n\t\t\t\twhereWithAppliedExternalIdFields\n\t\t\t);\n\n\t\t\tif (deletedCount !== toDelete) {\n\t\t\t\tthrow new Error('We did not delete any rows, rolling back.');\n\t\t\t}\n\n\t\t\treturn deletedCount;\n\t\t});\n\n\t\tlogger.trace(`delete ${this.entityType.name} result: deleted ${deletedRows} row(s)`);\n\n\t\treturn true;\n\t}\n\n\tpublic foreignKeyForRelationshipField?(field: FieldMetadata, dataEntity: D) {\n\t\tconst value = dataEntity[field.name as keyof D];\n\n\t\tif (Reference.isReference(value)) {\n\t\t\tconst { properties } = this.database.em.getMetadata().get(this.entityType);\n\t\t\tconst property = properties[field.name];\n\t\t\tconst [primaryKey] = property.targetMeta?.primaryKeys ?? [];\n\t\t\tif (!primaryKey) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Could not determine primary key for ${field.name} on ${this.entityType.name}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst foreignKey = (value.unwrap() as any)[primaryKey];\n\t\t\tif (foreignKey === undefined || foreignKey === null) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Could not read foreign key from reference: ${value.unwrap()} with primary key name ${primaryKey}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn foreignKey;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t@TraceMethod()\n\tpublic async aggregate(\n\t\tfilter: Filter<D>,\n\t\trequestedAggregations: Set<AggregationType>,\n\t\ttrace?: TraceOptions\n\t): Promise<AggregationResult> {\n\t\ttrace?.span.updateName(`Mikro-Orm - aggregate ${this.entityType.name}`);\n\t\tlogger.trace(`Running aggregate ${this.entityType.name} with filter`, {\n\t\t\tfilter: JSON.stringify(filter),\n\t\t});\n\n\t\t// Strip custom types out of the equation.\n\t\t// This query only works if we JSON.parse(JSON.stringify(filter)):\n\t\t//\n\t\t// query {\n\t\t// drivers (filter: { region: { name: \"North Shore\" }}) {\n\t\t// id\n\t\t// }\n\t\t// }\n\t\tconst where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\n\t\t// Convert from: { account: {id: '6' }}\n\t\t// to { accountId: '6' }\n\t\t// This conversion only works on root level objects\n\t\tconst whereWithAppliedExternalIdFields = where\n\t\t\t? this.applyExternalIdFields(this.entityType, where)\n\t\t\t: {};\n\n\t\t// Regions need some fancy handling with Query Builder. Process the where further\n\t\t// and return a Query Builder instance.\n\t\tconst query = this.em.createQueryBuilder(this.entityType);\n\n\t\tif (Object.keys(whereWithAppliedExternalIdFields).length > 0) {\n\t\t\tquery.andWhere(whereWithAppliedExternalIdFields);\n\t\t}\n\n\t\tconst result: AggregationResult = {};\n\n\t\ttry {\n\t\t\tif (requestedAggregations.has(AggregationType.COUNT)) {\n\t\t\t\tconst meta = this.database.em.getMetadata().get(this.entityType.name);\n\t\t\t\tif (meta.primaryKeys.length) {\n\t\t\t\t\t// It's a standard entity with primary keys, we can do a full distinct\n\t\t\t\t\t// on these keys.\n\t\t\t\t\tresult.count = await query.getCount(meta.primaryKeys, true);\n\t\t\t\t} else {\n\t\t\t\t\t// It's either a virtual entity, or it's an entity without primary keys.\n\t\t\t\t\t// We just need to count * as a fallback, no distinct.\n\t\t\t\t\tconst [firstRow] = await query.select(sql`count(*)`.as('count')).execute();\n\t\t\t\t\tresult.count = firstRow.count;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger.error(`find ${this.entityType.name} error: ${JSON.stringify(err)}`);\n\n\t\t\tif ((err as PostgresError)?.routine === 'InitializeSessionUserId') {\n\t\t\t\t// Throw if the user credentials are incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct user credentials for the database.'\n\t\t\t\t);\n\t\t\t} else if ((err as PostgresError)?.code === 'ECONNREFUSED') {\n\t\t\t\t// Throw if the database address or port is incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct address and port for the database.'\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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AAK,KAAuB,YAAY,2BAA2B;AAElE,cAAM,IAAI;AAAA,UACT;AAAA,QACD;AAAA,MACD,WAAY,KAAuB,SAAS,gBAAgB;AAE3D,cAAM,IAAI;AAAA,UACT;AAAA,QACD;AAAA,MACD,OAAO;AACN,cAAM;AAAA,MACP;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;AAncc;AAAA,MADZ,gCAAY;AAAA,GAzLD,qBA0LC;AAqFA;AAAA,MADZ,gCAAY;AAAA,GA9QD,qBA+QC;AAoCA;AAAA,MADZ,gCAAY;AAAA,GAlTD,qBAmTC;AAqBA;AAAA,MADZ,gCAAY;AAAA,GAvUD,qBAwUC;AAyCA;AAAA,MADZ,gCAAY;AAAA,GAhXD,qBAiXC;AA+BA;AAAA,MADZ,gCAAY;AAAA,GA/YD,qBAgZC;AAwCA;AAAA,MADZ,gCAAY;AAAA,GAvbD,qBAwbC;AAgBA;AAAA,MADZ,gCAAY;AAAA,GAvcD,qBAwcC;AA+BA;AAAA,MADZ,gCAAY;AAAA,GAteD,qBAueC;AAsBA;AAAA,MADZ,gCAAY;AAAA,GA5fD,qBA6fC;AAyDA;AAAA,MADZ,gCAAY;AAAA,GArjBD,qBAsjBC;",
4
+ "sourcesContent": ["import {\n\tBackendProvider,\n\tPaginationOptions,\n\tSort,\n\tFilter,\n\tBackendProviderConfig,\n\tFieldMetadata,\n\tAggregationResult,\n\tAggregationType,\n\tTraceMethod,\n\tTraceOptions,\n\ttraceSync,\n\ttrace as startTrace,\n\tGraphweaverRequestEvent,\n\tGraphweaverPluginNextFunction,\n\tEntityMetadata,\n\tgraphweaverMetadata,\n} from '@exogee/graphweaver';\nimport { logger } from '@exogee/logger';\nimport { Reference, RequestContext, sql } from '@mikro-orm/core';\nimport { AutoPath, PopulateHint } from '@mikro-orm/postgresql';\nimport { pluginManager, apolloPluginManager } from '@exogee/graphweaver-server';\n\nimport {\n\tLockMode,\n\tQueryFlag,\n\tReferenceKind,\n\tConnectionManager,\n\texternalIdFieldMap,\n\tAnyEntity,\n\tIsolationLevel,\n\tConnectionOptions,\n\tconnectToDatabase,\n} from '..';\n\nimport { OptimisticLockError } from '../utils/errors';\nimport { assign } from './assign';\n\ntype PostgresError = {\n\tcode: string;\n\troutine: string;\n};\n\nconst objectOperations = new Set(['_and', '_or', '_not']);\nconst mikroObjectOperations = new Set(['$and', '$or', '$not']);\n\nconst appendPath = (path: string, newPath: string) =>\n\tpath.length ? `${path}.${newPath}` : newPath;\n\nexport const gqlToMikro: (filter: any) => any = (filter: any) => {\n\tif (Array.isArray(filter)) {\n\t\treturn filter.map((element) => gqlToMikro(element));\n\t} else if (typeof filter === 'object') {\n\t\tfor (const key of Object.keys(filter)) {\n\t\t\t// A null here is a user-specified value and is valid to filter on\n\t\t\tif (filter[key] === null) continue;\n\n\t\t\tif (objectOperations.has(key)) {\n\t\t\t\t// { _not: '1' } => { $not: '1' }\n\t\t\t\tfilter[key.replace('_', '$')] = gqlToMikro(filter[key]);\n\t\t\t\tdelete filter[key];\n\t\t\t} else if (typeof filter[key] === 'object' && !Array.isArray(filter[key])) {\n\t\t\t\t// Recurse over nested filters only (arrays are an argument to a filter, not a nested filter)\n\t\t\t\tfilter[key] = gqlToMikro(filter[key]);\n\t\t\t} else if (key.indexOf('_') >= 0) {\n\t\t\t\t// { firstName_in: ['k', 'b'] } => { firstName: { $in: ['k', 'b'] } }\n\t\t\t\tconst [newKey, operator] = key.split('_');\n\t\t\t\tconst newValue = { [`$${operator}`]: gqlToMikro(filter[key]) };\n\n\t\t\t\t// They can construct multiple filters for the same key. In that case we need\n\t\t\t\t// to append them all into an object.\n\t\t\t\tif (typeof filter[newKey] !== 'undefined') {\n\t\t\t\t\tfilter[newKey] = { ...filter[newKey], ...newValue };\n\t\t\t\t} else {\n\t\t\t\t\tfilter[newKey] = newValue;\n\t\t\t\t}\n\n\t\t\t\tdelete filter[key];\n\t\t\t}\n\t\t}\n\t}\n\treturn filter;\n};\n\nexport class MikroBackendProvider<D> implements BackendProvider<D> {\n\tprivate _backendId: string;\n\n\tprivate connection: ConnectionOptions;\n\n\tpublic entityType: new () => D;\n\tpublic connectionManagerId?: string;\n\tprivate transactionIsolationLevel!: IsolationLevel;\n\n\tpublic readonly supportsInFilter = true;\n\n\t// Default backend provider config\n\tpublic readonly backendProviderConfig: BackendProviderConfig = {\n\t\tfilter: true,\n\t\tpagination: false,\n\t\torderBy: false,\n\t\tsupportedAggregationTypes: new Set<AggregationType>([AggregationType.COUNT]),\n\t};\n\n\tget backendId() {\n\t\treturn this._backendId;\n\t}\n\n\tprivate get database() {\n\t\t// If we have a connection manager ID then use that else fallback to the Database\n\t\tif (!this.connectionManagerId) return ConnectionManager.default;\n\t\treturn ConnectionManager.database(this.connectionManagerId) || ConnectionManager.default;\n\t}\n\n\t// This is exposed for use in the RLS package\n\tpublic get transactional() {\n\t\treturn this.database.transactional;\n\t}\n\n\tpublic async withTransaction<T>(callback: () => Promise<T>) {\n\t\treturn this.database.transactional<T>(callback, this.transactionIsolationLevel);\n\t}\n\n\t// This is exposed for use in the RLS package\n\tpublic get em() {\n\t\treturn this.database.em;\n\t}\n\n\tpublic constructor(\n\t\tmikroType: new () => D,\n\t\tconnection: ConnectionOptions,\n\t\ttransactionIsolationLevel: IsolationLevel = IsolationLevel.REPEATABLE_READ\n\t) {\n\t\tthis.entityType = mikroType;\n\t\tthis.connectionManagerId = connection.connectionManagerId;\n\t\tthis._backendId = `mikro-orm-${connection.connectionManagerId || ''}`;\n\t\tthis.transactionIsolationLevel = transactionIsolationLevel;\n\t\tthis.connection = connection;\n\t\tthis.addRequestContext();\n\t\tthis.connectToDatabase();\n\t}\n\n\tprivate connectToDatabase = async () => {\n\t\tconst connectionManagerId = this.connectionManagerId;\n\t\tif (!connectionManagerId) {\n\t\t\tthrow new Error('Expected connectionManagerId to be defined when calling addRequestContext.');\n\t\t}\n\n\t\tapolloPluginManager.addPlugin(connectionManagerId, connectToDatabase(this.connection));\n\t};\n\n\tprivate addRequestContext = () => {\n\t\tconst connectionManagerId = this.connectionManagerId;\n\t\tif (!connectionManagerId) {\n\t\t\tthrow new Error('Expected connectionManagerId to be defined when calling addRequestContext.');\n\t\t}\n\n\t\tconst connectionPlugin = {\n\t\t\tname: connectionManagerId,\n\t\t\tevent: GraphweaverRequestEvent.OnRequest,\n\t\t\tnext: (_: GraphweaverRequestEvent, _next: GraphweaverPluginNextFunction) => {\n\t\t\t\tlogger.trace(`Graphweaver OnRequest plugin called`);\n\n\t\t\t\tconst connection = ConnectionManager.database(connectionManagerId);\n\t\t\t\tif (!connection) throw new Error('No database connection found');\n\n\t\t\t\treturn RequestContext.create(connection.orm.em, _next, {});\n\t\t\t},\n\t\t};\n\t\tpluginManager.addPlugin(connectionPlugin);\n\t};\n\n\tprivate mapAndAssignKeys = (result: D, entityType: new () => D, inputArgs: Partial<D>) => {\n\t\t// Clean the input and remove any GraphQL classes from the object\n\t\tconst assignmentObj = this.applyExternalIdFields(entityType, inputArgs);\n\t\treturn assign(result, assignmentObj, undefined, undefined, this.database.em);\n\t};\n\n\tprivate applyExternalIdFields = (target: AnyEntity | string, values: any) => {\n\t\tconst targetName = typeof target === 'string' ? target : target.name;\n\t\tconst map = externalIdFieldMap.get(targetName);\n\n\t\tconst mapFieldNames = (partialFilterObj: any) => {\n\t\t\tfor (const [from, to] of Object.entries(map || {})) {\n\t\t\t\tif (partialFilterObj[from]) {\n\t\t\t\t\tconst keys = Object.keys(partialFilterObj[from]);\n\t\t\t\t\tif (keys.length > 1) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Expected precisely 1 key in queryObj.${from} on ${target}, got ${JSON.stringify(\n\t\t\t\t\t\t\t\tpartialFilterObj[from],\n\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\t4\n\t\t\t\t\t\t\t)}`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tpartialFilterObj[to] = partialFilterObj[from][keys[0]];\n\t\t\t\t\tdelete partialFilterObj[from];\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Check for and/or/etc at the root level and handle correctly\n\t\tfor (const rootLevelKey of Object.keys(values)) {\n\t\t\tif (mikroObjectOperations.has(rootLevelKey)) {\n\t\t\t\tfor (const field of values[rootLevelKey]) {\n\t\t\t\t\tmapFieldNames(field);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Map the rest of the field names as well\n\t\tmapFieldNames(values);\n\n\t\t// Traverse the nested entities\n\t\tconst { properties } = this.database.em.getMetadata().get(targetName);\n\t\tObject.values(properties)\n\t\t\t.filter((property) => typeof property.entity !== 'undefined' && values[property.name])\n\t\t\t.forEach((property) => {\n\t\t\t\tif (Array.isArray(values[property.name])) {\n\t\t\t\t\tvalues[property.name].forEach((value: any) =>\n\t\t\t\t\t\tthis.applyExternalIdFields(property.type, value)\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tvalues[property.name] = this.applyExternalIdFields(property.type, values[property.name]);\n\t\t\t\t}\n\t\t\t});\n\n\t\treturn values;\n\t};\n\n\t// Check if we have any keys that are a collection of entities\n\tpublic visitPathForPopulate = (entityName: string, updateArgBranch: any, populateBranch = '') => {\n\t\tconst { properties } = this.database.em.getMetadata().get(entityName);\n\t\tconst collectedPaths = populateBranch ? new Set<string>([populateBranch]) : new Set<string>([]);\n\n\t\tfor (const [key, value] of Object.entries(updateArgBranch ?? {})) {\n\t\t\tif (\n\t\t\t\t// If it's a relationship, go ahead and and '.' it in, recurse.\n\t\t\t\tproperties[key]?.kind === ReferenceKind.ONE_TO_ONE ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.ONE_TO_MANY ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.MANY_TO_ONE ||\n\t\t\t\tproperties[key]?.kind === ReferenceKind.MANY_TO_MANY\n\t\t\t) {\n\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\t// In the case where the array is empty we also need to make sure we load the collection.\n\t\t\t\t\tcollectedPaths.add(appendPath(populateBranch, key));\n\n\t\t\t\t\tfor (const entry of value) {\n\t\t\t\t\t\t// Recurse\n\t\t\t\t\t\tconst newPaths = this.visitPathForPopulate(\n\t\t\t\t\t\t\tproperties[key].type,\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t\tappendPath(populateBranch, key)\n\t\t\t\t\t\t);\n\t\t\t\t\t\tnewPaths.forEach((path) => collectedPaths.add(path));\n\t\t\t\t\t}\n\t\t\t\t} else if (typeof value === 'object') {\n\t\t\t\t\t// Recurse\n\t\t\t\t\tconst newPaths = this.visitPathForPopulate(\n\t\t\t\t\t\tproperties[key].type,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t\tappendPath(populateBranch, key)\n\t\t\t\t\t);\n\t\t\t\t\tnewPaths.forEach((path) => collectedPaths.add(path));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn collectedPaths;\n\t};\n\n\t@TraceMethod()\n\tpublic async find(\n\t\tfilter: Filter<D>,\n\t\tpagination?: PaginationOptions,\n\t\tentityMetadata?: EntityMetadata,\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\t// If we have a span, update the name\n\t\ttrace?.span.updateName(`Mikro-Orm - Find ${this.entityType.name}`);\n\n\t\tlogger.trace(`Running find ${this.entityType.name} with filter`, {\n\t\t\tfilter: JSON.stringify(filter),\n\t\t});\n\n\t\t// Strip custom types out of the equation.\n\t\t// This query only works if we JSON.parse(JSON.stringify(filter)):\n\t\t//\n\t\t// query {\n\t\t// drivers (filter: { region: { name: \"North Shore\" }}) {\n\t\t// id\n\t\t// }\n\t\t// }\n\t\tconst where = traceSync((trace?: TraceOptions) => {\n\t\t\ttrace?.span.updateName('Convert filter to Mikro-Orm format');\n\t\t\treturn filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\t\t})();\n\n\t\t// Convert from: { account: {id: '6' }}\n\t\t// to { accountId: '6' }\n\t\t// This conversion only works on root level objects\n\t\tconst whereWithAppliedExternalIdFields = where\n\t\t\t? this.applyExternalIdFields(this.entityType, where)\n\t\t\t: {};\n\n\t\t// Regions need some fancy handling with Query Builder. Process the where further\n\t\t// and return a Query Builder instance.\n\t\tconst query = this.em.createQueryBuilder(this.entityType);\n\t\tif (Object.keys(whereWithAppliedExternalIdFields).length > 0) {\n\t\t\tquery.andWhere(whereWithAppliedExternalIdFields);\n\t\t}\n\n\t\t// If we have specified a limit, offset or order then update the query\n\t\tif (pagination?.limit) query.limit(pagination.limit);\n\t\tif (pagination?.offset) query.offset(pagination.offset);\n\t\tif (pagination?.orderBy) query.orderBy({ ...pagination.orderBy });\n\n\t\t// Certain query filters can result in duplicate records once all joins are resolved\n\t\t// These duplicates can be discarded as related entities are returned to the\n\t\t// API consumer via field resolvers\n\t\tquery.setFlag(QueryFlag.DISTINCT);\n\n\t\t// 1:1 relations that aren't on the owning side need to get populated so the references get set.\n\t\t// This method is protected, but we need to use it from here, hence the `as any`.\n\t\tconst driver = this.database.em.getDriver();\n\t\tconst meta = this.database.em.getMetadata().get(this.entityType.name);\n\t\tquery.populate((driver as any).autoJoinOneToOneOwner(meta, []));\n\n\t\ttry {\n\t\t\tconst result = await startTrace(async (trace?: TraceOptions) => {\n\t\t\t\ttrace?.span.updateName('Mikro-Orm - Fetch Data');\n\t\t\t\treturn query.getResult();\n\t\t\t})();\n\n\t\t\tlogger.trace(`find ${this.entityType.name} result: ${result.length} rows`);\n\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tlogger.error(`find ${this.entityType.name} error: ${JSON.stringify(err)}`);\n\n\t\t\tif ((err as PostgresError)?.routine === 'InitializeSessionUserId') {\n\t\t\t\t// Throw if the user credentials are incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct user credentials for the database.'\n\t\t\t\t);\n\t\t\t} else if ((err as PostgresError)?.code === 'ECONNREFUSED') {\n\t\t\t\t// Throw if the database address or port is incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct address and port for the database.'\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t}\n\n\t@TraceMethod()\n\tpublic async findOne(\n\t\tfilter: Filter<D>,\n\t\tentityMetadata?: EntityMetadata,\n\t\ttrace?: TraceOptions\n\t): Promise<D | null> {\n\t\ttrace?.span.updateName(`Mikro-Orm - FindOne ${this.entityType.name}`);\n\t\tlogger.trace(`Running findOne ${this.entityType.name} with filter ${filter}`);\n\n\t\tconst metadata = this.em.getMetadata().get(this.entityType.name);\n\t\tlet primaryKeyField = metadata.primaryKeys[0];\n\n\t\tif (!primaryKeyField && entityMetadata) {\n\t\t\t// When using virtual entities, MikroORM will have no primary keys.\n\t\t\t// In this scenario we actually know what the primary key is from\n\t\t\t// the GraphQL metadata, so we can go ahead and use it.\n\t\t\tprimaryKeyField = graphweaverMetadata.primaryKeyFieldForEntity(entityMetadata);\n\t\t}\n\n\t\tif (!primaryKeyField || metadata.primaryKeys.length > 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`Entity ${this.entityType.name} has ${metadata.primaryKeys.length} primary keys. We only support entities with a single primary key at this stage.`\n\t\t\t);\n\t\t}\n\n\t\tconst [result] = await this.find(filter, {\n\t\t\torderBy: { [primaryKeyField]: Sort.DESC },\n\t\t\toffset: 0,\n\t\t\tlimit: 1,\n\t\t});\n\n\t\tlogger.trace(`findOne ${this.entityType.name} result`, { result });\n\n\t\treturn result;\n\t}\n\n\t@TraceMethod()\n\tpublic async findByRelatedId(\n\t\tentity: any,\n\t\trelatedField: string,\n\t\trelatedFieldIds: string[],\n\t\tfilter?: any,\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - findByRelatedId ${this.entityType.name}`);\n\t\tconst queryFilter = {\n\t\t\t$and: [{ [relatedField]: { $in: relatedFieldIds } }, ...[gqlToMikro(filter) ?? []]],\n\t\t};\n\n\t\tconst populate = [relatedField as AutoPath<typeof entity, PopulateHint>];\n\t\tconst result = await this.database.em.find(entity, queryFilter, {\n\t\t\tpopulate,\n\t\t});\n\n\t\treturn result as D[];\n\t}\n\n\t@TraceMethod()\n\tpublic async updateOne(\n\t\tid: string | number,\n\t\tupdateArgs: Partial<D & { version?: number }>,\n\t\ttrace?: TraceOptions\n\t): Promise<D> {\n\t\ttrace?.span.updateName(`Mikro-Orm - updateOne ${this.entityType.name}`);\n\n\t\tlogger.trace(`Running update ${this.entityType.name} with args`, {\n\t\t\tid,\n\t\t\tupdateArgs: JSON.stringify(updateArgs),\n\t\t});\n\n\t\tconst entity = await this.database.em.findOne(this.entityType, id, {\n\t\t\t// This is an optimisation so that assign() doesn't have to go fetch everything one at a time.\n\t\t\tpopulate: [...this.visitPathForPopulate(this.entityType.name, updateArgs)] as `${string}.`[],\n\t\t});\n\n\t\tif (entity === null) {\n\t\t\tthrow new Error(`Unable to locate ${this.entityType.name} with ID: '${id}' for updating.`);\n\t\t}\n\n\t\tconst { version, ...updateArgsWithoutVersion } = updateArgs;\n\n\t\t// If a version has been sent, let's check it\n\t\tif (version) {\n\t\t\ttry {\n\t\t\t\tawait this.database.em.lock(entity, LockMode.OPTIMISTIC, version);\n\t\t\t} catch (err) {\n\t\t\t\tthrow new OptimisticLockError((err as Error)?.message, { entity });\n\t\t\t}\n\t\t}\n\n\t\tawait this.mapAndAssignKeys(entity, this.entityType, updateArgsWithoutVersion as Partial<D>);\n\t\tawait this.database.em.persistAndFlush(entity);\n\n\t\tlogger.trace(`update ${this.entityType.name} entity`, entity);\n\n\t\treturn entity;\n\t}\n\n\t@TraceMethod()\n\tpublic async updateMany(\n\t\tupdateItems: (Partial<D> & { id: string })[],\n\t\ttrace?: TraceOptions\n\t): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - updateMany ${this.entityType.name}`);\n\t\tlogger.trace(`Running update many ${this.entityType.name} with args`, {\n\t\t\tupdateItems: JSON.stringify(updateItems),\n\t\t});\n\n\t\tconst entities = await this.database.transactional<D[]>(async () => {\n\t\t\treturn Promise.all<D>(\n\t\t\t\tupdateItems.map(async (item) => {\n\t\t\t\t\tif (!item?.id) throw new Error('You must pass an ID for this entity to update it.');\n\n\t\t\t\t\t// Find the entity in the database\n\t\t\t\t\tconst entity = await this.database.em.findOneOrFail(this.entityType, item.id, {\n\t\t\t\t\t\tpopulate: [...this.visitPathForPopulate(this.entityType.name, item)] as `${string}.`[],\n\t\t\t\t\t});\n\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\tthis.database.em.persist(entity);\n\t\t\t\t\treturn entity;\n\t\t\t\t})\n\t\t\t);\n\t\t});\n\n\t\tlogger.trace(`updated ${this.entityType.name} items `, entities);\n\n\t\treturn entities;\n\t}\n\n\t@TraceMethod()\n\tpublic async createOrUpdateMany(items: Partial<D>[], trace?: TraceOptions): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createOrUpdateMany ${this.entityType.name}`);\n\t\tlogger.trace(`Running create or update many for ${this.entityType.name} with args`, {\n\t\t\titems: JSON.stringify(items),\n\t\t});\n\n\t\tconst entities = await this.database.transactional<D[]>(async () => {\n\t\t\treturn Promise.all<D>(\n\t\t\t\titems.map(async (item) => {\n\t\t\t\t\tlet entity;\n\t\t\t\t\tconst { id } = item as any;\n\t\t\t\t\tif (id) {\n\t\t\t\t\t\tentity = await this.database.em.findOneOrFail(this.entityType, id, {\n\t\t\t\t\t\t\tpopulate: [\n\t\t\t\t\t\t\t\t...this.visitPathForPopulate(this.entityType.name, item),\n\t\t\t\t\t\t\t] as `${string}.`[],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tlogger.trace(`Running update on ${this.entityType.name} with item`, {\n\t\t\t\t\t\t\titem: JSON.stringify(item),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tentity = new this.entityType();\n\t\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\t\tlogger.trace(`Running create on ${this.entityType.name} with item`, {\n\t\t\t\t\t\t\titem: JSON.stringify(item),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tthis.database.em.persist(entity);\n\t\t\t\t\treturn entity;\n\t\t\t\t})\n\t\t\t);\n\t\t});\n\n\t\tlogger.trace(`created or updated ${this.entityType.name} items `, entities);\n\n\t\treturn entities;\n\t}\n\n\t@TraceMethod()\n\tpublic async createOne(createArgs: Partial<D>, trace?: TraceOptions): Promise<D> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createOne ${this.entityType.name}`);\n\t\tlogger.trace(`Running create ${this.entityType.name} with args`, {\n\t\t\tcreateArgs: JSON.stringify(createArgs),\n\t\t});\n\n\t\tconst entity = new this.entityType();\n\t\tawait this.mapAndAssignKeys(entity, this.entityType, createArgs);\n\t\tawait this.database.em.persistAndFlush(entity as Partial<D>);\n\n\t\tlogger.trace(`create ${this.entityType.name} result`, entity);\n\n\t\treturn entity;\n\t}\n\n\t@TraceMethod()\n\tpublic async createMany(createItems: Partial<D>[], trace?: TraceOptions): Promise<D[]> {\n\t\ttrace?.span.updateName(`Mikro-Orm - createMany ${this.entityType.name}`);\n\t\treturn this._createMany(createItems);\n\t}\n\n\tpublic async createTraces(createItems: Partial<D>[]): Promise<D[]> {\n\t\treturn this._createMany(createItems);\n\t}\n\n\tprivate async _createMany(createItems: Partial<D>[]) {\n\t\tlogger.trace(`Running create ${this.entityType.name} with args`, {\n\t\t\tcreateArgs: JSON.stringify(createItems),\n\t\t});\n\n\t\tconst entities = await this.database.transactional<D[]>(async () => {\n\t\t\treturn Promise.all<D>(\n\t\t\t\tcreateItems.map(async (item) => {\n\t\t\t\t\tconst entity = new this.entityType();\n\t\t\t\t\tawait this.mapAndAssignKeys(entity, this.entityType, item);\n\t\t\t\t\tthis.database.em.persist(entity as Partial<D>);\n\t\t\t\t\treturn entity;\n\t\t\t\t})\n\t\t\t);\n\t\t});\n\n\t\tlogger.trace(`created ${this.entityType.name} items `, entities);\n\n\t\treturn entities;\n\t}\n\n\t@TraceMethod()\n\tpublic async deleteOne(filter: Filter<D>, trace?: TraceOptions): Promise<boolean> {\n\t\ttrace?.span.updateName(`Mikro-Orm - deleteOne ${this.entityType.name}`);\n\t\tlogger.trace(filter, `Running delete ${this.entityType.name} with filter.`);\n\t\tconst where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\t\tconst whereWithAppliedExternalIdFields =\n\t\t\twhere && this.applyExternalIdFields(this.entityType, where);\n\n\t\tconst deletedRows = await this.database.em.nativeDelete(\n\t\t\tthis.entityType,\n\t\t\twhereWithAppliedExternalIdFields\n\t\t);\n\n\t\tif (deletedRows > 1) {\n\t\t\tthrow new Error('Multiple deleted rows');\n\t\t}\n\n\t\tlogger.trace(`delete ${this.entityType.name} result: deleted ${deletedRows} row(s)`);\n\n\t\treturn deletedRows === 1;\n\t}\n\n\t@TraceMethod()\n\tpublic async deleteMany(filter: Filter<D>, trace?: TraceOptions): Promise<boolean> {\n\t\ttrace?.span.updateName(`Mikro-Orm - deleteMany ${this.entityType.name}`);\n\t\tlogger.trace(`Running delete ${this.entityType.name}`);\n\n\t\tconst deletedRows = await this.database.transactional<number>(async () => {\n\t\t\tconst where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\t\t\tconst whereWithAppliedExternalIdFields =\n\t\t\t\twhere && this.applyExternalIdFields(this.entityType, where);\n\n\t\t\tconst toDelete = await this.database.em.count(\n\t\t\t\tthis.entityType,\n\t\t\t\twhereWithAppliedExternalIdFields\n\t\t\t);\n\t\t\tconst deletedCount = await this.database.em.nativeDelete(\n\t\t\t\tthis.entityType,\n\t\t\t\twhereWithAppliedExternalIdFields\n\t\t\t);\n\n\t\t\tif (deletedCount !== toDelete) {\n\t\t\t\tthrow new Error('We did not delete any rows, rolling back.');\n\t\t\t}\n\n\t\t\treturn deletedCount;\n\t\t});\n\n\t\tlogger.trace(`delete ${this.entityType.name} result: deleted ${deletedRows} row(s)`);\n\n\t\treturn true;\n\t}\n\n\tpublic foreignKeyForRelationshipField?(field: FieldMetadata, dataEntity: D) {\n\t\tconst value = dataEntity[field.name as keyof D];\n\n\t\tif (Reference.isReference(value)) {\n\t\t\tconst { properties } = this.database.em.getMetadata().get(this.entityType);\n\t\t\tconst property = properties[field.name];\n\t\t\tconst [primaryKey] = property.targetMeta?.primaryKeys ?? [];\n\t\t\tif (!primaryKey) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Could not determine primary key for ${field.name} on ${this.entityType.name}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst foreignKey = (value.unwrap() as any)[primaryKey];\n\t\t\tif (foreignKey === undefined || foreignKey === null) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Could not read foreign key from reference: ${value.unwrap()} with primary key name ${primaryKey}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn foreignKey;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t@TraceMethod()\n\tpublic async aggregate(\n\t\tfilter: Filter<D>,\n\t\trequestedAggregations: Set<AggregationType>,\n\t\ttrace?: TraceOptions\n\t): Promise<AggregationResult> {\n\t\ttrace?.span.updateName(`Mikro-Orm - aggregate ${this.entityType.name}`);\n\t\tlogger.trace(`Running aggregate ${this.entityType.name} with filter`, {\n\t\t\tfilter: JSON.stringify(filter),\n\t\t});\n\n\t\t// Strip custom types out of the equation.\n\t\t// This query only works if we JSON.parse(JSON.stringify(filter)):\n\t\t//\n\t\t// query {\n\t\t// drivers (filter: { region: { name: \"North Shore\" }}) {\n\t\t// id\n\t\t// }\n\t\t// }\n\t\tconst where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : undefined;\n\n\t\t// Convert from: { account: {id: '6' }}\n\t\t// to { accountId: '6' }\n\t\t// This conversion only works on root level objects\n\t\tconst whereWithAppliedExternalIdFields = where\n\t\t\t? this.applyExternalIdFields(this.entityType, where)\n\t\t\t: {};\n\n\t\t// Regions need some fancy handling with Query Builder. Process the where further\n\t\t// and return a Query Builder instance.\n\t\tconst query = this.em.createQueryBuilder(this.entityType);\n\n\t\tif (Object.keys(whereWithAppliedExternalIdFields).length > 0) {\n\t\t\tquery.andWhere(whereWithAppliedExternalIdFields);\n\t\t}\n\n\t\tconst result: AggregationResult = {};\n\n\t\ttry {\n\t\t\tif (requestedAggregations.has(AggregationType.COUNT)) {\n\t\t\t\tconst meta = this.database.em.getMetadata().get(this.entityType.name);\n\t\t\t\tif (meta.primaryKeys.length) {\n\t\t\t\t\t// It's a standard entity with primary keys, we can do a full distinct\n\t\t\t\t\t// on these keys.\n\t\t\t\t\tresult.count = await query.getCount(meta.primaryKeys, true);\n\t\t\t\t} else {\n\t\t\t\t\t// It's either a virtual entity, or it's an entity without primary keys.\n\t\t\t\t\t// We just need to count * as a fallback, no distinct.\n\t\t\t\t\tconst [firstRow] = await query.select(sql`count(*)`.as('count')).execute();\n\t\t\t\t\tresult.count = firstRow.count;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger.error(`find ${this.entityType.name} error: ${JSON.stringify(err)}`);\n\n\t\t\tif ((err as PostgresError)?.routine === 'InitializeSessionUserId') {\n\t\t\t\t// Throw if the user credentials are incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct user credentials for the database.'\n\t\t\t\t);\n\t\t\t} else if ((err as PostgresError)?.code === 'ECONNREFUSED') {\n\t\t\t\t// Throw if the database address or port is incorrect\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Database connection failed, please check you are using the correct address and port for the database.'\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAiBO;AACP,oBAAuB;AACvB,kBAA+C;AAE/C,gCAAmD;AAE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AAA,UACT;AAAA,QACD;AAAA,MACD,WAAY,KAAuB,SAAS,gBAAgB;AAE3D,cAAM,IAAI;AAAA,UACT;AAAA,QACD;AAAA,MACD,OAAO;AACN,cAAM;AAAA,MACP;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;AAncc;AAAA,MADZ,gCAAY;AAAA,GA1LD,qBA2LC;AAqFA;AAAA,MADZ,gCAAY;AAAA,GA/QD,qBAgRC;AAoCA;AAAA,MADZ,gCAAY;AAAA,GAnTD,qBAoTC;AAqBA;AAAA,MADZ,gCAAY;AAAA,GAxUD,qBAyUC;AAyCA;AAAA,MADZ,gCAAY;AAAA,GAjXD,qBAkXC;AA+BA;AAAA,MADZ,gCAAY;AAAA,GAhZD,qBAiZC;AAwCA;AAAA,MADZ,gCAAY;AAAA,GAxbD,qBAybC;AAgBA;AAAA,MADZ,gCAAY;AAAA,GAxcD,qBAycC;AA+BA;AAAA,MADZ,gCAAY;AAAA,GAveD,qBAweC;AAsBA;AAAA,MADZ,gCAAY;AAAA,GA7fD,qBA8fC;AAyDA;AAAA,MADZ,gCAAY;AAAA,GAtjBD,qBAujBC;",
6
6
  "names": ["trace", "startTrace"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exogee/graphweaver-mikroorm",
3
- "version": "2.3.0",
3
+ "version": "2.3.2",
4
4
  "description": "MikroORM backend for @exogee/graphweaver",
5
5
  "license": "Apache-2.0",
6
6
  "main": "lib/index.js",
@@ -20,17 +20,17 @@
20
20
  "graphql": "16.9.0",
21
21
  "pluralize": "8.0.0",
22
22
  "reflect-metadata": "0.2.2",
23
- "@exogee/graphweaver-server": "2.3.0",
24
- "@exogee/graphweaver": "2.3.0",
25
- "@exogee/logger": "2.3.0"
23
+ "@exogee/graphweaver": "2.3.2",
24
+ "@exogee/graphweaver-server": "2.3.2",
25
+ "@exogee/logger": "2.3.2"
26
26
  },
27
27
  "devDependencies": {
28
- "@mikro-orm/core": "6.3.7",
29
- "@mikro-orm/knex": "6.3.7",
30
- "@mikro-orm/mysql": "6.3.7",
31
- "@mikro-orm/postgresql": "6.3.7",
32
- "@mikro-orm/sqlite": "6.3.7",
33
- "@types/node": "22.5.0",
28
+ "@mikro-orm/core": "6.3.8",
29
+ "@mikro-orm/knex": "6.3.8",
30
+ "@mikro-orm/mysql": "6.3.8",
31
+ "@mikro-orm/postgresql": "6.3.8",
32
+ "@mikro-orm/sqlite": "6.3.8",
33
+ "@types/node": "22.5.3",
34
34
  "@types/pluralize": "0.0.33",
35
35
  "esbuild": "0.23.1",
36
36
  "glob": "10.4.3",
@@ -38,14 +38,14 @@
38
38
  "typescript": "5.5.4"
39
39
  },
40
40
  "optionalDependencies": {
41
- "@mikro-orm/knex": "6.3.7",
42
- "@mikro-orm/mysql": "6.3.7",
43
- "@mikro-orm/postgresql": "6.3.7",
44
- "@mikro-orm/sqlite": "6.3.7"
41
+ "@mikro-orm/knex": "6.3.8",
42
+ "@mikro-orm/mysql": "6.3.8",
43
+ "@mikro-orm/postgresql": "6.3.8",
44
+ "@mikro-orm/sqlite": "6.3.8"
45
45
  },
46
46
  "peerDependencies": {
47
- "@mikro-orm/core": "6.3.7",
48
- "@mikro-orm/knex": "6.3.7"
47
+ "@mikro-orm/core": "6.3.8",
48
+ "@mikro-orm/knex": "6.3.8"
49
49
  },
50
50
  "keywords": [
51
51
  "graphql",
@@ -64,6 +64,7 @@
64
64
  "generate:schema": "tsx ./src/utils/generate-db-schema.ts",
65
65
  "package:pack": "pnpm pack",
66
66
  "prettier": "prettier --write src/**/*.ts",
67
+ "test": "tsx scripts/check-mikro-overrides-match-installed-versions.ts",
67
68
  "test-introspection": "tsx scripts/test-introspection.ts",
68
69
  "version": "npm version --no-git-tag-version"
69
70
  }