@exogee/graphweaver-mikroorm 2.12.0 → 2.12.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,6 +1,6 @@
1
1
  import type { Dictionary, EntityMetadata, EntityProperty, NamingStrategy, Platform } from '@mikro-orm/core';
2
- import { BaseFile } from './base-file';
3
2
  import { DatabaseType } from '../../database';
3
+ import { BaseFile } from './base-file';
4
4
  export declare class DataEntityFile extends BaseFile {
5
5
  protected readonly meta: EntityMetadata;
6
6
  protected readonly namingStrategy: NamingStrategy;
@@ -22,8 +22,8 @@ __export(data_entity_file_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(data_entity_file_exports);
24
24
  var import_core = require("@mikro-orm/core");
25
- var import_base_file = require("./base-file");
26
25
  var import_utils = require("../utils");
26
+ var import_base_file = require("./base-file");
27
27
  class DataEntityFile extends import_base_file.BaseFile {
28
28
  constructor(meta, namingStrategy, platform, databaseType) {
29
29
  super(meta, namingStrategy, platform);
@@ -98,6 +98,9 @@ ${file}`;
98
98
  return "string";
99
99
  }
100
100
  }
101
+ if (prop.type === "bigint") {
102
+ return "string";
103
+ }
101
104
  return prop.runtimeType;
102
105
  }
103
106
  getPropertyDefinition(prop) {
@@ -247,7 +250,12 @@ ${file}`;
247
250
  if (columnType1 !== columnType2 || [mappedType1, mappedType2].some((t2) => t2 instanceof import_core.UnknownType)) {
248
251
  options.type = this.quote(prop.columnTypes[0]);
249
252
  } else {
250
- options.type = this.quote(prop.type);
253
+ if (mappedType1 instanceof import_core.BigIntType) {
254
+ this.coreImports.add("BigIntType");
255
+ options.type = "new BigIntType('string')";
256
+ } else {
257
+ options.type = this.quote(prop.type);
258
+ }
251
259
  }
252
260
  if (prop.length) {
253
261
  options.length = prop.length;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/introspection/files/data-entity-file.ts"],
4
- "sourcesContent": ["// This file is a modified version of source from MikroORM, located here:\n// https://github.com/mikro-orm/mikro-orm/blob/6ba3d4004deef00b754a4ca2011cf64e44a4a3a3/packages/entity-generator/src/SourceFile.ts\n//\n// MIT License\n//\n// Copyright (c) 2018 Martin Ad\u00E1mek\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport type {\n\tDictionary,\n\tEntityMetadata,\n\tEntityOptions,\n\tEntityProperty,\n\tNamingStrategy,\n\tPlatform,\n} from '@mikro-orm/core';\nimport { ReferenceKind, UnknownType, Utils } from '@mikro-orm/core';\nimport { BaseFile } from './base-file';\nimport { DatabaseType } from '../../database';\nimport { identifierForEnumValue, pascalToKebabCaseString } from '../utils';\n\nexport class DataEntityFile extends BaseFile {\n\tprotected readonly coreImports = new Set<string>();\n\tprotected readonly entityImports = new Set<string>();\n\n\tconstructor(\n\t\tprotected readonly meta: EntityMetadata,\n\t\tprotected readonly namingStrategy: NamingStrategy,\n\t\tprotected readonly platform: Platform,\n\t\tprotected readonly databaseType: DatabaseType\n\t) {\n\t\tsuper(meta, namingStrategy, platform);\n\t}\n\n\tgetBasePath() {\n\t\treturn `backend/entities/${this.databaseType}/`;\n\t}\n\n\tgetBaseName() {\n\t\tconst fileName = pascalToKebabCaseString(this.meta.className);\n\t\treturn `${fileName}.ts`;\n\t}\n\n\tgenerate(): string {\n\t\tconst enumDefinitions: string[] = [];\n\t\tlet classBody = '';\n\t\tconst props = Object.values(this.meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tconst decorator = this.getPropertyDecorator(prop);\n\t\t\tconst definition = this.getPropertyDefinition(prop);\n\n\t\t\tif (!classBody.endsWith('\\n\\n')) {\n\t\t\t\tclassBody += '\\n';\n\t\t\t}\n\n\t\t\tclassBody += decorator;\n\t\t\tclassBody += definition;\n\n\t\t\tif (props[props.length - 1] !== prop) classBody += '\\n';\n\n\t\t\tif (prop.enum) {\n\t\t\t\tconst enumClassName = this.namingStrategy.getClassName(\n\t\t\t\t\tthis.meta.collection + '_' + prop.fieldNames[0],\n\t\t\t\t\t'_'\n\t\t\t\t);\n\t\t\t\tenumDefinitions.push(this.getEnumClassDefinition(enumClassName, prop.items as string[]));\n\t\t\t}\n\t\t});\n\n\t\tlet file = ``;\n\n\t\tthis.coreImports.add('Entity');\n\t\tconst imports = [\n\t\t\t`import { ${[...this.coreImports].sort().join(', ')} } from '@mikro-orm/core';`,\n\t\t];\n\t\tconst entityImports = [...this.entityImports].filter((e) => e !== this.meta.className);\n\t\tentityImports.sort().forEach((entity) => {\n\t\t\timports.push(`import { ${entity} } from './${pascalToKebabCaseString(entity)}';`);\n\t\t});\n\n\t\tif (enumDefinitions.length) {\n\t\t\tfile += enumDefinitions.join('\\n');\n\t\t\tfile += '\\n';\n\t\t}\n\n\t\tfile += `@Entity(${this.getCollectionDecl()})\\n`;\n\t\tfile += `export class ${this.meta.className} {`;\n\n\t\tfile += `${classBody}}\\n`;\n\n\t\tfile = `${imports.join('\\n')}\\n\\n${file}`;\n\n\t\treturn file;\n\t}\n\n\tprotected getPropertyType(prop: EntityProperty): string {\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\treturn prop.type.charAt(0).toUpperCase() + prop.type.slice(1);\n\t\t}\n\n\t\tconst columnType = prop.columnTypes?.[0]?.toLowerCase();\n\n\t\tif (['jsonb', 'json', 'any'].includes(columnType)) {\n\t\t\treturn `Record<string, unknown>`;\n\t\t}\n\n\t\t// Mikro doesn't infer column types for some columns very well. We can augment.\n\t\tif (prop.type === 'unknown') {\n\t\t\tif (columnType?.startsWith('nvarchar(') || columnType?.startsWith('varchar(')) {\n\t\t\t\treturn 'string';\n\t\t\t}\n\t\t}\n\n\t\treturn prop.runtimeType;\n\t}\n\n\tprotected getPropertyDefinition(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('Collection');\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name} = new Collection<${prop.type}>(this);\\n`;\n\t\t}\n\n\t\t// string defaults are usually things like SQL functions, but can be also enums, for that `useDefault` should be true\n\t\tconst isEnumOrNonStringDefault = prop.enum || typeof prop.default !== 'string';\n\t\tconst useDefault = prop.default != null && isEnumOrNonStringDefault;\n\t\tconst optional = prop.nullable ? '?' : useDefault ? '' : '!';\n\n\t\tif (prop.ref) {\n\t\t\tthis.coreImports.add('Ref');\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name}${optional}: Ref<${prop.type}>;\\n`;\n\t\t}\n\n\t\tconst file = `${prop.name}${optional}: ${this.getPropertyType(prop)}`;\n\n\t\tif (!useDefault) {\n\t\t\treturn `${padding + file};\\n`;\n\t\t}\n\n\t\tif (prop.enum && typeof prop.default === 'string') {\n\t\t\treturn `${padding}${file} = ${prop.runtimeType}.${identifierForEnumValue(prop.default)};\\n`;\n\t\t}\n\n\t\treturn `${padding}${prop.name} = ${prop.default};\\n`;\n\t}\n\n\tprotected getEnumClassDefinition(enumClassName: string, enumValues: string[]): string {\n\t\tconst padding = '\\t';\n\t\tlet file = `export enum ${enumClassName} {\\n`;\n\n\t\tfor (const enumValue of enumValues) {\n\t\t\tfile += `${padding}${identifierForEnumValue(enumValue)} = '${enumValue}',\\n`;\n\t\t}\n\n\t\tfile += '}\\n';\n\n\t\treturn file;\n\t}\n\n\tprivate getCollectionDecl() {\n\t\tconst options: EntityOptions<unknown> = {};\n\n\t\toptions.tableName = this.quote(this.meta.collection);\n\n\t\tif (this.meta.schema && this.meta.schema !== this.platform.getDefaultSchemaName()) {\n\t\t\toptions.schema = this.quote(this.meta.schema);\n\t\t}\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn '';\n\t\t}\n\n\t\treturn `{ ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${val}`)\n\t\t\t.join(', ')} }`;\n\t}\n\n\tprivate getPropertyDecorator(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\t\tconst options = {} as Dictionary;\n\t\tlet decorator = this.getDecoratorType(prop);\n\t\tthis.coreImports.add(decorator.substring(1));\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\tthis.getManyToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\tthis.getOneToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind !== ReferenceKind.SCALAR) {\n\t\t\tthis.getForeignKeyDecoratorOptions(options, prop);\n\t\t} else {\n\t\t\tthis.getScalarPropertyDecoratorOptions(options, prop);\n\t\t}\n\n\t\tif (prop.enum) {\n\t\t\toptions.items = `() => ${prop.runtimeType}`;\n\t\t}\n\n\t\tthis.getCommonDecoratorOptions(options, prop);\n\t\tconst indexes = this.getPropertyIndexes(prop, options);\n\t\tdecorator = [...indexes.sort(), decorator].map((d) => padding + d).join('\\n');\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn `${decorator}()\\n`;\n\t\t}\n\n\t\treturn `${decorator}({ ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${val}`)\n\t\t\t.join(', ')} })\\n`;\n\t}\n\n\tprotected getPropertyIndexes(prop: EntityProperty, options: Dictionary): string[] {\n\t\tif (prop.kind === ReferenceKind.SCALAR) {\n\t\t\tconst ret: string[] = [];\n\n\t\t\tif (prop.index) {\n\t\t\t\tthis.coreImports.add('Index');\n\t\t\t\tret.push(`@Index({ name: '${prop.index}' })`);\n\t\t\t}\n\n\t\t\tif (prop.unique) {\n\t\t\t\tthis.coreImports.add('Unique');\n\t\t\t\tret.push(`@Unique({ name: '${prop.unique}' })`);\n\t\t\t}\n\n\t\t\treturn ret;\n\t\t}\n\n\t\tconst processIndex = (type: 'index' | 'unique') => {\n\t\t\tif (!prop[type]) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst defaultName = this.platform.getIndexName(this.meta.collection, prop.fieldNames, type);\n\t\t\toptions[type] = defaultName === prop[type] ? 'true' : `'${prop[type]}'`;\n\t\t\tconst expected = {\n\t\t\t\tindex: this.platform.indexForeignKeys(),\n\t\t\t\tunique: prop.kind === ReferenceKind.ONE_TO_ONE,\n\t\t\t};\n\n\t\t\tif (expected[type] && options[type] === 'true') {\n\t\t\t\tdelete options[type];\n\t\t\t}\n\t\t};\n\n\t\tprocessIndex('index');\n\t\tprocessIndex('unique');\n\n\t\treturn [];\n\t}\n\n\tprotected getCommonDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tif (prop.nullable && !prop.mappedBy) {\n\t\t\toptions.nullable = true;\n\t\t}\n\n\t\tif (prop.default == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (typeof prop.default !== 'string') {\n\t\t\toptions.default = prop.default;\n\t\t\treturn;\n\t\t}\n\n\t\tif ([`''`, ''].includes(prop.default)) {\n\t\t\toptions.default = `''`;\n\t\t} else if (prop.defaultRaw === this.quote(prop.default)) {\n\t\t\toptions.default = this.quote(prop.default);\n\t\t} else {\n\t\t\toptions.defaultRaw = `\\`${prop.default}\\``;\n\t\t}\n\t}\n\n\tprotected getScalarPropertyDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tlet t = prop.type.toLowerCase();\n\n\t\tif (t === 'date') {\n\t\t\tt = 'datetime';\n\t\t}\n\n\t\tif (prop.fieldNames[0] !== this.namingStrategy.propertyToColumnName(prop.name)) {\n\t\t\toptions.fieldName = `'${prop.fieldNames[0]}'`;\n\t\t}\n\n\t\t// for enum properties, we don't need a column type or the property length\n\t\t// in the decorator so return early.\n\t\tif (prop.enum) {\n\t\t\toptions.type = this.quote('string');\n\t\t\treturn;\n\t\t}\n\n\t\tconst mappedType1 = this.platform.getMappedType(t);\n\t\tconst mappedType2 = this.platform.getMappedType(prop.columnTypes[0]);\n\t\tconst columnType1 = mappedType1.getColumnType({ ...prop, autoincrement: false }, this.platform);\n\t\tconst columnType2 = mappedType2.getColumnType({ ...prop, autoincrement: false }, this.platform);\n\n\t\tif (\n\t\t\tcolumnType1 !== columnType2 ||\n\t\t\t[mappedType1, mappedType2].some((t) => t instanceof UnknownType)\n\t\t) {\n\t\t\toptions.type = this.quote(prop.columnTypes[0]);\n\t\t} else {\n\t\t\toptions.type = this.quote(prop.type);\n\t\t}\n\n\t\tif (prop.length) {\n\t\t\toptions.length = prop.length;\n\t\t}\n\t}\n\n\tprotected getManyToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\n\t\tif (prop.mappedBy) {\n\t\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t\t\treturn;\n\t\t}\n\n\t\tif (\n\t\t\tprop.pivotTable !==\n\t\t\tthis.namingStrategy.joinTableName(this.meta.collection, prop.type, prop.name)\n\t\t) {\n\t\t\toptions.pivotTable = this.quote(prop.pivotTable);\n\t\t}\n\n\t\tif (prop.joinColumns.length === 1) {\n\t\t\toptions.joinColumn = this.quote(prop.joinColumns[0]);\n\t\t} else {\n\t\t\toptions.joinColumns = `[${prop.joinColumns.map(this.quote).join(', ')}]`;\n\t\t}\n\n\t\tif (prop.inverseJoinColumns.length === 1) {\n\t\t\toptions.inverseJoinColumn = this.quote(prop.inverseJoinColumns[0]);\n\t\t} else {\n\t\t\toptions.inverseJoinColumns = `[${prop.inverseJoinColumns.map(this.quote).join(', ')}]`;\n\t\t}\n\t}\n\n\tprotected getOneToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t}\n\n\tprotected getForeignKeyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\n\t\tif (prop.ref) {\n\t\t\toptions.ref = true;\n\t\t}\n\n\t\tif (prop.mappedBy) {\n\t\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t\t\treturn;\n\t\t}\n\n\t\tif (\n\t\t\tprop.fieldNames[0] !==\n\t\t\tthis.namingStrategy.joinKeyColumnName(prop.name, prop.referencedColumnNames[0])\n\t\t) {\n\t\t\toptions.fieldName = this.quote(prop.fieldNames[0]);\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\toptions.primary = true;\n\t\t}\n\t}\n\n\tprotected getDecoratorType(prop: EntityProperty): string {\n\t\tif (prop.kind === ReferenceKind.ONE_TO_ONE) {\n\t\t\treturn '@OneToOne';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_ONE) {\n\t\t\treturn '@ManyToOne';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\treturn '@OneToMany';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\treturn '@ManyToMany';\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\treturn '@Pr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B;AACxD,QAAI,KAAK,SAAS,0BAAc,YAAY;AAC3C,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,SAAS,0BAAc,aAAa;AAC5C,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,SAAS,0BAAc,aAAa;AAC5C,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,SAAS,0BAAc,cAAc;AAC7C,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,SAAS;AACjB,aAAO;AAAA,IACR;AAEA,QAAI,KAAK,MAAM;AACd,aAAO;AAAA,IACR;AAEA,WAAO;AAAA,EACR;AACD;",
4
+ "sourcesContent": ["// This file is a modified version of source from MikroORM, located here:\n// https://github.com/mikro-orm/mikro-orm/blob/6ba3d4004deef00b754a4ca2011cf64e44a4a3a3/packages/entity-generator/src/SourceFile.ts\n//\n// MIT License\n//\n// Copyright (c) 2018 Martin Ad\u00E1mek\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport type {\n\tDictionary,\n\tEntityMetadata,\n\tEntityOptions,\n\tEntityProperty,\n\tNamingStrategy,\n\tPlatform,\n} from '@mikro-orm/core';\nimport { BigIntType, ReferenceKind, UnknownType, Utils } from '@mikro-orm/core';\nimport { DatabaseType } from '../../database';\nimport { identifierForEnumValue, pascalToKebabCaseString } from '../utils';\nimport { BaseFile } from './base-file';\n\nexport class DataEntityFile extends BaseFile {\n\tprotected readonly coreImports = new Set<string>();\n\tprotected readonly entityImports = new Set<string>();\n\n\tconstructor(\n\t\tprotected readonly meta: EntityMetadata,\n\t\tprotected readonly namingStrategy: NamingStrategy,\n\t\tprotected readonly platform: Platform,\n\t\tprotected readonly databaseType: DatabaseType\n\t) {\n\t\tsuper(meta, namingStrategy, platform);\n\t}\n\n\tgetBasePath() {\n\t\treturn `backend/entities/${this.databaseType}/`;\n\t}\n\n\tgetBaseName() {\n\t\tconst fileName = pascalToKebabCaseString(this.meta.className);\n\t\treturn `${fileName}.ts`;\n\t}\n\n\tgenerate(): string {\n\t\tconst enumDefinitions: string[] = [];\n\t\tlet classBody = '';\n\t\tconst props = Object.values(this.meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tconst decorator = this.getPropertyDecorator(prop);\n\t\t\tconst definition = this.getPropertyDefinition(prop);\n\n\t\t\tif (!classBody.endsWith('\\n\\n')) {\n\t\t\t\tclassBody += '\\n';\n\t\t\t}\n\n\t\t\tclassBody += decorator;\n\t\t\tclassBody += definition;\n\n\t\t\tif (props[props.length - 1] !== prop) classBody += '\\n';\n\n\t\t\tif (prop.enum) {\n\t\t\t\tconst enumClassName = this.namingStrategy.getClassName(\n\t\t\t\t\tthis.meta.collection + '_' + prop.fieldNames[0],\n\t\t\t\t\t'_'\n\t\t\t\t);\n\t\t\t\tenumDefinitions.push(this.getEnumClassDefinition(enumClassName, prop.items as string[]));\n\t\t\t}\n\t\t});\n\n\t\tlet file = ``;\n\n\t\tthis.coreImports.add('Entity');\n\t\tconst imports = [\n\t\t\t`import { ${[...this.coreImports].sort().join(', ')} } from '@mikro-orm/core';`,\n\t\t];\n\t\tconst entityImports = [...this.entityImports].filter((e) => e !== this.meta.className);\n\t\tentityImports.sort().forEach((entity) => {\n\t\t\timports.push(`import { ${entity} } from './${pascalToKebabCaseString(entity)}';`);\n\t\t});\n\n\t\tif (enumDefinitions.length) {\n\t\t\tfile += enumDefinitions.join('\\n');\n\t\t\tfile += '\\n';\n\t\t}\n\n\t\tfile += `@Entity(${this.getCollectionDecl()})\\n`;\n\t\tfile += `export class ${this.meta.className} {`;\n\n\t\tfile += `${classBody}}\\n`;\n\n\t\tfile = `${imports.join('\\n')}\\n\\n${file}`;\n\n\t\treturn file;\n\t}\n\n\tprotected getPropertyType(prop: EntityProperty): string {\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\treturn prop.type.charAt(0).toUpperCase() + prop.type.slice(1);\n\t\t}\n\n\t\tconst columnType = prop.columnTypes?.[0]?.toLowerCase();\n\n\t\tif (['jsonb', 'json', 'any'].includes(columnType)) {\n\t\t\treturn `Record<string, unknown>`;\n\t\t}\n\n\t\t// Mikro doesn't infer column types for some columns very well. We can augment.\n\t\tif (prop.type === 'unknown') {\n\t\t\tif (columnType?.startsWith('nvarchar(') || columnType?.startsWith('varchar(')) {\n\t\t\t\treturn 'string';\n\t\t\t}\n\t\t}\n\n\t\tif (prop.type === 'bigint') {\n\t\t\treturn 'string';\n\t\t}\n\n\t\treturn prop.runtimeType;\n\t}\n\n\tprotected getPropertyDefinition(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('Collection');\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name} = new Collection<${prop.type}>(this);\\n`;\n\t\t}\n\n\t\t// string defaults are usually things like SQL functions, but can be also enums, for that `useDefault` should be true\n\t\tconst isEnumOrNonStringDefault = prop.enum || typeof prop.default !== 'string';\n\t\tconst useDefault = prop.default != null && isEnumOrNonStringDefault;\n\t\tconst optional = prop.nullable ? '?' : useDefault ? '' : '!';\n\n\t\tif (prop.ref) {\n\t\t\tthis.coreImports.add('Ref');\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name}${optional}: Ref<${prop.type}>;\\n`;\n\t\t}\n\n\t\tconst file = `${prop.name}${optional}: ${this.getPropertyType(prop)}`;\n\n\t\tif (!useDefault) {\n\t\t\treturn `${padding + file};\\n`;\n\t\t}\n\n\t\tif (prop.enum && typeof prop.default === 'string') {\n\t\t\treturn `${padding}${file} = ${prop.runtimeType}.${identifierForEnumValue(prop.default)};\\n`;\n\t\t}\n\n\t\treturn `${padding}${prop.name} = ${prop.default};\\n`;\n\t}\n\n\tprotected getEnumClassDefinition(enumClassName: string, enumValues: string[]): string {\n\t\tconst padding = '\\t';\n\t\tlet file = `export enum ${enumClassName} {\\n`;\n\n\t\tfor (const enumValue of enumValues) {\n\t\t\tfile += `${padding}${identifierForEnumValue(enumValue)} = '${enumValue}',\\n`;\n\t\t}\n\n\t\tfile += '}\\n';\n\n\t\treturn file;\n\t}\n\n\tprivate getCollectionDecl() {\n\t\tconst options: EntityOptions<unknown> = {};\n\n\t\toptions.tableName = this.quote(this.meta.collection);\n\n\t\tif (this.meta.schema && this.meta.schema !== this.platform.getDefaultSchemaName()) {\n\t\t\toptions.schema = this.quote(this.meta.schema);\n\t\t}\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn '';\n\t\t}\n\n\t\treturn `{ ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${val}`)\n\t\t\t.join(', ')} }`;\n\t}\n\n\tprivate getPropertyDecorator(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\t\tconst options = {} as Dictionary;\n\t\tlet decorator = this.getDecoratorType(prop);\n\t\tthis.coreImports.add(decorator.substring(1));\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\tthis.getManyToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\tthis.getOneToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind !== ReferenceKind.SCALAR) {\n\t\t\tthis.getForeignKeyDecoratorOptions(options, prop);\n\t\t} else {\n\t\t\tthis.getScalarPropertyDecoratorOptions(options, prop);\n\t\t}\n\n\t\tif (prop.enum) {\n\t\t\toptions.items = `() => ${prop.runtimeType}`;\n\t\t}\n\n\t\tthis.getCommonDecoratorOptions(options, prop);\n\t\tconst indexes = this.getPropertyIndexes(prop, options);\n\t\tdecorator = [...indexes.sort(), decorator].map((d) => padding + d).join('\\n');\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn `${decorator}()\\n`;\n\t\t}\n\n\t\treturn `${decorator}({ ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${val}`)\n\t\t\t.join(', ')} })\\n`;\n\t}\n\n\tprotected getPropertyIndexes(prop: EntityProperty, options: Dictionary): string[] {\n\t\tif (prop.kind === ReferenceKind.SCALAR) {\n\t\t\tconst ret: string[] = [];\n\n\t\t\tif (prop.index) {\n\t\t\t\tthis.coreImports.add('Index');\n\t\t\t\tret.push(`@Index({ name: '${prop.index}' })`);\n\t\t\t}\n\n\t\t\tif (prop.unique) {\n\t\t\t\tthis.coreImports.add('Unique');\n\t\t\t\tret.push(`@Unique({ name: '${prop.unique}' })`);\n\t\t\t}\n\n\t\t\treturn ret;\n\t\t}\n\n\t\tconst processIndex = (type: 'index' | 'unique') => {\n\t\t\tif (!prop[type]) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst defaultName = this.platform.getIndexName(this.meta.collection, prop.fieldNames, type);\n\t\t\toptions[type] = defaultName === prop[type] ? 'true' : `'${prop[type]}'`;\n\t\t\tconst expected = {\n\t\t\t\tindex: this.platform.indexForeignKeys(),\n\t\t\t\tunique: prop.kind === ReferenceKind.ONE_TO_ONE,\n\t\t\t};\n\n\t\t\tif (expected[type] && options[type] === 'true') {\n\t\t\t\tdelete options[type];\n\t\t\t}\n\t\t};\n\n\t\tprocessIndex('index');\n\t\tprocessIndex('unique');\n\n\t\treturn [];\n\t}\n\n\tprotected getCommonDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tif (prop.nullable && !prop.mappedBy) {\n\t\t\toptions.nullable = true;\n\t\t}\n\n\t\tif (prop.default == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (typeof prop.default !== 'string') {\n\t\t\toptions.default = prop.default;\n\t\t\treturn;\n\t\t}\n\n\t\tif ([`''`, ''].includes(prop.default)) {\n\t\t\toptions.default = `''`;\n\t\t} else if (prop.defaultRaw === this.quote(prop.default)) {\n\t\t\toptions.default = this.quote(prop.default);\n\t\t} else {\n\t\t\toptions.defaultRaw = `\\`${prop.default}\\``;\n\t\t}\n\t}\n\n\tprotected getScalarPropertyDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tlet t = prop.type.toLowerCase();\n\n\t\tif (t === 'date') {\n\t\t\tt = 'datetime';\n\t\t}\n\n\t\tif (prop.fieldNames[0] !== this.namingStrategy.propertyToColumnName(prop.name)) {\n\t\t\toptions.fieldName = `'${prop.fieldNames[0]}'`;\n\t\t}\n\n\t\t// for enum properties, we don't need a column type or the property length\n\t\t// in the decorator so return early.\n\t\tif (prop.enum) {\n\t\t\toptions.type = this.quote('string');\n\t\t\treturn;\n\t\t}\n\n\t\tconst mappedType1 = this.platform.getMappedType(t);\n\t\tconst mappedType2 = this.platform.getMappedType(prop.columnTypes[0]);\n\t\tconst columnType1 = mappedType1.getColumnType({ ...prop, autoincrement: false }, this.platform);\n\t\tconst columnType2 = mappedType2.getColumnType({ ...prop, autoincrement: false }, this.platform);\n\n\t\tif (\n\t\t\tcolumnType1 !== columnType2 ||\n\t\t\t[mappedType1, mappedType2].some((t) => t instanceof UnknownType)\n\t\t) {\n\t\t\toptions.type = this.quote(prop.columnTypes[0]);\n\t\t} else {\n\t\t\t// Special case for when prop.type is BigIntType\n\t\t\tif (mappedType1 instanceof BigIntType) {\n\t\t\t\tthis.coreImports.add('BigIntType');\n\t\t\t\toptions.type = \"new BigIntType('string')\";\n\t\t\t} else {\n\t\t\t\toptions.type = this.quote(prop.type);\n\t\t\t}\n\t\t}\n\n\t\tif (prop.length) {\n\t\t\toptions.length = prop.length;\n\t\t}\n\t}\n\n\tprotected getManyToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\n\t\tif (prop.mappedBy) {\n\t\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t\t\treturn;\n\t\t}\n\n\t\tif (\n\t\t\tprop.pivotTable !==\n\t\t\tthis.namingStrategy.joinTableName(this.meta.collection, prop.type, prop.name)\n\t\t) {\n\t\t\toptions.pivotTable = this.quote(prop.pivotTable);\n\t\t}\n\n\t\tif (prop.joinColumns.length === 1) {\n\t\t\toptions.joinColumn = this.quote(prop.joinColumns[0]);\n\t\t} else {\n\t\t\toptions.joinColumns = `[${prop.joinColumns.map(this.quote).join(', ')}]`;\n\t\t}\n\n\t\tif (prop.inverseJoinColumns.length === 1) {\n\t\t\toptions.inverseJoinColumn = this.quote(prop.inverseJoinColumns[0]);\n\t\t} else {\n\t\t\toptions.inverseJoinColumns = `[${prop.inverseJoinColumns.map(this.quote).join(', ')}]`;\n\t\t}\n\t}\n\n\tprotected getOneToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t}\n\n\tprotected getForeignKeyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.entity = `() => ${prop.type}`;\n\n\t\tif (prop.ref) {\n\t\t\toptions.ref = true;\n\t\t}\n\n\t\tif (prop.mappedBy) {\n\t\t\toptions.mappedBy = this.quote(prop.mappedBy);\n\t\t\treturn;\n\t\t}\n\n\t\tif (\n\t\t\tprop.fieldNames[0] !==\n\t\t\tthis.namingStrategy.joinKeyColumnName(prop.name, prop.referencedColumnNames[0])\n\t\t) {\n\t\t\toptions.fieldName = this.quote(prop.fieldNames[0]);\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\toptions.primary = true;\n\t\t}\n\t}\n\n\tprotected getDecoratorType(prop: EntityProperty): string {\n\t\tif (prop.kind === ReferenceKind.ONE_TO_ONE) {\n\t\t\treturn '@OneToOne';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_ONE) {\n\t\t\treturn '@ManyToOne';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\treturn '@OneToMany';\n\t\t}\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\treturn '@ManyToMany';\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\treturn '@PrimaryKey';\n\t\t}\n\n\t\tif (prop.enum) {\n\t\t\treturn '@Enum';\n\t\t}\n\n\t\treturn '@Property';\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAiCA,kBAA8D;AAE9D,mBAAgE;AAChE,uBAAyB;AAElB,MAAM,uBAAuB,0BAAS;AAAA,EAI5C,YACoB,MACA,gBACA,UACA,cAClB;AACD,UAAM,MAAM,gBAAgB,QAAQ;AALjB;AACA;AACA;AACA;AAPpB,SAAmB,cAAc,oBAAI,IAAY;AACjD,SAAmB,gBAAgB,oBAAI,IAAY;AAAA,EASnD;AAAA,EAEA,cAAc;AACb,WAAO,oBAAoB,KAAK,YAAY;AAAA,EAC7C;AAAA,EAEA,cAAc;AACb,UAAM,eAAW,sCAAwB,KAAK,KAAK,SAAS;AAC5D,WAAO,GAAG,QAAQ;AAAA,EACnB;AAAA,EAEA,WAAmB;AAClB,UAAM,kBA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
33
  module.exports = __toCommonJS(schema_entity_file_exports);
34
34
  var import_core = require("@mikro-orm/core");
35
- var import_base_file = require("./base-file");
36
- var import_utils = require("../utils");
37
35
  var import_pluralize = __toESM(require("pluralize"));
36
+ var import_utils = require("../utils");
37
+ var import_base_file = require("./base-file");
38
38
  class SchemaEntityFile extends import_base_file.BaseFile {
39
39
  constructor(meta, namingStrategy, platform, entityLookup) {
40
40
  super(meta, namingStrategy, platform);
@@ -124,6 +124,9 @@ ${file}`;
124
124
  if (prop.type === "unknown") {
125
125
  return "string";
126
126
  }
127
+ if (prop.type === "bigint") {
128
+ return "string";
129
+ }
127
130
  return prop.runtimeType;
128
131
  }
129
132
  getPropertyDefinition(prop) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/introspection/files/schema-entity-file.ts"],
4
- "sourcesContent": ["import type {\n\tDictionary,\n\tEntityMetadata,\n\tEntityProperty,\n\tNamingStrategy,\n\tPlatform,\n} from '@mikro-orm/core';\nimport { ReferenceKind, Utils } from '@mikro-orm/core';\n\nimport { BaseFile } from './base-file';\nimport { identifierForEnumValue, pascalToCamelCaseString, pascalToKebabCaseString } from '../utils';\nimport pluralize from 'pluralize';\n\nexport class SchemaEntityFile extends BaseFile {\n\tprotected readonly coreImports = new Set<string>();\n\tprotected readonly scalarImports = new Set<string>();\n\tprotected readonly entityImports = new Set<string>();\n\tprotected readonly enumImports = new Set<string>();\n\n\tconstructor(\n\t\tprotected readonly meta: EntityMetadata,\n\t\tprotected readonly namingStrategy: NamingStrategy,\n\t\tprotected readonly platform: Platform,\n\t\tprotected readonly entityLookup: Map<string, EntityMetadata<any>>\n\t) {\n\t\tsuper(meta, namingStrategy, platform);\n\t}\n\n\tgetBasePath() {\n\t\treturn `backend/schema/`;\n\t}\n\n\tgetBaseName() {\n\t\tconst fileName = pascalToKebabCaseString(this.meta.className);\n\t\treturn `${fileName}.ts`;\n\t}\n\n\tgenerate(): string {\n\t\tconst enumDefinitions: string[] = [];\n\t\tlet classBody = '';\n\t\tconst props = Object.values(this.meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tconst decorator = this.getPropertyDecorator(prop);\n\t\t\tconst definition = this.getPropertyDefinition(prop);\n\n\t\t\tif (classBody && !classBody.endsWith('\\n\\n')) {\n\t\t\t\tclassBody += '\\n';\n\t\t\t}\n\n\t\t\tclassBody += decorator;\n\t\t\tclassBody += definition;\n\n\t\t\tif (props[props.length - 1] !== prop) classBody += '\\n';\n\n\t\t\tif (prop.enum) {\n\t\t\t\tconst enumClassName = this.namingStrategy.getClassName(\n\t\t\t\t\tthis.meta.collection + '_' + prop.fieldNames[0],\n\t\t\t\t\t'_'\n\t\t\t\t);\n\t\t\t\tenumDefinitions.push(this.getEnumClassDefinition(enumClassName));\n\t\t\t}\n\t\t});\n\n\t\tlet file = '';\n\n\t\tif (enumDefinitions.length) {\n\t\t\tfile += enumDefinitions.join('\\n');\n\t\t\tfile += '\\n\\n';\n\t\t}\n\n\t\tthis.coreImports.add('Entity');\n\t\tfile += `@Entity<${this.meta.className}>(${this.quote(this.meta.className)}, {\\n\\tprovider: new MikroBackendProvider(Orm${this.meta.className}, connection),\\n})\\n`;\n\t\tfile += `export class ${this.meta.className} {\\n`;\n\t\tfile += `${classBody}}\\n`;\n\t\tconst imports = [\n\t\t\t`import { ${[...this.coreImports].sort().join(', ')} } from '@exogee/graphweaver';`,\n\t\t];\n\n\t\tif (this.scalarImports.size > 0) {\n\t\t\timports.push(\n\t\t\t\t`import { ${[...this.scalarImports]\n\t\t\t\t\t.sort()\n\t\t\t\t\t.join(', ')} } from '@exogee/graphweaver-scalars';`\n\t\t\t);\n\t\t}\n\n\t\timports.push(`import { MikroBackendProvider } from '@exogee/graphweaver-mikroorm';`);\n\n\t\tconst entityImports = [...this.entityImports].filter((e) => e !== this.meta.className);\n\t\tentityImports.sort().forEach((entity) => {\n\t\t\timports.push(`import { ${entity} } from './${pascalToKebabCaseString(entity)}';`);\n\t\t});\n\n\t\timports.push(\n\t\t\t`import { ${this.enumImports.size > 0 ? [...this.enumImports].sort().join(', ') + ', ' : ''}${\n\t\t\t\tthis.meta.className\n\t\t\t} as Orm${this.meta.className} } from '../entities';`,\n\t\t\t`import { connection } from '../database';`\n\t\t);\n\n\t\tfile = `${imports.join('\\n')}\\n\\n${file}`;\n\n\t\treturn file;\n\t}\n\n\tprotected getTypescriptPropertyType(prop: EntityProperty): string {\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\treturn prop.type.charAt(0).toUpperCase() + prop.type.slice(1);\n\t\t}\n\n\t\tif (['jsonb', 'json', 'any'].includes(prop.columnTypes?.[0])) {\n\t\t\treturn `Record<string, unknown>`;\n\t\t}\n\n\t\tif (prop.columnTypes?.[0] === 'date') {\n\t\t\treturn 'Date';\n\t\t}\n\n\t\tif (prop.type === 'unknown') {\n\t\t\t//fallback to string if unknown\n\t\t\treturn 'string';\n\t\t}\n\n\t\treturn prop.runtimeType;\n\t}\n\n\tprotected getPropertyDefinition(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name}!: ${prop.type}[];\\n`;\n\t\t}\n\n\t\t// string defaults are usually things like SQL functions, but can be also enums, for that `useDefault` should be true\n\t\tconst isEnumOrNonStringDefault = prop.enum || typeof prop.default !== 'string';\n\t\tconst useDefault = prop.default != null && isEnumOrNonStringDefault;\n\t\tconst optional = prop.nullable ? '?' : useDefault ? '' : '!';\n\n\t\tconst file = `${prop.name}${optional}: ${this.getTypescriptPropertyType(prop)}`;\n\n\t\tif (!useDefault) {\n\t\t\treturn `${padding + file};\\n`;\n\t\t}\n\n\t\tif (prop.enum && typeof prop.default === 'string') {\n\t\t\treturn `${padding}${file} = ${prop.runtimeType}.${identifierForEnumValue(prop.default)};\\n`;\n\t\t}\n\n\t\treturn `${padding}${prop.name} = ${prop.default};\\n`;\n\t}\n\n\tprotected getEnumClassDefinition(enumClassName: string): string {\n\t\tthis.coreImports.add('graphweaverMetadata');\n\t\tthis.enumImports.add(enumClassName);\n\t\treturn `graphweaverMetadata.collectEnumInformation({ target: ${enumClassName}, name: ${this.quote(enumClassName)} });`;\n\t}\n\n\tprivate getGraphQLPropertyType(prop: EntityProperty): string {\n\t\tif (prop.primary) {\n\t\t\tthis.coreImports.add('ID');\n\t\t\treturn 'ID';\n\t\t}\n\n\t\tif (prop.runtimeType === 'Date') {\n\t\t\tthis.scalarImports.add('ISODateStringScalar');\n\t\t\treturn 'ISODateStringScalar';\n\t\t}\n\n\t\tif (prop.columnTypes?.[0] === 'date') {\n\t\t\treturn 'Date';\n\t\t}\n\n\t\tif (prop.runtimeType === 'unknown') {\n\t\t\treturn 'String';\n\t\t}\n\n\t\tif (prop.runtimeType === 'bigint') {\n\t\t\tthis.scalarImports.add('GraphQLBigInt');\n\t\t\treturn 'GraphQLBigInt';\n\t\t}\n\n\t\tif (['jsonb', 'json', 'any'].includes(prop.columnTypes?.[0])) {\n\t\t\tthis.scalarImports.add('GraphQLJSON');\n\t\t\treturn `GraphQLJSON`;\n\t\t}\n\n\t\tif (prop.runtimeType?.includes('[]')) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1).replace('[]', '')}]`;\n\t\t}\n\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\treturn prop.type.charAt(0).toUpperCase() + prop.type.slice(1);\n\t\t}\n\n\t\tif ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1).replace('[]', '')}]`;\n\t\t}\n\n\t\tif (prop.pivotTable) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1)}]`;\n\t\t}\n\n\t\tconst lastChanceType = prop.runtimeType ?? prop.type;\n\n\t\tif (!lastChanceType) {\n\t\t\tconsole.error(`Property is malformed, it has no type or runtimeType:`, prop);\n\t\t\tthrow new Error(`Property ${prop.name} on ${prop.entity} entity has no type or runtimeType.`);\n\t\t}\n\n\t\treturn lastChanceType.charAt(0).toUpperCase() + lastChanceType.slice(1);\n\t}\n\n\tprivate getPropertyDecorator(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\t\tconst options = {} as Dictionary;\n\t\tlet decorator = this.getDecoratorType(prop);\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\tthis.getManyToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\tthis.getOneToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind !== ReferenceKind.SCALAR) {\n\t\t\tthis.getForeignKeyDecoratorOptions(options, prop);\n\t\t}\n\n\t\tthis.getCommonDecoratorOptions(options, prop);\n\t\tdecorator = [decorator].map((d) => padding + d).join('\\n');\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn `${decorator}(() => ${this.getGraphQLPropertyType(prop)})\\n`;\n\t\t}\n\n\t\treturn `${decorator}(() => ${this.getGraphQLPropertyType(prop)}, { ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${JSON.stringify(val).replaceAll('\"', '')}`)\n\t\t\t.join(', ')} })\\n`;\n\t}\n\n\tprotected getCommonDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tif (prop.nullable && !prop.mappedBy) {\n\t\t\toptions.nullable = true;\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\toptions.primaryKeyField = true;\n\t\t}\n\n\t\t// If there's a property called 'name' it should be the summary field. If not, and there's a field called 'title'\n\t\t// then it should be the summary field.\n\t\tif (prop.name === 'name') {\n\t\t\toptions.adminUIOptions = { summaryField: true };\n\t\t} else if (prop.name === 'title' && !this.meta.props.find((prop) => prop.name === 'name')) {\n\t\t\toptions.adminUIOptions = { summaryField: true };\n\t\t}\n\t}\n\n\tprotected getManyToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.relatedField = this.quote(pluralize(pascalToCamelCaseString(this.meta.className)));\n\t}\n\n\tprotected getOneToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.relatedField = this.quote(prop.mappedBy);\n\t}\n\n\tprotected getForeignKeyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\n\t\tconst relatedEntity = this.entityLookup.get(prop.type);\n\t\tif (!relatedEntity) {\n\t\t\tthrow new Error(\n\t\t\t\t`Internal Error: Related entity ${prop.type} should exist but could not be found in the entity lookup.`\n\t\t\t);\n\t\t}\n\t\tif (relatedEntity.primaryKeys.length !== 1) {\n\t\t\tthrow new Error(`Composite primary keys are not supported.`);\n\t\t}\n\t\tconst [primaryKey] = relatedEntity.getPrimaryProps();\n\n\t\toptions.id = `(entity) => entity.${prop.name}?.${primaryKey.name}`;\n\t}\n\n\tprotected getDecoratorType(prop: EntityProperty): string {\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('RelationshipField');\n\t\t\treturn `@RelationshipField<${this.meta.className}>`;\n\t\t}\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('RelationshipField');\n\t\t\treturn `@RelationshipField<${prop.type}>`;\n\t\t}\n\n\t\tthis.coreImports.add('Field');\n\t\treturn '@Field';\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,kBAAqC;AAErC,uBAAyB;AACzB,mBAA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\tPlatform,\n} from '@mikro-orm/core';\nimport { ReferenceKind, Utils } from '@mikro-orm/core';\n\nimport pluralize from 'pluralize';\nimport { identifierForEnumValue, pascalToCamelCaseString, pascalToKebabCaseString } from '../utils';\nimport { BaseFile } from './base-file';\n\nexport class SchemaEntityFile extends BaseFile {\n\tprotected readonly coreImports = new Set<string>();\n\tprotected readonly scalarImports = new Set<string>();\n\tprotected readonly entityImports = new Set<string>();\n\tprotected readonly enumImports = new Set<string>();\n\n\tconstructor(\n\t\tprotected readonly meta: EntityMetadata,\n\t\tprotected readonly namingStrategy: NamingStrategy,\n\t\tprotected readonly platform: Platform,\n\t\tprotected readonly entityLookup: Map<string, EntityMetadata<any>>\n\t) {\n\t\tsuper(meta, namingStrategy, platform);\n\t}\n\n\tgetBasePath() {\n\t\treturn `backend/schema/`;\n\t}\n\n\tgetBaseName() {\n\t\tconst fileName = pascalToKebabCaseString(this.meta.className);\n\t\treturn `${fileName}.ts`;\n\t}\n\n\tgenerate(): string {\n\t\tconst enumDefinitions: string[] = [];\n\t\tlet classBody = '';\n\t\tconst props = Object.values(this.meta.properties);\n\t\tprops.forEach((prop) => {\n\t\t\tconst decorator = this.getPropertyDecorator(prop);\n\t\t\tconst definition = this.getPropertyDefinition(prop);\n\n\t\t\tif (classBody && !classBody.endsWith('\\n\\n')) {\n\t\t\t\tclassBody += '\\n';\n\t\t\t}\n\n\t\t\tclassBody += decorator;\n\t\t\tclassBody += definition;\n\n\t\t\tif (props[props.length - 1] !== prop) classBody += '\\n';\n\n\t\t\tif (prop.enum) {\n\t\t\t\tconst enumClassName = this.namingStrategy.getClassName(\n\t\t\t\t\tthis.meta.collection + '_' + prop.fieldNames[0],\n\t\t\t\t\t'_'\n\t\t\t\t);\n\t\t\t\tenumDefinitions.push(this.getEnumClassDefinition(enumClassName));\n\t\t\t}\n\t\t});\n\n\t\tlet file = '';\n\n\t\tif (enumDefinitions.length) {\n\t\t\tfile += enumDefinitions.join('\\n');\n\t\t\tfile += '\\n\\n';\n\t\t}\n\n\t\tthis.coreImports.add('Entity');\n\t\tfile += `@Entity<${this.meta.className}>(${this.quote(this.meta.className)}, {\\n\\tprovider: new MikroBackendProvider(Orm${this.meta.className}, connection),\\n})\\n`;\n\t\tfile += `export class ${this.meta.className} {\\n`;\n\t\tfile += `${classBody}}\\n`;\n\t\tconst imports = [\n\t\t\t`import { ${[...this.coreImports].sort().join(', ')} } from '@exogee/graphweaver';`,\n\t\t];\n\n\t\tif (this.scalarImports.size > 0) {\n\t\t\timports.push(\n\t\t\t\t`import { ${[...this.scalarImports]\n\t\t\t\t\t.sort()\n\t\t\t\t\t.join(', ')} } from '@exogee/graphweaver-scalars';`\n\t\t\t);\n\t\t}\n\n\t\timports.push(`import { MikroBackendProvider } from '@exogee/graphweaver-mikroorm';`);\n\n\t\tconst entityImports = [...this.entityImports].filter((e) => e !== this.meta.className);\n\t\tentityImports.sort().forEach((entity) => {\n\t\t\timports.push(`import { ${entity} } from './${pascalToKebabCaseString(entity)}';`);\n\t\t});\n\n\t\timports.push(\n\t\t\t`import { ${this.enumImports.size > 0 ? [...this.enumImports].sort().join(', ') + ', ' : ''}${\n\t\t\t\tthis.meta.className\n\t\t\t} as Orm${this.meta.className} } from '../entities';`,\n\t\t\t`import { connection } from '../database';`\n\t\t);\n\n\t\tfile = `${imports.join('\\n')}\\n\\n${file}`;\n\n\t\treturn file;\n\t}\n\n\tprotected getTypescriptPropertyType(prop: EntityProperty): string {\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\treturn prop.type.charAt(0).toUpperCase() + prop.type.slice(1);\n\t\t}\n\n\t\tif (['jsonb', 'json', 'any'].includes(prop.columnTypes?.[0])) {\n\t\t\treturn `Record<string, unknown>`;\n\t\t}\n\n\t\tif (prop.columnTypes?.[0] === 'date') {\n\t\t\treturn 'Date';\n\t\t}\n\n\t\tif (prop.type === 'unknown') {\n\t\t\t//fallback to string if unknown\n\t\t\treturn 'string';\n\t\t}\n\n\t\tif (prop.type === 'bigint') {\n\t\t\treturn 'string';\n\t\t}\n\n\t\treturn prop.runtimeType;\n\t}\n\n\tprotected getPropertyDefinition(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.entityImports.add(prop.type);\n\t\t\treturn `${padding}${prop.name}!: ${prop.type}[];\\n`;\n\t\t}\n\n\t\t// string defaults are usually things like SQL functions, but can be also enums, for that `useDefault` should be true\n\t\tconst isEnumOrNonStringDefault = prop.enum || typeof prop.default !== 'string';\n\t\tconst useDefault = prop.default != null && isEnumOrNonStringDefault;\n\t\tconst optional = prop.nullable ? '?' : useDefault ? '' : '!';\n\n\t\tconst file = `${prop.name}${optional}: ${this.getTypescriptPropertyType(prop)}`;\n\n\t\tif (!useDefault) {\n\t\t\treturn `${padding + file};\\n`;\n\t\t}\n\n\t\tif (prop.enum && typeof prop.default === 'string') {\n\t\t\treturn `${padding}${file} = ${prop.runtimeType}.${identifierForEnumValue(prop.default)};\\n`;\n\t\t}\n\n\t\treturn `${padding}${prop.name} = ${prop.default};\\n`;\n\t}\n\n\tprotected getEnumClassDefinition(enumClassName: string): string {\n\t\tthis.coreImports.add('graphweaverMetadata');\n\t\tthis.enumImports.add(enumClassName);\n\t\treturn `graphweaverMetadata.collectEnumInformation({ target: ${enumClassName}, name: ${this.quote(enumClassName)} });`;\n\t}\n\n\tprivate getGraphQLPropertyType(prop: EntityProperty): string {\n\t\tif (prop.primary) {\n\t\t\tthis.coreImports.add('ID');\n\t\t\treturn 'ID';\n\t\t}\n\n\t\tif (prop.runtimeType === 'Date') {\n\t\t\tthis.scalarImports.add('ISODateStringScalar');\n\t\t\treturn 'ISODateStringScalar';\n\t\t}\n\n\t\tif (prop.columnTypes?.[0] === 'date') {\n\t\t\treturn 'Date';\n\t\t}\n\n\t\tif (prop.runtimeType === 'unknown') {\n\t\t\treturn 'String';\n\t\t}\n\n\t\tif (prop.runtimeType === 'bigint') {\n\t\t\tthis.scalarImports.add('GraphQLBigInt');\n\t\t\treturn 'GraphQLBigInt';\n\t\t}\n\n\t\tif (['jsonb', 'json', 'any'].includes(prop.columnTypes?.[0])) {\n\t\t\tthis.scalarImports.add('GraphQLJSON');\n\t\t\treturn `GraphQLJSON`;\n\t\t}\n\n\t\tif (prop.runtimeType?.includes('[]')) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1).replace('[]', '')}]`;\n\t\t}\n\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\treturn prop.type.charAt(0).toUpperCase() + prop.type.slice(1);\n\t\t}\n\n\t\tif ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1).replace('[]', '')}]`;\n\t\t}\n\n\t\tif (prop.pivotTable) {\n\t\t\treturn `[${prop.type.charAt(0).toUpperCase() + prop.type.slice(1)}]`;\n\t\t}\n\n\t\tconst lastChanceType = prop.runtimeType ?? prop.type;\n\n\t\tif (!lastChanceType) {\n\t\t\tconsole.error(`Property is malformed, it has no type or runtimeType:`, prop);\n\t\t\tthrow new Error(`Property ${prop.name} on ${prop.entity} entity has no type or runtimeType.`);\n\t\t}\n\n\t\treturn lastChanceType.charAt(0).toUpperCase() + lastChanceType.slice(1);\n\t}\n\n\tprivate getPropertyDecorator(prop: EntityProperty): string {\n\t\tconst padding = '\\t';\n\t\tconst options = {} as Dictionary;\n\t\tlet decorator = this.getDecoratorType(prop);\n\n\t\tif (prop.kind === ReferenceKind.MANY_TO_MANY) {\n\t\t\tthis.getManyToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind === ReferenceKind.ONE_TO_MANY) {\n\t\t\tthis.getOneToManyDecoratorOptions(options, prop);\n\t\t} else if (prop.kind !== ReferenceKind.SCALAR) {\n\t\t\tthis.getForeignKeyDecoratorOptions(options, prop);\n\t\t}\n\n\t\tthis.getCommonDecoratorOptions(options, prop);\n\t\tdecorator = [decorator].map((d) => padding + d).join('\\n');\n\n\t\tif (!Utils.hasObjectKeys(options)) {\n\t\t\treturn `${decorator}(() => ${this.getGraphQLPropertyType(prop)})\\n`;\n\t\t}\n\n\t\treturn `${decorator}(() => ${this.getGraphQLPropertyType(prop)}, { ${Object.entries(options)\n\t\t\t.map(([opt, val]) => `${opt}: ${JSON.stringify(val).replaceAll('\"', '')}`)\n\t\t\t.join(', ')} })\\n`;\n\t}\n\n\tprotected getCommonDecoratorOptions(options: Dictionary, prop: EntityProperty): void {\n\t\tif (prop.nullable && !prop.mappedBy) {\n\t\t\toptions.nullable = true;\n\t\t}\n\n\t\tif (prop.primary) {\n\t\t\toptions.primaryKeyField = true;\n\t\t}\n\n\t\t// If there's a property called 'name' it should be the summary field. If not, and there's a field called 'title'\n\t\t// then it should be the summary field.\n\t\tif (prop.name === 'name') {\n\t\t\toptions.adminUIOptions = { summaryField: true };\n\t\t} else if (prop.name === 'title' && !this.meta.props.find((prop) => prop.name === 'name')) {\n\t\t\toptions.adminUIOptions = { summaryField: true };\n\t\t}\n\t}\n\n\tprotected getManyToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.relatedField = this.quote(pluralize(pascalToCamelCaseString(this.meta.className)));\n\t}\n\n\tprotected getOneToManyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\t\toptions.relatedField = this.quote(prop.mappedBy);\n\t}\n\n\tprotected getForeignKeyDecoratorOptions(options: Dictionary, prop: EntityProperty) {\n\t\tthis.entityImports.add(prop.type);\n\n\t\tconst relatedEntity = this.entityLookup.get(prop.type);\n\t\tif (!relatedEntity) {\n\t\t\tthrow new Error(\n\t\t\t\t`Internal Error: Related entity ${prop.type} should exist but could not be found in the entity lookup.`\n\t\t\t);\n\t\t}\n\t\tif (relatedEntity.primaryKeys.length !== 1) {\n\t\t\tthrow new Error(`Composite primary keys are not supported.`);\n\t\t}\n\t\tconst [primaryKey] = relatedEntity.getPrimaryProps();\n\n\t\toptions.id = `(entity) => entity.${prop.name}?.${primaryKey.name}`;\n\t}\n\n\tprotected getDecoratorType(prop: EntityProperty): string {\n\t\tif ([ReferenceKind.ONE_TO_ONE, ReferenceKind.MANY_TO_ONE].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('RelationshipField');\n\t\t\treturn `@RelationshipField<${this.meta.className}>`;\n\t\t}\n\n\t\tif ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {\n\t\t\tthis.coreImports.add('RelationshipField');\n\t\t\treturn `@RelationshipField<${prop.type}>`;\n\t\t}\n\n\t\tthis.coreImports.add('Field');\n\t\treturn '@Field';\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,kBAAqC;AAErC,uBAAsB;AACtB,mBAAyF;AACzF,uBAAyB;AAElB,MAAM,yBAAyB,0BAAS;AAAA,EAM9C,YACoB,MACA,gBACA,UACA,cAClB;AACD,UAAM,MAAM,gBAAgB,QAAQ;AALjB;AACA;AACA;AACA;AATpB,SAAmB,cAAc,oBAAI,IAAY;AACjD,SAAmB,gBAAgB,oBAAI,IAAY;AACnD,SAAmB,gBAAgB,oBAAI,IAAY;AACnD,SAAmB,cAAc,oBAAI,IAAY;AAAA,EASjD;AAAA,EAEA,cAAc;AACb,WAAO;AAAA,EACR;AAAA,EAEA,cAAc;AACb,UAAM,eAAW,sCAAwB,KAAK,KAAK,SAAS;AAC5D,WAAO,GAAG,QAAQ;AAAA,EACnB;AAAA,EAEA,WAAmB;AAClB,UAAM,kBAA4B,CAAC;AACnC,QAAI,YAAY;AAChB,UAAM,QAAQ,OAAO,OAAO,KAAK,KAAK,UAAU;AAChD,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B,YAAM,IAAI;AAAA,QACT,kCAAkC,KAAK,IAAI;AAAA,MAC5C;AAAA,IACD;AACA,QAAI,cAAc,YAAY,WAAW,GAAG;AAC3C,YAAM,IAAI,MAAM,2CAA2C;AAAA,IAC5D;AACA,UAAM,CAAC,UAAU,IAAI,cAAc,gBAAgB;AAEnD,YAAQ,KAAK,sBAAsB,KAAK,IAAI,KAAK,WAAW,IAAI;AAAA,EACjE;AAAA,EAEU,iBAAiB,MAA8B;AACxD,QAAI,CAAC,0BAAc,YAAY,0BAAc,WAAW,EAAE,SAAS,KAAK,IAAI,GAAG;AAC9E,WAAK,YAAY,IAAI,mBAAmB;AACxC,aAAO,sBAAsB,KAAK,KAAK,SAAS;AAAA,IACjD;AAEA,QAAI,CAAC,0BAAc,aAAa,0BAAc,YAAY,EAAE,SAAS,KAAK,IAAI,GAAG;AAChF,WAAK,YAAY,IAAI,mBAAmB;AACxC,aAAO,sBAAsB,KAAK,IAAI;AAAA,IACvC;AAEA,SAAK,YAAY,IAAI,OAAO;AAC5B,WAAO;AAAA,EACR;AACD;",
6
6
  "names": ["prop", "pluralize"]
7
7
  }
@@ -1,6 +1,9 @@
1
1
  import { BackendProvider, PaginationOptions, Filter, BackendProviderConfig, FieldMetadata, AggregationResult, AggregationType, TraceOptions, EntityMetadata } from '@exogee/graphweaver';
2
- import { IsolationLevel, ConnectionOptions } from '..';
3
- export declare const gqlToMikro: (filter: any) => any;
2
+ import { PostgreSqlDriver } from '@mikro-orm/postgresql';
3
+ import { SqliteDriver } from '@mikro-orm/sqlite';
4
+ import { MySqlDriver } from '@mikro-orm/mysql';
5
+ import { IsolationLevel, ConnectionOptions, DatabaseType } from '..';
6
+ export declare const gqlToMikro: (filter: any, databaseType?: DatabaseType) => any;
4
7
  export declare class MikroBackendProvider<D> implements BackendProvider<D> {
5
8
  private _backendId;
6
9
  private connection;
@@ -13,8 +16,9 @@ export declare class MikroBackendProvider<D> implements BackendProvider<D> {
13
16
  private get database();
14
17
  get transactional(): <T>(callback: () => Promise<T>, isolationLevel?: IsolationLevel) => Promise<T>;
15
18
  withTransaction<T>(callback: () => Promise<T>): Promise<T>;
16
- get em(): import("@mikro-orm/postgresql").EntityManager<import("@mikro-orm/postgresql").PostgreSqlDriver> | import("@mikro-orm/postgresql").EntityManager<import("@mikro-orm/mysql").MySqlDriver> | import("@mikro-orm/postgresql").EntityManager<import("@mikro-orm/sqlite").SqliteDriver>;
19
+ get em(): import("@mikro-orm/postgresql").EntityManager<PostgreSqlDriver> | import("@mikro-orm/postgresql").EntityManager<MySqlDriver> | import("@mikro-orm/postgresql").EntityManager<SqliteDriver>;
17
20
  constructor(mikroType: new () => D, connection: ConnectionOptions, transactionIsolationLevel?: IsolationLevel);
21
+ private getDbType;
18
22
  private connectToDatabase;
19
23
  private addRequestContext;
20
24
  private mapAndAssignKeys;
@@ -34,29 +34,56 @@ var import_graphweaver = require("@exogee/graphweaver");
34
34
  var import_logger = require("@exogee/logger");
35
35
  var import_core = require("@mikro-orm/core");
36
36
  var import_postgresql = require("@mikro-orm/postgresql");
37
+ var import_sqlite = require("@mikro-orm/sqlite");
38
+ var import_mysql = require("@mikro-orm/mysql");
37
39
  var import_graphweaver_server = require("@exogee/graphweaver-server");
38
40
  var import__ = require("..");
39
41
  var import_errors = require("../utils/errors");
40
42
  var import_assign = require("./assign");
41
43
  const objectOperations = /* @__PURE__ */ new Set(["_and", "_or", "_not"]);
42
44
  const mikroObjectOperations = /* @__PURE__ */ new Set(["$and", "$or", "$not"]);
45
+ const nullBooleanOperations = /* @__PURE__ */ new Set(["null", "notnull"]);
43
46
  const appendPath = (path, newPath) => path.length ? `${path}.${newPath}` : newPath;
44
- const gqlToMikro = (filter) => {
47
+ const gqlToMikro = (filter, databaseType) => {
45
48
  if (Array.isArray(filter)) {
46
- return filter.map((element) => gqlToMikro(element));
49
+ return filter.map((element) => gqlToMikro(element, databaseType));
47
50
  } else if (typeof filter === "object") {
48
51
  for (const key of Object.keys(filter)) {
49
52
  if (filter[key] === null) continue;
50
53
  if (objectOperations.has(key)) {
51
- filter[key.replace("_", "$")] = gqlToMikro(filter[key]);
54
+ filter[key.replace("_", "$")] = gqlToMikro(filter[key], databaseType);
52
55
  delete filter[key];
53
56
  } else if (typeof filter[key] === "object" && !Array.isArray(filter[key])) {
54
- filter[key] = gqlToMikro(filter[key]);
57
+ filter[key] = gqlToMikro(filter[key], databaseType);
55
58
  } else if (key.indexOf("_") >= 0) {
56
59
  const [newKey, operator] = key.split("_");
57
- const newValue = { [`$${operator}`]: gqlToMikro(filter[key]) };
60
+ let newValue;
61
+ if (nullBooleanOperations.has(operator) && typeof filter[key] === "boolean") {
62
+ newValue = filter[key] && operator === "null" || !filter[key] && operator === "notnull" ? { $eq: null } : { $ne: null };
63
+ } else if (operator === "ilike" && databaseType !== "postgresql") {
64
+ import_logger.logger.warn(`The $ilike operator is not supported by ${databaseType} databases. Operator coerced to $like.`);
65
+ newValue = { $like: filter[key] };
66
+ } else {
67
+ newValue = { [`$${operator}`]: gqlToMikro(filter[key], databaseType) };
68
+ }
58
69
  if (typeof filter[newKey] !== "undefined") {
59
- filter[newKey] = { ...filter[newKey], ...newValue };
70
+ if (typeof filter[newKey] !== "object") {
71
+ if (typeof newValue === "object" && "$eq" in newValue) {
72
+ throw new Error(
73
+ `property ${newKey} on filter is ambiguous. There are two values for this property: ${filter[newKey]} and ${newValue.$eq}`
74
+ );
75
+ }
76
+ filter[newKey] = { ...{ $eq: filter[newKey] }, ...newValue };
77
+ } else {
78
+ if (newValue && typeof newValue === "object" && "$eq" in newValue) {
79
+ throw new Error(
80
+ `property ${newKey} on filter is ambiguous. There are two values for this property: ${JSON.stringify(
81
+ filter[newKey]
82
+ )} and ${JSON.stringify(newValue)}`
83
+ );
84
+ }
85
+ filter[newKey] = { ...filter[newKey], ...newValue };
86
+ }
60
87
  } else {
61
88
  filter[newKey] = newValue;
62
89
  }
@@ -211,6 +238,19 @@ class MikroBackendProvider {
211
238
  get em() {
212
239
  return this.database.em;
213
240
  }
241
+ getDbType() {
242
+ const driver = this.em.getDriver().constructor.name;
243
+ switch (driver) {
244
+ case import_sqlite.SqliteDriver.name:
245
+ return "sqlite";
246
+ case import_mysql.MySqlDriver.name:
247
+ return "mysql";
248
+ case import_postgresql.PostgreSqlDriver.name:
249
+ return "postgresql";
250
+ default:
251
+ throw new Error(`This driver (${driver}) is not supported!`);
252
+ }
253
+ }
214
254
  async find(filter, pagination, entityMetadata, trace) {
215
255
  trace?.span.updateName(`Mikro-Orm - Find ${this.entityType.name}`);
216
256
  import_logger.logger.trace(`Running find ${this.entityType.name} with filter`, {
@@ -218,7 +258,7 @@ class MikroBackendProvider {
218
258
  });
219
259
  const where = (0, import_graphweaver.traceSync)((trace2) => {
220
260
  trace2?.span.updateName("Convert filter to Mikro-Orm format");
221
- return filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : void 0;
261
+ return filter ? gqlToMikro(JSON.parse(JSON.stringify(filter)), this.getDbType()) : void 0;
222
262
  })();
223
263
  const whereWithAppliedExternalIdFields = where ? this.applyExternalIdFields(this.entityType, where) : {};
224
264
  const query = this.em.createQueryBuilder(this.entityType);
@@ -280,7 +320,7 @@ class MikroBackendProvider {
280
320
  let queryFilter = { [relatedField]: { $in: relatedFieldIds } };
281
321
  if (filter) {
282
322
  queryFilter = {
283
- $and: [queryFilter, ...[gqlToMikro(filter)]]
323
+ $and: [queryFilter, ...[gqlToMikro(filter, this.getDbType())]]
284
324
  };
285
325
  }
286
326
  const populate = [relatedField];
@@ -424,7 +464,7 @@ class MikroBackendProvider {
424
464
  async deleteOne(filter, trace) {
425
465
  trace?.span.updateName(`Mikro-Orm - deleteOne ${this.entityType.name}`);
426
466
  import_logger.logger.trace(filter, `Running delete ${this.entityType.name} with filter.`);
427
- const where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : void 0;
467
+ const where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter)), this.getDbType()) : void 0;
428
468
  const whereWithAppliedExternalIdFields = where && this.applyExternalIdFields(this.entityType, where);
429
469
  const deletedRows = await this.database.em.nativeDelete(
430
470
  this.entityType,
@@ -440,7 +480,7 @@ class MikroBackendProvider {
440
480
  trace?.span.updateName(`Mikro-Orm - deleteMany ${this.entityType.name}`);
441
481
  import_logger.logger.trace(`Running delete ${this.entityType.name}`);
442
482
  const deletedRows = await this.database.transactional(async () => {
443
- const where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : void 0;
483
+ const where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter)), this.getDbType()) : void 0;
444
484
  const whereWithAppliedExternalIdFields = where && this.applyExternalIdFields(this.entityType, where);
445
485
  const toDelete = await this.database.em.count(
446
486
  this.entityType,
@@ -484,7 +524,7 @@ class MikroBackendProvider {
484
524
  import_logger.logger.trace(`Running aggregate ${this.entityType.name} with filter`, {
485
525
  filter: JSON.stringify(filter)
486
526
  });
487
- const where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter))) : void 0;
527
+ const where = filter ? gqlToMikro(JSON.parse(JSON.stringify(filter)), this.getDbType()) : void 0;
488
528
  const whereWithAppliedExternalIdFields = where ? this.applyExternalIdFields(this.entityType, where) : {};
489
529
  const query = this.em.createQueryBuilder(this.entityType);
490
530
  if (Object.keys(whereWithAppliedExternalIdFields).length > 0) {
@@ -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 { LoadStrategy, 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\tsupportsPseudoCursorPagination: true,\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: async (_: GraphweaverRequestEvent, _next: GraphweaverPluginNextFunction) => {\n\t\t\t\tlogger.trace(`Graphweaver OnRequest plugin called`);\n\n\t\t\t\tconst connection = await ConnectionManager.awaitableDatabase(connectionManagerId);\n\n\t\t\t\tif (!connection) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`No database connection found for connectionManagerId: ${connectionManagerId} after waiting for connection. This should not happen.`\n\t\t\t\t\t);\n\t\t\t\t}\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\tif (Array.isArray(values[rootLevelKey])) {\n\t\t\t\t\tfor (const field of values[rootLevelKey]) {\n\t\t\t\t\t\tmapFieldNames(field);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmapFieldNames(values[rootLevelKey]);\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\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\n\t\t// Any is the actual type from MikroORM, sorry folks.\n\t\tlet queryFilter: any = { [relatedField]: { $in: relatedFieldIds } };\n\n\t\tif (filter) {\n\t\t\t// Since the user has supplied a filter, we need to and it in.\n\t\t\tqueryFilter = {\n\t\t\t\t$and: [queryFilter, ...[gqlToMikro(filter)]],\n\t\t\t};\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\t// We only need one result per entity.\n\t\t\tflags: [QueryFlag.DISTINCT],\n\n\t\t\t// We do want to populate the relation, however, see below.\n\t\t\tpopulate,\n\n\t\t\t// We'd love to use the default joined loading strategy, but it doesn't work with the populateWhere option.\n\t\t\tstrategy: LoadStrategy.SELECT_IN,\n\n\t\t\t// This tells MikroORM we only need to load the related entities if they match the filter specified above.\n\t\t\tpopulateWhere: PopulateHint.INFER,\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\t// For an update we also want to go ahead and remove the primary key if it's autoincremented, as\n\t\t// users should not be able to change the primary key. There are also scenarios like\n\t\t// GENERATED ALWAYS AS IDENTITY where even supplying the primary key in the update query will\n\t\t// cause an error.\n\t\tconst meta = this.database.em.getMetadata().get(this.entityType.name);\n\t\tfor (const key of meta.primaryKeys) {\n\t\t\tif (meta.properties[key].autoincrement) delete (updateArgsWithoutVersion as any)[key];\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 meta = this.database.em.getMetadata().get(this.entityType.name);\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\n\t\t\t\t\t// For an update we also want to go ahead and remove the primary key if it's autoincremented, as\n\t\t\t\t\t// users should not be able to change the primary key. There are also scenarios like\n\t\t\t\t\t// GENERATED ALWAYS AS IDENTITY where even supplying the primary key in the update query will\n\t\t\t\t\t// cause an error.\n\t\t\t\t\tfor (const key of meta.primaryKeys) {\n\t\t\t\t\t\tif (meta.properties[key].autoincrement) delete (item as any)[key];\n\t\t\t\t\t}\n\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,kBAA6D;AAC7D,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;AAAA,MADZ,gCAAY;AAAA,GAjfD,qBAkfC;AA+BA;AAAA,MADZ,gCAAY;AAAA,GAhhBD,qBAihBC;AAsBA;AAAA,MADZ,gCAAY;AAAA,GAtiBD,qBAuiBC;AAyDA;AAAA,MADZ,gCAAY;AAAA,GA/lBD,qBAgmBC;",
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 { LoadStrategy, Reference, RequestContext, sql } from '@mikro-orm/core';\nimport { AutoPath, PopulateHint, PostgreSqlDriver } from '@mikro-orm/postgresql';\nimport { SqliteDriver } from '@mikro-orm/sqlite';\nimport { MySqlDriver } from '@mikro-orm/mysql';\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\tDatabaseType\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']);\nconst nullBooleanOperations = new Set(['null', 'notnull']);\n\nconst appendPath = (path: string, newPath: string) =>\n\tpath.length ? `${path}.${newPath}` : newPath;\n\nexport const gqlToMikro = (filter: any, databaseType?: DatabaseType): any => {\n\tif (Array.isArray(filter)) {\n\t\treturn filter.map((element) => gqlToMikro(element, databaseType));\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], databaseType);\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], databaseType);\n\t\t\t} else if (key.indexOf('_') >= 0) {\n\t\t\t\tconst [newKey, operator] = key.split('_');\n\t\t\t\tlet newValue;\n\t\t\t\tif (nullBooleanOperations.has(operator) && typeof filter[key] === 'boolean') {\n\t\t\t\t\t// { firstName_null: true } => { firstName: { $eq: null } } or { firstName_null: false } => { firstName: { $ne: null } }\n\t\t\t\t\t// { firstName_notnull: true } => { firstName: { $ne: null } } or { firstName_notnull: false } => { firstName: { $eq: null } }\n\t\t\t\t\tnewValue =\n\t\t\t\t\t\t(filter[key] && operator === 'null') || (!filter[key] && operator === 'notnull')\n\t\t\t\t\t\t\t? { $eq: null }\n\t\t\t\t\t\t\t: { $ne: null };\n\t\t\t\t} else if (operator === 'ilike' && databaseType !== \"postgresql\") {\n\t\t\t\t\tlogger.warn(`The $ilike operator is not supported by ${databaseType} databases. Operator coerced to $like.`)\n\t\t\t\t\tnewValue = { $like: filter[key] };\n\t\t\t\t} else {\n\t\t\t\t\t// { firstName_in: ['k', 'b'] } => { firstName: { $in: ['k', 'b'] } }\n\t\t\t\t\tnewValue = { [`$${operator}`]: gqlToMikro(filter[key], databaseType) };\n\t\t\t\t\t// They can construct multiple filters for the same key. In that case we need\n\t\t\t\t\t// to append them all into an object.\n\t\t\t\t}\n\n\t\t\t\tif (typeof filter[newKey] !== 'undefined') {\n\t\t\t\t\tif (typeof filter[newKey] !== 'object') {\n\t\t\t\t\t\tif (typeof newValue === 'object' && '$eq' in newValue) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`property ${newKey} on filter is ambiguous. There are two values for this property: ${filter[newKey]} and ${newValue.$eq}`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfilter[newKey] = { ...{ $eq: filter[newKey] }, ...newValue };\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (newValue && typeof newValue === 'object' && '$eq' in newValue) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`property ${newKey} on filter is ambiguous. There are two values for this property: ${JSON.stringify(\n\t\t\t\t\t\t\t\t\tfilter[newKey]\n\t\t\t\t\t\t\t\t)} and ${JSON.stringify(newValue)}`\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfilter[newKey] = { ...filter[newKey], ...newValue };\n\t\t\t\t\t}\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\tsupportsPseudoCursorPagination: true,\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\t\n\t}\n\tprivate getDbType(): DatabaseType {\n\t\tconst driver = this.em.getDriver().constructor.name;\n\t\tswitch (driver) {\n\t\t\tcase SqliteDriver.name:\n\t\t\t\treturn \"sqlite\";\n\t\t\tcase MySqlDriver.name:\n\t\t\t\treturn \"mysql\";\n\t\t\tcase PostgreSqlDriver.name:\n\t\t\t\treturn \"postgresql\";\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`This driver (${driver}) is not supported!`);\n\t\t}\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: async (_: GraphweaverRequestEvent, _next: GraphweaverPluginNextFunction) => {\n\t\t\t\tlogger.trace(`Graphweaver OnRequest plugin called`);\n\n\t\t\t\tconst connection = await ConnectionManager.awaitableDatabase(connectionManagerId);\n\n\t\t\t\tif (!connection) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`No database connection found for connectionManagerId: ${connectionManagerId} after waiting for connection. This should not happen.`\n\t\t\t\t\t);\n\t\t\t\t}\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\tif (Array.isArray(values[rootLevelKey])) {\n\t\t\t\t\tfor (const field of values[rootLevelKey]) {\n\t\t\t\t\t\tmapFieldNames(field);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmapFieldNames(values[rootLevelKey]);\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\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)), this.getDbType()) : 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\n\t\t// Any is the actual type from MikroORM, sorry folks.\n\t\tlet queryFilter: any = { [relatedField]: { $in: relatedFieldIds } };\n\n\t\tif (filter) {\n\t\t\t// Since the user has supplied a filter, we need to and it in.\n\t\t\tqueryFilter = {\n\t\t\t\t$and: [queryFilter, ...[gqlToMikro(filter, this.getDbType())]],\n\t\t\t};\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\t// We only need one result per entity.\n\t\t\tflags: [QueryFlag.DISTINCT],\n\n\t\t\t// We do want to populate the relation, however, see below.\n\t\t\tpopulate,\n\n\t\t\t// We'd love to use the default joined loading strategy, but it doesn't work with the populateWhere option.\n\t\t\tstrategy: LoadStrategy.SELECT_IN,\n\n\t\t\t// This tells MikroORM we only need to load the related entities if they match the filter specified above.\n\t\t\tpopulateWhere: PopulateHint.INFER,\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\t// For an update we also want to go ahead and remove the primary key if it's autoincremented, as\n\t\t// users should not be able to change the primary key. There are also scenarios like\n\t\t// GENERATED ALWAYS AS IDENTITY where even supplying the primary key in the update query will\n\t\t// cause an error.\n\t\tconst meta = this.database.em.getMetadata().get(this.entityType.name);\n\t\tfor (const key of meta.primaryKeys) {\n\t\t\tif (meta.properties[key].autoincrement) delete (updateArgsWithoutVersion as any)[key];\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 meta = this.database.em.getMetadata().get(this.entityType.name);\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\n\t\t\t\t\t// For an update we also want to go ahead and remove the primary key if it's autoincremented, as\n\t\t\t\t\t// users should not be able to change the primary key. There are also scenarios like\n\t\t\t\t\t// GENERATED ALWAYS AS IDENTITY where even supplying the primary key in the update query will\n\t\t\t\t\t// cause an error.\n\t\t\t\t\tfor (const key of meta.primaryKeys) {\n\t\t\t\t\t\tif (meta.properties[key].autoincrement) delete (item as any)[key];\n\t\t\t\t\t}\n\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)), this.getDbType()) : 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)), this.getDbType()) : 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)), this.getDbType()) : 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,kBAA6D;AAC7D,wBAAyD;AACzD,oBAA6B;AAC7B,mBAA4B;AAC5B,gCAAmD;AAEnD,eAWO;AAEP,oBAAoC;AACpC,oBAAuB;AAOvB,MAAM,mBAAmB,oBAAI,IAAI,CAAC,QAAQ,OAAO,MAAM,CAAC;AACxD,MAAM,wBAAwB,oBAAI,IAAI,CAAC,QAAQ,OAAO,MAAM,CAAC;AAC7D,MAAM,wBAAwB,oBAAI,IAAI,CAAC,QAAQ,SAAS,CAAC;AAE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AAAA,MADZ,gCAAY;AAAA,GA7mBD,qBA8mBC;",
6
6
  "names": ["trace", "startTrace"]
7
7
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,187 @@
1
+ "use strict";
2
+ var import_vitest = require("vitest");
3
+ var import_provider = require("./provider");
4
+ (0, import_vitest.describe)("gqlToMikro", () => {
5
+ (0, import_vitest.it)("transforms filter: nested -> with numbers", () => {
6
+ const test = {
7
+ field1_gt: 1,
8
+ field1_lt: 2,
9
+ field1_in: [1, 2, 3],
10
+ nested: {
11
+ field1: 1,
12
+ field2_gte: 3,
13
+ field2_lte: 4,
14
+ field2_in: [1, 2, 3]
15
+ }
16
+ };
17
+ const expectedResult = {
18
+ field1: {
19
+ $gt: 1,
20
+ $lt: 2,
21
+ $in: [1, 2, 3]
22
+ },
23
+ nested: {
24
+ field1: 1,
25
+ field2: {
26
+ $gte: 3,
27
+ $lte: 4,
28
+ $in: [1, 2, 3]
29
+ }
30
+ }
31
+ };
32
+ (0, import_vitest.expect)((0, import_provider.gqlToMikro)(test)).toEqual(expectedResult);
33
+ });
34
+ (0, import_vitest.it)("transforms filter: numbers -> and null", () => {
35
+ const test = {
36
+ field1_gt: 1,
37
+ field1_lt: 2,
38
+ field1_in: [1, 2, 3],
39
+ field1_null: false,
40
+ field1_notnull: true
41
+ };
42
+ const expectedResult = {
43
+ field1: {
44
+ $gt: 1,
45
+ $lt: 2,
46
+ $in: [1, 2, 3],
47
+ $ne: null
48
+ }
49
+ };
50
+ (0, import_vitest.expect)((0, import_provider.gqlToMikro)(test)).toEqual(expectedResult);
51
+ });
52
+ (0, import_vitest.it)("transforms filter: numbers -> in and eq", () => {
53
+ const test = {
54
+ field1_in: [1, 2, 3],
55
+ field1: 4
56
+ };
57
+ const expectedResult = {
58
+ field1: { $in: [1, 2, 3], $eq: 4 }
59
+ };
60
+ (0, import_vitest.expect)((0, import_provider.gqlToMikro)(test)).toEqual(expectedResult);
61
+ });
62
+ (0, import_vitest.it)("transforms filter: strings -> nested", () => {
63
+ const test = {
64
+ nested: {
65
+ field1: { id: "uno" },
66
+ field2_gte: "someValue",
67
+ field2_lte: "someValue",
68
+ field2_nin: ["someValue"]
69
+ }
70
+ };
71
+ const expectedResult = {
72
+ nested: {
73
+ field1: { id: "uno" },
74
+ field2: {
75
+ $gte: "someValue",
76
+ $lte: "someValue",
77
+ $nin: ["someValue"]
78
+ }
79
+ }
80
+ };
81
+ (0, import_vitest.expect)((0, import_provider.gqlToMikro)(test)).toEqual(expectedResult);
82
+ });
83
+ (0, import_vitest.it)("should throw error -> ambiguous property", () => {
84
+ const test = {
85
+ _and: [{ field1_in: [1, 2, 3], field1: 4, field1_null: true }, { field1_nin: [1, 2, 3] }]
86
+ };
87
+ (0, import_vitest.expect)(() => (0, import_provider.gqlToMikro)(test)).toThrow();
88
+ });
89
+ (0, import_vitest.it)("should throw error -> ambiguous property - null then string", () => {
90
+ const test = { field1_null: true, field1: "dos" };
91
+ (0, import_vitest.expect)(() => (0, import_provider.gqlToMikro)(test)).toThrow();
92
+ });
93
+ (0, import_vitest.it)("should throw error -> ambiguous property - we don't support collapsing same values", () => {
94
+ const test = { field1_null: true, field1: null };
95
+ (0, import_vitest.expect)(() => (0, import_provider.gqlToMikro)(test)).toThrow();
96
+ });
97
+ (0, import_vitest.it)("transforms filter: strings -> in and eq", () => {
98
+ const test = { field1_nin: ["one"], field1: "two" };
99
+ const expectedResult = { field1: { $nin: ["one"], $eq: "two" } };
100
+ (0, import_vitest.expect)((0, import_provider.gqlToMikro)(test)).toEqual(expectedResult);
101
+ });
102
+ (0, import_vitest.it)("transforms filter: strings -> or and null", () => {
103
+ const test = {
104
+ _or: [
105
+ {
106
+ user: {
107
+ id_null: true
108
+ }
109
+ },
110
+ {
111
+ user: {
112
+ id: "seis"
113
+ }
114
+ }
115
+ ]
116
+ };
117
+ const expectedResult = {
118
+ $or: [
119
+ {
120
+ user: {
121
+ id: { $eq: null }
122
+ }
123
+ },
124
+ {
125
+ user: {
126
+ id: "seis"
127
+ }
128
+ }
129
+ ]
130
+ };
131
+ (0, import_vitest.expect)((0, import_provider.gqlToMikro)(test)).toEqual(expectedResult);
132
+ });
133
+ (0, import_vitest.it)("transforms filter: complicated filter with nested properties, arrays, nulls, strings, and numbers", () => {
134
+ const test = {
135
+ field1_gt: 5,
136
+ field2_lt: 10,
137
+ field3_in: ["a", "b", "c"],
138
+ field4_null: true,
139
+ field5_notnull: true,
140
+ nested1: {
141
+ subfield1: 1,
142
+ subfield2_gte: 2,
143
+ subfield3_lte: 3,
144
+ subfield4_in: [4, 5, 6],
145
+ subnested: {
146
+ subsubfield1: "value1",
147
+ subsubfield2_nin: ["value2", "value3"],
148
+ subsubfield3_null: false
149
+ }
150
+ },
151
+ nested2: {
152
+ subfield1: "string1",
153
+ subfield2: {
154
+ subsubfield1: "string2",
155
+ subsubfield2_gt: 7
156
+ }
157
+ }
158
+ };
159
+ const expectedResult = {
160
+ field1: { $gt: 5 },
161
+ field2: { $lt: 10 },
162
+ field3: { $in: ["a", "b", "c"] },
163
+ field4: { $eq: null },
164
+ field5: { $ne: null },
165
+ nested1: {
166
+ subfield1: 1,
167
+ subfield2: { $gte: 2 },
168
+ subfield3: { $lte: 3 },
169
+ subfield4: { $in: [4, 5, 6] },
170
+ subnested: {
171
+ subsubfield1: "value1",
172
+ subsubfield2: { $nin: ["value2", "value3"] },
173
+ subsubfield3: { $ne: null }
174
+ }
175
+ },
176
+ nested2: {
177
+ subfield1: "string1",
178
+ subfield2: {
179
+ subsubfield1: "string2",
180
+ subsubfield2: { $gt: 7 }
181
+ }
182
+ }
183
+ };
184
+ (0, import_vitest.expect)((0, import_provider.gqlToMikro)(test)).toEqual(expectedResult);
185
+ });
186
+ });
187
+ //# sourceMappingURL=provider.test.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/provider/provider.test.ts"],
4
+ "sourcesContent": ["import { describe, it, expect } from 'vitest';\nimport { gqlToMikro } from './provider';\n\ndescribe('gqlToMikro', () => {\n\tit('transforms filter: nested -> with numbers', () => {\n\t\tconst test = {\n\t\t\tfield1_gt: 1,\n\t\t\tfield1_lt: 2,\n\t\t\tfield1_in: [1, 2, 3],\n\t\t\tnested: {\n\t\t\t\tfield1: 1,\n\n\t\t\t\tfield2_gte: 3,\n\t\t\t\tfield2_lte: 4,\n\t\t\t\tfield2_in: [1, 2, 3],\n\t\t\t},\n\t\t};\n\t\tconst expectedResult = {\n\t\t\tfield1: {\n\t\t\t\t$gt: 1,\n\t\t\t\t$lt: 2,\n\t\t\t\t$in: [1, 2, 3],\n\t\t\t},\n\t\t\tnested: {\n\t\t\t\tfield1: 1,\n\t\t\t\tfield2: {\n\t\t\t\t\t$gte: 3,\n\t\t\t\t\t$lte: 4,\n\t\t\t\t\t$in: [1, 2, 3],\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t\texpect(gqlToMikro(test)).toEqual(expectedResult);\n\t});\n\n\tit('transforms filter: numbers -> and null', () => {\n\t\tconst test = {\n\t\t\tfield1_gt: 1,\n\t\t\tfield1_lt: 2,\n\t\t\tfield1_in: [1, 2, 3],\n\t\t\tfield1_null: false,\n\t\t\tfield1_notnull: true,\n\t\t};\n\t\tconst expectedResult = {\n\t\t\tfield1: {\n\t\t\t\t$gt: 1,\n\t\t\t\t$lt: 2,\n\t\t\t\t$in: [1, 2, 3],\n\t\t\t\t$ne: null,\n\t\t\t},\n\t\t};\n\t\texpect(gqlToMikro(test)).toEqual(expectedResult);\n\t});\n\n\tit('transforms filter: numbers -> in and eq', () => {\n\t\tconst test = {\n\t\t\tfield1_in: [1, 2, 3],\n\t\t\tfield1: 4,\n\t\t};\n\t\tconst expectedResult = {\n\t\t\tfield1: { $in: [1, 2, 3], $eq: 4 },\n\t\t};\n\t\texpect(gqlToMikro(test)).toEqual(expectedResult);\n\t});\n\n\tit('transforms filter: strings -> nested', () => {\n\t\tconst test = {\n\t\t\tnested: {\n\t\t\t\tfield1: { id: 'uno' },\n\t\t\t\tfield2_gte: 'someValue',\n\t\t\t\tfield2_lte: 'someValue',\n\t\t\t\tfield2_nin: ['someValue'],\n\t\t\t},\n\t\t};\n\t\tconst expectedResult = {\n\t\t\tnested: {\n\t\t\t\tfield1: { id: 'uno' },\n\t\t\t\tfield2: {\n\t\t\t\t\t$gte: 'someValue',\n\t\t\t\t\t$lte: 'someValue',\n\t\t\t\t\t$nin: ['someValue'],\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t\texpect(gqlToMikro(test)).toEqual(expectedResult);\n\t});\n\n\tit('should throw error -> ambiguous property', () => {\n\t\tconst test = {\n\t\t\t_and: [{ field1_in: [1, 2, 3], field1: 4, field1_null: true }, { field1_nin: [1, 2, 3] }],\n\t\t};\n\t\texpect(() => gqlToMikro(test)).toThrow();\n\t});\n\n\tit('should throw error -> ambiguous property - null then string', () => {\n\t\tconst test = { field1_null: true, field1: 'dos' };\n\t\texpect(() => gqlToMikro(test)).toThrow();\n\t});\n\n\tit(\"should throw error -> ambiguous property - we don't support collapsing same values\", () => {\n\t\tconst test = { field1_null: true, field1: null };\n\t\texpect(() => gqlToMikro(test)).toThrow();\n\t});\n\n\tit('transforms filter: strings -> in and eq', () => {\n\t\tconst test = { field1_nin: ['one'], field1: 'two' };\n\t\tconst expectedResult = { field1: { $nin: ['one'], $eq: 'two' } };\n\t\texpect(gqlToMikro(test)).toEqual(expectedResult);\n\t});\n\n\tit('transforms filter: strings -> or and null', () => {\n\t\tconst test = {\n\t\t\t_or: [\n\t\t\t\t{\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tid_null: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tid: 'seis',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t\tconst expectedResult = {\n\t\t\t$or: [\n\t\t\t\t{\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tid: { $eq: null },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tid: 'seis',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t\texpect(gqlToMikro(test)).toEqual(expectedResult);\n\t});\n\n\tit('transforms filter: complicated filter with nested properties, arrays, nulls, strings, and numbers', () => {\n\t\tconst test = {\n\t\t\tfield1_gt: 5,\n\t\t\tfield2_lt: 10,\n\t\t\tfield3_in: ['a', 'b', 'c'],\n\t\t\tfield4_null: true,\n\t\t\tfield5_notnull: true,\n\t\t\tnested1: {\n\t\t\t\tsubfield1: 1,\n\t\t\t\tsubfield2_gte: 2,\n\t\t\t\tsubfield3_lte: 3,\n\t\t\t\tsubfield4_in: [4, 5, 6],\n\t\t\t\tsubnested: {\n\t\t\t\t\tsubsubfield1: 'value1',\n\t\t\t\t\tsubsubfield2_nin: ['value2', 'value3'],\n\t\t\t\t\tsubsubfield3_null: false,\n\t\t\t\t},\n\t\t\t},\n\t\t\tnested2: {\n\t\t\t\tsubfield1: 'string1',\n\t\t\t\tsubfield2: {\n\t\t\t\t\tsubsubfield1: 'string2',\n\t\t\t\t\tsubsubfield2_gt: 7,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t\tconst expectedResult = {\n\t\t\tfield1: { $gt: 5 },\n\t\t\tfield2: { $lt: 10 },\n\t\t\tfield3: { $in: ['a', 'b', 'c'] },\n\t\t\tfield4: { $eq: null },\n\t\t\tfield5: { $ne: null },\n\t\t\tnested1: {\n\t\t\t\tsubfield1: 1,\n\t\t\t\tsubfield2: { $gte: 2 },\n\t\t\t\tsubfield3: { $lte: 3 },\n\t\t\t\tsubfield4: { $in: [4, 5, 6] },\n\t\t\t\tsubnested: {\n\t\t\t\t\tsubsubfield1: 'value1',\n\t\t\t\t\tsubsubfield2: { $nin: ['value2', 'value3'] },\n\t\t\t\t\tsubsubfield3: { $ne: null },\n\t\t\t\t},\n\t\t\t},\n\t\t\tnested2: {\n\t\t\t\tsubfield1: 'string1',\n\t\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WAAW;AAAA,QACX,WAAW;AAAA,UACV,cAAc;AAAA,UACd,iBAAiB;AAAA,QAClB;AAAA,MACD;AAAA,IACD;AACA,UAAM,iBAAiB;AAAA,MACtB,QAAQ,EAAE,KAAK,EAAE;AAAA,MACjB,QAAQ,EAAE,KAAK,GAAG;AAAA,MAClB,QAAQ,EAAE,KAAK,CAAC,KAAK,KAAK,GAAG,EAAE;AAAA,MAC/B,QAAQ,EAAE,KAAK,KAAK;AAAA,MACpB,QAAQ,EAAE,KAAK,KAAK;AAAA,MACpB,SAAS;AAAA,QACR,WAAW;AAAA,QACX,WAAW,EAAE,MAAM,EAAE;AAAA,QACrB,WAAW,EAAE,MAAM,EAAE;AAAA,QACrB,WAAW,EAAE,KAAK,CAAC,GAAG,GAAG,CAAC,EAAE;AAAA,QAC5B,WAAW;AAAA,UACV,cAAc;AAAA,UACd,cAAc,EAAE,MAAM,CAAC,UAAU,QAAQ,EAAE;AAAA,UAC3C,cAAc,EAAE,KAAK,KAAK;AAAA,QAC3B;AAAA,MACD;AAAA,MACA,SAAS;AAAA,QACR,WAAW;AAAA,QACX,WAAW;AAAA,UACV,cAAc;AAAA,UACd,cAAc,EAAE,KAAK,EAAE;AAAA,QACxB;AAAA,MACD;AAAA,IACD;AACA,kCAAO,4BAAW,IAAI,CAAC,EAAE,QAAQ,cAAc;AAAA,EAChD,CAAC;AACF,CAAC;",
6
+ "names": []
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exogee/graphweaver-mikroorm",
3
- "version": "2.12.0",
3
+ "version": "2.12.2",
4
4
  "description": "MikroORM backend for @exogee/graphweaver",
5
5
  "license": "Apache-2.0",
6
6
  "main": "lib/index.js",
@@ -13,15 +13,15 @@
13
13
  ],
14
14
  "dependencies": {
15
15
  "@apollo/server": "4.11.2",
16
- "@aws-sdk/client-secrets-manager": "3.750.0",
16
+ "@aws-sdk/client-secrets-manager": "3.758.0",
17
17
  "dataloader": "2.2.3",
18
18
  "decimal.js": "10.5.0",
19
19
  "dotenv": "16.4.7",
20
20
  "pluralize": "8.0.0",
21
21
  "reflect-metadata": "0.2.2",
22
- "@exogee/graphweaver": "2.12.0",
23
- "@exogee/graphweaver-server": "2.12.0",
24
- "@exogee/logger": "2.12.0"
22
+ "@exogee/logger": "2.12.2",
23
+ "@exogee/graphweaver": "2.12.2",
24
+ "@exogee/graphweaver-server": "2.12.2"
25
25
  },
26
26
  "peerDependencies": {
27
27
  "graphql": "16",
@@ -29,24 +29,25 @@
29
29
  "@mikro-orm/knex": "6"
30
30
  },
31
31
  "devDependencies": {
32
- "@mikro-orm/core": "6.4.6",
33
- "@mikro-orm/knex": "6.4.6",
34
- "@mikro-orm/mysql": "6.4.6",
35
- "@mikro-orm/postgresql": "6.4.6",
36
- "@mikro-orm/sqlite": "6.4.6",
32
+ "@mikro-orm/core": "6.4.7",
33
+ "@mikro-orm/knex": "6.4.7",
34
+ "@mikro-orm/mysql": "6.4.7",
35
+ "@mikro-orm/postgresql": "6.4.7",
36
+ "@mikro-orm/sqlite": "6.4.7",
37
37
  "@types/node": "22.10.1",
38
38
  "@types/pluralize": "0.0.33",
39
39
  "esbuild": "0.25.0",
40
40
  "glob": "11.0.1",
41
41
  "graphql": "16.10.0",
42
- "tsx": "4.19.2",
43
- "typescript": "5.7.2"
42
+ "tsx": "4.19.3",
43
+ "typescript": "5.7.2",
44
+ "vitest": "2.1.9"
44
45
  },
45
46
  "optionalDependencies": {
46
- "@mikro-orm/knex": "^6.4.6",
47
- "@mikro-orm/mysql": "^6.4.6",
48
- "@mikro-orm/postgresql": "^6.4.6",
49
- "@mikro-orm/sqlite": "^6.4.6"
47
+ "@mikro-orm/knex": "^6.4.7",
48
+ "@mikro-orm/mysql": "^6.4.7",
49
+ "@mikro-orm/postgresql": "^6.4.7",
50
+ "@mikro-orm/sqlite": "^6.4.7"
50
51
  },
51
52
  "keywords": [
52
53
  "graphql",
@@ -65,8 +66,9 @@
65
66
  "generate:schema": "tsx ./src/utils/generate-db-schema.ts",
66
67
  "package:pack": "pnpm pack",
67
68
  "prettier": "prettier --write src/**/*.ts",
68
- "test": "tsx scripts/check-mikro-overrides-match-installed-versions.ts",
69
+ "test": "tsx scripts/check-mikro-overrides-match-installed-versions.ts && pnpm run:unit:tests",
69
70
  "test-introspection": "tsx scripts/test-introspection.ts",
71
+ "run:unit:tests": "vitest",
70
72
  "version": "npm version --no-git-tag-version"
71
73
  }
72
74
  }