forge-sql-orm 1.0.25 → 1.0.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ForgeSQLORM.js.map +1 -1
- package/dist/ForgeSQLORM.mjs.map +1 -1
- package/dist/core/ForgeSQLCrudOperations.d.ts +1 -1
- package/dist/core/ForgeSQLCrudOperations.d.ts.map +1 -1
- package/dist/core/ForgeSQLORM.d.ts +1 -1
- package/dist/core/ForgeSQLORM.d.ts.map +1 -1
- package/dist-cli/cli.js +12 -7
- package/dist-cli/cli.js.map +1 -1
- package/dist-cli/cli.mjs +12 -7
- package/dist-cli/cli.mjs.map +1 -1
- package/dist-cli/{forgeSqlCLI.js → forgeSqlOrmCLI.js} +0 -0
- package/package.json +2 -2
- package/src/core/ForgeSQLCrudOperations.ts +1 -1
- package/src/core/ForgeSQLORM.ts +1 -1
package/dist/ForgeSQLORM.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ForgeSQLORM.js","sources":["../src/utils/sqlUtils.ts","../src/core/ForgeSQLCrudOperations.ts","../src/core/ForgeSQLSelectOperations.ts","../src/core/ForgeSQLORM.ts"],"sourcesContent":["import { types } from \"@mikro-orm/core/types\";\nimport moment from \"moment\";\nimport { AnyString } from \"@mikro-orm/core/typings\";\n\nconst wrapIfNeeded=(data:string, wrap:boolean):string => {\n return wrap?`'${data}'`:data;\n}\n\nexport const transformValue = <U>(value: {\n type: keyof typeof types | AnyString;\n value: U;\n}, wrapValue: boolean = false): U => {\n switch (value.type) {\n case \"text\":\n case \"string\":\n return <U>wrapIfNeeded(`${value.value}`,wrapValue);\n case \"datetime\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"YYYY-MM-DDTHH:mm:ss.SSS\")}`,wrapValue);\n case \"date\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"YYYY-MM-DD\")}`, wrapValue);\n case \"time\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"HH:mm:ss.SSS\")}`,wrapValue);\n default:\n return value.value;\n }\n};\n\nexport const parseDateTime = (value: string, format: string): Date => {\n const m = moment(value, format, true);\n if (!m.isValid()) {\n return moment(value).toDate();\n }\n return m.toDate();\n};\n","import { sql, UpdateQueryResponse } from \"@forge/sql\";\nimport { EntityProperty, EntitySchema, ForgeSqlOrmOptions } from \"..\";\nimport type { types } from \"@mikro-orm/core/types\";\nimport { transformValue } from \"../utils/sqlUtils\";\nimport { CRUDForgeSQL, ForgeSqlOperation } from \"./ForgeSQLQueryBuilder\";\nimport { EntityKey, QBFilterQuery } from \"@mikro-orm/core\";\nimport Knex from \"../knex\";\n\nexport class ForgeSQLCrudOperations implements CRUDForgeSQL {\n private readonly forgeOperations: ForgeSqlOperation;\n private readonly options: ForgeSqlOrmOptions;\n\n constructor(forgeSqlOperations: ForgeSqlOperation, options: ForgeSqlOrmOptions) {\n this.forgeOperations = forgeSqlOperations;\n this.options = options;\n }\n\n /**\n * Generates an SQL INSERT statement for the provided models.\n * If a version field exists in the schema, its value is set accordingly.\n *\n * @param schema - The entity schema.\n * @param models - The list of entities to insert.\n * @param updateIfExists - Whether to update the row if it already exists.\n * @returns An object containing the SQL query, column names, and values.\n */\n private async generateInsertScript<T extends object>(\n schema: EntitySchema<T>,\n models: T[],\n updateIfExists: boolean,\n ): Promise<{\n sql: string;\n query: string;\n fields: string[];\n values: { type: keyof typeof types; value: unknown }[];\n }> {\n const columnNames = new Set<string>();\n const modelFieldValues: Record<string, { type: keyof typeof types; value: unknown }>[] = [];\n\n // Build field values for each model.\n models.forEach((model) => {\n const fieldValues: Record<string, { type: keyof typeof types; value: unknown }> = {};\n schema.meta.props.forEach((prop) => {\n const value = model[prop.name];\n if (prop.kind === \"scalar\" && value !== undefined) {\n const columnName = this.getRealFieldNameFromSchema(prop);\n columnNames.add(columnName);\n fieldValues[columnName] = { type: prop.type as keyof typeof types, value };\n }\n });\n modelFieldValues.push(fieldValues);\n });\n\n // If a version field exists, set or update its value.\n const versionField = this.getVersionField(schema);\n if (versionField) {\n modelFieldValues.forEach((mv) => {\n const versionRealName = this.getRealFieldNameFromSchema(versionField);\n if (mv[versionRealName]) {\n mv[versionRealName].value = transformValue(\n { value: this.createVersionField(versionField), type: versionField.name },\n true,\n );\n } else {\n mv[versionRealName] = {\n type: versionField.type as keyof typeof types,\n value: transformValue(\n { value: this.createVersionField(versionField), type: versionField.name },\n true,\n ),\n };\n columnNames.add(versionField.name);\n }\n });\n }\n\n const columns = Array.from(columnNames);\n\n // Flatten values for each row in the order of columns.\n const values = modelFieldValues.flatMap((fieldValueMap) =>\n columns.map(\n (column) =>\n fieldValueMap[column] || {\n type: \"string\",\n value: null,\n },\n ),\n );\n\n // Build the VALUES clause.\n const insertValues = modelFieldValues\n .map((fieldValueMap) => {\n const rowValues = columns\n .map((column) =>\n transformValue(\n fieldValueMap[column] || { type: \"string\", value: null },\n true,\n ),\n )\n .join(\",\");\n return `(${rowValues})`;\n })\n .join(\", \");\n // Build the VALUES ? clause.\n const insertEmptyValues = modelFieldValues\n .map(() => {\n const rowValues = columns\n .map(() =>\n '?',\n )\n .join(\",\");\n return `(${rowValues})`;\n })\n .join(\", \");\n\n const updateClause = updateIfExists\n ? ` ON DUPLICATE KEY UPDATE ${columns.map((col) => `${col} = VALUES(${col})`).join(\",\")}`\n : \"\";\n\n return {\n sql: `INSERT INTO ${schema.meta.collection} (${columns.join(\",\")}) VALUES ${insertValues}${updateClause}`,\n query: `INSERT INTO ${schema.meta.collection} (${columns.join(\",\")}) VALUES ${insertEmptyValues}${updateClause}`,\n fields: columns,\n values,\n };\n }\n\n /**\n * Inserts records into the database.\n * If a version field exists in the schema, versioning is applied.\n *\n * @param schema - The entity schema.\n * @param models - The list of entities to insert.\n * @param updateIfExists - Whether to update the row if it already exists.\n * @returns The ID of the inserted row.\n */\n async insert<T extends object>(\n schema: EntitySchema<T>,\n models: T[],\n updateIfExists: boolean = false,\n ): Promise<number> {\n if (!models || models.length === 0) return 0;\n\n const query = await this.generateInsertScript(schema, models, updateIfExists);\n if (this.options?.logRawSqlQuery) {\n console.debug(\"INSERT SQL: \" + query.query);\n }\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query.sql);\n const result = await sqlStatement.execute();\n return result.rows.insertId;\n }\n\n /**\n * Retrieves the primary key properties from the entity schema.\n *\n * @param schema - The entity schema.\n * @returns An array of primary key properties.\n * @throws If no primary keys are found.\n */\n private getPrimaryKeys<T extends object>(schema: EntitySchema<T>): EntityProperty<T, unknown>[] {\n const primaryKeys = schema.meta.props.filter((prop) => prop.primary);\n if (!primaryKeys.length) {\n throw new Error(`No primary keys found for schema: ${schema.meta.className}`);\n }\n return primaryKeys;\n }\n\n /**\n * Deletes a record by its primary key.\n *\n * @param id - The ID of the record to delete.\n * @param schema - The entity schema.\n * @returns The number of rows affected.\n * @throws If the entity has more than one primary key.\n */\n async deleteById<T extends object>(id: unknown, schema: EntitySchema<T>): Promise<number> {\n const primaryKeys = this.getPrimaryKeys(schema);\n if (primaryKeys.length > 1) {\n throw new Error(\"Only one primary key is supported\");\n }\n\n const primaryKey = primaryKeys[0];\n const queryBuilder = this.forgeOperations.createQueryBuilder(schema.meta.class).delete();\n queryBuilder.andWhere({ [primaryKey.name]: { $eq: id } });\n\n const query = queryBuilder.getFormattedQuery();\n if (this.options?.logRawSqlQuery) {\n console.debug(\"DELETE SQL: \" + queryBuilder.getQuery());\n }\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query);\n const result = await sqlStatement.execute();\n return result.rows.affectedRows;\n }\n\n /**\n * Retrieves the version field from the entity schema.\n * The version field must be of type datetime, integer, or decimal, not a primary key, and not nullable.\n *\n * @param schema - The entity schema.\n * @returns The version field property if it exists.\n */\n getVersionField<T>(schema: EntitySchema<T>) {\n if (this.options.disableOptimisticLocking){\n return undefined;\n }\n return schema.meta.props\n .filter((prop) => prop.version)\n .filter((prop) => {\n const validType =\n prop.type === \"datetime\" || prop.type === \"integer\" || prop.type === \"decimal\";\n if (!validType) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} must be datetime, integer, or decimal, but is \"${prop.type}\"`,\n );\n }\n return validType;\n })\n .filter((prop) => {\n if (prop.primary) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} cannot be a primary key`,\n );\n return false;\n }\n return true;\n })\n .find((prop) => {\n if (prop.nullable) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} should not be nullable`,\n );\n return false;\n }\n return true;\n });\n }\n\n /**\n * Increments the version field of an entity.\n * For datetime types, sets the current date; for numeric types, increments by 1.\n *\n * @param versionField - The version field property.\n * @param updateModel - The entity to update.\n */\n incrementVersionField<T>(versionField: EntityProperty<T, any>, updateModel: T): void {\n const key = versionField.name as keyof T;\n switch (versionField.type) {\n case \"datetime\": {\n updateModel[key] = new Date() as unknown as T[keyof T];\n break;\n }\n case \"decimal\":\n case \"integer\": {\n updateModel[key] = ((updateModel[key] as number) + 1) as unknown as T[keyof T];\n break;\n }\n default:\n throw new Error(`Unsupported version field type: ${versionField.type}`);\n }\n }\n\n /**\n * Creates the initial version field value for an entity.\n * For datetime types, returns the current date; for numeric types, returns 0.\n *\n * @param versionField - The version field property.\n */\n createVersionField<T>(versionField: EntityProperty<T>): unknown {\n switch (versionField.type) {\n case \"datetime\": {\n return new Date() as unknown as T[keyof T];\n }\n case \"decimal\":\n case \"integer\": {\n return 0;\n }\n default:\n throw new Error(`Unsupported version field type: ${versionField.type}`);\n }\n }\n\n /**\n * Updates a record by its primary key using the provided entity data.\n *\n * @param entity - The entity with updated values.\n * @param schema - The entity schema.\n */\n async updateById<T extends object>(entity: Partial<T>, schema: EntitySchema<T>): Promise<void> {\n const fields = schema.meta.props\n .filter((prop) => prop.kind === \"scalar\")\n .map((prop) => prop.name);\n await this.updateFieldById(entity as T, fields, schema);\n }\n\n /**\n * Updates specified fields of records based on provided conditions.\n * If the \"where\" parameter is not provided, the WHERE clause is built from the entity fields\n * that are not included in the list of fields to update.\n *\n * @param entity - The object containing values to update and potential criteria for filtering.\n * @param fields - Array of field names to update.\n * @param schema - The entity schema.\n * @param where - Optional filtering conditions for the WHERE clause.\n * @returns The number of affected rows.\n * @throws If no filtering criteria are provided (either via \"where\" or from the remaining entity fields).\n */\n async updateFields<T extends object>(\n entity: Partial<T>,\n fields: EntityKey<T>[],\n schema: EntitySchema<T>,\n where?: QBFilterQuery<T>,\n ): Promise<number> {\n // Extract update data from the entity based on the provided fields.\n const updateData = this.filterEntityFields(entity, fields);\n const updateModel = this.modifyModel(updateData as T, schema);\n\n // Create the query builder for the entity.\n let queryBuilder = this.forgeOperations\n .createQueryBuilder(schema.meta.class)\n .getKnexQuery();\n\n // Set the update data.\n queryBuilder.update(updateModel as T);\n\n // Use the provided \"where\" conditions if available; otherwise, build conditions from the remaining entity fields.\n if (where) {\n queryBuilder.where(where);\n } else {\n const filterCriteria = (Object.keys(entity) as Array<keyof T>)\n .filter((key: keyof T) => !fields.includes(key as EntityKey<T>))\n .reduce((criteria, key) => {\n if (entity[key] !== undefined) {\n // Cast key to string to use it as an object key.\n criteria[key as string] = entity[key];\n }\n return criteria;\n }, {} as Record<string, unknown>);\n\n\n if (Object.keys(filterCriteria).length === 0) {\n throw new Error(\n \"Filtering criteria (WHERE clause) must be provided either via the 'where' parameter or through non-updated entity fields\"\n );\n }\n queryBuilder.where(filterCriteria);\n }\n\n if (this.options?.logRawSqlQuery) {\n console.debug(\"UPDATE SQL (updateFields): \" + queryBuilder.toSQL().sql);\n }\n\n // Execute the update query.\n const sqlQuery = queryBuilder.toQuery();\n const updateQueryResponse = await this.forgeOperations.fetch().executeRawUpdateSQL(sqlQuery);\n return updateQueryResponse.affectedRows;\n }\n\n\n /**\n * Updates specific fields of a record identified by its primary key.\n * If a version field exists in the schema, versioning is applied.\n *\n * @param entity - The entity with updated values.\n * @param fields - The list of field names to update.\n * @param schema - The entity schema.\n * @throws If the primary key is not included in the update fields.\n */\n async updateFieldById<T extends object>(\n entity: T,\n fields: EntityKey<T>[],\n schema: EntitySchema<T>,\n ): Promise<void> {\n const primaryKeys = this.getPrimaryKeys(schema);\n primaryKeys.forEach((pk) => {\n if (!fields.includes(pk.name)) {\n throw new Error(\"Update fields must include primary key: \" + pk.name);\n }\n });\n\n // Prepare updated entity and query builder.\n const updatedEntity = this.filterEntityFields(entity, fields);\n let queryBuilder = this.forgeOperations.createQueryBuilder(schema.meta.class).getKnexQuery();\n const versionField = this.getVersionField(schema);\n const useVersion = Boolean(versionField);\n let updateModel = { ...updatedEntity };\n\n if (useVersion && versionField) {\n // If the version field is missing from the entity, load the old record.\n let oldModel = entity;\n if (entity[versionField.name] === undefined || entity[versionField.name] === null) {\n oldModel = await this.getOldModel(primaryKeys, entity, schema, versionField);\n }\n const primaryFieldNames = primaryKeys.map((pk) => pk.name);\n const fieldsToRetain = primaryFieldNames.concat(versionField.name);\n const fromEntries = Object.fromEntries(fieldsToRetain.map((key) => [key, oldModel[key]]));\n updateModel = { ...updatedEntity, ...fromEntries };\n\n // Increment the version field.\n this.incrementVersionField(versionField, updateModel as T);\n\n updateModel = this.modifyModel(updateModel as T, schema);\n queryBuilder.update(updateModel as T);\n if (oldModel[versionField.name]!==undefined || oldModel[versionField.name]!==null && this.isValid(oldModel[versionField.name])) {\n queryBuilder.andWhere(this.optWhere(oldModel, versionField));\n }\n } else {\n updateModel = this.modifyModel(updatedEntity as T, schema);\n queryBuilder.update(updateModel as T);\n }\n\n this.addPrimaryWhere(queryBuilder as unknown as Knex.QueryBuilder<any, any>, primaryKeys, updateModel as T);\n const sqlQuery = queryBuilder.toQuery();\n\n if (this.options?.logRawSqlQuery) {\n console.debug(\"UPDATE SQL: \" + queryBuilder.toSQL().sql);\n }\n const updateQueryResponse = await this.forgeOperations.fetch().executeRawUpdateSQL(sqlQuery);\n if (versionField && !updateQueryResponse.affectedRows) {\n throw new Error(\n \"Optimistic locking failed: the record with primary key(s) \" +\n primaryKeys.map((p) => updateModel[p.name]).join(\", \") +\n \" has been modified by another process.\",\n );\n }\n }\n\n /**\n * Constructs an optional WHERE clause for the version field.\n *\n * @param updateModel - The model containing the current version field value.\n * @param versionField - The version field property.\n * @returns A filter query for the version field.\n */\n private optWhere<T>(\n updateModel: T,\n versionField: EntityProperty<T>,\n ): QBFilterQuery<unknown> {\n const currentVersionValue = transformValue(\n { value: updateModel[versionField.name], type: versionField.type },\n false,\n );\n return { [versionField.name]: currentVersionValue };\n }\n\n /**\n * Retrieves the current state of a record from the database.\n *\n * @param primaryKeys - The primary key properties.\n * @param entity - The entity with updated values.\n * @param schema - The entity schema.\n * @param versionField - The version field property.\n * @returns The existing record from the database.\n * @throws If the record does not exist or if multiple records are found.\n */\n private async getOldModel<T>(\n primaryKeys: EntityProperty<T, unknown>[],\n entity: T,\n schema: EntitySchema<T>,\n versionField: EntityProperty<T>,\n ): Promise<T> {\n const primaryFieldNames = primaryKeys.map((pk) => pk.name);\n const fieldsToSelect = primaryFieldNames.concat(versionField.name);\n const queryBuilder = this.forgeOperations\n .createQueryBuilder(schema as EntitySchema)\n .select(fieldsToSelect);\n this.addPrimaryWhere(queryBuilder, primaryKeys, entity);\n const formattedQuery = queryBuilder.getFormattedQuery();\n const models: T[] = await this.forgeOperations.fetch().executeSchemaSQL(formattedQuery, schema as EntitySchema);\n\n if (!models || models.length === 0) {\n throw new Error(`Cannot modify record because it does not exist in table ${schema.meta.tableName}`);\n }\n if (models.length > 1) {\n throw new Error(\n `Cannot modify record because multiple rows with the same ID were found in table ${schema.meta.tableName}. Please verify the table metadata.`,\n );\n }\n return models[0];\n }\n\n /**\n * Adds primary key conditions to the query builder.\n *\n * @param queryBuilder - The Knex query builder instance.\n * @param primaryKeys - The primary key properties.\n * @param entity - The entity containing primary key values.\n * @throws If any primary key value is missing.\n */\n private addPrimaryWhere<T>(\n queryBuilder: Knex.QueryBuilder<any, any>,\n primaryKeys: EntityProperty<T, unknown>[],\n entity: T,\n ) {\n primaryKeys.forEach((pk) => {\n const fieldName = this.getRealFieldNameFromSchema(pk);\n const value = entity[fieldName];\n if (value === null || value === undefined) {\n throw new Error(`Primary key ${fieldName} must exist in the model`);\n }\n queryBuilder.andWhere({ [fieldName]: value });\n });\n }\n\n /**\n * Filters the entity to include only the specified fields.\n *\n * @param entity - The original entity.\n * @param fields - The list of fields to retain.\n * @returns A partial entity object containing only the specified fields.\n */\n filterEntityFields = <T extends object>(entity: T, fields: (keyof T)[]): Partial<T> =>\n fields.reduce((result, field) => {\n if (field in entity) {\n result[field] = entity[field];\n }\n return result;\n }, {} as Partial<T>);\n\n /**\n * Transforms and modifies the updated entity model based on the schema.\n *\n * @param updatedEntity - The updated entity.\n * @param schema - The entity schema.\n * @returns The modified entity.\n */\n private modifyModel<T>(updatedEntity: T, schema: EntitySchema<T>): T {\n const modifiedModel: Record<string, any> = {};\n schema.meta.props\n .filter((p) => p.kind === \"scalar\")\n .forEach((p) => {\n const value = updatedEntity[p.name];\n if (value !== undefined && value !== null) {\n const fieldName = this.getRealFieldNameFromSchema(p);\n modifiedModel[fieldName] = transformValue({ value, type: p.type }, false);\n }\n });\n return modifiedModel as T;\n }\n\n /**\n * Returns the real field name from the entity property based on the schema.\n *\n * @param p - The entity property.\n * @returns The real field name.\n */\n private getRealFieldNameFromSchema<T>(p: EntityProperty<T>): EntityKey<T> {\n return p.fieldNames && p.fieldNames.length\n ? (p.fieldNames[0] as EntityKey<T>)\n : p.name;\n }\n\n /**\n * Validates the provided value.\n *\n * @param value - The value to validate.\n * @returns True if the value is valid, false otherwise.\n */\n isValid(value: any): boolean {\n if (value instanceof Date) {\n return !isNaN(value.getTime());\n }\n return true;\n }\n}\n","import { sql, UpdateQueryResponse } from \"@forge/sql\";\nimport type { EntitySchema } from \"@mikro-orm/core/metadata/EntitySchema\";\nimport { parseDateTime } from \"../utils/sqlUtils\";\nimport { ForgeSqlOrmOptions, SchemaSqlForgeSql } from \"./ForgeSQLQueryBuilder\";\nimport {SqlParameters} from \"@forge/sql/out/sql-statement\";\n\nexport class ForgeSQLSelectOperations implements SchemaSqlForgeSql {\n private readonly options: ForgeSqlOrmOptions;\n\n constructor(options: ForgeSqlOrmOptions) {\n this.options = options;\n }\n\n async executeSchemaSQLOnlyOne<T extends object>(query: string, schema: EntitySchema<T>): Promise<T|undefined> {\n const results = await this.executeSchemaSQL(query, schema);\n if (!results || results.length === 0){\n return undefined;\n }\n if (results.length>1){\n throw new Error('Expected 1 record but returned '+results.length)\n }\n return results[0];\n }\n\n /**\n * Executes a schema-based SQL query and maps the result to the entity schema.\n * @param query - The SQL query to execute.\n * @param schema - The entity schema defining the structure.\n * @returns A list of mapped entity objects.\n */\n async executeSchemaSQL<T extends object>(query: string, schema: EntitySchema<T>): Promise<T[]> {\n const datas = await this.executeRawSQL<unknown>(query);\n if (!datas.length) return [];\n\n return datas.map((r) => {\n const rawModel = r as Record<string, unknown>;\n const newModel: Record<string, unknown> = {};\n\n schema.meta.props\n .filter((p) => p.kind === \"scalar\")\n .forEach((p) => {\n const fieldName = p.name;\n const fieldNames = p.fieldNames;\n const rawFieldName = fieldNames && Array.isArray(fieldNames) ? fieldNames[0] : p.name;\n\n switch (p.type) {\n case \"datetime\":\n newModel[fieldName] = parseDateTime(\n rawModel[rawFieldName] as string,\n \"YYYY-MM-DDTHH:mm:ss.SSS\",\n );\n break;\n case \"date\":\n newModel[fieldName] = parseDateTime(rawModel[rawFieldName] as string, \"YYYY-MM-DD\");\n break;\n case \"time\":\n newModel[fieldName] = parseDateTime(rawModel[rawFieldName] as string, \"HH:mm:ss.SSS\");\n break;\n default:\n newModel[fieldName] = rawModel[rawFieldName];\n }\n });\n return newModel as T;\n });\n }\n\n /**\n * Executes a raw SQL query and returns the results.\n * @param query - The raw SQL query to execute.\n * @returns A list of results as objects.\n */\n async executeRawSQL<T extends object | unknown>(query: string): Promise<T[]> {\n if (this.options.logRawSqlQuery) {\n console.debug(\"Executing raw SQL: \" + query);\n }\n const sqlStatement = await sql.prepare<T>(query).execute();\n return sqlStatement.rows as T[];\n }\n\n /**\n * Executes a raw SQL update query.\n * @param query - The raw SQL update query.\n * @param params - sql parameters.\n * @returns The update response containing affected rows.\n */\n async executeRawUpdateSQL(query: string, params?: SqlParameters[]): Promise<UpdateQueryResponse> {\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query);\n if (params) {\n sqlStatement.bindParams(params);\n }\n const updateQueryResponseResults = await sqlStatement.execute();\n return updateQueryResponseResults.rows;\n }\n}\n","import type { EntityName, LoggingOptions } from \"@mikro-orm/core\";\nimport type { EntitySchema } from \"@mikro-orm/core/metadata/EntitySchema\";\nimport type { AnyEntity, EntityClass, EntityClassGroup } from \"@mikro-orm/core/typings\";\nimport type { QueryBuilder } from \"@mikro-orm/knex/query\";\nimport { MemoryCacheAdapter, MikroORM, NullCacheAdapter } from \"@mikro-orm/mysql\";\nimport { ForgeSQLCrudOperations } from \"./ForgeSQLCrudOperations\";\nimport {\n CRUDForgeSQL,\n ForgeSqlOperation,\n ForgeSqlOrmOptions,\n SchemaSqlForgeSql,\n} from \"./ForgeSQLQueryBuilder\";\nimport { ForgeSQLSelectOperations } from \"./ForgeSQLSelectOperations\";\nimport type { Knex } from \"knex\";\n\n/**\n * Implementation of ForgeSQLORM that interacts with MikroORM.\n */\nclass ForgeSQLORMImpl implements ForgeSqlOperation {\n private static instance: ForgeSQLORMImpl | null = null;\n private readonly mikroORM: MikroORM;\n private readonly crudOperations: CRUDForgeSQL;\n private readonly fetchOperations: SchemaSqlForgeSql;\n\n /**\n * Private constructor to enforce singleton behavior.\n * @param entities - The list of entities for ORM initialization.\n * @param options - Options for configuring ForgeSQL ORM behavior.\n */\n private constructor(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ) {\n console.debug(\"Initializing ForgeSQLORM...\");\n\n try {\n this.mikroORM = MikroORM.initSync({\n dbName: \"inmemory\",\n schemaGenerator: {\n disableForeignKeys: false,\n },\n discovery: {\n warnWhenNoEntities: true,\n },\n resultCache: {\n adapter: NullCacheAdapter,\n },\n metadataCache: {\n enabled: false,\n adapter: MemoryCacheAdapter,\n },\n entities: entities,\n preferTs: false,\n debug: false,\n });\n const newOptions: ForgeSqlOrmOptions = options ?? { logRawSqlQuery: false, disableOptimisticLocking: false };\n this.crudOperations = new ForgeSQLCrudOperations(this, newOptions);\n this.fetchOperations = new ForgeSQLSelectOperations(newOptions);\n } catch (error) {\n console.error(\"ForgeSQLORM initialization failed:\", error);\n throw error; // Prevents inconsistent state\n }\n }\n\n /**\n * Returns the singleton instance of ForgeSQLORMImpl.\n * @param entities - List of entities (required only on first initialization).\n * @param options - Options for configuring ForgeSQL ORM behavior.\n * @returns The singleton instance of ForgeSQLORMImpl.\n */\n static getInstance(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ): ForgeSqlOperation {\n if (!ForgeSQLORMImpl.instance) {\n ForgeSQLORMImpl.instance = new ForgeSQLORMImpl(entities, options);\n }\n return ForgeSQLORMImpl.instance;\n }\n\n /**\n * Retrieves the CRUD operations instance.\n * @returns CRUD operations.\n */\n crud(): CRUDForgeSQL {\n return this.crudOperations;\n }\n\n /**\n * Retrieves the fetch operations instance.\n * @returns Fetch operations.\n */\n fetch(): SchemaSqlForgeSql {\n return this.fetchOperations;\n }\n\n /**\n * Creates a new query builder for the given entity.\n * @param entityName - The entity name or an existing query builder.\n * @param alias - The alias for the entity.\n * @param loggerContext - Logging options.\n * @returns The query builder instance.\n */\n createQueryBuilder<Entity extends object, RootAlias extends string = never>(\n entityName: EntityName<Entity> | QueryBuilder<Entity>,\n alias?: RootAlias,\n loggerContext?: LoggingOptions,\n ): QueryBuilder<Entity, RootAlias> {\n return this.mikroORM.em.createQueryBuilder(entityName, alias, undefined, loggerContext);\n }\n\n /**\n * Provides access to the underlying Knex instance for building complex query parts.\n * enabling advanced query customization and performance tuning.\n * @returns The Knex instance, which can be used for query building.\n */\n getKnex(): Knex<any, any[]> {\n return this.mikroORM.em.getKnex();\n }\n}\n\n/**\n * Public class that acts as a wrapper around the private ForgeSQLORMImpl.\n */\nclass ForgeSQLORM {\n private readonly ormInstance: ForgeSqlOperation;\n\n constructor(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ) {\n this.ormInstance = ForgeSQLORMImpl.getInstance(entities, options);\n }\n\n /**\n * Proxies the `crud` method from `ForgeSQLORMImpl`.\n * @returns CRUD operations.\n */\n crud(): CRUDForgeSQL {\n return this.ormInstance.crud();\n }\n\n /**\n * Proxies the `fetch` method from `ForgeSQLORMImpl`.\n * @returns Fetch operations.\n */\n fetch(): SchemaSqlForgeSql {\n return this.ormInstance.fetch();\n }\n\n getKnex(): Knex<any, any[]> {\n return this.ormInstance.getKnex();\n }\n\n /**\n * Proxies the `createQueryBuilder` method from `ForgeSQLORMImpl`.\n * @returns A new query builder instance.\n */\n createQueryBuilder<Entity extends object, RootAlias extends string = never>(\n entityName: EntityName<Entity> | QueryBuilder<Entity>,\n alias?: RootAlias,\n loggerContext?: LoggingOptions,\n ): QueryBuilder<Entity, RootAlias> {\n return this.ormInstance.createQueryBuilder(entityName, alias, loggerContext);\n }\n}\n\nexport default ForgeSQLORM;\n"],"names":["sql","MikroORM","NullCacheAdapter","MemoryCacheAdapter"],"mappings":";;;;;;AAIA,MAAM,eAAa,CAAC,MAAa,SAAwB;AAChD,SAAA,OAAK,IAAI,IAAI,MAAI;AAC1B;AAEO,MAAM,iBAAiB,CAAI,OAG/B,YAAqB,UAAa;AACnC,UAAQ,MAAM,MAAM;AAAA,IAClB,KAAK;AAAA,IACL,KAAK;AACH,aAAU,aAAa,GAAG,MAAM,KAAK,IAAG,SAAS;AAAA,IACnD,KAAK;AACO,aAAA,aAAa,GAAG,OAAO,MAAM,KAAa,EAAE,OAAO,yBAAyB,CAAC,IAAG,SAAS;AAAA,IACrG,KAAK;AACO,aAAA,aAAa,GAAG,OAAO,MAAM,KAAa,EAAE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AAAA;AAAA;AAAA;AAAA;AAAA,EAQxF,UAA4B;AACnB,WAAA,KAAK,SAAS,GAAG,QAAQ;AAAA,EAAA;AAEpC;AAKA,MAAM,YAAY;AAAA,EACC;AAAA,EAEjB,YACE,UACA,SACA;AACA,SAAK,cAAc,gBAAgB,YAAY,UAAU,OAAO;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlE,OAAqB;AACZ,WAAA,KAAK,YAAY,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO/B,QAA2B;AAClB,WAAA,KAAK,YAAY,MAAM;AAAA,EAAA;AAAA,EAGhC,UAA4B;AACnB,WAAA,KAAK,YAAY,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlC,mBACE,YACA,OACA,eACiC;AACjC,WAAO,KAAK,YAAY,mBAAmB,YAAY,OAAO,aAAa;AAAA,EAAA;AAE/E;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"ForgeSQLORM.js","sources":["../src/utils/sqlUtils.ts","../src/core/ForgeSQLCrudOperations.ts","../src/core/ForgeSQLSelectOperations.ts","../src/core/ForgeSQLORM.ts"],"sourcesContent":["import { types } from \"@mikro-orm/core/types\";\nimport moment from \"moment\";\nimport { AnyString } from \"@mikro-orm/core/typings\";\n\nconst wrapIfNeeded=(data:string, wrap:boolean):string => {\n return wrap?`'${data}'`:data;\n}\n\nexport const transformValue = <U>(value: {\n type: keyof typeof types | AnyString;\n value: U;\n}, wrapValue: boolean = false): U => {\n switch (value.type) {\n case \"text\":\n case \"string\":\n return <U>wrapIfNeeded(`${value.value}`,wrapValue);\n case \"datetime\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"YYYY-MM-DDTHH:mm:ss.SSS\")}`,wrapValue);\n case \"date\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"YYYY-MM-DD\")}`, wrapValue);\n case \"time\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"HH:mm:ss.SSS\")}`,wrapValue);\n default:\n return value.value;\n }\n};\n\nexport const parseDateTime = (value: string, format: string): Date => {\n const m = moment(value, format, true);\n if (!m.isValid()) {\n return moment(value).toDate();\n }\n return m.toDate();\n};\n","import { sql, UpdateQueryResponse } from \"@forge/sql\";\nimport { EntityProperty, EntitySchema, ForgeSqlOrmOptions } from \"..\";\nimport type { types } from \"@mikro-orm/core/types\";\nimport { transformValue } from \"../utils/sqlUtils\";\nimport { CRUDForgeSQL, ForgeSqlOperation } from \"./ForgeSQLQueryBuilder\";\nimport { EntityKey, QBFilterQuery } from \"..\";\nimport Knex from \"../knex\";\n\nexport class ForgeSQLCrudOperations implements CRUDForgeSQL {\n private readonly forgeOperations: ForgeSqlOperation;\n private readonly options: ForgeSqlOrmOptions;\n\n constructor(forgeSqlOperations: ForgeSqlOperation, options: ForgeSqlOrmOptions) {\n this.forgeOperations = forgeSqlOperations;\n this.options = options;\n }\n\n /**\n * Generates an SQL INSERT statement for the provided models.\n * If a version field exists in the schema, its value is set accordingly.\n *\n * @param schema - The entity schema.\n * @param models - The list of entities to insert.\n * @param updateIfExists - Whether to update the row if it already exists.\n * @returns An object containing the SQL query, column names, and values.\n */\n private async generateInsertScript<T extends object>(\n schema: EntitySchema<T>,\n models: T[],\n updateIfExists: boolean,\n ): Promise<{\n sql: string;\n query: string;\n fields: string[];\n values: { type: keyof typeof types; value: unknown }[];\n }> {\n const columnNames = new Set<string>();\n const modelFieldValues: Record<string, { type: keyof typeof types; value: unknown }>[] = [];\n\n // Build field values for each model.\n models.forEach((model) => {\n const fieldValues: Record<string, { type: keyof typeof types; value: unknown }> = {};\n schema.meta.props.forEach((prop) => {\n const value = model[prop.name];\n if (prop.kind === \"scalar\" && value !== undefined) {\n const columnName = this.getRealFieldNameFromSchema(prop);\n columnNames.add(columnName);\n fieldValues[columnName] = { type: prop.type as keyof typeof types, value };\n }\n });\n modelFieldValues.push(fieldValues);\n });\n\n // If a version field exists, set or update its value.\n const versionField = this.getVersionField(schema);\n if (versionField) {\n modelFieldValues.forEach((mv) => {\n const versionRealName = this.getRealFieldNameFromSchema(versionField);\n if (mv[versionRealName]) {\n mv[versionRealName].value = transformValue(\n { value: this.createVersionField(versionField), type: versionField.name },\n true,\n );\n } else {\n mv[versionRealName] = {\n type: versionField.type as keyof typeof types,\n value: transformValue(\n { value: this.createVersionField(versionField), type: versionField.name },\n true,\n ),\n };\n columnNames.add(versionField.name);\n }\n });\n }\n\n const columns = Array.from(columnNames);\n\n // Flatten values for each row in the order of columns.\n const values = modelFieldValues.flatMap((fieldValueMap) =>\n columns.map(\n (column) =>\n fieldValueMap[column] || {\n type: \"string\",\n value: null,\n },\n ),\n );\n\n // Build the VALUES clause.\n const insertValues = modelFieldValues\n .map((fieldValueMap) => {\n const rowValues = columns\n .map((column) =>\n transformValue(\n fieldValueMap[column] || { type: \"string\", value: null },\n true,\n ),\n )\n .join(\",\");\n return `(${rowValues})`;\n })\n .join(\", \");\n // Build the VALUES ? clause.\n const insertEmptyValues = modelFieldValues\n .map(() => {\n const rowValues = columns\n .map(() =>\n '?',\n )\n .join(\",\");\n return `(${rowValues})`;\n })\n .join(\", \");\n\n const updateClause = updateIfExists\n ? ` ON DUPLICATE KEY UPDATE ${columns.map((col) => `${col} = VALUES(${col})`).join(\",\")}`\n : \"\";\n\n return {\n sql: `INSERT INTO ${schema.meta.collection} (${columns.join(\",\")}) VALUES ${insertValues}${updateClause}`,\n query: `INSERT INTO ${schema.meta.collection} (${columns.join(\",\")}) VALUES ${insertEmptyValues}${updateClause}`,\n fields: columns,\n values,\n };\n }\n\n /**\n * Inserts records into the database.\n * If a version field exists in the schema, versioning is applied.\n *\n * @param schema - The entity schema.\n * @param models - The list of entities to insert.\n * @param updateIfExists - Whether to update the row if it already exists.\n * @returns The ID of the inserted row.\n */\n async insert<T extends object>(\n schema: EntitySchema<T>,\n models: T[],\n updateIfExists: boolean = false,\n ): Promise<number> {\n if (!models || models.length === 0) return 0;\n\n const query = await this.generateInsertScript(schema, models, updateIfExists);\n if (this.options?.logRawSqlQuery) {\n console.debug(\"INSERT SQL: \" + query.query);\n }\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query.sql);\n const result = await sqlStatement.execute();\n return result.rows.insertId;\n }\n\n /**\n * Retrieves the primary key properties from the entity schema.\n *\n * @param schema - The entity schema.\n * @returns An array of primary key properties.\n * @throws If no primary keys are found.\n */\n private getPrimaryKeys<T extends object>(schema: EntitySchema<T>): EntityProperty<T, unknown>[] {\n const primaryKeys = schema.meta.props.filter((prop) => prop.primary);\n if (!primaryKeys.length) {\n throw new Error(`No primary keys found for schema: ${schema.meta.className}`);\n }\n return primaryKeys;\n }\n\n /**\n * Deletes a record by its primary key.\n *\n * @param id - The ID of the record to delete.\n * @param schema - The entity schema.\n * @returns The number of rows affected.\n * @throws If the entity has more than one primary key.\n */\n async deleteById<T extends object>(id: unknown, schema: EntitySchema<T>): Promise<number> {\n const primaryKeys = this.getPrimaryKeys(schema);\n if (primaryKeys.length > 1) {\n throw new Error(\"Only one primary key is supported\");\n }\n\n const primaryKey = primaryKeys[0];\n const queryBuilder = this.forgeOperations.createQueryBuilder(schema.meta.class).delete();\n queryBuilder.andWhere({ [primaryKey.name]: { $eq: id } });\n\n const query = queryBuilder.getFormattedQuery();\n if (this.options?.logRawSqlQuery) {\n console.debug(\"DELETE SQL: \" + queryBuilder.getQuery());\n }\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query);\n const result = await sqlStatement.execute();\n return result.rows.affectedRows;\n }\n\n /**\n * Retrieves the version field from the entity schema.\n * The version field must be of type datetime, integer, or decimal, not a primary key, and not nullable.\n *\n * @param schema - The entity schema.\n * @returns The version field property if it exists.\n */\n getVersionField<T>(schema: EntitySchema<T>) {\n if (this.options.disableOptimisticLocking){\n return undefined;\n }\n return schema.meta.props\n .filter((prop) => prop.version)\n .filter((prop) => {\n const validType =\n prop.type === \"datetime\" || prop.type === \"integer\" || prop.type === \"decimal\";\n if (!validType) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} must be datetime, integer, or decimal, but is \"${prop.type}\"`,\n );\n }\n return validType;\n })\n .filter((prop) => {\n if (prop.primary) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} cannot be a primary key`,\n );\n return false;\n }\n return true;\n })\n .find((prop) => {\n if (prop.nullable) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} should not be nullable`,\n );\n return false;\n }\n return true;\n });\n }\n\n /**\n * Increments the version field of an entity.\n * For datetime types, sets the current date; for numeric types, increments by 1.\n *\n * @param versionField - The version field property.\n * @param updateModel - The entity to update.\n */\n incrementVersionField<T>(versionField: EntityProperty<T, any>, updateModel: T): void {\n const key = versionField.name as keyof T;\n switch (versionField.type) {\n case \"datetime\": {\n updateModel[key] = new Date() as unknown as T[keyof T];\n break;\n }\n case \"decimal\":\n case \"integer\": {\n updateModel[key] = ((updateModel[key] as number) + 1) as unknown as T[keyof T];\n break;\n }\n default:\n throw new Error(`Unsupported version field type: ${versionField.type}`);\n }\n }\n\n /**\n * Creates the initial version field value for an entity.\n * For datetime types, returns the current date; for numeric types, returns 0.\n *\n * @param versionField - The version field property.\n */\n createVersionField<T>(versionField: EntityProperty<T>): unknown {\n switch (versionField.type) {\n case \"datetime\": {\n return new Date() as unknown as T[keyof T];\n }\n case \"decimal\":\n case \"integer\": {\n return 0;\n }\n default:\n throw new Error(`Unsupported version field type: ${versionField.type}`);\n }\n }\n\n /**\n * Updates a record by its primary key using the provided entity data.\n *\n * @param entity - The entity with updated values.\n * @param schema - The entity schema.\n */\n async updateById<T extends object>(entity: Partial<T>, schema: EntitySchema<T>): Promise<void> {\n const fields = schema.meta.props\n .filter((prop) => prop.kind === \"scalar\")\n .map((prop) => prop.name);\n await this.updateFieldById(entity as T, fields, schema);\n }\n\n /**\n * Updates specified fields of records based on provided conditions.\n * If the \"where\" parameter is not provided, the WHERE clause is built from the entity fields\n * that are not included in the list of fields to update.\n *\n * @param entity - The object containing values to update and potential criteria for filtering.\n * @param fields - Array of field names to update.\n * @param schema - The entity schema.\n * @param where - Optional filtering conditions for the WHERE clause.\n * @returns The number of affected rows.\n * @throws If no filtering criteria are provided (either via \"where\" or from the remaining entity fields).\n */\n async updateFields<T extends object>(\n entity: Partial<T>,\n fields: EntityKey<T>[],\n schema: EntitySchema<T>,\n where?: QBFilterQuery<T>,\n ): Promise<number> {\n // Extract update data from the entity based on the provided fields.\n const updateData = this.filterEntityFields(entity, fields);\n const updateModel = this.modifyModel(updateData as T, schema);\n\n // Create the query builder for the entity.\n let queryBuilder = this.forgeOperations\n .createQueryBuilder(schema.meta.class)\n .getKnexQuery();\n\n // Set the update data.\n queryBuilder.update(updateModel as T);\n\n // Use the provided \"where\" conditions if available; otherwise, build conditions from the remaining entity fields.\n if (where) {\n queryBuilder.where(where);\n } else {\n const filterCriteria = (Object.keys(entity) as Array<keyof T>)\n .filter((key: keyof T) => !fields.includes(key as EntityKey<T>))\n .reduce((criteria, key) => {\n if (entity[key] !== undefined) {\n // Cast key to string to use it as an object key.\n criteria[key as string] = entity[key];\n }\n return criteria;\n }, {} as Record<string, unknown>);\n\n\n if (Object.keys(filterCriteria).length === 0) {\n throw new Error(\n \"Filtering criteria (WHERE clause) must be provided either via the 'where' parameter or through non-updated entity fields\"\n );\n }\n queryBuilder.where(filterCriteria);\n }\n\n if (this.options?.logRawSqlQuery) {\n console.debug(\"UPDATE SQL (updateFields): \" + queryBuilder.toSQL().sql);\n }\n\n // Execute the update query.\n const sqlQuery = queryBuilder.toQuery();\n const updateQueryResponse = await this.forgeOperations.fetch().executeRawUpdateSQL(sqlQuery);\n return updateQueryResponse.affectedRows;\n }\n\n\n /**\n * Updates specific fields of a record identified by its primary key.\n * If a version field exists in the schema, versioning is applied.\n *\n * @param entity - The entity with updated values.\n * @param fields - The list of field names to update.\n * @param schema - The entity schema.\n * @throws If the primary key is not included in the update fields.\n */\n async updateFieldById<T extends object>(\n entity: T,\n fields: EntityKey<T>[],\n schema: EntitySchema<T>,\n ): Promise<void> {\n const primaryKeys = this.getPrimaryKeys(schema);\n primaryKeys.forEach((pk) => {\n if (!fields.includes(pk.name)) {\n throw new Error(\"Update fields must include primary key: \" + pk.name);\n }\n });\n\n // Prepare updated entity and query builder.\n const updatedEntity = this.filterEntityFields(entity, fields);\n let queryBuilder = this.forgeOperations.createQueryBuilder(schema.meta.class).getKnexQuery();\n const versionField = this.getVersionField(schema);\n const useVersion = Boolean(versionField);\n let updateModel = { ...updatedEntity };\n\n if (useVersion && versionField) {\n // If the version field is missing from the entity, load the old record.\n let oldModel = entity;\n if (entity[versionField.name] === undefined || entity[versionField.name] === null) {\n oldModel = await this.getOldModel(primaryKeys, entity, schema, versionField);\n }\n const primaryFieldNames = primaryKeys.map((pk) => pk.name);\n const fieldsToRetain = primaryFieldNames.concat(versionField.name);\n const fromEntries = Object.fromEntries(fieldsToRetain.map((key) => [key, oldModel[key]]));\n updateModel = { ...updatedEntity, ...fromEntries };\n\n // Increment the version field.\n this.incrementVersionField(versionField, updateModel as T);\n\n updateModel = this.modifyModel(updateModel as T, schema);\n queryBuilder.update(updateModel as T);\n if (oldModel[versionField.name]!==undefined || oldModel[versionField.name]!==null && this.isValid(oldModel[versionField.name])) {\n queryBuilder.andWhere(this.optWhere(oldModel, versionField));\n }\n } else {\n updateModel = this.modifyModel(updatedEntity as T, schema);\n queryBuilder.update(updateModel as T);\n }\n\n this.addPrimaryWhere(queryBuilder as unknown as Knex.QueryBuilder<any, any>, primaryKeys, updateModel as T);\n const sqlQuery = queryBuilder.toQuery();\n\n if (this.options?.logRawSqlQuery) {\n console.debug(\"UPDATE SQL: \" + queryBuilder.toSQL().sql);\n }\n const updateQueryResponse = await this.forgeOperations.fetch().executeRawUpdateSQL(sqlQuery);\n if (versionField && !updateQueryResponse.affectedRows) {\n throw new Error(\n \"Optimistic locking failed: the record with primary key(s) \" +\n primaryKeys.map((p) => updateModel[p.name]).join(\", \") +\n \" has been modified by another process.\",\n );\n }\n }\n\n /**\n * Constructs an optional WHERE clause for the version field.\n *\n * @param updateModel - The model containing the current version field value.\n * @param versionField - The version field property.\n * @returns A filter query for the version field.\n */\n private optWhere<T>(\n updateModel: T,\n versionField: EntityProperty<T>,\n ): QBFilterQuery<unknown> {\n const currentVersionValue = transformValue(\n { value: updateModel[versionField.name], type: versionField.type },\n false,\n );\n return { [versionField.name]: currentVersionValue };\n }\n\n /**\n * Retrieves the current state of a record from the database.\n *\n * @param primaryKeys - The primary key properties.\n * @param entity - The entity with updated values.\n * @param schema - The entity schema.\n * @param versionField - The version field property.\n * @returns The existing record from the database.\n * @throws If the record does not exist or if multiple records are found.\n */\n private async getOldModel<T>(\n primaryKeys: EntityProperty<T, unknown>[],\n entity: T,\n schema: EntitySchema<T>,\n versionField: EntityProperty<T>,\n ): Promise<T> {\n const primaryFieldNames = primaryKeys.map((pk) => pk.name);\n const fieldsToSelect = primaryFieldNames.concat(versionField.name);\n const queryBuilder = this.forgeOperations\n .createQueryBuilder(schema as EntitySchema)\n .select(fieldsToSelect);\n this.addPrimaryWhere(queryBuilder, primaryKeys, entity);\n const formattedQuery = queryBuilder.getFormattedQuery();\n const models: T[] = await this.forgeOperations.fetch().executeSchemaSQL(formattedQuery, schema as EntitySchema);\n\n if (!models || models.length === 0) {\n throw new Error(`Cannot modify record because it does not exist in table ${schema.meta.tableName}`);\n }\n if (models.length > 1) {\n throw new Error(\n `Cannot modify record because multiple rows with the same ID were found in table ${schema.meta.tableName}. Please verify the table metadata.`,\n );\n }\n return models[0];\n }\n\n /**\n * Adds primary key conditions to the query builder.\n *\n * @param queryBuilder - The Knex query builder instance.\n * @param primaryKeys - The primary key properties.\n * @param entity - The entity containing primary key values.\n * @throws If any primary key value is missing.\n */\n private addPrimaryWhere<T>(\n queryBuilder: Knex.QueryBuilder<any, any>,\n primaryKeys: EntityProperty<T, unknown>[],\n entity: T,\n ) {\n primaryKeys.forEach((pk) => {\n const fieldName = this.getRealFieldNameFromSchema(pk);\n const value = entity[fieldName];\n if (value === null || value === undefined) {\n throw new Error(`Primary key ${fieldName} must exist in the model`);\n }\n queryBuilder.andWhere({ [fieldName]: value });\n });\n }\n\n /**\n * Filters the entity to include only the specified fields.\n *\n * @param entity - The original entity.\n * @param fields - The list of fields to retain.\n * @returns A partial entity object containing only the specified fields.\n */\n filterEntityFields = <T extends object>(entity: T, fields: (keyof T)[]): Partial<T> =>\n fields.reduce((result, field) => {\n if (field in entity) {\n result[field] = entity[field];\n }\n return result;\n }, {} as Partial<T>);\n\n /**\n * Transforms and modifies the updated entity model based on the schema.\n *\n * @param updatedEntity - The updated entity.\n * @param schema - The entity schema.\n * @returns The modified entity.\n */\n private modifyModel<T>(updatedEntity: T, schema: EntitySchema<T>): T {\n const modifiedModel: Record<string, any> = {};\n schema.meta.props\n .filter((p) => p.kind === \"scalar\")\n .forEach((p) => {\n const value = updatedEntity[p.name];\n if (value !== undefined && value !== null) {\n const fieldName = this.getRealFieldNameFromSchema(p);\n modifiedModel[fieldName] = transformValue({ value, type: p.type }, false);\n }\n });\n return modifiedModel as T;\n }\n\n /**\n * Returns the real field name from the entity property based on the schema.\n *\n * @param p - The entity property.\n * @returns The real field name.\n */\n private getRealFieldNameFromSchema<T>(p: EntityProperty<T>): EntityKey<T> {\n return p.fieldNames && p.fieldNames.length\n ? (p.fieldNames[0] as EntityKey<T>)\n : p.name;\n }\n\n /**\n * Validates the provided value.\n *\n * @param value - The value to validate.\n * @returns True if the value is valid, false otherwise.\n */\n isValid(value: any): boolean {\n if (value instanceof Date) {\n return !isNaN(value.getTime());\n }\n return true;\n }\n}\n","import { sql, UpdateQueryResponse } from \"@forge/sql\";\nimport type { EntitySchema } from \"@mikro-orm/core/metadata/EntitySchema\";\nimport { parseDateTime } from \"../utils/sqlUtils\";\nimport { ForgeSqlOrmOptions, SchemaSqlForgeSql } from \"./ForgeSQLQueryBuilder\";\nimport {SqlParameters} from \"@forge/sql/out/sql-statement\";\n\nexport class ForgeSQLSelectOperations implements SchemaSqlForgeSql {\n private readonly options: ForgeSqlOrmOptions;\n\n constructor(options: ForgeSqlOrmOptions) {\n this.options = options;\n }\n\n async executeSchemaSQLOnlyOne<T extends object>(query: string, schema: EntitySchema<T>): Promise<T|undefined> {\n const results = await this.executeSchemaSQL(query, schema);\n if (!results || results.length === 0){\n return undefined;\n }\n if (results.length>1){\n throw new Error('Expected 1 record but returned '+results.length)\n }\n return results[0];\n }\n\n /**\n * Executes a schema-based SQL query and maps the result to the entity schema.\n * @param query - The SQL query to execute.\n * @param schema - The entity schema defining the structure.\n * @returns A list of mapped entity objects.\n */\n async executeSchemaSQL<T extends object>(query: string, schema: EntitySchema<T>): Promise<T[]> {\n const datas = await this.executeRawSQL<unknown>(query);\n if (!datas.length) return [];\n\n return datas.map((r) => {\n const rawModel = r as Record<string, unknown>;\n const newModel: Record<string, unknown> = {};\n\n schema.meta.props\n .filter((p) => p.kind === \"scalar\")\n .forEach((p) => {\n const fieldName = p.name;\n const fieldNames = p.fieldNames;\n const rawFieldName = fieldNames && Array.isArray(fieldNames) ? fieldNames[0] : p.name;\n\n switch (p.type) {\n case \"datetime\":\n newModel[fieldName] = parseDateTime(\n rawModel[rawFieldName] as string,\n \"YYYY-MM-DDTHH:mm:ss.SSS\",\n );\n break;\n case \"date\":\n newModel[fieldName] = parseDateTime(rawModel[rawFieldName] as string, \"YYYY-MM-DD\");\n break;\n case \"time\":\n newModel[fieldName] = parseDateTime(rawModel[rawFieldName] as string, \"HH:mm:ss.SSS\");\n break;\n default:\n newModel[fieldName] = rawModel[rawFieldName];\n }\n });\n return newModel as T;\n });\n }\n\n /**\n * Executes a raw SQL query and returns the results.\n * @param query - The raw SQL query to execute.\n * @returns A list of results as objects.\n */\n async executeRawSQL<T extends object | unknown>(query: string): Promise<T[]> {\n if (this.options.logRawSqlQuery) {\n console.debug(\"Executing raw SQL: \" + query);\n }\n const sqlStatement = await sql.prepare<T>(query).execute();\n return sqlStatement.rows as T[];\n }\n\n /**\n * Executes a raw SQL update query.\n * @param query - The raw SQL update query.\n * @param params - sql parameters.\n * @returns The update response containing affected rows.\n */\n async executeRawUpdateSQL(query: string, params?: SqlParameters[]): Promise<UpdateQueryResponse> {\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query);\n if (params) {\n sqlStatement.bindParams(params);\n }\n const updateQueryResponseResults = await sqlStatement.execute();\n return updateQueryResponseResults.rows;\n }\n}\n","import type { EntityName, LoggingOptions } from \"..\";\nimport type { EntitySchema } from \"@mikro-orm/core/metadata/EntitySchema\";\nimport type { AnyEntity, EntityClass, EntityClassGroup } from \"@mikro-orm/core/typings\";\nimport type { QueryBuilder } from \"@mikro-orm/knex/query\";\nimport { MemoryCacheAdapter, MikroORM, NullCacheAdapter } from \"@mikro-orm/mysql\";\nimport { ForgeSQLCrudOperations } from \"./ForgeSQLCrudOperations\";\nimport {\n CRUDForgeSQL,\n ForgeSqlOperation,\n ForgeSqlOrmOptions,\n SchemaSqlForgeSql,\n} from \"./ForgeSQLQueryBuilder\";\nimport { ForgeSQLSelectOperations } from \"./ForgeSQLSelectOperations\";\nimport type { Knex } from \"knex\";\n\n/**\n * Implementation of ForgeSQLORM that interacts with MikroORM.\n */\nclass ForgeSQLORMImpl implements ForgeSqlOperation {\n private static instance: ForgeSQLORMImpl | null = null;\n private readonly mikroORM: MikroORM;\n private readonly crudOperations: CRUDForgeSQL;\n private readonly fetchOperations: SchemaSqlForgeSql;\n\n /**\n * Private constructor to enforce singleton behavior.\n * @param entities - The list of entities for ORM initialization.\n * @param options - Options for configuring ForgeSQL ORM behavior.\n */\n private constructor(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ) {\n console.debug(\"Initializing ForgeSQLORM...\");\n\n try {\n this.mikroORM = MikroORM.initSync({\n dbName: \"inmemory\",\n schemaGenerator: {\n disableForeignKeys: false,\n },\n discovery: {\n warnWhenNoEntities: true,\n },\n resultCache: {\n adapter: NullCacheAdapter,\n },\n metadataCache: {\n enabled: false,\n adapter: MemoryCacheAdapter,\n },\n entities: entities,\n preferTs: false,\n debug: false,\n });\n const newOptions: ForgeSqlOrmOptions = options ?? { logRawSqlQuery: false, disableOptimisticLocking: false };\n this.crudOperations = new ForgeSQLCrudOperations(this, newOptions);\n this.fetchOperations = new ForgeSQLSelectOperations(newOptions);\n } catch (error) {\n console.error(\"ForgeSQLORM initialization failed:\", error);\n throw error; // Prevents inconsistent state\n }\n }\n\n /**\n * Returns the singleton instance of ForgeSQLORMImpl.\n * @param entities - List of entities (required only on first initialization).\n * @param options - Options for configuring ForgeSQL ORM behavior.\n * @returns The singleton instance of ForgeSQLORMImpl.\n */\n static getInstance(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ): ForgeSqlOperation {\n if (!ForgeSQLORMImpl.instance) {\n ForgeSQLORMImpl.instance = new ForgeSQLORMImpl(entities, options);\n }\n return ForgeSQLORMImpl.instance;\n }\n\n /**\n * Retrieves the CRUD operations instance.\n * @returns CRUD operations.\n */\n crud(): CRUDForgeSQL {\n return this.crudOperations;\n }\n\n /**\n * Retrieves the fetch operations instance.\n * @returns Fetch operations.\n */\n fetch(): SchemaSqlForgeSql {\n return this.fetchOperations;\n }\n\n /**\n * Creates a new query builder for the given entity.\n * @param entityName - The entity name or an existing query builder.\n * @param alias - The alias for the entity.\n * @param loggerContext - Logging options.\n * @returns The query builder instance.\n */\n createQueryBuilder<Entity extends object, RootAlias extends string = never>(\n entityName: EntityName<Entity> | QueryBuilder<Entity>,\n alias?: RootAlias,\n loggerContext?: LoggingOptions,\n ): QueryBuilder<Entity, RootAlias> {\n return this.mikroORM.em.createQueryBuilder(entityName, alias, undefined, loggerContext);\n }\n\n /**\n * Provides access to the underlying Knex instance for building complex query parts.\n * enabling advanced query customization and performance tuning.\n * @returns The Knex instance, which can be used for query building.\n */\n getKnex(): Knex<any, any[]> {\n return this.mikroORM.em.getKnex();\n }\n}\n\n/**\n * Public class that acts as a wrapper around the private ForgeSQLORMImpl.\n */\nclass ForgeSQLORM {\n private readonly ormInstance: ForgeSqlOperation;\n\n constructor(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ) {\n this.ormInstance = ForgeSQLORMImpl.getInstance(entities, options);\n }\n\n /**\n * Proxies the `crud` method from `ForgeSQLORMImpl`.\n * @returns CRUD operations.\n */\n crud(): CRUDForgeSQL {\n return this.ormInstance.crud();\n }\n\n /**\n * Proxies the `fetch` method from `ForgeSQLORMImpl`.\n * @returns Fetch operations.\n */\n fetch(): SchemaSqlForgeSql {\n return this.ormInstance.fetch();\n }\n\n getKnex(): Knex<any, any[]> {\n return this.ormInstance.getKnex();\n }\n\n /**\n * Proxies the `createQueryBuilder` method from `ForgeSQLORMImpl`.\n * @returns A new query builder instance.\n */\n createQueryBuilder<Entity extends object, RootAlias extends string = never>(\n entityName: EntityName<Entity> | QueryBuilder<Entity>,\n alias?: RootAlias,\n loggerContext?: LoggingOptions,\n ): QueryBuilder<Entity, RootAlias> {\n return this.ormInstance.createQueryBuilder(entityName, alias, loggerContext);\n }\n}\n\nexport default ForgeSQLORM;\n"],"names":["sql","MikroORM","NullCacheAdapter","MemoryCacheAdapter"],"mappings":";;;;;;AAIA,MAAM,eAAa,CAAC,MAAa,SAAwB;AAChD,SAAA,OAAK,IAAI,IAAI,MAAI;AAC1B;AAEO,MAAM,iBAAiB,CAAI,OAG/B,YAAqB,UAAa;AACnC,UAAQ,MAAM,MAAM;AAAA,IAClB,KAAK;AAAA,IACL,KAAK;AACH,aAAU,aAAa,GAAG,MAAM,KAAK,IAAG,SAAS;AAAA,IACnD,KAAK;AACO,aAAA,aAAa,GAAG,OAAO,MAAM,KAAa,EAAE,OAAO,yBAAyB,CAAC,IAAG,SAAS;AAAA,IACrG,KAAK;AACO,aAAA,aAAa,GAAG,OAAO,MAAM,KAAa,EAAE,OAAO,YAAY,CAAC,IAA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;AAAA,EAQxF,UAA4B;AACnB,WAAA,KAAK,SAAS,GAAG,QAAQ;AAAA,EAAA;AAEpC;AAKA,MAAM,YAAY;AAAA,EACC;AAAA,EAEjB,YACE,UACA,SACA;AACA,SAAK,cAAc,gBAAgB,YAAY,UAAU,OAAO;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlE,OAAqB;AACZ,WAAA,KAAK,YAAY,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO/B,QAA2B;AAClB,WAAA,KAAK,YAAY,MAAM;AAAA,EAAA;AAAA,EAGhC,UAA4B;AACnB,WAAA,KAAK,YAAY,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlC,mBACE,YACA,OACA,eACiC;AACjC,WAAO,KAAK,YAAY,mBAAmB,YAAY,OAAO,aAAa;AAAA,EAAA;AAE/E;;;;;;;;;;;;;;;;"}
|
package/dist/ForgeSQLORM.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ForgeSQLORM.mjs","sources":["../src/utils/sqlUtils.ts","../src/core/ForgeSQLCrudOperations.ts","../src/core/ForgeSQLSelectOperations.ts","../src/core/ForgeSQLORM.ts"],"sourcesContent":["import { types } from \"@mikro-orm/core/types\";\nimport moment from \"moment\";\nimport { AnyString } from \"@mikro-orm/core/typings\";\n\nconst wrapIfNeeded=(data:string, wrap:boolean):string => {\n return wrap?`'${data}'`:data;\n}\n\nexport const transformValue = <U>(value: {\n type: keyof typeof types | AnyString;\n value: U;\n}, wrapValue: boolean = false): U => {\n switch (value.type) {\n case \"text\":\n case \"string\":\n return <U>wrapIfNeeded(`${value.value}`,wrapValue);\n case \"datetime\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"YYYY-MM-DDTHH:mm:ss.SSS\")}`,wrapValue);\n case \"date\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"YYYY-MM-DD\")}`, wrapValue);\n case \"time\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"HH:mm:ss.SSS\")}`,wrapValue);\n default:\n return value.value;\n }\n};\n\nexport const parseDateTime = (value: string, format: string): Date => {\n const m = moment(value, format, true);\n if (!m.isValid()) {\n return moment(value).toDate();\n }\n return m.toDate();\n};\n","import { sql, UpdateQueryResponse } from \"@forge/sql\";\nimport { EntityProperty, EntitySchema, ForgeSqlOrmOptions } from \"..\";\nimport type { types } from \"@mikro-orm/core/types\";\nimport { transformValue } from \"../utils/sqlUtils\";\nimport { CRUDForgeSQL, ForgeSqlOperation } from \"./ForgeSQLQueryBuilder\";\nimport { EntityKey, QBFilterQuery } from \"@mikro-orm/core\";\nimport Knex from \"../knex\";\n\nexport class ForgeSQLCrudOperations implements CRUDForgeSQL {\n private readonly forgeOperations: ForgeSqlOperation;\n private readonly options: ForgeSqlOrmOptions;\n\n constructor(forgeSqlOperations: ForgeSqlOperation, options: ForgeSqlOrmOptions) {\n this.forgeOperations = forgeSqlOperations;\n this.options = options;\n }\n\n /**\n * Generates an SQL INSERT statement for the provided models.\n * If a version field exists in the schema, its value is set accordingly.\n *\n * @param schema - The entity schema.\n * @param models - The list of entities to insert.\n * @param updateIfExists - Whether to update the row if it already exists.\n * @returns An object containing the SQL query, column names, and values.\n */\n private async generateInsertScript<T extends object>(\n schema: EntitySchema<T>,\n models: T[],\n updateIfExists: boolean,\n ): Promise<{\n sql: string;\n query: string;\n fields: string[];\n values: { type: keyof typeof types; value: unknown }[];\n }> {\n const columnNames = new Set<string>();\n const modelFieldValues: Record<string, { type: keyof typeof types; value: unknown }>[] = [];\n\n // Build field values for each model.\n models.forEach((model) => {\n const fieldValues: Record<string, { type: keyof typeof types; value: unknown }> = {};\n schema.meta.props.forEach((prop) => {\n const value = model[prop.name];\n if (prop.kind === \"scalar\" && value !== undefined) {\n const columnName = this.getRealFieldNameFromSchema(prop);\n columnNames.add(columnName);\n fieldValues[columnName] = { type: prop.type as keyof typeof types, value };\n }\n });\n modelFieldValues.push(fieldValues);\n });\n\n // If a version field exists, set or update its value.\n const versionField = this.getVersionField(schema);\n if (versionField) {\n modelFieldValues.forEach((mv) => {\n const versionRealName = this.getRealFieldNameFromSchema(versionField);\n if (mv[versionRealName]) {\n mv[versionRealName].value = transformValue(\n { value: this.createVersionField(versionField), type: versionField.name },\n true,\n );\n } else {\n mv[versionRealName] = {\n type: versionField.type as keyof typeof types,\n value: transformValue(\n { value: this.createVersionField(versionField), type: versionField.name },\n true,\n ),\n };\n columnNames.add(versionField.name);\n }\n });\n }\n\n const columns = Array.from(columnNames);\n\n // Flatten values for each row in the order of columns.\n const values = modelFieldValues.flatMap((fieldValueMap) =>\n columns.map(\n (column) =>\n fieldValueMap[column] || {\n type: \"string\",\n value: null,\n },\n ),\n );\n\n // Build the VALUES clause.\n const insertValues = modelFieldValues\n .map((fieldValueMap) => {\n const rowValues = columns\n .map((column) =>\n transformValue(\n fieldValueMap[column] || { type: \"string\", value: null },\n true,\n ),\n )\n .join(\",\");\n return `(${rowValues})`;\n })\n .join(\", \");\n // Build the VALUES ? clause.\n const insertEmptyValues = modelFieldValues\n .map(() => {\n const rowValues = columns\n .map(() =>\n '?',\n )\n .join(\",\");\n return `(${rowValues})`;\n })\n .join(\", \");\n\n const updateClause = updateIfExists\n ? ` ON DUPLICATE KEY UPDATE ${columns.map((col) => `${col} = VALUES(${col})`).join(\",\")}`\n : \"\";\n\n return {\n sql: `INSERT INTO ${schema.meta.collection} (${columns.join(\",\")}) VALUES ${insertValues}${updateClause}`,\n query: `INSERT INTO ${schema.meta.collection} (${columns.join(\",\")}) VALUES ${insertEmptyValues}${updateClause}`,\n fields: columns,\n values,\n };\n }\n\n /**\n * Inserts records into the database.\n * If a version field exists in the schema, versioning is applied.\n *\n * @param schema - The entity schema.\n * @param models - The list of entities to insert.\n * @param updateIfExists - Whether to update the row if it already exists.\n * @returns The ID of the inserted row.\n */\n async insert<T extends object>(\n schema: EntitySchema<T>,\n models: T[],\n updateIfExists: boolean = false,\n ): Promise<number> {\n if (!models || models.length === 0) return 0;\n\n const query = await this.generateInsertScript(schema, models, updateIfExists);\n if (this.options?.logRawSqlQuery) {\n console.debug(\"INSERT SQL: \" + query.query);\n }\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query.sql);\n const result = await sqlStatement.execute();\n return result.rows.insertId;\n }\n\n /**\n * Retrieves the primary key properties from the entity schema.\n *\n * @param schema - The entity schema.\n * @returns An array of primary key properties.\n * @throws If no primary keys are found.\n */\n private getPrimaryKeys<T extends object>(schema: EntitySchema<T>): EntityProperty<T, unknown>[] {\n const primaryKeys = schema.meta.props.filter((prop) => prop.primary);\n if (!primaryKeys.length) {\n throw new Error(`No primary keys found for schema: ${schema.meta.className}`);\n }\n return primaryKeys;\n }\n\n /**\n * Deletes a record by its primary key.\n *\n * @param id - The ID of the record to delete.\n * @param schema - The entity schema.\n * @returns The number of rows affected.\n * @throws If the entity has more than one primary key.\n */\n async deleteById<T extends object>(id: unknown, schema: EntitySchema<T>): Promise<number> {\n const primaryKeys = this.getPrimaryKeys(schema);\n if (primaryKeys.length > 1) {\n throw new Error(\"Only one primary key is supported\");\n }\n\n const primaryKey = primaryKeys[0];\n const queryBuilder = this.forgeOperations.createQueryBuilder(schema.meta.class).delete();\n queryBuilder.andWhere({ [primaryKey.name]: { $eq: id } });\n\n const query = queryBuilder.getFormattedQuery();\n if (this.options?.logRawSqlQuery) {\n console.debug(\"DELETE SQL: \" + queryBuilder.getQuery());\n }\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query);\n const result = await sqlStatement.execute();\n return result.rows.affectedRows;\n }\n\n /**\n * Retrieves the version field from the entity schema.\n * The version field must be of type datetime, integer, or decimal, not a primary key, and not nullable.\n *\n * @param schema - The entity schema.\n * @returns The version field property if it exists.\n */\n getVersionField<T>(schema: EntitySchema<T>) {\n if (this.options.disableOptimisticLocking){\n return undefined;\n }\n return schema.meta.props\n .filter((prop) => prop.version)\n .filter((prop) => {\n const validType =\n prop.type === \"datetime\" || prop.type === \"integer\" || prop.type === \"decimal\";\n if (!validType) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} must be datetime, integer, or decimal, but is \"${prop.type}\"`,\n );\n }\n return validType;\n })\n .filter((prop) => {\n if (prop.primary) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} cannot be a primary key`,\n );\n return false;\n }\n return true;\n })\n .find((prop) => {\n if (prop.nullable) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} should not be nullable`,\n );\n return false;\n }\n return true;\n });\n }\n\n /**\n * Increments the version field of an entity.\n * For datetime types, sets the current date; for numeric types, increments by 1.\n *\n * @param versionField - The version field property.\n * @param updateModel - The entity to update.\n */\n incrementVersionField<T>(versionField: EntityProperty<T, any>, updateModel: T): void {\n const key = versionField.name as keyof T;\n switch (versionField.type) {\n case \"datetime\": {\n updateModel[key] = new Date() as unknown as T[keyof T];\n break;\n }\n case \"decimal\":\n case \"integer\": {\n updateModel[key] = ((updateModel[key] as number) + 1) as unknown as T[keyof T];\n break;\n }\n default:\n throw new Error(`Unsupported version field type: ${versionField.type}`);\n }\n }\n\n /**\n * Creates the initial version field value for an entity.\n * For datetime types, returns the current date; for numeric types, returns 0.\n *\n * @param versionField - The version field property.\n */\n createVersionField<T>(versionField: EntityProperty<T>): unknown {\n switch (versionField.type) {\n case \"datetime\": {\n return new Date() as unknown as T[keyof T];\n }\n case \"decimal\":\n case \"integer\": {\n return 0;\n }\n default:\n throw new Error(`Unsupported version field type: ${versionField.type}`);\n }\n }\n\n /**\n * Updates a record by its primary key using the provided entity data.\n *\n * @param entity - The entity with updated values.\n * @param schema - The entity schema.\n */\n async updateById<T extends object>(entity: Partial<T>, schema: EntitySchema<T>): Promise<void> {\n const fields = schema.meta.props\n .filter((prop) => prop.kind === \"scalar\")\n .map((prop) => prop.name);\n await this.updateFieldById(entity as T, fields, schema);\n }\n\n /**\n * Updates specified fields of records based on provided conditions.\n * If the \"where\" parameter is not provided, the WHERE clause is built from the entity fields\n * that are not included in the list of fields to update.\n *\n * @param entity - The object containing values to update and potential criteria for filtering.\n * @param fields - Array of field names to update.\n * @param schema - The entity schema.\n * @param where - Optional filtering conditions for the WHERE clause.\n * @returns The number of affected rows.\n * @throws If no filtering criteria are provided (either via \"where\" or from the remaining entity fields).\n */\n async updateFields<T extends object>(\n entity: Partial<T>,\n fields: EntityKey<T>[],\n schema: EntitySchema<T>,\n where?: QBFilterQuery<T>,\n ): Promise<number> {\n // Extract update data from the entity based on the provided fields.\n const updateData = this.filterEntityFields(entity, fields);\n const updateModel = this.modifyModel(updateData as T, schema);\n\n // Create the query builder for the entity.\n let queryBuilder = this.forgeOperations\n .createQueryBuilder(schema.meta.class)\n .getKnexQuery();\n\n // Set the update data.\n queryBuilder.update(updateModel as T);\n\n // Use the provided \"where\" conditions if available; otherwise, build conditions from the remaining entity fields.\n if (where) {\n queryBuilder.where(where);\n } else {\n const filterCriteria = (Object.keys(entity) as Array<keyof T>)\n .filter((key: keyof T) => !fields.includes(key as EntityKey<T>))\n .reduce((criteria, key) => {\n if (entity[key] !== undefined) {\n // Cast key to string to use it as an object key.\n criteria[key as string] = entity[key];\n }\n return criteria;\n }, {} as Record<string, unknown>);\n\n\n if (Object.keys(filterCriteria).length === 0) {\n throw new Error(\n \"Filtering criteria (WHERE clause) must be provided either via the 'where' parameter or through non-updated entity fields\"\n );\n }\n queryBuilder.where(filterCriteria);\n }\n\n if (this.options?.logRawSqlQuery) {\n console.debug(\"UPDATE SQL (updateFields): \" + queryBuilder.toSQL().sql);\n }\n\n // Execute the update query.\n const sqlQuery = queryBuilder.toQuery();\n const updateQueryResponse = await this.forgeOperations.fetch().executeRawUpdateSQL(sqlQuery);\n return updateQueryResponse.affectedRows;\n }\n\n\n /**\n * Updates specific fields of a record identified by its primary key.\n * If a version field exists in the schema, versioning is applied.\n *\n * @param entity - The entity with updated values.\n * @param fields - The list of field names to update.\n * @param schema - The entity schema.\n * @throws If the primary key is not included in the update fields.\n */\n async updateFieldById<T extends object>(\n entity: T,\n fields: EntityKey<T>[],\n schema: EntitySchema<T>,\n ): Promise<void> {\n const primaryKeys = this.getPrimaryKeys(schema);\n primaryKeys.forEach((pk) => {\n if (!fields.includes(pk.name)) {\n throw new Error(\"Update fields must include primary key: \" + pk.name);\n }\n });\n\n // Prepare updated entity and query builder.\n const updatedEntity = this.filterEntityFields(entity, fields);\n let queryBuilder = this.forgeOperations.createQueryBuilder(schema.meta.class).getKnexQuery();\n const versionField = this.getVersionField(schema);\n const useVersion = Boolean(versionField);\n let updateModel = { ...updatedEntity };\n\n if (useVersion && versionField) {\n // If the version field is missing from the entity, load the old record.\n let oldModel = entity;\n if (entity[versionField.name] === undefined || entity[versionField.name] === null) {\n oldModel = await this.getOldModel(primaryKeys, entity, schema, versionField);\n }\n const primaryFieldNames = primaryKeys.map((pk) => pk.name);\n const fieldsToRetain = primaryFieldNames.concat(versionField.name);\n const fromEntries = Object.fromEntries(fieldsToRetain.map((key) => [key, oldModel[key]]));\n updateModel = { ...updatedEntity, ...fromEntries };\n\n // Increment the version field.\n this.incrementVersionField(versionField, updateModel as T);\n\n updateModel = this.modifyModel(updateModel as T, schema);\n queryBuilder.update(updateModel as T);\n if (oldModel[versionField.name]!==undefined || oldModel[versionField.name]!==null && this.isValid(oldModel[versionField.name])) {\n queryBuilder.andWhere(this.optWhere(oldModel, versionField));\n }\n } else {\n updateModel = this.modifyModel(updatedEntity as T, schema);\n queryBuilder.update(updateModel as T);\n }\n\n this.addPrimaryWhere(queryBuilder as unknown as Knex.QueryBuilder<any, any>, primaryKeys, updateModel as T);\n const sqlQuery = queryBuilder.toQuery();\n\n if (this.options?.logRawSqlQuery) {\n console.debug(\"UPDATE SQL: \" + queryBuilder.toSQL().sql);\n }\n const updateQueryResponse = await this.forgeOperations.fetch().executeRawUpdateSQL(sqlQuery);\n if (versionField && !updateQueryResponse.affectedRows) {\n throw new Error(\n \"Optimistic locking failed: the record with primary key(s) \" +\n primaryKeys.map((p) => updateModel[p.name]).join(\", \") +\n \" has been modified by another process.\",\n );\n }\n }\n\n /**\n * Constructs an optional WHERE clause for the version field.\n *\n * @param updateModel - The model containing the current version field value.\n * @param versionField - The version field property.\n * @returns A filter query for the version field.\n */\n private optWhere<T>(\n updateModel: T,\n versionField: EntityProperty<T>,\n ): QBFilterQuery<unknown> {\n const currentVersionValue = transformValue(\n { value: updateModel[versionField.name], type: versionField.type },\n false,\n );\n return { [versionField.name]: currentVersionValue };\n }\n\n /**\n * Retrieves the current state of a record from the database.\n *\n * @param primaryKeys - The primary key properties.\n * @param entity - The entity with updated values.\n * @param schema - The entity schema.\n * @param versionField - The version field property.\n * @returns The existing record from the database.\n * @throws If the record does not exist or if multiple records are found.\n */\n private async getOldModel<T>(\n primaryKeys: EntityProperty<T, unknown>[],\n entity: T,\n schema: EntitySchema<T>,\n versionField: EntityProperty<T>,\n ): Promise<T> {\n const primaryFieldNames = primaryKeys.map((pk) => pk.name);\n const fieldsToSelect = primaryFieldNames.concat(versionField.name);\n const queryBuilder = this.forgeOperations\n .createQueryBuilder(schema as EntitySchema)\n .select(fieldsToSelect);\n this.addPrimaryWhere(queryBuilder, primaryKeys, entity);\n const formattedQuery = queryBuilder.getFormattedQuery();\n const models: T[] = await this.forgeOperations.fetch().executeSchemaSQL(formattedQuery, schema as EntitySchema);\n\n if (!models || models.length === 0) {\n throw new Error(`Cannot modify record because it does not exist in table ${schema.meta.tableName}`);\n }\n if (models.length > 1) {\n throw new Error(\n `Cannot modify record because multiple rows with the same ID were found in table ${schema.meta.tableName}. Please verify the table metadata.`,\n );\n }\n return models[0];\n }\n\n /**\n * Adds primary key conditions to the query builder.\n *\n * @param queryBuilder - The Knex query builder instance.\n * @param primaryKeys - The primary key properties.\n * @param entity - The entity containing primary key values.\n * @throws If any primary key value is missing.\n */\n private addPrimaryWhere<T>(\n queryBuilder: Knex.QueryBuilder<any, any>,\n primaryKeys: EntityProperty<T, unknown>[],\n entity: T,\n ) {\n primaryKeys.forEach((pk) => {\n const fieldName = this.getRealFieldNameFromSchema(pk);\n const value = entity[fieldName];\n if (value === null || value === undefined) {\n throw new Error(`Primary key ${fieldName} must exist in the model`);\n }\n queryBuilder.andWhere({ [fieldName]: value });\n });\n }\n\n /**\n * Filters the entity to include only the specified fields.\n *\n * @param entity - The original entity.\n * @param fields - The list of fields to retain.\n * @returns A partial entity object containing only the specified fields.\n */\n filterEntityFields = <T extends object>(entity: T, fields: (keyof T)[]): Partial<T> =>\n fields.reduce((result, field) => {\n if (field in entity) {\n result[field] = entity[field];\n }\n return result;\n }, {} as Partial<T>);\n\n /**\n * Transforms and modifies the updated entity model based on the schema.\n *\n * @param updatedEntity - The updated entity.\n * @param schema - The entity schema.\n * @returns The modified entity.\n */\n private modifyModel<T>(updatedEntity: T, schema: EntitySchema<T>): T {\n const modifiedModel: Record<string, any> = {};\n schema.meta.props\n .filter((p) => p.kind === \"scalar\")\n .forEach((p) => {\n const value = updatedEntity[p.name];\n if (value !== undefined && value !== null) {\n const fieldName = this.getRealFieldNameFromSchema(p);\n modifiedModel[fieldName] = transformValue({ value, type: p.type }, false);\n }\n });\n return modifiedModel as T;\n }\n\n /**\n * Returns the real field name from the entity property based on the schema.\n *\n * @param p - The entity property.\n * @returns The real field name.\n */\n private getRealFieldNameFromSchema<T>(p: EntityProperty<T>): EntityKey<T> {\n return p.fieldNames && p.fieldNames.length\n ? (p.fieldNames[0] as EntityKey<T>)\n : p.name;\n }\n\n /**\n * Validates the provided value.\n *\n * @param value - The value to validate.\n * @returns True if the value is valid, false otherwise.\n */\n isValid(value: any): boolean {\n if (value instanceof Date) {\n return !isNaN(value.getTime());\n }\n return true;\n }\n}\n","import { sql, UpdateQueryResponse } from \"@forge/sql\";\nimport type { EntitySchema } from \"@mikro-orm/core/metadata/EntitySchema\";\nimport { parseDateTime } from \"../utils/sqlUtils\";\nimport { ForgeSqlOrmOptions, SchemaSqlForgeSql } from \"./ForgeSQLQueryBuilder\";\nimport {SqlParameters} from \"@forge/sql/out/sql-statement\";\n\nexport class ForgeSQLSelectOperations implements SchemaSqlForgeSql {\n private readonly options: ForgeSqlOrmOptions;\n\n constructor(options: ForgeSqlOrmOptions) {\n this.options = options;\n }\n\n async executeSchemaSQLOnlyOne<T extends object>(query: string, schema: EntitySchema<T>): Promise<T|undefined> {\n const results = await this.executeSchemaSQL(query, schema);\n if (!results || results.length === 0){\n return undefined;\n }\n if (results.length>1){\n throw new Error('Expected 1 record but returned '+results.length)\n }\n return results[0];\n }\n\n /**\n * Executes a schema-based SQL query and maps the result to the entity schema.\n * @param query - The SQL query to execute.\n * @param schema - The entity schema defining the structure.\n * @returns A list of mapped entity objects.\n */\n async executeSchemaSQL<T extends object>(query: string, schema: EntitySchema<T>): Promise<T[]> {\n const datas = await this.executeRawSQL<unknown>(query);\n if (!datas.length) return [];\n\n return datas.map((r) => {\n const rawModel = r as Record<string, unknown>;\n const newModel: Record<string, unknown> = {};\n\n schema.meta.props\n .filter((p) => p.kind === \"scalar\")\n .forEach((p) => {\n const fieldName = p.name;\n const fieldNames = p.fieldNames;\n const rawFieldName = fieldNames && Array.isArray(fieldNames) ? fieldNames[0] : p.name;\n\n switch (p.type) {\n case \"datetime\":\n newModel[fieldName] = parseDateTime(\n rawModel[rawFieldName] as string,\n \"YYYY-MM-DDTHH:mm:ss.SSS\",\n );\n break;\n case \"date\":\n newModel[fieldName] = parseDateTime(rawModel[rawFieldName] as string, \"YYYY-MM-DD\");\n break;\n case \"time\":\n newModel[fieldName] = parseDateTime(rawModel[rawFieldName] as string, \"HH:mm:ss.SSS\");\n break;\n default:\n newModel[fieldName] = rawModel[rawFieldName];\n }\n });\n return newModel as T;\n });\n }\n\n /**\n * Executes a raw SQL query and returns the results.\n * @param query - The raw SQL query to execute.\n * @returns A list of results as objects.\n */\n async executeRawSQL<T extends object | unknown>(query: string): Promise<T[]> {\n if (this.options.logRawSqlQuery) {\n console.debug(\"Executing raw SQL: \" + query);\n }\n const sqlStatement = await sql.prepare<T>(query).execute();\n return sqlStatement.rows as T[];\n }\n\n /**\n * Executes a raw SQL update query.\n * @param query - The raw SQL update query.\n * @param params - sql parameters.\n * @returns The update response containing affected rows.\n */\n async executeRawUpdateSQL(query: string, params?: SqlParameters[]): Promise<UpdateQueryResponse> {\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query);\n if (params) {\n sqlStatement.bindParams(params);\n }\n const updateQueryResponseResults = await sqlStatement.execute();\n return updateQueryResponseResults.rows;\n }\n}\n","import type { EntityName, LoggingOptions } from \"@mikro-orm/core\";\nimport type { EntitySchema } from \"@mikro-orm/core/metadata/EntitySchema\";\nimport type { AnyEntity, EntityClass, EntityClassGroup } from \"@mikro-orm/core/typings\";\nimport type { QueryBuilder } from \"@mikro-orm/knex/query\";\nimport { MemoryCacheAdapter, MikroORM, NullCacheAdapter } from \"@mikro-orm/mysql\";\nimport { ForgeSQLCrudOperations } from \"./ForgeSQLCrudOperations\";\nimport {\n CRUDForgeSQL,\n ForgeSqlOperation,\n ForgeSqlOrmOptions,\n SchemaSqlForgeSql,\n} from \"./ForgeSQLQueryBuilder\";\nimport { ForgeSQLSelectOperations } from \"./ForgeSQLSelectOperations\";\nimport type { Knex } from \"knex\";\n\n/**\n * Implementation of ForgeSQLORM that interacts with MikroORM.\n */\nclass ForgeSQLORMImpl implements ForgeSqlOperation {\n private static instance: ForgeSQLORMImpl | null = null;\n private readonly mikroORM: MikroORM;\n private readonly crudOperations: CRUDForgeSQL;\n private readonly fetchOperations: SchemaSqlForgeSql;\n\n /**\n * Private constructor to enforce singleton behavior.\n * @param entities - The list of entities for ORM initialization.\n * @param options - Options for configuring ForgeSQL ORM behavior.\n */\n private constructor(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ) {\n console.debug(\"Initializing ForgeSQLORM...\");\n\n try {\n this.mikroORM = MikroORM.initSync({\n dbName: \"inmemory\",\n schemaGenerator: {\n disableForeignKeys: false,\n },\n discovery: {\n warnWhenNoEntities: true,\n },\n resultCache: {\n adapter: NullCacheAdapter,\n },\n metadataCache: {\n enabled: false,\n adapter: MemoryCacheAdapter,\n },\n entities: entities,\n preferTs: false,\n debug: false,\n });\n const newOptions: ForgeSqlOrmOptions = options ?? { logRawSqlQuery: false, disableOptimisticLocking: false };\n this.crudOperations = new ForgeSQLCrudOperations(this, newOptions);\n this.fetchOperations = new ForgeSQLSelectOperations(newOptions);\n } catch (error) {\n console.error(\"ForgeSQLORM initialization failed:\", error);\n throw error; // Prevents inconsistent state\n }\n }\n\n /**\n * Returns the singleton instance of ForgeSQLORMImpl.\n * @param entities - List of entities (required only on first initialization).\n * @param options - Options for configuring ForgeSQL ORM behavior.\n * @returns The singleton instance of ForgeSQLORMImpl.\n */\n static getInstance(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ): ForgeSqlOperation {\n if (!ForgeSQLORMImpl.instance) {\n ForgeSQLORMImpl.instance = new ForgeSQLORMImpl(entities, options);\n }\n return ForgeSQLORMImpl.instance;\n }\n\n /**\n * Retrieves the CRUD operations instance.\n * @returns CRUD operations.\n */\n crud(): CRUDForgeSQL {\n return this.crudOperations;\n }\n\n /**\n * Retrieves the fetch operations instance.\n * @returns Fetch operations.\n */\n fetch(): SchemaSqlForgeSql {\n return this.fetchOperations;\n }\n\n /**\n * Creates a new query builder for the given entity.\n * @param entityName - The entity name or an existing query builder.\n * @param alias - The alias for the entity.\n * @param loggerContext - Logging options.\n * @returns The query builder instance.\n */\n createQueryBuilder<Entity extends object, RootAlias extends string = never>(\n entityName: EntityName<Entity> | QueryBuilder<Entity>,\n alias?: RootAlias,\n loggerContext?: LoggingOptions,\n ): QueryBuilder<Entity, RootAlias> {\n return this.mikroORM.em.createQueryBuilder(entityName, alias, undefined, loggerContext);\n }\n\n /**\n * Provides access to the underlying Knex instance for building complex query parts.\n * enabling advanced query customization and performance tuning.\n * @returns The Knex instance, which can be used for query building.\n */\n getKnex(): Knex<any, any[]> {\n return this.mikroORM.em.getKnex();\n }\n}\n\n/**\n * Public class that acts as a wrapper around the private ForgeSQLORMImpl.\n */\nclass ForgeSQLORM {\n private readonly ormInstance: ForgeSqlOperation;\n\n constructor(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ) {\n this.ormInstance = ForgeSQLORMImpl.getInstance(entities, options);\n }\n\n /**\n * Proxies the `crud` method from `ForgeSQLORMImpl`.\n * @returns CRUD operations.\n */\n crud(): CRUDForgeSQL {\n return this.ormInstance.crud();\n }\n\n /**\n * Proxies the `fetch` method from `ForgeSQLORMImpl`.\n * @returns Fetch operations.\n */\n fetch(): SchemaSqlForgeSql {\n return this.ormInstance.fetch();\n }\n\n getKnex(): Knex<any, any[]> {\n return this.ormInstance.getKnex();\n }\n\n /**\n * Proxies the `createQueryBuilder` method from `ForgeSQLORMImpl`.\n * @returns A new query builder instance.\n */\n createQueryBuilder<Entity extends object, RootAlias extends string = never>(\n entityName: EntityName<Entity> | QueryBuilder<Entity>,\n alias?: RootAlias,\n loggerContext?: LoggingOptions,\n ): QueryBuilder<Entity, RootAlias> {\n return this.ormInstance.createQueryBuilder(entityName, alias, loggerContext);\n }\n}\n\nexport default ForgeSQLORM;\n"],"names":[],"mappings":";;;;;AAIA,MAAM,eAAa,CAAC,MAAa,SAAwB;AAChD,SAAA,OAAK,IAAI,IAAI,MAAI;AAC1B;AAEO,MAAM,iBAAiB,CAAI,OAG/B,YAAqB,UAAa;AACnC,UAAQ,MAAM,MAAM;AAAA,IAClB,KAAK;AAAA,IACL,KAAK;AACH,aAAU,aAAa,GAAG,MAAM,KAAK,IAAG,SAAS;AAAA,IACnD,KAAK;AACO,aAAA,aAAa,GAAG,OAAO,MAAM,KAAa,EAAE,OAAO,yBAAyB,CAAC,IAAG,SAAS;AAAA,IACrG,KAAK;AACO,aAAA,aAAa,GAAG,OAAO,MAAM,KAAa,EAAE,OAAO,Y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AAK,SAAS,GAAG,QAAQ;AAAA,EAAA;AAEpC;AAKA,MAAM,YAAY;AAAA,EACC;AAAA,EAEjB,YACE,UACA,SACA;AACA,SAAK,cAAc,gBAAgB,YAAY,UAAU,OAAO;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlE,OAAqB;AACZ,WAAA,KAAK,YAAY,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO/B,QAA2B;AAClB,WAAA,KAAK,YAAY,MAAM;AAAA,EAAA;AAAA,EAGhC,UAA4B;AACnB,WAAA,KAAK,YAAY,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlC,mBACE,YACA,OACA,eACiC;AACjC,WAAO,KAAK,YAAY,mBAAmB,YAAY,OAAO,aAAa;AAAA,EAAA;AAE/E;"}
|
|
1
|
+
{"version":3,"file":"ForgeSQLORM.mjs","sources":["../src/utils/sqlUtils.ts","../src/core/ForgeSQLCrudOperations.ts","../src/core/ForgeSQLSelectOperations.ts","../src/core/ForgeSQLORM.ts"],"sourcesContent":["import { types } from \"@mikro-orm/core/types\";\nimport moment from \"moment\";\nimport { AnyString } from \"@mikro-orm/core/typings\";\n\nconst wrapIfNeeded=(data:string, wrap:boolean):string => {\n return wrap?`'${data}'`:data;\n}\n\nexport const transformValue = <U>(value: {\n type: keyof typeof types | AnyString;\n value: U;\n}, wrapValue: boolean = false): U => {\n switch (value.type) {\n case \"text\":\n case \"string\":\n return <U>wrapIfNeeded(`${value.value}`,wrapValue);\n case \"datetime\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"YYYY-MM-DDTHH:mm:ss.SSS\")}`,wrapValue);\n case \"date\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"YYYY-MM-DD\")}`, wrapValue);\n case \"time\":\n return <U>wrapIfNeeded(`${moment(value.value as Date).format(\"HH:mm:ss.SSS\")}`,wrapValue);\n default:\n return value.value;\n }\n};\n\nexport const parseDateTime = (value: string, format: string): Date => {\n const m = moment(value, format, true);\n if (!m.isValid()) {\n return moment(value).toDate();\n }\n return m.toDate();\n};\n","import { sql, UpdateQueryResponse } from \"@forge/sql\";\nimport { EntityProperty, EntitySchema, ForgeSqlOrmOptions } from \"..\";\nimport type { types } from \"@mikro-orm/core/types\";\nimport { transformValue } from \"../utils/sqlUtils\";\nimport { CRUDForgeSQL, ForgeSqlOperation } from \"./ForgeSQLQueryBuilder\";\nimport { EntityKey, QBFilterQuery } from \"..\";\nimport Knex from \"../knex\";\n\nexport class ForgeSQLCrudOperations implements CRUDForgeSQL {\n private readonly forgeOperations: ForgeSqlOperation;\n private readonly options: ForgeSqlOrmOptions;\n\n constructor(forgeSqlOperations: ForgeSqlOperation, options: ForgeSqlOrmOptions) {\n this.forgeOperations = forgeSqlOperations;\n this.options = options;\n }\n\n /**\n * Generates an SQL INSERT statement for the provided models.\n * If a version field exists in the schema, its value is set accordingly.\n *\n * @param schema - The entity schema.\n * @param models - The list of entities to insert.\n * @param updateIfExists - Whether to update the row if it already exists.\n * @returns An object containing the SQL query, column names, and values.\n */\n private async generateInsertScript<T extends object>(\n schema: EntitySchema<T>,\n models: T[],\n updateIfExists: boolean,\n ): Promise<{\n sql: string;\n query: string;\n fields: string[];\n values: { type: keyof typeof types; value: unknown }[];\n }> {\n const columnNames = new Set<string>();\n const modelFieldValues: Record<string, { type: keyof typeof types; value: unknown }>[] = [];\n\n // Build field values for each model.\n models.forEach((model) => {\n const fieldValues: Record<string, { type: keyof typeof types; value: unknown }> = {};\n schema.meta.props.forEach((prop) => {\n const value = model[prop.name];\n if (prop.kind === \"scalar\" && value !== undefined) {\n const columnName = this.getRealFieldNameFromSchema(prop);\n columnNames.add(columnName);\n fieldValues[columnName] = { type: prop.type as keyof typeof types, value };\n }\n });\n modelFieldValues.push(fieldValues);\n });\n\n // If a version field exists, set or update its value.\n const versionField = this.getVersionField(schema);\n if (versionField) {\n modelFieldValues.forEach((mv) => {\n const versionRealName = this.getRealFieldNameFromSchema(versionField);\n if (mv[versionRealName]) {\n mv[versionRealName].value = transformValue(\n { value: this.createVersionField(versionField), type: versionField.name },\n true,\n );\n } else {\n mv[versionRealName] = {\n type: versionField.type as keyof typeof types,\n value: transformValue(\n { value: this.createVersionField(versionField), type: versionField.name },\n true,\n ),\n };\n columnNames.add(versionField.name);\n }\n });\n }\n\n const columns = Array.from(columnNames);\n\n // Flatten values for each row in the order of columns.\n const values = modelFieldValues.flatMap((fieldValueMap) =>\n columns.map(\n (column) =>\n fieldValueMap[column] || {\n type: \"string\",\n value: null,\n },\n ),\n );\n\n // Build the VALUES clause.\n const insertValues = modelFieldValues\n .map((fieldValueMap) => {\n const rowValues = columns\n .map((column) =>\n transformValue(\n fieldValueMap[column] || { type: \"string\", value: null },\n true,\n ),\n )\n .join(\",\");\n return `(${rowValues})`;\n })\n .join(\", \");\n // Build the VALUES ? clause.\n const insertEmptyValues = modelFieldValues\n .map(() => {\n const rowValues = columns\n .map(() =>\n '?',\n )\n .join(\",\");\n return `(${rowValues})`;\n })\n .join(\", \");\n\n const updateClause = updateIfExists\n ? ` ON DUPLICATE KEY UPDATE ${columns.map((col) => `${col} = VALUES(${col})`).join(\",\")}`\n : \"\";\n\n return {\n sql: `INSERT INTO ${schema.meta.collection} (${columns.join(\",\")}) VALUES ${insertValues}${updateClause}`,\n query: `INSERT INTO ${schema.meta.collection} (${columns.join(\",\")}) VALUES ${insertEmptyValues}${updateClause}`,\n fields: columns,\n values,\n };\n }\n\n /**\n * Inserts records into the database.\n * If a version field exists in the schema, versioning is applied.\n *\n * @param schema - The entity schema.\n * @param models - The list of entities to insert.\n * @param updateIfExists - Whether to update the row if it already exists.\n * @returns The ID of the inserted row.\n */\n async insert<T extends object>(\n schema: EntitySchema<T>,\n models: T[],\n updateIfExists: boolean = false,\n ): Promise<number> {\n if (!models || models.length === 0) return 0;\n\n const query = await this.generateInsertScript(schema, models, updateIfExists);\n if (this.options?.logRawSqlQuery) {\n console.debug(\"INSERT SQL: \" + query.query);\n }\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query.sql);\n const result = await sqlStatement.execute();\n return result.rows.insertId;\n }\n\n /**\n * Retrieves the primary key properties from the entity schema.\n *\n * @param schema - The entity schema.\n * @returns An array of primary key properties.\n * @throws If no primary keys are found.\n */\n private getPrimaryKeys<T extends object>(schema: EntitySchema<T>): EntityProperty<T, unknown>[] {\n const primaryKeys = schema.meta.props.filter((prop) => prop.primary);\n if (!primaryKeys.length) {\n throw new Error(`No primary keys found for schema: ${schema.meta.className}`);\n }\n return primaryKeys;\n }\n\n /**\n * Deletes a record by its primary key.\n *\n * @param id - The ID of the record to delete.\n * @param schema - The entity schema.\n * @returns The number of rows affected.\n * @throws If the entity has more than one primary key.\n */\n async deleteById<T extends object>(id: unknown, schema: EntitySchema<T>): Promise<number> {\n const primaryKeys = this.getPrimaryKeys(schema);\n if (primaryKeys.length > 1) {\n throw new Error(\"Only one primary key is supported\");\n }\n\n const primaryKey = primaryKeys[0];\n const queryBuilder = this.forgeOperations.createQueryBuilder(schema.meta.class).delete();\n queryBuilder.andWhere({ [primaryKey.name]: { $eq: id } });\n\n const query = queryBuilder.getFormattedQuery();\n if (this.options?.logRawSqlQuery) {\n console.debug(\"DELETE SQL: \" + queryBuilder.getQuery());\n }\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query);\n const result = await sqlStatement.execute();\n return result.rows.affectedRows;\n }\n\n /**\n * Retrieves the version field from the entity schema.\n * The version field must be of type datetime, integer, or decimal, not a primary key, and not nullable.\n *\n * @param schema - The entity schema.\n * @returns The version field property if it exists.\n */\n getVersionField<T>(schema: EntitySchema<T>) {\n if (this.options.disableOptimisticLocking){\n return undefined;\n }\n return schema.meta.props\n .filter((prop) => prop.version)\n .filter((prop) => {\n const validType =\n prop.type === \"datetime\" || prop.type === \"integer\" || prop.type === \"decimal\";\n if (!validType) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} must be datetime, integer, or decimal, but is \"${prop.type}\"`,\n );\n }\n return validType;\n })\n .filter((prop) => {\n if (prop.primary) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} cannot be a primary key`,\n );\n return false;\n }\n return true;\n })\n .find((prop) => {\n if (prop.nullable) {\n console.warn(\n `Version field \"${prop.name}\" in table ${schema.meta.tableName} should not be nullable`,\n );\n return false;\n }\n return true;\n });\n }\n\n /**\n * Increments the version field of an entity.\n * For datetime types, sets the current date; for numeric types, increments by 1.\n *\n * @param versionField - The version field property.\n * @param updateModel - The entity to update.\n */\n incrementVersionField<T>(versionField: EntityProperty<T, any>, updateModel: T): void {\n const key = versionField.name as keyof T;\n switch (versionField.type) {\n case \"datetime\": {\n updateModel[key] = new Date() as unknown as T[keyof T];\n break;\n }\n case \"decimal\":\n case \"integer\": {\n updateModel[key] = ((updateModel[key] as number) + 1) as unknown as T[keyof T];\n break;\n }\n default:\n throw new Error(`Unsupported version field type: ${versionField.type}`);\n }\n }\n\n /**\n * Creates the initial version field value for an entity.\n * For datetime types, returns the current date; for numeric types, returns 0.\n *\n * @param versionField - The version field property.\n */\n createVersionField<T>(versionField: EntityProperty<T>): unknown {\n switch (versionField.type) {\n case \"datetime\": {\n return new Date() as unknown as T[keyof T];\n }\n case \"decimal\":\n case \"integer\": {\n return 0;\n }\n default:\n throw new Error(`Unsupported version field type: ${versionField.type}`);\n }\n }\n\n /**\n * Updates a record by its primary key using the provided entity data.\n *\n * @param entity - The entity with updated values.\n * @param schema - The entity schema.\n */\n async updateById<T extends object>(entity: Partial<T>, schema: EntitySchema<T>): Promise<void> {\n const fields = schema.meta.props\n .filter((prop) => prop.kind === \"scalar\")\n .map((prop) => prop.name);\n await this.updateFieldById(entity as T, fields, schema);\n }\n\n /**\n * Updates specified fields of records based on provided conditions.\n * If the \"where\" parameter is not provided, the WHERE clause is built from the entity fields\n * that are not included in the list of fields to update.\n *\n * @param entity - The object containing values to update and potential criteria for filtering.\n * @param fields - Array of field names to update.\n * @param schema - The entity schema.\n * @param where - Optional filtering conditions for the WHERE clause.\n * @returns The number of affected rows.\n * @throws If no filtering criteria are provided (either via \"where\" or from the remaining entity fields).\n */\n async updateFields<T extends object>(\n entity: Partial<T>,\n fields: EntityKey<T>[],\n schema: EntitySchema<T>,\n where?: QBFilterQuery<T>,\n ): Promise<number> {\n // Extract update data from the entity based on the provided fields.\n const updateData = this.filterEntityFields(entity, fields);\n const updateModel = this.modifyModel(updateData as T, schema);\n\n // Create the query builder for the entity.\n let queryBuilder = this.forgeOperations\n .createQueryBuilder(schema.meta.class)\n .getKnexQuery();\n\n // Set the update data.\n queryBuilder.update(updateModel as T);\n\n // Use the provided \"where\" conditions if available; otherwise, build conditions from the remaining entity fields.\n if (where) {\n queryBuilder.where(where);\n } else {\n const filterCriteria = (Object.keys(entity) as Array<keyof T>)\n .filter((key: keyof T) => !fields.includes(key as EntityKey<T>))\n .reduce((criteria, key) => {\n if (entity[key] !== undefined) {\n // Cast key to string to use it as an object key.\n criteria[key as string] = entity[key];\n }\n return criteria;\n }, {} as Record<string, unknown>);\n\n\n if (Object.keys(filterCriteria).length === 0) {\n throw new Error(\n \"Filtering criteria (WHERE clause) must be provided either via the 'where' parameter or through non-updated entity fields\"\n );\n }\n queryBuilder.where(filterCriteria);\n }\n\n if (this.options?.logRawSqlQuery) {\n console.debug(\"UPDATE SQL (updateFields): \" + queryBuilder.toSQL().sql);\n }\n\n // Execute the update query.\n const sqlQuery = queryBuilder.toQuery();\n const updateQueryResponse = await this.forgeOperations.fetch().executeRawUpdateSQL(sqlQuery);\n return updateQueryResponse.affectedRows;\n }\n\n\n /**\n * Updates specific fields of a record identified by its primary key.\n * If a version field exists in the schema, versioning is applied.\n *\n * @param entity - The entity with updated values.\n * @param fields - The list of field names to update.\n * @param schema - The entity schema.\n * @throws If the primary key is not included in the update fields.\n */\n async updateFieldById<T extends object>(\n entity: T,\n fields: EntityKey<T>[],\n schema: EntitySchema<T>,\n ): Promise<void> {\n const primaryKeys = this.getPrimaryKeys(schema);\n primaryKeys.forEach((pk) => {\n if (!fields.includes(pk.name)) {\n throw new Error(\"Update fields must include primary key: \" + pk.name);\n }\n });\n\n // Prepare updated entity and query builder.\n const updatedEntity = this.filterEntityFields(entity, fields);\n let queryBuilder = this.forgeOperations.createQueryBuilder(schema.meta.class).getKnexQuery();\n const versionField = this.getVersionField(schema);\n const useVersion = Boolean(versionField);\n let updateModel = { ...updatedEntity };\n\n if (useVersion && versionField) {\n // If the version field is missing from the entity, load the old record.\n let oldModel = entity;\n if (entity[versionField.name] === undefined || entity[versionField.name] === null) {\n oldModel = await this.getOldModel(primaryKeys, entity, schema, versionField);\n }\n const primaryFieldNames = primaryKeys.map((pk) => pk.name);\n const fieldsToRetain = primaryFieldNames.concat(versionField.name);\n const fromEntries = Object.fromEntries(fieldsToRetain.map((key) => [key, oldModel[key]]));\n updateModel = { ...updatedEntity, ...fromEntries };\n\n // Increment the version field.\n this.incrementVersionField(versionField, updateModel as T);\n\n updateModel = this.modifyModel(updateModel as T, schema);\n queryBuilder.update(updateModel as T);\n if (oldModel[versionField.name]!==undefined || oldModel[versionField.name]!==null && this.isValid(oldModel[versionField.name])) {\n queryBuilder.andWhere(this.optWhere(oldModel, versionField));\n }\n } else {\n updateModel = this.modifyModel(updatedEntity as T, schema);\n queryBuilder.update(updateModel as T);\n }\n\n this.addPrimaryWhere(queryBuilder as unknown as Knex.QueryBuilder<any, any>, primaryKeys, updateModel as T);\n const sqlQuery = queryBuilder.toQuery();\n\n if (this.options?.logRawSqlQuery) {\n console.debug(\"UPDATE SQL: \" + queryBuilder.toSQL().sql);\n }\n const updateQueryResponse = await this.forgeOperations.fetch().executeRawUpdateSQL(sqlQuery);\n if (versionField && !updateQueryResponse.affectedRows) {\n throw new Error(\n \"Optimistic locking failed: the record with primary key(s) \" +\n primaryKeys.map((p) => updateModel[p.name]).join(\", \") +\n \" has been modified by another process.\",\n );\n }\n }\n\n /**\n * Constructs an optional WHERE clause for the version field.\n *\n * @param updateModel - The model containing the current version field value.\n * @param versionField - The version field property.\n * @returns A filter query for the version field.\n */\n private optWhere<T>(\n updateModel: T,\n versionField: EntityProperty<T>,\n ): QBFilterQuery<unknown> {\n const currentVersionValue = transformValue(\n { value: updateModel[versionField.name], type: versionField.type },\n false,\n );\n return { [versionField.name]: currentVersionValue };\n }\n\n /**\n * Retrieves the current state of a record from the database.\n *\n * @param primaryKeys - The primary key properties.\n * @param entity - The entity with updated values.\n * @param schema - The entity schema.\n * @param versionField - The version field property.\n * @returns The existing record from the database.\n * @throws If the record does not exist or if multiple records are found.\n */\n private async getOldModel<T>(\n primaryKeys: EntityProperty<T, unknown>[],\n entity: T,\n schema: EntitySchema<T>,\n versionField: EntityProperty<T>,\n ): Promise<T> {\n const primaryFieldNames = primaryKeys.map((pk) => pk.name);\n const fieldsToSelect = primaryFieldNames.concat(versionField.name);\n const queryBuilder = this.forgeOperations\n .createQueryBuilder(schema as EntitySchema)\n .select(fieldsToSelect);\n this.addPrimaryWhere(queryBuilder, primaryKeys, entity);\n const formattedQuery = queryBuilder.getFormattedQuery();\n const models: T[] = await this.forgeOperations.fetch().executeSchemaSQL(formattedQuery, schema as EntitySchema);\n\n if (!models || models.length === 0) {\n throw new Error(`Cannot modify record because it does not exist in table ${schema.meta.tableName}`);\n }\n if (models.length > 1) {\n throw new Error(\n `Cannot modify record because multiple rows with the same ID were found in table ${schema.meta.tableName}. Please verify the table metadata.`,\n );\n }\n return models[0];\n }\n\n /**\n * Adds primary key conditions to the query builder.\n *\n * @param queryBuilder - The Knex query builder instance.\n * @param primaryKeys - The primary key properties.\n * @param entity - The entity containing primary key values.\n * @throws If any primary key value is missing.\n */\n private addPrimaryWhere<T>(\n queryBuilder: Knex.QueryBuilder<any, any>,\n primaryKeys: EntityProperty<T, unknown>[],\n entity: T,\n ) {\n primaryKeys.forEach((pk) => {\n const fieldName = this.getRealFieldNameFromSchema(pk);\n const value = entity[fieldName];\n if (value === null || value === undefined) {\n throw new Error(`Primary key ${fieldName} must exist in the model`);\n }\n queryBuilder.andWhere({ [fieldName]: value });\n });\n }\n\n /**\n * Filters the entity to include only the specified fields.\n *\n * @param entity - The original entity.\n * @param fields - The list of fields to retain.\n * @returns A partial entity object containing only the specified fields.\n */\n filterEntityFields = <T extends object>(entity: T, fields: (keyof T)[]): Partial<T> =>\n fields.reduce((result, field) => {\n if (field in entity) {\n result[field] = entity[field];\n }\n return result;\n }, {} as Partial<T>);\n\n /**\n * Transforms and modifies the updated entity model based on the schema.\n *\n * @param updatedEntity - The updated entity.\n * @param schema - The entity schema.\n * @returns The modified entity.\n */\n private modifyModel<T>(updatedEntity: T, schema: EntitySchema<T>): T {\n const modifiedModel: Record<string, any> = {};\n schema.meta.props\n .filter((p) => p.kind === \"scalar\")\n .forEach((p) => {\n const value = updatedEntity[p.name];\n if (value !== undefined && value !== null) {\n const fieldName = this.getRealFieldNameFromSchema(p);\n modifiedModel[fieldName] = transformValue({ value, type: p.type }, false);\n }\n });\n return modifiedModel as T;\n }\n\n /**\n * Returns the real field name from the entity property based on the schema.\n *\n * @param p - The entity property.\n * @returns The real field name.\n */\n private getRealFieldNameFromSchema<T>(p: EntityProperty<T>): EntityKey<T> {\n return p.fieldNames && p.fieldNames.length\n ? (p.fieldNames[0] as EntityKey<T>)\n : p.name;\n }\n\n /**\n * Validates the provided value.\n *\n * @param value - The value to validate.\n * @returns True if the value is valid, false otherwise.\n */\n isValid(value: any): boolean {\n if (value instanceof Date) {\n return !isNaN(value.getTime());\n }\n return true;\n }\n}\n","import { sql, UpdateQueryResponse } from \"@forge/sql\";\nimport type { EntitySchema } from \"@mikro-orm/core/metadata/EntitySchema\";\nimport { parseDateTime } from \"../utils/sqlUtils\";\nimport { ForgeSqlOrmOptions, SchemaSqlForgeSql } from \"./ForgeSQLQueryBuilder\";\nimport {SqlParameters} from \"@forge/sql/out/sql-statement\";\n\nexport class ForgeSQLSelectOperations implements SchemaSqlForgeSql {\n private readonly options: ForgeSqlOrmOptions;\n\n constructor(options: ForgeSqlOrmOptions) {\n this.options = options;\n }\n\n async executeSchemaSQLOnlyOne<T extends object>(query: string, schema: EntitySchema<T>): Promise<T|undefined> {\n const results = await this.executeSchemaSQL(query, schema);\n if (!results || results.length === 0){\n return undefined;\n }\n if (results.length>1){\n throw new Error('Expected 1 record but returned '+results.length)\n }\n return results[0];\n }\n\n /**\n * Executes a schema-based SQL query and maps the result to the entity schema.\n * @param query - The SQL query to execute.\n * @param schema - The entity schema defining the structure.\n * @returns A list of mapped entity objects.\n */\n async executeSchemaSQL<T extends object>(query: string, schema: EntitySchema<T>): Promise<T[]> {\n const datas = await this.executeRawSQL<unknown>(query);\n if (!datas.length) return [];\n\n return datas.map((r) => {\n const rawModel = r as Record<string, unknown>;\n const newModel: Record<string, unknown> = {};\n\n schema.meta.props\n .filter((p) => p.kind === \"scalar\")\n .forEach((p) => {\n const fieldName = p.name;\n const fieldNames = p.fieldNames;\n const rawFieldName = fieldNames && Array.isArray(fieldNames) ? fieldNames[0] : p.name;\n\n switch (p.type) {\n case \"datetime\":\n newModel[fieldName] = parseDateTime(\n rawModel[rawFieldName] as string,\n \"YYYY-MM-DDTHH:mm:ss.SSS\",\n );\n break;\n case \"date\":\n newModel[fieldName] = parseDateTime(rawModel[rawFieldName] as string, \"YYYY-MM-DD\");\n break;\n case \"time\":\n newModel[fieldName] = parseDateTime(rawModel[rawFieldName] as string, \"HH:mm:ss.SSS\");\n break;\n default:\n newModel[fieldName] = rawModel[rawFieldName];\n }\n });\n return newModel as T;\n });\n }\n\n /**\n * Executes a raw SQL query and returns the results.\n * @param query - The raw SQL query to execute.\n * @returns A list of results as objects.\n */\n async executeRawSQL<T extends object | unknown>(query: string): Promise<T[]> {\n if (this.options.logRawSqlQuery) {\n console.debug(\"Executing raw SQL: \" + query);\n }\n const sqlStatement = await sql.prepare<T>(query).execute();\n return sqlStatement.rows as T[];\n }\n\n /**\n * Executes a raw SQL update query.\n * @param query - The raw SQL update query.\n * @param params - sql parameters.\n * @returns The update response containing affected rows.\n */\n async executeRawUpdateSQL(query: string, params?: SqlParameters[]): Promise<UpdateQueryResponse> {\n const sqlStatement = sql.prepare<UpdateQueryResponse>(query);\n if (params) {\n sqlStatement.bindParams(params);\n }\n const updateQueryResponseResults = await sqlStatement.execute();\n return updateQueryResponseResults.rows;\n }\n}\n","import type { EntityName, LoggingOptions } from \"..\";\nimport type { EntitySchema } from \"@mikro-orm/core/metadata/EntitySchema\";\nimport type { AnyEntity, EntityClass, EntityClassGroup } from \"@mikro-orm/core/typings\";\nimport type { QueryBuilder } from \"@mikro-orm/knex/query\";\nimport { MemoryCacheAdapter, MikroORM, NullCacheAdapter } from \"@mikro-orm/mysql\";\nimport { ForgeSQLCrudOperations } from \"./ForgeSQLCrudOperations\";\nimport {\n CRUDForgeSQL,\n ForgeSqlOperation,\n ForgeSqlOrmOptions,\n SchemaSqlForgeSql,\n} from \"./ForgeSQLQueryBuilder\";\nimport { ForgeSQLSelectOperations } from \"./ForgeSQLSelectOperations\";\nimport type { Knex } from \"knex\";\n\n/**\n * Implementation of ForgeSQLORM that interacts with MikroORM.\n */\nclass ForgeSQLORMImpl implements ForgeSqlOperation {\n private static instance: ForgeSQLORMImpl | null = null;\n private readonly mikroORM: MikroORM;\n private readonly crudOperations: CRUDForgeSQL;\n private readonly fetchOperations: SchemaSqlForgeSql;\n\n /**\n * Private constructor to enforce singleton behavior.\n * @param entities - The list of entities for ORM initialization.\n * @param options - Options for configuring ForgeSQL ORM behavior.\n */\n private constructor(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ) {\n console.debug(\"Initializing ForgeSQLORM...\");\n\n try {\n this.mikroORM = MikroORM.initSync({\n dbName: \"inmemory\",\n schemaGenerator: {\n disableForeignKeys: false,\n },\n discovery: {\n warnWhenNoEntities: true,\n },\n resultCache: {\n adapter: NullCacheAdapter,\n },\n metadataCache: {\n enabled: false,\n adapter: MemoryCacheAdapter,\n },\n entities: entities,\n preferTs: false,\n debug: false,\n });\n const newOptions: ForgeSqlOrmOptions = options ?? { logRawSqlQuery: false, disableOptimisticLocking: false };\n this.crudOperations = new ForgeSQLCrudOperations(this, newOptions);\n this.fetchOperations = new ForgeSQLSelectOperations(newOptions);\n } catch (error) {\n console.error(\"ForgeSQLORM initialization failed:\", error);\n throw error; // Prevents inconsistent state\n }\n }\n\n /**\n * Returns the singleton instance of ForgeSQLORMImpl.\n * @param entities - List of entities (required only on first initialization).\n * @param options - Options for configuring ForgeSQL ORM behavior.\n * @returns The singleton instance of ForgeSQLORMImpl.\n */\n static getInstance(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ): ForgeSqlOperation {\n if (!ForgeSQLORMImpl.instance) {\n ForgeSQLORMImpl.instance = new ForgeSQLORMImpl(entities, options);\n }\n return ForgeSQLORMImpl.instance;\n }\n\n /**\n * Retrieves the CRUD operations instance.\n * @returns CRUD operations.\n */\n crud(): CRUDForgeSQL {\n return this.crudOperations;\n }\n\n /**\n * Retrieves the fetch operations instance.\n * @returns Fetch operations.\n */\n fetch(): SchemaSqlForgeSql {\n return this.fetchOperations;\n }\n\n /**\n * Creates a new query builder for the given entity.\n * @param entityName - The entity name or an existing query builder.\n * @param alias - The alias for the entity.\n * @param loggerContext - Logging options.\n * @returns The query builder instance.\n */\n createQueryBuilder<Entity extends object, RootAlias extends string = never>(\n entityName: EntityName<Entity> | QueryBuilder<Entity>,\n alias?: RootAlias,\n loggerContext?: LoggingOptions,\n ): QueryBuilder<Entity, RootAlias> {\n return this.mikroORM.em.createQueryBuilder(entityName, alias, undefined, loggerContext);\n }\n\n /**\n * Provides access to the underlying Knex instance for building complex query parts.\n * enabling advanced query customization and performance tuning.\n * @returns The Knex instance, which can be used for query building.\n */\n getKnex(): Knex<any, any[]> {\n return this.mikroORM.em.getKnex();\n }\n}\n\n/**\n * Public class that acts as a wrapper around the private ForgeSQLORMImpl.\n */\nclass ForgeSQLORM {\n private readonly ormInstance: ForgeSqlOperation;\n\n constructor(\n entities: (EntityClass<AnyEntity> | EntityClassGroup<AnyEntity> | EntitySchema)[],\n options?: ForgeSqlOrmOptions,\n ) {\n this.ormInstance = ForgeSQLORMImpl.getInstance(entities, options);\n }\n\n /**\n * Proxies the `crud` method from `ForgeSQLORMImpl`.\n * @returns CRUD operations.\n */\n crud(): CRUDForgeSQL {\n return this.ormInstance.crud();\n }\n\n /**\n * Proxies the `fetch` method from `ForgeSQLORMImpl`.\n * @returns Fetch operations.\n */\n fetch(): SchemaSqlForgeSql {\n return this.ormInstance.fetch();\n }\n\n getKnex(): Knex<any, any[]> {\n return this.ormInstance.getKnex();\n }\n\n /**\n * Proxies the `createQueryBuilder` method from `ForgeSQLORMImpl`.\n * @returns A new query builder instance.\n */\n createQueryBuilder<Entity extends object, RootAlias extends string = never>(\n entityName: EntityName<Entity> | QueryBuilder<Entity>,\n alias?: RootAlias,\n loggerContext?: LoggingOptions,\n ): QueryBuilder<Entity, RootAlias> {\n return this.ormInstance.createQueryBuilder(entityName, alias, loggerContext);\n }\n}\n\nexport default ForgeSQLORM;\n"],"names":[],"mappings":";;;;;AAIA,MAAM,eAAa,CAAC,MAAa,SAAwB;AAChD,SAAA,OAAK,IAAI,IAAI,MAAI;AAC1B;AAEO,MAAM,iBAAiB,CAAI,OAG/B,YAAqB,UAAa;AACnC,UAAQ,MAAM,MAAM;AAAA,IAClB,KAAK;AAAA,IACL,KAAK;AACH,aAAU,aAAa,GAAG,MAAM,KAAK,IAAG,SAAS;AAAA,IACnD,KAAK;AACO,aAAA,aAAa,GAAG,OAAO,MAAM,KAAa,EAAE,OAAO,yBAAyB,CAAC,IAAG,SAAS;AAAA,IACrG,KAAK;AACO,aAAA,aAAa,GAAG,OAAO,MAAM,KAAa,EAAE,OAAO,YAAY,CAAC,IAAI,SAAS;AAAA,IACzF,KAAK;AACO,aAAA,aAAa,GAAG,OAAO,MAAM,KAAa,EAAE,OAAO,cAAc,CAAC,IAAG,SAAS;AAAA,IA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AAY,UAAU,OAAO;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlE,OAAqB;AACZ,WAAA,KAAK,YAAY,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO/B,QAA2B;AAClB,WAAA,KAAK,YAAY,MAAM;AAAA,EAAA;AAAA,EAGhC,UAA4B;AACnB,WAAA,KAAK,YAAY,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlC,mBACE,YACA,OACA,eACiC;AACjC,WAAO,KAAK,YAAY,mBAAmB,YAAY,OAAO,aAAa;AAAA,EAAA;AAE/E;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { EntityProperty, EntitySchema, ForgeSqlOrmOptions } from "..";
|
|
2
2
|
import { CRUDForgeSQL, ForgeSqlOperation } from "./ForgeSQLQueryBuilder";
|
|
3
|
-
import { EntityKey, QBFilterQuery } from "
|
|
3
|
+
import { EntityKey, QBFilterQuery } from "..";
|
|
4
4
|
export declare class ForgeSQLCrudOperations implements CRUDForgeSQL {
|
|
5
5
|
private readonly forgeOperations;
|
|
6
6
|
private readonly options;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ForgeSQLCrudOperations.d.ts","sourceRoot":"","sources":["../../src/core/ForgeSQLCrudOperations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,IAAI,CAAC;AAGtE,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"ForgeSQLCrudOperations.d.ts","sourceRoot":"","sources":["../../src/core/ForgeSQLCrudOperations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,IAAI,CAAC;AAGtE,OAAO,EAAE,YAAY,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AS,MAAM,EAC/B,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAClB,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,EACtB,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC,EACvB,KAAK,CAAC,EAAE,aAAa,CAAC,CAAC,CAAC,GACzB,OAAO,CAAC,MAAM,CAAC;IA+ClB;;;;;;;;OAQG;IACG,eAAe,CAAC,CAAC,SAAS,MAAM,EAClC,MAAM,EAAE,CAAC,EACT,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,EACtB,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC,GACxB,OAAO,CAAC,IAAI,CAAC;IAuDhB;;;;;;OAMG;IACH,OAAO,CAAC,QAAQ;IAWhB;;;;;;;;;OASG;YACW,WAAW;IA0BzB;;;;;;;OAOG;IACH,OAAO,CAAC,eAAe;IAevB;;;;;;OAMG;IACH,kBAAkB,GAAI,CAAC,SAAS,MAAM,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,EAAE,KAAG,OAAO,CAAC,CAAC,CAAC,CAM1D;IAEzB;;;;;;OAMG;IACH,OAAO,CAAC,WAAW;IAcnB;;;;;OAKG;IACH,OAAO,CAAC,0BAA0B;IAMlC;;;;;OAKG;IACH,OAAO,CAAC,KAAK,EAAE,GAAG,GAAG,OAAO;CAM7B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EntityName, LoggingOptions } from "
|
|
1
|
+
import type { EntityName, LoggingOptions } from "..";
|
|
2
2
|
import type { EntitySchema } from "@mikro-orm/core/metadata/EntitySchema";
|
|
3
3
|
import type { AnyEntity, EntityClass, EntityClassGroup } from "@mikro-orm/core/typings";
|
|
4
4
|
import type { QueryBuilder } from "@mikro-orm/knex/query";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ForgeSQLORM.d.ts","sourceRoot":"","sources":["../../src/core/ForgeSQLORM.ts"],"names":[],"mappings":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
@@ -365,6 +365,18 @@ const PATCHES = [
|
|
|
365
365
|
deleteFolder: "node_modules/@mikro-orm/knex/dialects/sqlite",
|
|
366
366
|
description: "Removing sqlite dialect from MikroORM"
|
|
367
367
|
},
|
|
368
|
+
{
|
|
369
|
+
deleteFolder: "node_modules/@mikro-orm/mysql/node_modules",
|
|
370
|
+
description: "Removing sqlite dialect from MikroORM"
|
|
371
|
+
},
|
|
372
|
+
{
|
|
373
|
+
deleteFolder: "node_modules/@mikro-orm/knex/node_modules",
|
|
374
|
+
description: "Removing sqlite dialect from MikroORM"
|
|
375
|
+
},
|
|
376
|
+
{
|
|
377
|
+
deleteFolder: "node_modules/@mikro-orm/core/node_modules",
|
|
378
|
+
description: "Removing sqlite dialect from MikroORM"
|
|
379
|
+
},
|
|
368
380
|
// 🔄 Fix Webpack `Critical dependency: the request of a dependency is an expression`
|
|
369
381
|
{
|
|
370
382
|
file: "node_modules/@mikro-orm/core/utils/Configuration.js",
|
|
@@ -406,13 +418,6 @@ const PATCHES = [
|
|
|
406
418
|
replace: "return null;",
|
|
407
419
|
description: "Replacing `return new Seeder(this);` with `return null;`"
|
|
408
420
|
},
|
|
409
|
-
// 🔄 Patch for MikroORM Entity Generator to use 'forge-sql-orm'
|
|
410
|
-
// {
|
|
411
|
-
// file: "node_modules/@mikro-orm/entity-generator/SourceFile.js",
|
|
412
|
-
// search: /^.* from '@mikro-orm.*$/gim,
|
|
413
|
-
// replace: " }).join(', '))} } from 'forge-sql-orm';`);",
|
|
414
|
-
// description: "Replacing entity generator imports with 'forge-sql-orm'"
|
|
415
|
-
// },
|
|
416
421
|
{
|
|
417
422
|
file: "node_modules/knex/lib/dialects/index.js",
|
|
418
423
|
deleteLines: [
|
package/dist-cli/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sources":["../scripts/actions/generate-models.ts","../scripts/actions/migrations-create.ts","../scripts/actions/migrations-update.ts","../scripts/actions/PatchPostinstall.ts","../scripts/cli.ts"],"sourcesContent":["import \"reflect-metadata\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { defineConfig, MikroORM, MongoNamingStrategy } from \"@mikro-orm/mysql\";\nimport { EntityGenerator } from \"@mikro-orm/entity-generator\";\nimport { EntityMetadata } from \"@mikro-orm/core/typings\";\n\nconst regenerateIndexFile = (outputPath: string) => {\n const entitiesDir = path.resolve(outputPath);\n const indexPath = path.join(entitiesDir, \"index.ts\");\n\n const entityFiles = fs\n .readdirSync(entitiesDir)\n .filter((file) => file.endsWith(\".ts\") && file !== \"index.ts\");\n\n const imports = entityFiles.map((file) => {\n const entityName = path.basename(file, \".ts\");\n return `import { ${entityName} } from \"./${entityName}\";`;\n });\n\n const indexContent = `${imports.join(\"\\n\")}\\n\\nexport default [${entityFiles.map((file) => path.basename(file, \".ts\")).join(\", \")}];\\n`;\n\n fs.writeFileSync(indexPath, indexContent, \"utf8\");\n console.log(`✅ Updated index.ts with ${entityFiles.length} entities.`);\n};\n\nexport const generateModels = async (options: any) => {\n try {\n const ormConfig = defineConfig({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n namingStrategy: MongoNamingStrategy,\n discovery: { warnWhenNoEntities: false },\n extensions: [EntityGenerator],\n debug: true,\n }) as Parameters<typeof MikroORM.initSync>[0];\n\n const orm = MikroORM.initSync(ormConfig);\n console.log(`✅ Connected to ${options.dbName} at ${options.host}:${options.port}`);\n\n const onCreatingVersionField = async (metadatas: EntityMetadata[]) => {\n metadatas.forEach((m) => {\n if (options.versionField) {\n const versionFieldName = Object.keys(m.properties).find((p) => {\n return (\n p === options.versionField ||\n m.properties[p]?.name === options.versionField ||\n m.properties[p]?.fieldNames?.find((f) => f === options.versionField)\n );\n });\n if (versionFieldName) {\n const property = m.properties[versionFieldName];\n if (\n property.type !== \"datetime\" &&\n property.type !== \"integer\" &&\n property.type !== \"decimal\"\n ) {\n console.warn(\n `Version field \"${property.name}\" can be only datetime or integer Table ${m.tableName} but now is \"${property.type}\"`,\n );\n return;\n }\n if (property.primary) {\n console.warn(\n `Version field \"${property.name}\" can not be primary key Table ${m.tableName}`,\n );\n return;\n }\n if (property.nullable) {\n console.warn(\n `Version field \"${property.name}\" should not be nullable Table ${m.tableName}`,\n );\n return;\n }\n property.version = true;\n }\n }\n });\n };\n await orm.entityGenerator.generate({\n entitySchema: true,\n bidirectionalRelations: true,\n identifiedReferences: false,\n forceUndefined: true,\n undefinedDefaults: true,\n useCoreBaseEntity: false,\n onlyPurePivotTables: false,\n outputPurePivotTables: false,\n scalarPropertiesForRelations: \"always\",\n save: true,\n path: options.output,\n onInitialMetadata: onCreatingVersionField,\n });\n\n regenerateIndexFile(options.output);\n\n console.log(`✅ Entities generated at: ${options.output}`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error generating entities:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MikroORM } from \"@mikro-orm/mysql\";\nimport { execSync } from \"child_process\";\nimport { rmSync } from \"fs\";\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nfunction cleanSQLStatement(sql: string): string {\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \\\"${cleanSQLStatement(stmt)}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nconst extractCreateStatements = (schema: string): string[] => {\n const statements = schema.split(\";\").map((s) => s.trim());\n\n return statements.filter(\n (stmt) =>\n stmt.startsWith(\"create table\") ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add index\")) ||\n stmt.startsWith(\"primary\"),\n );\n};\n\n/**\n * Dynamically loads `entities` from `index.ts` in the specified directory.\n * @param entitiesPath - Path to the directory containing `index.ts`.\n * @returns Array of entity classes.\n */\nconst loadEntities = async (entitiesPath: string) => {\n try {\n const indexFilePath = path.resolve(path.join(entitiesPath, \"index.ts\"));\n if (!fs.existsSync(indexFilePath)) {\n console.error(`❌ Error: index.ts not found in ${indexFilePath}`);\n process.exit(1);\n }\n\n const { default: entities } = await import(indexFilePath);\n console.log(`✅ Loaded ${entities.length} entities from ${entitiesPath}`);\n return entities;\n } catch (error) {\n console.error(`❌ Error loading index.ts from ${entitiesPath}:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const createMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version > 0) {\n console.error(`❌ Error: Migration has already been created.`);\n process.exit(1);\n }\n\n // Start from version 1 if no previous migrations exist\n version = 1;\n\n // Load entities dynamically from index.ts\n const entities = await loadEntities(options.entitiesPath);\n\n // Initialize MikroORM\n const orm = MikroORM.initSync({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n entities: entities,\n });\n\n // Generate SQL schema\n const createSchemaSQL = await orm.schema.getCreateSchemaSQL({ wrap: true });\n const statements = extractCreateStatements(createSchemaSQL);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(statements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MikroORM } from \"@mikro-orm/mysql\";\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nfunction cleanSQLStatement(sql: string): string {\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \\\"${cleanSQLStatement(stmt)}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nconst extractCreateStatements = (schema: string): string[] => {\n const statements = schema.split(\";\").map((s) => s.trim());\n\n return statements.filter(\n (stmt) =>\n stmt.startsWith(\"create table\") ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add index\")) ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add\") && !stmt.includes(\"foreign\")) ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"modify\") && !stmt.includes(\"foreign\")),\n );\n};\n\n/**\n * Dynamically loads `entities` from `index.ts` in the specified directory.\n * @param entitiesPath - Path to the directory containing `index.ts`.\n * @returns Array of entity classes.\n */\nconst loadEntities = async (entitiesPath: string) => {\n try {\n const indexFilePath = path.resolve(path.join(entitiesPath, \"index.ts\"));\n if (!fs.existsSync(indexFilePath)) {\n console.error(`❌ Error: index.ts not found in ${entitiesPath}`);\n process.exit(1);\n }\n\n const { default: entities } = await import(indexFilePath);\n console.log(`✅ Loaded ${entities.length} entities from ${entitiesPath}`);\n return entities;\n } catch (error) {\n console.error(`❌ Error loading index.ts from ${entitiesPath}:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.warn(\n `⚠️ Warning: migrationCount.ts not found in ${migrationCountFilePath}, assuming no previous migrations.`,\n );\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Updates an existing database migration by generating schema modifications.\n * @param options - Database connection settings and output paths.\n */\nexport const updateMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version < 1) {\n console.log(\n `⚠️ Initial migration not found. Run \"npx forge-sql-orm migrations:create\" first.`,\n );\n process.exit(0);\n }\n version += 1;\n\n // Load entities dynamically from index.ts\n const entities = await loadEntities(options.entitiesPath);\n\n // Initialize MikroORM\n const orm = MikroORM.initSync({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n entities,\n debug: true,\n });\n\n // Generate SQL schema updates\n const createSchemaSQL = await orm.schema.getUpdateSchemaMigrationSQL({ wrap: true });\n const statements = extractCreateStatements(createSchemaSQL?.down || \"\");\n\n if (statements.length) {\n const migrationFile = generateMigrationFile(statements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully updated!`);\n process.exit(0);\n } else {\n console.log(`⚠️ No new migration changes detected.`);\n process.exit(0);\n }\n } catch (error) {\n console.error(`❌ Error during migration update:`, error);\n process.exit(1);\n }\n};\n","import fs from \"fs\";\nimport path from \"path\";\n\n/**\n * Automates patches for MikroORM and Knex to fix Webpack issues.\n * - Removes problematic `require()` calls.\n * - Deletes unnecessary files and folders.\n * - Fixes dynamic imports (`import(id)`) in MikroORM.\n */\n\ninterface Patch {\n file?: string; // File to modify (optional)\n search?: RegExp; // Regex pattern to find problematic code\n replace?: string; // Replacement string for problematic code\n deleteLines?: RegExp[]; // List of regex patterns to remove specific lines\n description: string; // Description of the patch\n deleteFile?: string; // Path of the file to delete (optional)\n deleteFolder?: string; // Path of the folder to delete (optional)\n}\n\nconst PATCHES: Patch[] = [\n // 🗑️ Remove unused dialects (mssql, postgres, sqlite) in MikroORM\n {\n file: \"node_modules/@mikro-orm/knex/MonkeyPatchable.d.ts\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^\\s*Postgres.*$/gm,\n /^.*Sqlite3.*$/gm,\n /^.*BetterSqlite3.*$/gim,\n ],\n description: \"Removing unused dialects from MonkeyPatchable.d.ts\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/MonkeyPatchable.js\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^.*postgres.*$/gim,\n /^.*sqlite.*$/gim,\n /^.*Sqlite.*$/gim,\n ],\n description: \"Removing unused dialects from MonkeyPatchable.js\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/dialects/index.js\",\n deleteLines: [/^.*mssql.*$/gim, /^.*MsSql.*$/gim, /^.*postgresql.*$/gim, /^.*sqlite.*$/gim],\n description: \"Removing unused dialects from @mikro-orm/knex/dialects/index.js\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/mssql\",\n description: \"Removing mssql dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/postgresql\",\n description: \"Removing postgresql dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/sqlite\",\n description: \"Removing sqlite dialect from MikroORM\",\n },\n\n // 🔄 Fix Webpack `Critical dependency: the request of a dependency is an expression`\n {\n file: \"node_modules/@mikro-orm/core/utils/Configuration.js\",\n search: /dynamicImportProvider:\\s*\\/\\* istanbul ignore next \\*\\/\\s*\\(id\\) => import\\(id\\),/g,\n replace: \"dynamicImportProvider: /* istanbul ignore next */ () => Promise.resolve({}),\",\n description: \"Fixing dynamic imports in MikroORM Configuration\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /static dynamicImportProvider = \\(id\\) => import\\(id\\);/g,\n replace: \"static dynamicImportProvider = () => Promise.resolve({});\",\n description: \"Fixing dynamic imports in MikroORM Utils.js\",\n },\n\n // 🛑 Remove deprecated `require.extensions` usage\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /\\s\\|\\|\\s*\\(require\\.extensions\\s*&&\\s*!!require\\.extensions\\['\\.ts'\\]\\);\\s*/g,\n replace: \";\",\n description: \"Removing deprecated `require.extensions` check in MikroORM\",\n },\n\n // 🛠️ Patch Knex to remove `Migrator` and `Seeder`\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n deleteLines: [\n /^const \\{ Migrator \\} = require\\('\\.\\.\\/migrations\\/migrate\\/Migrator'\\);$/gm,\n /^const Seeder = require\\('\\.\\.\\/migrations\\/seed\\/Seeder'\\);$/gm,\n ],\n description: \"Removing `Migrator` and `Seeder` requires from make-knex.js\",\n },\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n search: /\\sreturn new Migrator\\(this\\);/g,\n replace: \"return null;\",\n description: \"Replacing `return new Migrator(this);` with `return null;`\",\n },\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n search: /\\sreturn new Seeder\\(this\\);/g,\n replace: \"return null;\",\n description: \"Replacing `return new Seeder(this);` with `return null;`\",\n },\n // 🔄 Patch for MikroORM Entity Generator to use 'forge-sql-orm'\n // {\n // file: \"node_modules/@mikro-orm/entity-generator/SourceFile.js\",\n // search: /^.* from '@mikro-orm.*$/gim,\n // replace: \" }).join(', '))} } from 'forge-sql-orm';`);\",\n // description: \"Replacing entity generator imports with 'forge-sql-orm'\"\n // },\n {\n file: \"node_modules/knex/lib/dialects/index.js\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^.*postgresql.*$/gim,\n /^.*sqlite.*$/gim,\n /^.*oracle.*$/gim,\n /^.*oracledb.*$/gim,\n /^.*pgnative.*$/gim,\n /^.*postgres.*$/gim,\n /^.*redshift.*$/gim,\n /^.*sqlite3.*$/gim,\n /^.*cockroachdb.*$/gim,\n ],\n description: \"Removing unused dialects from @mikro-orm/knex/dialects/index.js\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /\\s\\|\\|\\s*\\(require\\.extensions\\s*&&\\s*!!require\\.extensions\\['\\.ts'\\]\\);\\s*/g,\n replace: \";\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /^.*extensions.*$/gim,\n replace: \"{\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /^.*package.json.*$/gim,\n replace: \"return 0;\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/dialects/mysql/index.js\",\n deleteLines: [/^.*MariaDbKnexDialect.*$/gim],\n description: \"Removing MariaDbKnexDialect\",\n },\n];\n\n/**\n * Runs the MikroORM & Knex patching logic.\n */\nexport function runPostInstallPatch() {\n console.log(\"🔧 Applying MikroORM & Knex patches...\");\n PATCHES.forEach(\n ({ file, search, replace, deleteLines, deleteFile, deleteFolder, description }) => {\n if (file) {\n const filePath = path.resolve(file);\n if (fs.existsSync(filePath)) {\n let content = fs.readFileSync(filePath, \"utf8\");\n let originalContent = content;\n\n // 🔄 Replace text\n if (search && replace) {\n if (typeof search === \"string\" ? content.includes(search) : search.test(content)) {\n content = content.replace(search, replace);\n console.log(`[PATCHED] ${description}`);\n }\n }\n\n // 🗑️ Remove matching lines\n if (deleteLines) {\n deleteLines.forEach((pattern) => {\n content = content\n .split(\"\\n\")\n .filter((line) => !pattern.test(line))\n .join(\"\\n\");\n });\n if (content !== originalContent) {\n console.log(`[CLEANED] Removed matching lines in ${file}`);\n }\n }\n\n // 💾 Save changes only if file was modified\n if (content !== originalContent) {\n fs.writeFileSync(filePath, content, \"utf8\");\n }\n\n // 🚮 Remove empty files\n if (content.trim() === \"\") {\n fs.unlinkSync(filePath);\n console.log(`[REMOVED] ${filePath} (file is now empty)`);\n }\n } else {\n console.warn(`[WARNING] File not found: ${file}`);\n }\n }\n\n // 🚮 Delete specific files\n if (deleteFile) {\n const deleteFilePath = path.resolve(__dirname, \"../\", deleteFile);\n if (fs.existsSync(deleteFilePath)) {\n fs.unlinkSync(deleteFilePath);\n console.log(`[DELETED] ${description}`);\n }\n }\n\n // 🚮 Delete entire folders\n if (deleteFolder) {\n const deleteFolderPath = path.resolve(__dirname, \"../\", deleteFolder);\n if (fs.existsSync(deleteFolderPath)) {\n fs.rmSync(deleteFolderPath, { recursive: true, force: true });\n console.log(`[DELETED] ${description}`);\n }\n }\n },\n );\n\n console.log(\"🎉 MikroORM & Knex patching completed!\");\n}\n","#!/usr/bin/env node\n\nimport { Command } from \"commander\";\nimport dotenv from \"dotenv\";\nimport inquirer from \"inquirer\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { generateModels } from \"./actions/generate-models\";\nimport { createMigration } from \"./actions/migrations-create\";\nimport { updateMigration } from \"./actions/migrations-update\";\nimport { runPostInstallPatch } from \"./actions/PatchPostinstall\";\n\nconst ENV_PATH = path.resolve(process.cwd(), \".env\");\n// 🔄 Load environment variables from `.env` file\ndotenv.config({ path: ENV_PATH });\n\nconst saveEnvFile = (config: any) => {\n let envContent = \"\";\n const envFilePath = ENV_PATH;\n\n if (fs.existsSync(envFilePath)) {\n envContent = fs.readFileSync(envFilePath, \"utf8\");\n }\n\n const envVars = envContent\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\" && !line.startsWith(\"#\"))\n .reduce((acc: any, line) => {\n const [key, ...value] = line.split(\"=\");\n acc[key] = value.join(\"=\");\n return acc;\n }, {});\n\n Object.entries(config).forEach(([key, value]) => {\n envVars[`FORGE_SQL_ORM_${key.toUpperCase()}`] = value;\n });\n\n const updatedEnvContent = Object.entries(envVars)\n .map(([key, value]) => `${key}=${value}`)\n .join(\"\\n\");\n\n fs.writeFileSync(envFilePath, updatedEnvContent, { encoding: \"utf8\" });\n\n console.log(\"✅ Configuration saved to .env without overwriting other variables.\");\n};\n\n/**\n * Prompts the user for missing parameters using Inquirer.js.\n * @param config - The current configuration object.\n * @param defaultOutput - Default output path.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns Updated configuration with user input.\n */\nconst askMissingParams = async (\n config: any,\n defaultOutput: string,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n const questions: unknown[] = [];\n\n if (!config.host)\n questions.push({\n type: \"input\",\n name: \"host\",\n message: \"Enter database host:\",\n default: \"localhost\",\n });\n\n if (!config.port)\n questions.push({\n type: \"input\",\n name: \"port\",\n message: \"Enter database port:\",\n default: \"3306\",\n validate: (input: string) => !isNaN(parseInt(input, 10)),\n });\n\n if (!config.user)\n questions.push({\n type: \"input\",\n name: \"user\",\n message: \"Enter database user:\",\n default: \"root\",\n });\n\n if (!config.password)\n questions.push({\n type: \"password\",\n name: \"password\",\n message: \"Enter database password:\",\n mask: \"*\",\n });\n\n if (!config.dbName)\n questions.push({\n type: \"input\",\n name: \"dbName\",\n message: \"Enter database name:\",\n });\n\n if (!config.output)\n questions.push({\n type: \"input\",\n name: \"output\",\n message: \"Enter output path:\",\n default: defaultOutput,\n });\n\n // Allow additional questions from the caller\n if (customAskMissingParams) {\n customAskMissingParams(config, questions);\n }\n\n // If there are missing parameters, prompt the user\n if (questions.length > 0) {\n // @ts-ignore - Ignore TypeScript warning for dynamic question type\n const answers = await inquirer.prompt(questions);\n return { ...config, ...answers, port: parseInt(config.port ?? answers.port, 10) };\n }\n\n return config;\n};\n\n/**\n * Retrieves configuration parameters from command-line arguments and environment variables.\n * If any required parameters are missing, prompts the user for input.\n * @param cmd - The command object containing CLI options.\n * @param defaultOutput - Default output directory.\n * @param customConfig - Optional function for additional configuration parameters.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns A fully resolved configuration object.\n */\nconst getConfig = async (\n cmd: any,\n defaultOutput: string,\n customConfig?: () => any,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n let config = {\n host: cmd.host || process.env.FORGE_SQL_ORM_HOST,\n port: cmd.port\n ? parseInt(cmd.port, 10)\n : process.env.FORGE_SQL_ORM_PORT\n ? parseInt(process.env.FORGE_SQL_ORM_PORT, 10)\n : undefined,\n user: cmd.user || process.env.FORGE_SQL_ORM_USER,\n password: cmd.password || process.env.FORGE_SQL_ORM_PASSWORD,\n dbName: cmd.dbName || process.env.FORGE_SQL_ORM_DBNAME,\n output: cmd.output || process.env.FORGE_SQL_ORM_OUTPUT,\n };\n\n // Merge additional configurations if provided\n if (customConfig) {\n config = { ...config, ...customConfig() };\n }\n\n const conf = await askMissingParams(config, defaultOutput, customAskMissingParams);\n if (cmd.saveEnv) {\n saveEnvFile(conf);\n }\n return conf;\n};\n\n// 📌 Initialize CLI\nconst program = new Command();\nprogram.version(\"1.0.0\");\n\n// ✅ Command: Generate database models (Entities)\nprogram\n .command(\"generate:model\")\n .description(\"Generate MikroORM models from the database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for entities\")\n .option(\"--versionField <string>\", \"Field name for versioning\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/entities\",\n () => ({\n versionField: cmd.versionField || process.env.FORGE_SQL_ORM_VERSIONFIELD,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.versionField) {\n questions.push({\n type: \"input\",\n name: \"versionField\",\n message: \"Enter the field name for versioning (leave empty to skip):\",\n default: \"\",\n });\n }\n },\n );\n await generateModels(config);\n });\n\n// ✅ Command: Create initial database migration\nprogram\n .command(\"migrations:create\")\n .description(\"Generate an initial migration for the entire database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await createMigration(config);\n });\n\n// ✅ Command: Update migration for schema changes\nprogram\n .command(\"migrations:update\")\n .description(\"Generate a migration to update the database schema.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await updateMigration(config);\n });\n\n// Patch MikroORM and Knex\nprogram\n .command(\"patch:mikroorm\")\n .description(\"Patch MikroORM and Knex dependencies to work properly with Forge\")\n .action(async () => {\n console.log(\"Running MikroORM patch...\");\n await runPostInstallPatch();\n await runPostInstallPatch();\n await runPostInstallPatch();\n console.log(\"✅ MikroORM patch applied successfully!\");\n });\n\n// 🔥 Execute CLI\nprogram.parse(process.argv);\n"],"names":["defineConfig","MongoNamingStrategy","EntityGenerator","MikroORM","cleanSQLStatement","generateMigrationFile","saveMigrationFiles","extractCreateStatements","loadEntities","loadMigrationVersion","Command"],"mappings":";;;;;;;;;;AAOA,MAAM,sBAAsB,CAAC,eAAuB;AAC5C,QAAA,cAAc,KAAK,QAAQ,UAAU;AAC3C,QAAM,YAAY,KAAK,KAAK,aAAa,UAAU;AAEnD,QAAM,cAAc,GACjB,YAAY,WAAW,EACvB,OAAO,CAAC,SAAS,KAAK,SAAS,KAAK,KAAK,SAAS,UAAU;AAE/D,QAAM,UAAU,YAAY,IAAI,CAAC,SAAS;AACxC,UAAM,aAAa,KAAK,SAAS,MAAM,KAAK;AACrC,WAAA,YAAY,UAAU,cAAc,UAAU;AAAA,EAAA,CACtD;AAED,QAAM,eAAe,GAAG,QAAQ,KAAK,IAAI,CAAC;AAAA;AAAA,kBAAuB,YAAY,IAAI,CAAC,SAAS,KAAK,SAAS,MAAM,KAAK,CAAC,EAAE,KAAK,IAAI,CAAC;AAAA;AAE9H,KAAA,cAAc,WAAW,cAAc,MAAM;AAChD,UAAQ,IAAI,2BAA2B,YAAY,MAAM,YAAY;AACvE;AAEa,MAAA,iBAAiB,OAAO,YAAiB;AAChD,MAAA;AACF,UAAM,YAAYA,MAAAA,aAAa;AAAA,MAC7B,MAAM,QAAQ;AAAA,MACd,MAAM,QAAQ;AAAA,MACd,MAAM,QAAQ;AAAA,MACd,UAAU,QAAQ;AAAA,MAClB,QAAQ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P,kBAAU,KAAK;AAAA,UACb,MAAM;AAAA,UACN,MAAM;AAAA,UACN,SAAS;AAAA,UACT,SAAS;AAAA,QAAA,CACV;AAAA,IAAA;AAAA,EAEP;AACA,QAAM,gBAAgB,MAAM;AAC9B,CAAC;AAGH,QACG,QAAQ,mBAAmB,EAC3B,YAAY,qDAAqD,EACjE,OAAO,mBAAmB,eAAe,EACzC,OAAO,mBAAmB,eAAe,EACzC,OAAO,mBAAmB,eAAe,EACzC,OAAO,uBAAuB,mBAAmB,EACjD,OAAO,qBAAqB,eAAe,EAC3C,OAAO,qBAAqB,4BAA4B,EACxD,OAAO,2BAA2B,wCAAwC,EAC1E,OAAO,aAAa,iCAAiC,EACrD,OAAO,OAAO,QAAQ;AACrB,QAAM,SAAS,MAAM;AAAA,IACnB;AAAA,IACA;AAAA,IACA,OAAO;AAAA,MACL,cAAc,IAAI,gBAAgB,QAAQ,IAAI;AAAA,IAAA;AAAA,IAEhD,CAAC,KAAK,cAAyB;AAC7B,UAAI,CAAC,IAAI;AACP,kBAAU,KAAK;AAAA,UACb,MAAM;AAAA,UACN,MAAM;AAAA,UACN,SAAS;AAAA,UACT,SAAS;AAAA,QAAA,CACV;AAAA,IAAA;AAAA,EAEP;AACA,QAAM,gBAAgB,MAAM;AAC9B,CAAC;AAGH,QACG,QAAQ,gBAAgB,EACxB,YAAY,kEAAkE,EAC9E,OAAO,YAAY;AAClB,UAAQ,IAAI,2BAA2B;AACvC,QAAM,oBAAoB;AAC1B,QAAM,oBAAoB;AAC1B,QAAM,oBAAoB;AAC1B,UAAQ,IAAI,wCAAwC;AACtD,CAAC;AAGH,QAAQ,MAAM,QAAQ,IAAI;"}
|
|
1
|
+
{"version":3,"file":"cli.js","sources":["../scripts/actions/generate-models.ts","../scripts/actions/migrations-create.ts","../scripts/actions/migrations-update.ts","../scripts/actions/PatchPostinstall.ts","../scripts/cli.ts"],"sourcesContent":["import \"reflect-metadata\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { defineConfig, MikroORM, MongoNamingStrategy } from \"@mikro-orm/mysql\";\nimport { EntityGenerator } from \"@mikro-orm/entity-generator\";\nimport { EntityMetadata } from \"@mikro-orm/core/typings\";\n\nconst regenerateIndexFile = (outputPath: string) => {\n const entitiesDir = path.resolve(outputPath);\n const indexPath = path.join(entitiesDir, \"index.ts\");\n\n const entityFiles = fs\n .readdirSync(entitiesDir)\n .filter((file) => file.endsWith(\".ts\") && file !== \"index.ts\");\n\n const imports = entityFiles.map((file) => {\n const entityName = path.basename(file, \".ts\");\n return `import { ${entityName} } from \"./${entityName}\";`;\n });\n\n const indexContent = `${imports.join(\"\\n\")}\\n\\nexport default [${entityFiles.map((file) => path.basename(file, \".ts\")).join(\", \")}];\\n`;\n\n fs.writeFileSync(indexPath, indexContent, \"utf8\");\n console.log(`✅ Updated index.ts with ${entityFiles.length} entities.`);\n};\n\nexport const generateModels = async (options: any) => {\n try {\n const ormConfig = defineConfig({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n namingStrategy: MongoNamingStrategy,\n discovery: { warnWhenNoEntities: false },\n extensions: [EntityGenerator],\n debug: true,\n }) as Parameters<typeof MikroORM.initSync>[0];\n\n const orm = MikroORM.initSync(ormConfig);\n console.log(`✅ Connected to ${options.dbName} at ${options.host}:${options.port}`);\n\n const onCreatingVersionField = async (metadatas: EntityMetadata[]) => {\n metadatas.forEach((m) => {\n if (options.versionField) {\n const versionFieldName = Object.keys(m.properties).find((p) => {\n return (\n p === options.versionField ||\n m.properties[p]?.name === options.versionField ||\n m.properties[p]?.fieldNames?.find((f) => f === options.versionField)\n );\n });\n if (versionFieldName) {\n const property = m.properties[versionFieldName];\n if (\n property.type !== \"datetime\" &&\n property.type !== \"integer\" &&\n property.type !== \"decimal\"\n ) {\n console.warn(\n `Version field \"${property.name}\" can be only datetime or integer Table ${m.tableName} but now is \"${property.type}\"`,\n );\n return;\n }\n if (property.primary) {\n console.warn(\n `Version field \"${property.name}\" can not be primary key Table ${m.tableName}`,\n );\n return;\n }\n if (property.nullable) {\n console.warn(\n `Version field \"${property.name}\" should not be nullable Table ${m.tableName}`,\n );\n return;\n }\n property.version = true;\n }\n }\n });\n };\n await orm.entityGenerator.generate({\n entitySchema: true,\n bidirectionalRelations: true,\n identifiedReferences: false,\n forceUndefined: true,\n undefinedDefaults: true,\n useCoreBaseEntity: false,\n onlyPurePivotTables: false,\n outputPurePivotTables: false,\n scalarPropertiesForRelations: \"always\",\n save: true,\n path: options.output,\n onInitialMetadata: onCreatingVersionField,\n });\n\n regenerateIndexFile(options.output);\n\n console.log(`✅ Entities generated at: ${options.output}`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error generating entities:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MikroORM } from \"@mikro-orm/mysql\";\nimport { execSync } from \"child_process\";\nimport { rmSync } from \"fs\";\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nfunction cleanSQLStatement(sql: string): string {\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \\\"${cleanSQLStatement(stmt)}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nconst extractCreateStatements = (schema: string): string[] => {\n const statements = schema.split(\";\").map((s) => s.trim());\n\n return statements.filter(\n (stmt) =>\n stmt.startsWith(\"create table\") ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add index\")) ||\n stmt.startsWith(\"primary\"),\n );\n};\n\n/**\n * Dynamically loads `entities` from `index.ts` in the specified directory.\n * @param entitiesPath - Path to the directory containing `index.ts`.\n * @returns Array of entity classes.\n */\nconst loadEntities = async (entitiesPath: string) => {\n try {\n const indexFilePath = path.resolve(path.join(entitiesPath, \"index.ts\"));\n if (!fs.existsSync(indexFilePath)) {\n console.error(`❌ Error: index.ts not found in ${indexFilePath}`);\n process.exit(1);\n }\n\n const { default: entities } = await import(indexFilePath);\n console.log(`✅ Loaded ${entities.length} entities from ${entitiesPath}`);\n return entities;\n } catch (error) {\n console.error(`❌ Error loading index.ts from ${entitiesPath}:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const createMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version > 0) {\n console.error(`❌ Error: Migration has already been created.`);\n process.exit(1);\n }\n\n // Start from version 1 if no previous migrations exist\n version = 1;\n\n // Load entities dynamically from index.ts\n const entities = await loadEntities(options.entitiesPath);\n\n // Initialize MikroORM\n const orm = MikroORM.initSync({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n entities: entities,\n });\n\n // Generate SQL schema\n const createSchemaSQL = await orm.schema.getCreateSchemaSQL({ wrap: true });\n const statements = extractCreateStatements(createSchemaSQL);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(statements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MikroORM } from \"@mikro-orm/mysql\";\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nfunction cleanSQLStatement(sql: string): string {\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \\\"${cleanSQLStatement(stmt)}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nconst extractCreateStatements = (schema: string): string[] => {\n const statements = schema.split(\";\").map((s) => s.trim());\n\n return statements.filter(\n (stmt) =>\n stmt.startsWith(\"create table\") ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add index\")) ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add\") && !stmt.includes(\"foreign\")) ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"modify\") && !stmt.includes(\"foreign\")),\n );\n};\n\n/**\n * Dynamically loads `entities` from `index.ts` in the specified directory.\n * @param entitiesPath - Path to the directory containing `index.ts`.\n * @returns Array of entity classes.\n */\nconst loadEntities = async (entitiesPath: string) => {\n try {\n const indexFilePath = path.resolve(path.join(entitiesPath, \"index.ts\"));\n if (!fs.existsSync(indexFilePath)) {\n console.error(`❌ Error: index.ts not found in ${entitiesPath}`);\n process.exit(1);\n }\n\n const { default: entities } = await import(indexFilePath);\n console.log(`✅ Loaded ${entities.length} entities from ${entitiesPath}`);\n return entities;\n } catch (error) {\n console.error(`❌ Error loading index.ts from ${entitiesPath}:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.warn(\n `⚠️ Warning: migrationCount.ts not found in ${migrationCountFilePath}, assuming no previous migrations.`,\n );\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Updates an existing database migration by generating schema modifications.\n * @param options - Database connection settings and output paths.\n */\nexport const updateMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version < 1) {\n console.log(\n `⚠️ Initial migration not found. Run \"npx forge-sql-orm migrations:create\" first.`,\n );\n process.exit(0);\n }\n version += 1;\n\n // Load entities dynamically from index.ts\n const entities = await loadEntities(options.entitiesPath);\n\n // Initialize MikroORM\n const orm = MikroORM.initSync({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n entities,\n debug: true,\n });\n\n // Generate SQL schema updates\n const createSchemaSQL = await orm.schema.getUpdateSchemaMigrationSQL({ wrap: true });\n const statements = extractCreateStatements(createSchemaSQL?.down || \"\");\n\n if (statements.length) {\n const migrationFile = generateMigrationFile(statements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully updated!`);\n process.exit(0);\n } else {\n console.log(`⚠️ No new migration changes detected.`);\n process.exit(0);\n }\n } catch (error) {\n console.error(`❌ Error during migration update:`, error);\n process.exit(1);\n }\n};\n","import fs from \"fs\";\nimport path from \"path\";\n\n/**\n * Automates patches for MikroORM and Knex to fix Webpack issues.\n * - Removes problematic `require()` calls.\n * - Deletes unnecessary files and folders.\n * - Fixes dynamic imports (`import(id)`) in MikroORM.\n */\n\ninterface Patch {\n file?: string; // File to modify (optional)\n search?: RegExp; // Regex pattern to find problematic code\n replace?: string; // Replacement string for problematic code\n deleteLines?: RegExp[]; // List of regex patterns to remove specific lines\n description: string; // Description of the patch\n deleteFile?: string; // Path of the file to delete (optional)\n deleteFolder?: string; // Path of the folder to delete (optional)\n}\n\nconst PATCHES: Patch[] = [\n // 🗑️ Remove unused dialects (mssql, postgres, sqlite) in MikroORM\n {\n file: \"node_modules/@mikro-orm/knex/MonkeyPatchable.d.ts\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^\\s*Postgres.*$/gm,\n /^.*Sqlite3.*$/gm,\n /^.*BetterSqlite3.*$/gim,\n ],\n description: \"Removing unused dialects from MonkeyPatchable.d.ts\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/MonkeyPatchable.js\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^.*postgres.*$/gim,\n /^.*sqlite.*$/gim,\n /^.*Sqlite.*$/gim,\n ],\n description: \"Removing unused dialects from MonkeyPatchable.js\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/dialects/index.js\",\n deleteLines: [/^.*mssql.*$/gim, /^.*MsSql.*$/gim, /^.*postgresql.*$/gim, /^.*sqlite.*$/gim],\n description: \"Removing unused dialects from @mikro-orm/knex/dialects/index.js\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/mssql\",\n description: \"Removing mssql dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/postgresql\",\n description: \"Removing postgresql dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/sqlite\",\n description: \"Removing sqlite dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/mysql/node_modules\",\n description: \"Removing sqlite dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/node_modules\",\n description: \"Removing sqlite dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/core/node_modules\",\n description: \"Removing sqlite dialect from MikroORM\",\n },\n\n // 🔄 Fix Webpack `Critical dependency: the request of a dependency is an expression`\n {\n file: \"node_modules/@mikro-orm/core/utils/Configuration.js\",\n search: /dynamicImportProvider:\\s*\\/\\* istanbul ignore next \\*\\/\\s*\\(id\\) => import\\(id\\),/g,\n replace: \"dynamicImportProvider: /* istanbul ignore next */ () => Promise.resolve({}),\",\n description: \"Fixing dynamic imports in MikroORM Configuration\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /static dynamicImportProvider = \\(id\\) => import\\(id\\);/g,\n replace: \"static dynamicImportProvider = () => Promise.resolve({});\",\n description: \"Fixing dynamic imports in MikroORM Utils.js\",\n },\n\n // 🛑 Remove deprecated `require.extensions` usage\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /\\s\\|\\|\\s*\\(require\\.extensions\\s*&&\\s*!!require\\.extensions\\['\\.ts'\\]\\);\\s*/g,\n replace: \";\",\n description: \"Removing deprecated `require.extensions` check in MikroORM\",\n },\n\n // 🛠️ Patch Knex to remove `Migrator` and `Seeder`\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n deleteLines: [\n /^const \\{ Migrator \\} = require\\('\\.\\.\\/migrations\\/migrate\\/Migrator'\\);$/gm,\n /^const Seeder = require\\('\\.\\.\\/migrations\\/seed\\/Seeder'\\);$/gm,\n ],\n description: \"Removing `Migrator` and `Seeder` requires from make-knex.js\",\n },\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n search: /\\sreturn new Migrator\\(this\\);/g,\n replace: \"return null;\",\n description: \"Replacing `return new Migrator(this);` with `return null;`\",\n },\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n search: /\\sreturn new Seeder\\(this\\);/g,\n replace: \"return null;\",\n description: \"Replacing `return new Seeder(this);` with `return null;`\",\n },\n {\n file: \"node_modules/knex/lib/dialects/index.js\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^.*postgresql.*$/gim,\n /^.*sqlite.*$/gim,\n /^.*oracle.*$/gim,\n /^.*oracledb.*$/gim,\n /^.*pgnative.*$/gim,\n /^.*postgres.*$/gim,\n /^.*redshift.*$/gim,\n /^.*sqlite3.*$/gim,\n /^.*cockroachdb.*$/gim,\n ],\n description: \"Removing unused dialects from @mikro-orm/knex/dialects/index.js\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /\\s\\|\\|\\s*\\(require\\.extensions\\s*&&\\s*!!require\\.extensions\\['\\.ts'\\]\\);\\s*/g,\n replace: \";\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /^.*extensions.*$/gim,\n replace: \"{\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /^.*package.json.*$/gim,\n replace: \"return 0;\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/dialects/mysql/index.js\",\n deleteLines: [/^.*MariaDbKnexDialect.*$/gim],\n description: \"Removing MariaDbKnexDialect\",\n },\n];\n\n/**\n * Runs the MikroORM & Knex patching logic.\n */\nexport function runPostInstallPatch() {\n console.log(\"🔧 Applying MikroORM & Knex patches...\");\n PATCHES.forEach(\n ({ file, search, replace, deleteLines, deleteFile, deleteFolder, description }) => {\n if (file) {\n const filePath = path.resolve(file);\n if (fs.existsSync(filePath)) {\n let content = fs.readFileSync(filePath, \"utf8\");\n let originalContent = content;\n\n // 🔄 Replace text\n if (search && replace) {\n if (typeof search === \"string\" ? content.includes(search) : search.test(content)) {\n content = content.replace(search, replace);\n console.log(`[PATCHED] ${description}`);\n }\n }\n\n // 🗑️ Remove matching lines\n if (deleteLines) {\n deleteLines.forEach((pattern) => {\n content = content\n .split(\"\\n\")\n .filter((line) => !pattern.test(line))\n .join(\"\\n\");\n });\n if (content !== originalContent) {\n console.log(`[CLEANED] Removed matching lines in ${file}`);\n }\n }\n\n // 💾 Save changes only if file was modified\n if (content !== originalContent) {\n fs.writeFileSync(filePath, content, \"utf8\");\n }\n\n // 🚮 Remove empty files\n if (content.trim() === \"\") {\n fs.unlinkSync(filePath);\n console.log(`[REMOVED] ${filePath} (file is now empty)`);\n }\n } else {\n console.warn(`[WARNING] File not found: ${file}`);\n }\n }\n\n // 🚮 Delete specific files\n if (deleteFile) {\n const deleteFilePath = path.resolve(__dirname, \"../\", deleteFile);\n if (fs.existsSync(deleteFilePath)) {\n fs.unlinkSync(deleteFilePath);\n console.log(`[DELETED] ${description}`);\n }\n }\n\n // 🚮 Delete entire folders\n if (deleteFolder) {\n const deleteFolderPath = path.resolve(__dirname, \"../\", deleteFolder);\n if (fs.existsSync(deleteFolderPath)) {\n fs.rmSync(deleteFolderPath, { recursive: true, force: true });\n console.log(`[DELETED] ${description}`);\n }\n }\n },\n );\n\n console.log(\"🎉 MikroORM & Knex patching completed!\");\n}\n","#!/usr/bin/env node\n\nimport { Command } from \"commander\";\nimport dotenv from \"dotenv\";\nimport inquirer from \"inquirer\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { generateModels } from \"./actions/generate-models\";\nimport { createMigration } from \"./actions/migrations-create\";\nimport { updateMigration } from \"./actions/migrations-update\";\nimport { runPostInstallPatch } from \"./actions/PatchPostinstall\";\n\nconst ENV_PATH = path.resolve(process.cwd(), \".env\");\n// 🔄 Load environment variables from `.env` file\ndotenv.config({ path: ENV_PATH });\n\nconst saveEnvFile = (config: any) => {\n let envContent = \"\";\n const envFilePath = ENV_PATH;\n\n if (fs.existsSync(envFilePath)) {\n envContent = fs.readFileSync(envFilePath, \"utf8\");\n }\n\n const envVars = envContent\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\" && !line.startsWith(\"#\"))\n .reduce((acc: any, line) => {\n const [key, ...value] = line.split(\"=\");\n acc[key] = value.join(\"=\");\n return acc;\n }, {});\n\n Object.entries(config).forEach(([key, value]) => {\n envVars[`FORGE_SQL_ORM_${key.toUpperCase()}`] = value;\n });\n\n const updatedEnvContent = Object.entries(envVars)\n .map(([key, value]) => `${key}=${value}`)\n .join(\"\\n\");\n\n fs.writeFileSync(envFilePath, updatedEnvContent, { encoding: \"utf8\" });\n\n console.log(\"✅ Configuration saved to .env without overwriting other variables.\");\n};\n\n/**\n * Prompts the user for missing parameters using Inquirer.js.\n * @param config - The current configuration object.\n * @param defaultOutput - Default output path.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns Updated configuration with user input.\n */\nconst askMissingParams = async (\n config: any,\n defaultOutput: string,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n const questions: unknown[] = [];\n\n if (!config.host)\n questions.push({\n type: \"input\",\n name: \"host\",\n message: \"Enter database host:\",\n default: \"localhost\",\n });\n\n if (!config.port)\n questions.push({\n type: \"input\",\n name: \"port\",\n message: \"Enter database port:\",\n default: \"3306\",\n validate: (input: string) => !isNaN(parseInt(input, 10)),\n });\n\n if (!config.user)\n questions.push({\n type: \"input\",\n name: \"user\",\n message: \"Enter database user:\",\n default: \"root\",\n });\n\n if (!config.password)\n questions.push({\n type: \"password\",\n name: \"password\",\n message: \"Enter database password:\",\n mask: \"*\",\n });\n\n if (!config.dbName)\n questions.push({\n type: \"input\",\n name: \"dbName\",\n message: \"Enter database name:\",\n });\n\n if (!config.output)\n questions.push({\n type: \"input\",\n name: \"output\",\n message: \"Enter output path:\",\n default: defaultOutput,\n });\n\n // Allow additional questions from the caller\n if (customAskMissingParams) {\n customAskMissingParams(config, questions);\n }\n\n // If there are missing parameters, prompt the user\n if (questions.length > 0) {\n // @ts-ignore - Ignore TypeScript warning for dynamic question type\n const answers = await inquirer.prompt(questions);\n return { ...config, ...answers, port: parseInt(config.port ?? answers.port, 10) };\n }\n\n return config;\n};\n\n/**\n * Retrieves configuration parameters from command-line arguments and environment variables.\n * If any required parameters are missing, prompts the user for input.\n * @param cmd - The command object containing CLI options.\n * @param defaultOutput - Default output directory.\n * @param customConfig - Optional function for additional configuration parameters.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns A fully resolved configuration object.\n */\nconst getConfig = async (\n cmd: any,\n defaultOutput: string,\n customConfig?: () => any,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n let config = {\n host: cmd.host || process.env.FORGE_SQL_ORM_HOST,\n port: cmd.port\n ? parseInt(cmd.port, 10)\n : process.env.FORGE_SQL_ORM_PORT\n ? parseInt(process.env.FORGE_SQL_ORM_PORT, 10)\n : undefined,\n user: cmd.user || process.env.FORGE_SQL_ORM_USER,\n password: cmd.password || process.env.FORGE_SQL_ORM_PASSWORD,\n dbName: cmd.dbName || process.env.FORGE_SQL_ORM_DBNAME,\n output: cmd.output || process.env.FORGE_SQL_ORM_OUTPUT,\n };\n\n // Merge additional configurations if provided\n if (customConfig) {\n config = { ...config, ...customConfig() };\n }\n\n const conf = await askMissingParams(config, defaultOutput, customAskMissingParams);\n if (cmd.saveEnv) {\n saveEnvFile(conf);\n }\n return conf;\n};\n\n// 📌 Initialize CLI\nconst program = new Command();\nprogram.version(\"1.0.0\");\n\n// ✅ Command: Generate database models (Entities)\nprogram\n .command(\"generate:model\")\n .description(\"Generate MikroORM models from the database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for entities\")\n .option(\"--versionField <string>\", \"Field name for versioning\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/entities\",\n () => ({\n versionField: cmd.versionField || process.env.FORGE_SQL_ORM_VERSIONFIELD,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.versionField) {\n questions.push({\n type: \"input\",\n name: \"versionField\",\n message: \"Enter the field name for versioning (leave empty to skip):\",\n default: \"\",\n });\n }\n },\n );\n await generateModels(config);\n });\n\n// ✅ Command: Create initial database migration\nprogram\n .command(\"migrations:create\")\n .description(\"Generate an initial migration for the entire database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await createMigration(config);\n });\n\n// ✅ Command: Update migration for schema changes\nprogram\n .command(\"migrations:update\")\n .description(\"Generate a migration to update the database schema.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await updateMigration(config);\n });\n\n// Patch MikroORM and Knex\nprogram\n .command(\"patch:mikroorm\")\n .description(\"Patch MikroORM and Knex dependencies to work properly with Forge\")\n .action(async () => {\n console.log(\"Running MikroORM patch...\");\n await runPostInstallPatch();\n await runPostInstallPatch();\n await runPostInstallPatch();\n console.log(\"✅ MikroORM patch applied successfully!\");\n });\n\n// 🔥 Execute CLI\nprogram.parse(process.argv);\n"],"names":["defineConfig","MongoNamingStrategy","EntityGenerator","MikroORM","cleanSQLStatement","generateMigrationFile","saveMigrationFiles","extractCreateStatements","loadEntities","loadMigrationVersion","Command"],"mappings":";;;;;;;;;;AAOA,MAAM,sBAAsB,CAAC,eAAuB;AAC5C,QAAA,cAAc,KAAK,QAAQ,UAAU;AAC3C,QAAM,YAAY,KAAK,KAAK,aAAa,UAAU;AAEnD,QAAM,cAAc,GACjB,YAAY,WAAW,EACvB,OAAO,CAAC,SAAS,KAAK,SAAS,KAAK,KAAK,SAAS,UAAU;AAE/D,QAAM,UAAU,YAAY,IAAI,CAAC,SAAS;AACxC,UAAM,aAAa,KAAK,SAAS,MAAM,KAAK;AACrC,WAAA,YAAY,UAAU,cAAc,UAAU;AAAA,EAAA,CACtD;AAED,QAAM,eAAe,GAAG,QAAQ,KAAK,IAAI,CAAC;AAAA;AAAA,kBAAuB,YAAY,IAAI,CAAC,SAAS,KAAK,SAAS,MAAM,KAAK,CAAC,EAAE,KAAK,IAAI,CAAC;AAAA;AAE9H,KAAA,cAAc,WAAW,cAAc,MAAM;AAChD,UAAQ,IAAI,2BAA2B,YAAY,MAAM,YAAY;AACvE;AAEa,MAAA,iBAAiB,OAAO,YAAiB;AAChD,MAAA;AACF,UAAM,YAAYA,MAAAA,aAAa;AAAA,MAC7B,MAAM,QAAQ;AAAA,MACd,MAAM,QAAQ;AAAA,MACd,MAAM,QAAQ;AAAA,MACd,UAAU,QAAQ;AAAA,MAClB,QAAQ,QAAQ;AAAA,MAChB,gBAAgBC,MAAA;AAAA,MACh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
365
|
description: "Removing sqlite dialect from MikroORM"
|
|
366
366
|
},
|
|
367
|
+
{
|
|
368
|
+
deleteFolder: "node_modules/@mikro-orm/mysql/node_modules",
|
|
369
|
+
description: "Removing sqlite dialect from MikroORM"
|
|
370
|
+
},
|
|
371
|
+
{
|
|
372
|
+
deleteFolder: "node_modules/@mikro-orm/knex/node_modules",
|
|
373
|
+
description: "Removing sqlite dialect from MikroORM"
|
|
374
|
+
},
|
|
375
|
+
{
|
|
376
|
+
deleteFolder: "node_modules/@mikro-orm/core/node_modules",
|
|
377
|
+
description: "Removing sqlite dialect from MikroORM"
|
|
378
|
+
},
|
|
367
379
|
// 🔄 Fix Webpack `Critical dependency: the request of a dependency is an expression`
|
|
368
380
|
{
|
|
369
381
|
file: "node_modules/@mikro-orm/core/utils/Configuration.js",
|
|
@@ -405,13 +417,6 @@ const PATCHES = [
|
|
|
405
417
|
replace: "return null;",
|
|
406
418
|
description: "Replacing `return new Seeder(this);` with `return null;`"
|
|
407
419
|
},
|
|
408
|
-
// 🔄 Patch for MikroORM Entity Generator to use 'forge-sql-orm'
|
|
409
|
-
// {
|
|
410
|
-
// file: "node_modules/@mikro-orm/entity-generator/SourceFile.js",
|
|
411
|
-
// search: /^.* from '@mikro-orm.*$/gim,
|
|
412
|
-
// replace: " }).join(', '))} } from 'forge-sql-orm';`);",
|
|
413
|
-
// description: "Replacing entity generator imports with 'forge-sql-orm'"
|
|
414
|
-
// },
|
|
415
420
|
{
|
|
416
421
|
file: "node_modules/knex/lib/dialects/index.js",
|
|
417
422
|
deleteLines: [
|
package/dist-cli/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","sources":["../scripts/actions/generate-models.ts","../scripts/actions/migrations-create.ts","../scripts/actions/migrations-update.ts","../scripts/actions/PatchPostinstall.ts","../scripts/cli.ts"],"sourcesContent":["import \"reflect-metadata\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { defineConfig, MikroORM, MongoNamingStrategy } from \"@mikro-orm/mysql\";\nimport { EntityGenerator } from \"@mikro-orm/entity-generator\";\nimport { EntityMetadata } from \"@mikro-orm/core/typings\";\n\nconst regenerateIndexFile = (outputPath: string) => {\n const entitiesDir = path.resolve(outputPath);\n const indexPath = path.join(entitiesDir, \"index.ts\");\n\n const entityFiles = fs\n .readdirSync(entitiesDir)\n .filter((file) => file.endsWith(\".ts\") && file !== \"index.ts\");\n\n const imports = entityFiles.map((file) => {\n const entityName = path.basename(file, \".ts\");\n return `import { ${entityName} } from \"./${entityName}\";`;\n });\n\n const indexContent = `${imports.join(\"\\n\")}\\n\\nexport default [${entityFiles.map((file) => path.basename(file, \".ts\")).join(\", \")}];\\n`;\n\n fs.writeFileSync(indexPath, indexContent, \"utf8\");\n console.log(`✅ Updated index.ts with ${entityFiles.length} entities.`);\n};\n\nexport const generateModels = async (options: any) => {\n try {\n const ormConfig = defineConfig({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n namingStrategy: MongoNamingStrategy,\n discovery: { warnWhenNoEntities: false },\n extensions: [EntityGenerator],\n debug: true,\n }) as Parameters<typeof MikroORM.initSync>[0];\n\n const orm = MikroORM.initSync(ormConfig);\n console.log(`✅ Connected to ${options.dbName} at ${options.host}:${options.port}`);\n\n const onCreatingVersionField = async (metadatas: EntityMetadata[]) => {\n metadatas.forEach((m) => {\n if (options.versionField) {\n const versionFieldName = Object.keys(m.properties).find((p) => {\n return (\n p === options.versionField ||\n m.properties[p]?.name === options.versionField ||\n m.properties[p]?.fieldNames?.find((f) => f === options.versionField)\n );\n });\n if (versionFieldName) {\n const property = m.properties[versionFieldName];\n if (\n property.type !== \"datetime\" &&\n property.type !== \"integer\" &&\n property.type !== \"decimal\"\n ) {\n console.warn(\n `Version field \"${property.name}\" can be only datetime or integer Table ${m.tableName} but now is \"${property.type}\"`,\n );\n return;\n }\n if (property.primary) {\n console.warn(\n `Version field \"${property.name}\" can not be primary key Table ${m.tableName}`,\n );\n return;\n }\n if (property.nullable) {\n console.warn(\n `Version field \"${property.name}\" should not be nullable Table ${m.tableName}`,\n );\n return;\n }\n property.version = true;\n }\n }\n });\n };\n await orm.entityGenerator.generate({\n entitySchema: true,\n bidirectionalRelations: true,\n identifiedReferences: false,\n forceUndefined: true,\n undefinedDefaults: true,\n useCoreBaseEntity: false,\n onlyPurePivotTables: false,\n outputPurePivotTables: false,\n scalarPropertiesForRelations: \"always\",\n save: true,\n path: options.output,\n onInitialMetadata: onCreatingVersionField,\n });\n\n regenerateIndexFile(options.output);\n\n console.log(`✅ Entities generated at: ${options.output}`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error generating entities:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MikroORM } from \"@mikro-orm/mysql\";\nimport { execSync } from \"child_process\";\nimport { rmSync } from \"fs\";\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nfunction cleanSQLStatement(sql: string): string {\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \\\"${cleanSQLStatement(stmt)}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nconst extractCreateStatements = (schema: string): string[] => {\n const statements = schema.split(\";\").map((s) => s.trim());\n\n return statements.filter(\n (stmt) =>\n stmt.startsWith(\"create table\") ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add index\")) ||\n stmt.startsWith(\"primary\"),\n );\n};\n\n/**\n * Dynamically loads `entities` from `index.ts` in the specified directory.\n * @param entitiesPath - Path to the directory containing `index.ts`.\n * @returns Array of entity classes.\n */\nconst loadEntities = async (entitiesPath: string) => {\n try {\n const indexFilePath = path.resolve(path.join(entitiesPath, \"index.ts\"));\n if (!fs.existsSync(indexFilePath)) {\n console.error(`❌ Error: index.ts not found in ${indexFilePath}`);\n process.exit(1);\n }\n\n const { default: entities } = await import(indexFilePath);\n console.log(`✅ Loaded ${entities.length} entities from ${entitiesPath}`);\n return entities;\n } catch (error) {\n console.error(`❌ Error loading index.ts from ${entitiesPath}:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const createMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version > 0) {\n console.error(`❌ Error: Migration has already been created.`);\n process.exit(1);\n }\n\n // Start from version 1 if no previous migrations exist\n version = 1;\n\n // Load entities dynamically from index.ts\n const entities = await loadEntities(options.entitiesPath);\n\n // Initialize MikroORM\n const orm = MikroORM.initSync({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n entities: entities,\n });\n\n // Generate SQL schema\n const createSchemaSQL = await orm.schema.getCreateSchemaSQL({ wrap: true });\n const statements = extractCreateStatements(createSchemaSQL);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(statements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MikroORM } from \"@mikro-orm/mysql\";\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nfunction cleanSQLStatement(sql: string): string {\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \\\"${cleanSQLStatement(stmt)}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nconst extractCreateStatements = (schema: string): string[] => {\n const statements = schema.split(\";\").map((s) => s.trim());\n\n return statements.filter(\n (stmt) =>\n stmt.startsWith(\"create table\") ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add index\")) ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add\") && !stmt.includes(\"foreign\")) ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"modify\") && !stmt.includes(\"foreign\")),\n );\n};\n\n/**\n * Dynamically loads `entities` from `index.ts` in the specified directory.\n * @param entitiesPath - Path to the directory containing `index.ts`.\n * @returns Array of entity classes.\n */\nconst loadEntities = async (entitiesPath: string) => {\n try {\n const indexFilePath = path.resolve(path.join(entitiesPath, \"index.ts\"));\n if (!fs.existsSync(indexFilePath)) {\n console.error(`❌ Error: index.ts not found in ${entitiesPath}`);\n process.exit(1);\n }\n\n const { default: entities } = await import(indexFilePath);\n console.log(`✅ Loaded ${entities.length} entities from ${entitiesPath}`);\n return entities;\n } catch (error) {\n console.error(`❌ Error loading index.ts from ${entitiesPath}:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.warn(\n `⚠️ Warning: migrationCount.ts not found in ${migrationCountFilePath}, assuming no previous migrations.`,\n );\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Updates an existing database migration by generating schema modifications.\n * @param options - Database connection settings and output paths.\n */\nexport const updateMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version < 1) {\n console.log(\n `⚠️ Initial migration not found. Run \"npx forge-sql-orm migrations:create\" first.`,\n );\n process.exit(0);\n }\n version += 1;\n\n // Load entities dynamically from index.ts\n const entities = await loadEntities(options.entitiesPath);\n\n // Initialize MikroORM\n const orm = MikroORM.initSync({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n entities,\n debug: true,\n });\n\n // Generate SQL schema updates\n const createSchemaSQL = await orm.schema.getUpdateSchemaMigrationSQL({ wrap: true });\n const statements = extractCreateStatements(createSchemaSQL?.down || \"\");\n\n if (statements.length) {\n const migrationFile = generateMigrationFile(statements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully updated!`);\n process.exit(0);\n } else {\n console.log(`⚠️ No new migration changes detected.`);\n process.exit(0);\n }\n } catch (error) {\n console.error(`❌ Error during migration update:`, error);\n process.exit(1);\n }\n};\n","import fs from \"fs\";\nimport path from \"path\";\n\n/**\n * Automates patches for MikroORM and Knex to fix Webpack issues.\n * - Removes problematic `require()` calls.\n * - Deletes unnecessary files and folders.\n * - Fixes dynamic imports (`import(id)`) in MikroORM.\n */\n\ninterface Patch {\n file?: string; // File to modify (optional)\n search?: RegExp; // Regex pattern to find problematic code\n replace?: string; // Replacement string for problematic code\n deleteLines?: RegExp[]; // List of regex patterns to remove specific lines\n description: string; // Description of the patch\n deleteFile?: string; // Path of the file to delete (optional)\n deleteFolder?: string; // Path of the folder to delete (optional)\n}\n\nconst PATCHES: Patch[] = [\n // 🗑️ Remove unused dialects (mssql, postgres, sqlite) in MikroORM\n {\n file: \"node_modules/@mikro-orm/knex/MonkeyPatchable.d.ts\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^\\s*Postgres.*$/gm,\n /^.*Sqlite3.*$/gm,\n /^.*BetterSqlite3.*$/gim,\n ],\n description: \"Removing unused dialects from MonkeyPatchable.d.ts\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/MonkeyPatchable.js\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^.*postgres.*$/gim,\n /^.*sqlite.*$/gim,\n /^.*Sqlite.*$/gim,\n ],\n description: \"Removing unused dialects from MonkeyPatchable.js\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/dialects/index.js\",\n deleteLines: [/^.*mssql.*$/gim, /^.*MsSql.*$/gim, /^.*postgresql.*$/gim, /^.*sqlite.*$/gim],\n description: \"Removing unused dialects from @mikro-orm/knex/dialects/index.js\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/mssql\",\n description: \"Removing mssql dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/postgresql\",\n description: \"Removing postgresql dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/sqlite\",\n description: \"Removing sqlite dialect from MikroORM\",\n },\n\n // 🔄 Fix Webpack `Critical dependency: the request of a dependency is an expression`\n {\n file: \"node_modules/@mikro-orm/core/utils/Configuration.js\",\n search: /dynamicImportProvider:\\s*\\/\\* istanbul ignore next \\*\\/\\s*\\(id\\) => import\\(id\\),/g,\n replace: \"dynamicImportProvider: /* istanbul ignore next */ () => Promise.resolve({}),\",\n description: \"Fixing dynamic imports in MikroORM Configuration\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /static dynamicImportProvider = \\(id\\) => import\\(id\\);/g,\n replace: \"static dynamicImportProvider = () => Promise.resolve({});\",\n description: \"Fixing dynamic imports in MikroORM Utils.js\",\n },\n\n // 🛑 Remove deprecated `require.extensions` usage\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /\\s\\|\\|\\s*\\(require\\.extensions\\s*&&\\s*!!require\\.extensions\\['\\.ts'\\]\\);\\s*/g,\n replace: \";\",\n description: \"Removing deprecated `require.extensions` check in MikroORM\",\n },\n\n // 🛠️ Patch Knex to remove `Migrator` and `Seeder`\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n deleteLines: [\n /^const \\{ Migrator \\} = require\\('\\.\\.\\/migrations\\/migrate\\/Migrator'\\);$/gm,\n /^const Seeder = require\\('\\.\\.\\/migrations\\/seed\\/Seeder'\\);$/gm,\n ],\n description: \"Removing `Migrator` and `Seeder` requires from make-knex.js\",\n },\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n search: /\\sreturn new Migrator\\(this\\);/g,\n replace: \"return null;\",\n description: \"Replacing `return new Migrator(this);` with `return null;`\",\n },\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n search: /\\sreturn new Seeder\\(this\\);/g,\n replace: \"return null;\",\n description: \"Replacing `return new Seeder(this);` with `return null;`\",\n },\n // 🔄 Patch for MikroORM Entity Generator to use 'forge-sql-orm'\n // {\n // file: \"node_modules/@mikro-orm/entity-generator/SourceFile.js\",\n // search: /^.* from '@mikro-orm.*$/gim,\n // replace: \" }).join(', '))} } from 'forge-sql-orm';`);\",\n // description: \"Replacing entity generator imports with 'forge-sql-orm'\"\n // },\n {\n file: \"node_modules/knex/lib/dialects/index.js\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^.*postgresql.*$/gim,\n /^.*sqlite.*$/gim,\n /^.*oracle.*$/gim,\n /^.*oracledb.*$/gim,\n /^.*pgnative.*$/gim,\n /^.*postgres.*$/gim,\n /^.*redshift.*$/gim,\n /^.*sqlite3.*$/gim,\n /^.*cockroachdb.*$/gim,\n ],\n description: \"Removing unused dialects from @mikro-orm/knex/dialects/index.js\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /\\s\\|\\|\\s*\\(require\\.extensions\\s*&&\\s*!!require\\.extensions\\['\\.ts'\\]\\);\\s*/g,\n replace: \";\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /^.*extensions.*$/gim,\n replace: \"{\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /^.*package.json.*$/gim,\n replace: \"return 0;\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/dialects/mysql/index.js\",\n deleteLines: [/^.*MariaDbKnexDialect.*$/gim],\n description: \"Removing MariaDbKnexDialect\",\n },\n];\n\n/**\n * Runs the MikroORM & Knex patching logic.\n */\nexport function runPostInstallPatch() {\n console.log(\"🔧 Applying MikroORM & Knex patches...\");\n PATCHES.forEach(\n ({ file, search, replace, deleteLines, deleteFile, deleteFolder, description }) => {\n if (file) {\n const filePath = path.resolve(file);\n if (fs.existsSync(filePath)) {\n let content = fs.readFileSync(filePath, \"utf8\");\n let originalContent = content;\n\n // 🔄 Replace text\n if (search && replace) {\n if (typeof search === \"string\" ? content.includes(search) : search.test(content)) {\n content = content.replace(search, replace);\n console.log(`[PATCHED] ${description}`);\n }\n }\n\n // 🗑️ Remove matching lines\n if (deleteLines) {\n deleteLines.forEach((pattern) => {\n content = content\n .split(\"\\n\")\n .filter((line) => !pattern.test(line))\n .join(\"\\n\");\n });\n if (content !== originalContent) {\n console.log(`[CLEANED] Removed matching lines in ${file}`);\n }\n }\n\n // 💾 Save changes only if file was modified\n if (content !== originalContent) {\n fs.writeFileSync(filePath, content, \"utf8\");\n }\n\n // 🚮 Remove empty files\n if (content.trim() === \"\") {\n fs.unlinkSync(filePath);\n console.log(`[REMOVED] ${filePath} (file is now empty)`);\n }\n } else {\n console.warn(`[WARNING] File not found: ${file}`);\n }\n }\n\n // 🚮 Delete specific files\n if (deleteFile) {\n const deleteFilePath = path.resolve(__dirname, \"../\", deleteFile);\n if (fs.existsSync(deleteFilePath)) {\n fs.unlinkSync(deleteFilePath);\n console.log(`[DELETED] ${description}`);\n }\n }\n\n // 🚮 Delete entire folders\n if (deleteFolder) {\n const deleteFolderPath = path.resolve(__dirname, \"../\", deleteFolder);\n if (fs.existsSync(deleteFolderPath)) {\n fs.rmSync(deleteFolderPath, { recursive: true, force: true });\n console.log(`[DELETED] ${description}`);\n }\n }\n },\n );\n\n console.log(\"🎉 MikroORM & Knex patching completed!\");\n}\n","#!/usr/bin/env node\n\nimport { Command } from \"commander\";\nimport dotenv from \"dotenv\";\nimport inquirer from \"inquirer\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { generateModels } from \"./actions/generate-models\";\nimport { createMigration } from \"./actions/migrations-create\";\nimport { updateMigration } from \"./actions/migrations-update\";\nimport { runPostInstallPatch } from \"./actions/PatchPostinstall\";\n\nconst ENV_PATH = path.resolve(process.cwd(), \".env\");\n// 🔄 Load environment variables from `.env` file\ndotenv.config({ path: ENV_PATH });\n\nconst saveEnvFile = (config: any) => {\n let envContent = \"\";\n const envFilePath = ENV_PATH;\n\n if (fs.existsSync(envFilePath)) {\n envContent = fs.readFileSync(envFilePath, \"utf8\");\n }\n\n const envVars = envContent\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\" && !line.startsWith(\"#\"))\n .reduce((acc: any, line) => {\n const [key, ...value] = line.split(\"=\");\n acc[key] = value.join(\"=\");\n return acc;\n }, {});\n\n Object.entries(config).forEach(([key, value]) => {\n envVars[`FORGE_SQL_ORM_${key.toUpperCase()}`] = value;\n });\n\n const updatedEnvContent = Object.entries(envVars)\n .map(([key, value]) => `${key}=${value}`)\n .join(\"\\n\");\n\n fs.writeFileSync(envFilePath, updatedEnvContent, { encoding: \"utf8\" });\n\n console.log(\"✅ Configuration saved to .env without overwriting other variables.\");\n};\n\n/**\n * Prompts the user for missing parameters using Inquirer.js.\n * @param config - The current configuration object.\n * @param defaultOutput - Default output path.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns Updated configuration with user input.\n */\nconst askMissingParams = async (\n config: any,\n defaultOutput: string,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n const questions: unknown[] = [];\n\n if (!config.host)\n questions.push({\n type: \"input\",\n name: \"host\",\n message: \"Enter database host:\",\n default: \"localhost\",\n });\n\n if (!config.port)\n questions.push({\n type: \"input\",\n name: \"port\",\n message: \"Enter database port:\",\n default: \"3306\",\n validate: (input: string) => !isNaN(parseInt(input, 10)),\n });\n\n if (!config.user)\n questions.push({\n type: \"input\",\n name: \"user\",\n message: \"Enter database user:\",\n default: \"root\",\n });\n\n if (!config.password)\n questions.push({\n type: \"password\",\n name: \"password\",\n message: \"Enter database password:\",\n mask: \"*\",\n });\n\n if (!config.dbName)\n questions.push({\n type: \"input\",\n name: \"dbName\",\n message: \"Enter database name:\",\n });\n\n if (!config.output)\n questions.push({\n type: \"input\",\n name: \"output\",\n message: \"Enter output path:\",\n default: defaultOutput,\n });\n\n // Allow additional questions from the caller\n if (customAskMissingParams) {\n customAskMissingParams(config, questions);\n }\n\n // If there are missing parameters, prompt the user\n if (questions.length > 0) {\n // @ts-ignore - Ignore TypeScript warning for dynamic question type\n const answers = await inquirer.prompt(questions);\n return { ...config, ...answers, port: parseInt(config.port ?? answers.port, 10) };\n }\n\n return config;\n};\n\n/**\n * Retrieves configuration parameters from command-line arguments and environment variables.\n * If any required parameters are missing, prompts the user for input.\n * @param cmd - The command object containing CLI options.\n * @param defaultOutput - Default output directory.\n * @param customConfig - Optional function for additional configuration parameters.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns A fully resolved configuration object.\n */\nconst getConfig = async (\n cmd: any,\n defaultOutput: string,\n customConfig?: () => any,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n let config = {\n host: cmd.host || process.env.FORGE_SQL_ORM_HOST,\n port: cmd.port\n ? parseInt(cmd.port, 10)\n : process.env.FORGE_SQL_ORM_PORT\n ? parseInt(process.env.FORGE_SQL_ORM_PORT, 10)\n : undefined,\n user: cmd.user || process.env.FORGE_SQL_ORM_USER,\n password: cmd.password || process.env.FORGE_SQL_ORM_PASSWORD,\n dbName: cmd.dbName || process.env.FORGE_SQL_ORM_DBNAME,\n output: cmd.output || process.env.FORGE_SQL_ORM_OUTPUT,\n };\n\n // Merge additional configurations if provided\n if (customConfig) {\n config = { ...config, ...customConfig() };\n }\n\n const conf = await askMissingParams(config, defaultOutput, customAskMissingParams);\n if (cmd.saveEnv) {\n saveEnvFile(conf);\n }\n return conf;\n};\n\n// 📌 Initialize CLI\nconst program = new Command();\nprogram.version(\"1.0.0\");\n\n// ✅ Command: Generate database models (Entities)\nprogram\n .command(\"generate:model\")\n .description(\"Generate MikroORM models from the database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for entities\")\n .option(\"--versionField <string>\", \"Field name for versioning\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/entities\",\n () => ({\n versionField: cmd.versionField || process.env.FORGE_SQL_ORM_VERSIONFIELD,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.versionField) {\n questions.push({\n type: \"input\",\n name: \"versionField\",\n message: \"Enter the field name for versioning (leave empty to skip):\",\n default: \"\",\n });\n }\n },\n );\n await generateModels(config);\n });\n\n// ✅ Command: Create initial database migration\nprogram\n .command(\"migrations:create\")\n .description(\"Generate an initial migration for the entire database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await createMigration(config);\n });\n\n// ✅ Command: Update migration for schema changes\nprogram\n .command(\"migrations:update\")\n .description(\"Generate a migration to update the database schema.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await updateMigration(config);\n });\n\n// Patch MikroORM and Knex\nprogram\n .command(\"patch:mikroorm\")\n .description(\"Patch MikroORM and Knex dependencies to work properly with Forge\")\n .action(async () => {\n console.log(\"Running MikroORM patch...\");\n await runPostInstallPatch();\n await runPostInstallPatch();\n await runPostInstallPatch();\n console.log(\"✅ MikroORM patch applied successfully!\");\n });\n\n// 🔥 Execute CLI\nprogram.parse(process.argv);\n"],"names":["cleanSQLStatement","generateMigrationFile","saveMigrationFiles","extractCreateStatements","loadEntities","loadMigrationVersion"],"mappings":";;;;;;;;;AAOA,MAAM,sBAAsB,CAAC,eAAuB;AAC5C,QAAA,cAAc,KAAK,QAAQ,UAAU;AAC3C,QAAM,YAAY,KAAK,KAAK,aAAa,UAAU;AAEnD,QAAM,cAAc,GACjB,YAAY,WAAW,EACvB,OAAO,CAAC,SAAS,KAAK,SAAS,KAAK,KAAK,SAAS,UAAU;AAE/D,QAAM,UAAU,YAAY,IAAI,CAAC,SAAS;AACxC,UAAM,aAAa,KAAK,SAAS,MAAM,KAAK;AACrC,WAAA,YAAY,UAAU,cAAc,UAAU;AAAA,EAAA,CACtD;AAED,QAAM,eAAe,GAAG,QAAQ,KAAK,IAAI,CAAC;AAAA;AAAA,kBAAuB,YAAY,IAAI,CAAC,SAAS,KAAK,SAAS,MAAM,KAAK,CAAC,EAAE,KAAK,IAAI,CAAC;AAAA;AAE9H,KAAA,cAAc,WAAW,cAAc,MAAM;AAChD,UAAQ,IAAI,2BAA2B,YAAY,MAAM,YAAY;AACvE;AAEa,MAAA,iBAAiB,OAAO,YAAiB;AAChD,MAAA;AACF,UAAM,YAAY,aAAa;AAAA,MAC7B,MAAM,QAAQ;AAAA,MACd,MAAM,QAAQ;AAAA,MACd,MAAM,QAAQ;AAAA,MACd,UAAU,QAAQ;AAAA,MAClB,QAAQ,QAAQ;AAAA,MAChB,gBAAgB;AAAA,MAChB,WAAW,EAAE,oBAAoB,MAAM;AAAA,MACvC,YAAY,CAAC,eAAe;AAAA,MAC5B,OAAO;AAAA,IAAA,CACR;AAE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,QAAQ,mBAAmB,EAC3B,YAAY,qDAAqD,EACjE,OAAO,mBAAmB,eAAe,EACzC,OAAO,mBAAmB,eAAe,EACzC,OAAO,mBAAmB,eAAe,EACzC,OAAO,uBAAuB,mBAAmB,EACjD,OAAO,qBAAqB,eAAe,EAC3C,OAAO,qBAAqB,4BAA4B,EACxD,OAAO,2BAA2B,wCAAwC,EAC1E,OAAO,aAAa,iCAAiC,EACrD,OAAO,OAAO,QAAQ;AACrB,QAAM,SAAS,MAAM;AAAA,IACnB;AAAA,IACA;AAAA,IACA,OAAO;AAAA,MACL,cAAc,IAAI,gBAAgB,QAAQ,IAAI;AAAA,IAAA;AAAA,IAEhD,CAAC,KAAK,cAAyB;AAC7B,UAAI,CAAC,IAAI;AACP,kBAAU,KAAK;AAAA,UACb,MAAM;AAAA,UACN,MAAM;AAAA,UACN,SAAS;AAAA,UACT,SAAS;AAAA,QAAA,CACV;AAAA,IAAA;AAAA,EAEP;AACA,QAAM,gBAAgB,MAAM;AAC9B,CAAC;AAGH,QACG,QAAQ,gBAAgB,EACxB,YAAY,kEAAkE,EAC9E,OAAO,YAAY;AAClB,UAAQ,IAAI,2BAA2B;AACvC,QAAM,oBAAoB;AAC1B,QAAM,oBAAoB;AAC1B,QAAM,oBAAoB;AAC1B,UAAQ,IAAI,wCAAwC;AACtD,CAAC;AAGH,QAAQ,MAAM,QAAQ,IAAI;"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","sources":["../scripts/actions/generate-models.ts","../scripts/actions/migrations-create.ts","../scripts/actions/migrations-update.ts","../scripts/actions/PatchPostinstall.ts","../scripts/cli.ts"],"sourcesContent":["import \"reflect-metadata\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { defineConfig, MikroORM, MongoNamingStrategy } from \"@mikro-orm/mysql\";\nimport { EntityGenerator } from \"@mikro-orm/entity-generator\";\nimport { EntityMetadata } from \"@mikro-orm/core/typings\";\n\nconst regenerateIndexFile = (outputPath: string) => {\n const entitiesDir = path.resolve(outputPath);\n const indexPath = path.join(entitiesDir, \"index.ts\");\n\n const entityFiles = fs\n .readdirSync(entitiesDir)\n .filter((file) => file.endsWith(\".ts\") && file !== \"index.ts\");\n\n const imports = entityFiles.map((file) => {\n const entityName = path.basename(file, \".ts\");\n return `import { ${entityName} } from \"./${entityName}\";`;\n });\n\n const indexContent = `${imports.join(\"\\n\")}\\n\\nexport default [${entityFiles.map((file) => path.basename(file, \".ts\")).join(\", \")}];\\n`;\n\n fs.writeFileSync(indexPath, indexContent, \"utf8\");\n console.log(`✅ Updated index.ts with ${entityFiles.length} entities.`);\n};\n\nexport const generateModels = async (options: any) => {\n try {\n const ormConfig = defineConfig({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n namingStrategy: MongoNamingStrategy,\n discovery: { warnWhenNoEntities: false },\n extensions: [EntityGenerator],\n debug: true,\n }) as Parameters<typeof MikroORM.initSync>[0];\n\n const orm = MikroORM.initSync(ormConfig);\n console.log(`✅ Connected to ${options.dbName} at ${options.host}:${options.port}`);\n\n const onCreatingVersionField = async (metadatas: EntityMetadata[]) => {\n metadatas.forEach((m) => {\n if (options.versionField) {\n const versionFieldName = Object.keys(m.properties).find((p) => {\n return (\n p === options.versionField ||\n m.properties[p]?.name === options.versionField ||\n m.properties[p]?.fieldNames?.find((f) => f === options.versionField)\n );\n });\n if (versionFieldName) {\n const property = m.properties[versionFieldName];\n if (\n property.type !== \"datetime\" &&\n property.type !== \"integer\" &&\n property.type !== \"decimal\"\n ) {\n console.warn(\n `Version field \"${property.name}\" can be only datetime or integer Table ${m.tableName} but now is \"${property.type}\"`,\n );\n return;\n }\n if (property.primary) {\n console.warn(\n `Version field \"${property.name}\" can not be primary key Table ${m.tableName}`,\n );\n return;\n }\n if (property.nullable) {\n console.warn(\n `Version field \"${property.name}\" should not be nullable Table ${m.tableName}`,\n );\n return;\n }\n property.version = true;\n }\n }\n });\n };\n await orm.entityGenerator.generate({\n entitySchema: true,\n bidirectionalRelations: true,\n identifiedReferences: false,\n forceUndefined: true,\n undefinedDefaults: true,\n useCoreBaseEntity: false,\n onlyPurePivotTables: false,\n outputPurePivotTables: false,\n scalarPropertiesForRelations: \"always\",\n save: true,\n path: options.output,\n onInitialMetadata: onCreatingVersionField,\n });\n\n regenerateIndexFile(options.output);\n\n console.log(`✅ Entities generated at: ${options.output}`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error generating entities:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MikroORM } from \"@mikro-orm/mysql\";\nimport { execSync } from \"child_process\";\nimport { rmSync } from \"fs\";\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nfunction cleanSQLStatement(sql: string): string {\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \\\"${cleanSQLStatement(stmt)}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nconst extractCreateStatements = (schema: string): string[] => {\n const statements = schema.split(\";\").map((s) => s.trim());\n\n return statements.filter(\n (stmt) =>\n stmt.startsWith(\"create table\") ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add index\")) ||\n stmt.startsWith(\"primary\"),\n );\n};\n\n/**\n * Dynamically loads `entities` from `index.ts` in the specified directory.\n * @param entitiesPath - Path to the directory containing `index.ts`.\n * @returns Array of entity classes.\n */\nconst loadEntities = async (entitiesPath: string) => {\n try {\n const indexFilePath = path.resolve(path.join(entitiesPath, \"index.ts\"));\n if (!fs.existsSync(indexFilePath)) {\n console.error(`❌ Error: index.ts not found in ${indexFilePath}`);\n process.exit(1);\n }\n\n const { default: entities } = await import(indexFilePath);\n console.log(`✅ Loaded ${entities.length} entities from ${entitiesPath}`);\n return entities;\n } catch (error) {\n console.error(`❌ Error loading index.ts from ${entitiesPath}:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const createMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version > 0) {\n console.error(`❌ Error: Migration has already been created.`);\n process.exit(1);\n }\n\n // Start from version 1 if no previous migrations exist\n version = 1;\n\n // Load entities dynamically from index.ts\n const entities = await loadEntities(options.entitiesPath);\n\n // Initialize MikroORM\n const orm = MikroORM.initSync({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n entities: entities,\n });\n\n // Generate SQL schema\n const createSchemaSQL = await orm.schema.getCreateSchemaSQL({ wrap: true });\n const statements = extractCreateStatements(createSchemaSQL);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(statements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MikroORM } from \"@mikro-orm/mysql\";\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nfunction cleanSQLStatement(sql: string): string {\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \\\"${cleanSQLStatement(stmt)}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nconst extractCreateStatements = (schema: string): string[] => {\n const statements = schema.split(\";\").map((s) => s.trim());\n\n return statements.filter(\n (stmt) =>\n stmt.startsWith(\"create table\") ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add index\")) ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"add\") && !stmt.includes(\"foreign\")) ||\n (stmt.startsWith(\"alter table\") && stmt.includes(\"modify\") && !stmt.includes(\"foreign\")),\n );\n};\n\n/**\n * Dynamically loads `entities` from `index.ts` in the specified directory.\n * @param entitiesPath - Path to the directory containing `index.ts`.\n * @returns Array of entity classes.\n */\nconst loadEntities = async (entitiesPath: string) => {\n try {\n const indexFilePath = path.resolve(path.join(entitiesPath, \"index.ts\"));\n if (!fs.existsSync(indexFilePath)) {\n console.error(`❌ Error: index.ts not found in ${entitiesPath}`);\n process.exit(1);\n }\n\n const { default: entities } = await import(indexFilePath);\n console.log(`✅ Loaded ${entities.length} entities from ${entitiesPath}`);\n return entities;\n } catch (error) {\n console.error(`❌ Error loading index.ts from ${entitiesPath}:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.warn(\n `⚠️ Warning: migrationCount.ts not found in ${migrationCountFilePath}, assuming no previous migrations.`,\n );\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Updates an existing database migration by generating schema modifications.\n * @param options - Database connection settings and output paths.\n */\nexport const updateMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version < 1) {\n console.log(\n `⚠️ Initial migration not found. Run \"npx forge-sql-orm migrations:create\" first.`,\n );\n process.exit(0);\n }\n version += 1;\n\n // Load entities dynamically from index.ts\n const entities = await loadEntities(options.entitiesPath);\n\n // Initialize MikroORM\n const orm = MikroORM.initSync({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n dbName: options.dbName,\n entities,\n debug: true,\n });\n\n // Generate SQL schema updates\n const createSchemaSQL = await orm.schema.getUpdateSchemaMigrationSQL({ wrap: true });\n const statements = extractCreateStatements(createSchemaSQL?.down || \"\");\n\n if (statements.length) {\n const migrationFile = generateMigrationFile(statements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully updated!`);\n process.exit(0);\n } else {\n console.log(`⚠️ No new migration changes detected.`);\n process.exit(0);\n }\n } catch (error) {\n console.error(`❌ Error during migration update:`, error);\n process.exit(1);\n }\n};\n","import fs from \"fs\";\nimport path from \"path\";\n\n/**\n * Automates patches for MikroORM and Knex to fix Webpack issues.\n * - Removes problematic `require()` calls.\n * - Deletes unnecessary files and folders.\n * - Fixes dynamic imports (`import(id)`) in MikroORM.\n */\n\ninterface Patch {\n file?: string; // File to modify (optional)\n search?: RegExp; // Regex pattern to find problematic code\n replace?: string; // Replacement string for problematic code\n deleteLines?: RegExp[]; // List of regex patterns to remove specific lines\n description: string; // Description of the patch\n deleteFile?: string; // Path of the file to delete (optional)\n deleteFolder?: string; // Path of the folder to delete (optional)\n}\n\nconst PATCHES: Patch[] = [\n // 🗑️ Remove unused dialects (mssql, postgres, sqlite) in MikroORM\n {\n file: \"node_modules/@mikro-orm/knex/MonkeyPatchable.d.ts\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^\\s*Postgres.*$/gm,\n /^.*Sqlite3.*$/gm,\n /^.*BetterSqlite3.*$/gim,\n ],\n description: \"Removing unused dialects from MonkeyPatchable.d.ts\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/MonkeyPatchable.js\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^.*postgres.*$/gim,\n /^.*sqlite.*$/gim,\n /^.*Sqlite.*$/gim,\n ],\n description: \"Removing unused dialects from MonkeyPatchable.js\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/dialects/index.js\",\n deleteLines: [/^.*mssql.*$/gim, /^.*MsSql.*$/gim, /^.*postgresql.*$/gim, /^.*sqlite.*$/gim],\n description: \"Removing unused dialects from @mikro-orm/knex/dialects/index.js\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/mssql\",\n description: \"Removing mssql dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/postgresql\",\n description: \"Removing postgresql dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/dialects/sqlite\",\n description: \"Removing sqlite dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/mysql/node_modules\",\n description: \"Removing sqlite dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/knex/node_modules\",\n description: \"Removing sqlite dialect from MikroORM\",\n },\n {\n deleteFolder: \"node_modules/@mikro-orm/core/node_modules\",\n description: \"Removing sqlite dialect from MikroORM\",\n },\n\n // 🔄 Fix Webpack `Critical dependency: the request of a dependency is an expression`\n {\n file: \"node_modules/@mikro-orm/core/utils/Configuration.js\",\n search: /dynamicImportProvider:\\s*\\/\\* istanbul ignore next \\*\\/\\s*\\(id\\) => import\\(id\\),/g,\n replace: \"dynamicImportProvider: /* istanbul ignore next */ () => Promise.resolve({}),\",\n description: \"Fixing dynamic imports in MikroORM Configuration\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /static dynamicImportProvider = \\(id\\) => import\\(id\\);/g,\n replace: \"static dynamicImportProvider = () => Promise.resolve({});\",\n description: \"Fixing dynamic imports in MikroORM Utils.js\",\n },\n\n // 🛑 Remove deprecated `require.extensions` usage\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /\\s\\|\\|\\s*\\(require\\.extensions\\s*&&\\s*!!require\\.extensions\\['\\.ts'\\]\\);\\s*/g,\n replace: \";\",\n description: \"Removing deprecated `require.extensions` check in MikroORM\",\n },\n\n // 🛠️ Patch Knex to remove `Migrator` and `Seeder`\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n deleteLines: [\n /^const \\{ Migrator \\} = require\\('\\.\\.\\/migrations\\/migrate\\/Migrator'\\);$/gm,\n /^const Seeder = require\\('\\.\\.\\/migrations\\/seed\\/Seeder'\\);$/gm,\n ],\n description: \"Removing `Migrator` and `Seeder` requires from make-knex.js\",\n },\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n search: /\\sreturn new Migrator\\(this\\);/g,\n replace: \"return null;\",\n description: \"Replacing `return new Migrator(this);` with `return null;`\",\n },\n {\n file: \"node_modules/knex/lib/knex-builder/make-knex.js\",\n search: /\\sreturn new Seeder\\(this\\);/g,\n replace: \"return null;\",\n description: \"Replacing `return new Seeder(this);` with `return null;`\",\n },\n {\n file: \"node_modules/knex/lib/dialects/index.js\",\n deleteLines: [\n /^.*mssql.*$/gim,\n /^.*MsSql.*$/gim,\n /^.*postgresql.*$/gim,\n /^.*sqlite.*$/gim,\n /^.*oracle.*$/gim,\n /^.*oracledb.*$/gim,\n /^.*pgnative.*$/gim,\n /^.*postgres.*$/gim,\n /^.*redshift.*$/gim,\n /^.*sqlite3.*$/gim,\n /^.*cockroachdb.*$/gim,\n ],\n description: \"Removing unused dialects from @mikro-orm/knex/dialects/index.js\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /\\s\\|\\|\\s*\\(require\\.extensions\\s*&&\\s*!!require\\.extensions\\['\\.ts'\\]\\);\\s*/g,\n replace: \";\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /^.*extensions.*$/gim,\n replace: \"{\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/core/utils/Utils.js\",\n search: /^.*package.json.*$/gim,\n replace: \"return 0;\", // Replaces with semicolon to keep syntax valid\n description: \"Removing deprecated `require.extensions` check from MikroORM\",\n },\n {\n file: \"node_modules/@mikro-orm/knex/dialects/mysql/index.js\",\n deleteLines: [/^.*MariaDbKnexDialect.*$/gim],\n description: \"Removing MariaDbKnexDialect\",\n },\n];\n\n/**\n * Runs the MikroORM & Knex patching logic.\n */\nexport function runPostInstallPatch() {\n console.log(\"🔧 Applying MikroORM & Knex patches...\");\n PATCHES.forEach(\n ({ file, search, replace, deleteLines, deleteFile, deleteFolder, description }) => {\n if (file) {\n const filePath = path.resolve(file);\n if (fs.existsSync(filePath)) {\n let content = fs.readFileSync(filePath, \"utf8\");\n let originalContent = content;\n\n // 🔄 Replace text\n if (search && replace) {\n if (typeof search === \"string\" ? content.includes(search) : search.test(content)) {\n content = content.replace(search, replace);\n console.log(`[PATCHED] ${description}`);\n }\n }\n\n // 🗑️ Remove matching lines\n if (deleteLines) {\n deleteLines.forEach((pattern) => {\n content = content\n .split(\"\\n\")\n .filter((line) => !pattern.test(line))\n .join(\"\\n\");\n });\n if (content !== originalContent) {\n console.log(`[CLEANED] Removed matching lines in ${file}`);\n }\n }\n\n // 💾 Save changes only if file was modified\n if (content !== originalContent) {\n fs.writeFileSync(filePath, content, \"utf8\");\n }\n\n // 🚮 Remove empty files\n if (content.trim() === \"\") {\n fs.unlinkSync(filePath);\n console.log(`[REMOVED] ${filePath} (file is now empty)`);\n }\n } else {\n console.warn(`[WARNING] File not found: ${file}`);\n }\n }\n\n // 🚮 Delete specific files\n if (deleteFile) {\n const deleteFilePath = path.resolve(__dirname, \"../\", deleteFile);\n if (fs.existsSync(deleteFilePath)) {\n fs.unlinkSync(deleteFilePath);\n console.log(`[DELETED] ${description}`);\n }\n }\n\n // 🚮 Delete entire folders\n if (deleteFolder) {\n const deleteFolderPath = path.resolve(__dirname, \"../\", deleteFolder);\n if (fs.existsSync(deleteFolderPath)) {\n fs.rmSync(deleteFolderPath, { recursive: true, force: true });\n console.log(`[DELETED] ${description}`);\n }\n }\n },\n );\n\n console.log(\"🎉 MikroORM & Knex patching completed!\");\n}\n","#!/usr/bin/env node\n\nimport { Command } from \"commander\";\nimport dotenv from \"dotenv\";\nimport inquirer from \"inquirer\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { generateModels } from \"./actions/generate-models\";\nimport { createMigration } from \"./actions/migrations-create\";\nimport { updateMigration } from \"./actions/migrations-update\";\nimport { runPostInstallPatch } from \"./actions/PatchPostinstall\";\n\nconst ENV_PATH = path.resolve(process.cwd(), \".env\");\n// 🔄 Load environment variables from `.env` file\ndotenv.config({ path: ENV_PATH });\n\nconst saveEnvFile = (config: any) => {\n let envContent = \"\";\n const envFilePath = ENV_PATH;\n\n if (fs.existsSync(envFilePath)) {\n envContent = fs.readFileSync(envFilePath, \"utf8\");\n }\n\n const envVars = envContent\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\" && !line.startsWith(\"#\"))\n .reduce((acc: any, line) => {\n const [key, ...value] = line.split(\"=\");\n acc[key] = value.join(\"=\");\n return acc;\n }, {});\n\n Object.entries(config).forEach(([key, value]) => {\n envVars[`FORGE_SQL_ORM_${key.toUpperCase()}`] = value;\n });\n\n const updatedEnvContent = Object.entries(envVars)\n .map(([key, value]) => `${key}=${value}`)\n .join(\"\\n\");\n\n fs.writeFileSync(envFilePath, updatedEnvContent, { encoding: \"utf8\" });\n\n console.log(\"✅ Configuration saved to .env without overwriting other variables.\");\n};\n\n/**\n * Prompts the user for missing parameters using Inquirer.js.\n * @param config - The current configuration object.\n * @param defaultOutput - Default output path.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns Updated configuration with user input.\n */\nconst askMissingParams = async (\n config: any,\n defaultOutput: string,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n const questions: unknown[] = [];\n\n if (!config.host)\n questions.push({\n type: \"input\",\n name: \"host\",\n message: \"Enter database host:\",\n default: \"localhost\",\n });\n\n if (!config.port)\n questions.push({\n type: \"input\",\n name: \"port\",\n message: \"Enter database port:\",\n default: \"3306\",\n validate: (input: string) => !isNaN(parseInt(input, 10)),\n });\n\n if (!config.user)\n questions.push({\n type: \"input\",\n name: \"user\",\n message: \"Enter database user:\",\n default: \"root\",\n });\n\n if (!config.password)\n questions.push({\n type: \"password\",\n name: \"password\",\n message: \"Enter database password:\",\n mask: \"*\",\n });\n\n if (!config.dbName)\n questions.push({\n type: \"input\",\n name: \"dbName\",\n message: \"Enter database name:\",\n });\n\n if (!config.output)\n questions.push({\n type: \"input\",\n name: \"output\",\n message: \"Enter output path:\",\n default: defaultOutput,\n });\n\n // Allow additional questions from the caller\n if (customAskMissingParams) {\n customAskMissingParams(config, questions);\n }\n\n // If there are missing parameters, prompt the user\n if (questions.length > 0) {\n // @ts-ignore - Ignore TypeScript warning for dynamic question type\n const answers = await inquirer.prompt(questions);\n return { ...config, ...answers, port: parseInt(config.port ?? answers.port, 10) };\n }\n\n return config;\n};\n\n/**\n * Retrieves configuration parameters from command-line arguments and environment variables.\n * If any required parameters are missing, prompts the user for input.\n * @param cmd - The command object containing CLI options.\n * @param defaultOutput - Default output directory.\n * @param customConfig - Optional function for additional configuration parameters.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns A fully resolved configuration object.\n */\nconst getConfig = async (\n cmd: any,\n defaultOutput: string,\n customConfig?: () => any,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n let config = {\n host: cmd.host || process.env.FORGE_SQL_ORM_HOST,\n port: cmd.port\n ? parseInt(cmd.port, 10)\n : process.env.FORGE_SQL_ORM_PORT\n ? parseInt(process.env.FORGE_SQL_ORM_PORT, 10)\n : undefined,\n user: cmd.user || process.env.FORGE_SQL_ORM_USER,\n password: cmd.password || process.env.FORGE_SQL_ORM_PASSWORD,\n dbName: cmd.dbName || process.env.FORGE_SQL_ORM_DBNAME,\n output: cmd.output || process.env.FORGE_SQL_ORM_OUTPUT,\n };\n\n // Merge additional configurations if provided\n if (customConfig) {\n config = { ...config, ...customConfig() };\n }\n\n const conf = await askMissingParams(config, defaultOutput, customAskMissingParams);\n if (cmd.saveEnv) {\n saveEnvFile(conf);\n }\n return conf;\n};\n\n// 📌 Initialize CLI\nconst program = new Command();\nprogram.version(\"1.0.0\");\n\n// ✅ Command: Generate database models (Entities)\nprogram\n .command(\"generate:model\")\n .description(\"Generate MikroORM models from the database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for entities\")\n .option(\"--versionField <string>\", \"Field name for versioning\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/entities\",\n () => ({\n versionField: cmd.versionField || process.env.FORGE_SQL_ORM_VERSIONFIELD,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.versionField) {\n questions.push({\n type: \"input\",\n name: \"versionField\",\n message: \"Enter the field name for versioning (leave empty to skip):\",\n default: \"\",\n });\n }\n },\n );\n await generateModels(config);\n });\n\n// ✅ Command: Create initial database migration\nprogram\n .command(\"migrations:create\")\n .description(\"Generate an initial migration for the entire database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await createMigration(config);\n });\n\n// ✅ Command: Update migration for schema changes\nprogram\n .command(\"migrations:update\")\n .description(\"Generate a migration to update the database schema.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await updateMigration(config);\n });\n\n// Patch MikroORM and Knex\nprogram\n .command(\"patch:mikroorm\")\n .description(\"Patch MikroORM and Knex dependencies to work properly with Forge\")\n .action(async () => {\n console.log(\"Running MikroORM patch...\");\n await runPostInstallPatch();\n await runPostInstallPatch();\n await runPostInstallPatch();\n console.log(\"✅ MikroORM patch applied successfully!\");\n });\n\n// 🔥 Execute CLI\nprogram.parse(process.argv);\n"],"names":["cleanSQLStatement","generateMigrationFile","saveMigrationFiles","extractCreateStatements","loadEntities","loadMigrationVersion"],"mappings":";;;;;;;;;AAOA,MAAM,sBAAsB,CAAC,eAAuB;AAC5C,QAAA,cAAc,KAAK,QAAQ,UAAU;AAC3C,QAAM,YAAY,KAAK,KAAK,aAAa,UAAU;AAEnD,QAAM,cAAc,GACjB,YAAY,WAAW,EACvB,OAAO,CAAC,SAAS,KAAK,SAAS,KAAK,KAAK,SAAS,UAAU;AAE/D,QAAM,UAAU,YAAY,IAAI,CAAC,SAAS;AACxC,UAAM,aAAa,KAAK,SAAS,MAAM,KAAK;AACrC,WAAA,YAAY,UAAU,cAAc,UAAU;AAAA,EAAA,CACtD;AAED,QAAM,eAAe,GAAG,QAAQ,KAAK,IAAI,CAAC;AAAA;AAAA,kBAAuB,YAAY,IAAI,CAAC,SAAS,KAAK,SAAS,MAAM,KAAK,CAAC,EAAE,KAAK,IAAI,CAAC;AAAA;AAE9H,KAAA,cAAc,WAAW,cAAc,MAAM;AAChD,UAAQ,IAAI,2BAA2B,YAAY,MAAM,YAAY;AACvE;AAEa,MAAA,iBAAiB,OAAO,YAAiB;AAChD,MAAA;AACF,UAAM,YAAY,aAAa;AAAA,MAC7B,MAAM,QAAQ;AAAA,MACd,MAAM,QAAQ;AAAA,MACd,MAAM,QAAQ;AAAA,MACd,UAAU,QAAQ;AAAA,MAClB,QAAQ,QAAQ;AAAA,MAChB,gBAAgB;AAAA,MAChB,WAAW,EAAE,oBAAoB,MAAM;AAAA,MACvC,YAAY,CAAC,eAAe;AAAA,MAC5B,OAAO;AAAA,IAAA,CACR;AAEK,UAAA,MAAM,SAAS,SAAS,SAAS;AAC/B,YAAA,IAAI,kBAAkB,QAAQ,MAAM,OAAO,QAAQ,IAAI,IAAI,QAAQ,IAAI,EAAE;AAE3E,UAA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,mBAAmB,EAC3B,YAAY,qDAAqD,EACjE,OAAO,mBAAmB,eAAe,EACzC,OAAO,mBAAmB,eAAe,EACzC,OAAO,mBAAmB,eAAe,EACzC,OAAO,uBAAuB,mBAAmB,EACjD,OAAO,qBAAqB,eAAe,EAC3C,OAAO,qBAAqB,4BAA4B,EACxD,OAAO,2BAA2B,wCAAwC,EAC1E,OAAO,aAAa,iCAAiC,EACrD,OAAO,OAAO,QAAQ;AACrB,QAAM,SAAS,MAAM;AAAA,IACnB;AAAA,IACA;AAAA,IACA,OAAO;AAAA,MACL,cAAc,IAAI,gBAAgB,QAAQ,IAAI;AAAA,IAAA;AAAA,IAEhD,CAAC,KAAK,cAAyB;AAC7B,UAAI,CAAC,IAAI;AACP,kBAAU,KAAK;AAAA,UACb,MAAM;AAAA,UACN,MAAM;AAAA,UACN,SAAS;AAAA,UACT,SAAS;AAAA,QAAA,CACV;AAAA,IAAA;AAAA,EAEP;AACA,QAAM,gBAAgB,MAAM;AAC9B,CAAC;AAGH,QACG,QAAQ,gBAAgB,EACxB,YAAY,kEAAkE,EAC9E,OAAO,YAAY;AAClB,UAAQ,IAAI,2BAA2B;AACvC,QAAM,oBAAoB;AAC1B,QAAM,oBAAoB;AAC1B,QAAM,oBAAoB;AAC1B,UAAQ,IAAI,wCAAwC;AACtD,CAAC;AAGH,QAAQ,MAAM,QAAQ,IAAI;"}
|
|
File without changes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "forge-sql-orm",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.27",
|
|
4
4
|
"description": "Mikro-ORM integration for Forge-SQL in Atlassian Forge applications.",
|
|
5
5
|
"main": "dist/ForgeSQLORM.js",
|
|
6
6
|
"module": "dist/ForgeSQLORM.mjs",
|
|
@@ -93,6 +93,6 @@
|
|
|
93
93
|
"@forge/sql": "^2.4.0"
|
|
94
94
|
},
|
|
95
95
|
"bin": {
|
|
96
|
-
"forge-sql-orm": "dist-cli/
|
|
96
|
+
"forge-sql-orm": "dist-cli/forgeSqlOrmCLI.js"
|
|
97
97
|
}
|
|
98
98
|
}
|
|
@@ -3,7 +3,7 @@ import { EntityProperty, EntitySchema, ForgeSqlOrmOptions } from "..";
|
|
|
3
3
|
import type { types } from "@mikro-orm/core/types";
|
|
4
4
|
import { transformValue } from "../utils/sqlUtils";
|
|
5
5
|
import { CRUDForgeSQL, ForgeSqlOperation } from "./ForgeSQLQueryBuilder";
|
|
6
|
-
import { EntityKey, QBFilterQuery } from "
|
|
6
|
+
import { EntityKey, QBFilterQuery } from "..";
|
|
7
7
|
import Knex from "../knex";
|
|
8
8
|
|
|
9
9
|
export class ForgeSQLCrudOperations implements CRUDForgeSQL {
|
package/src/core/ForgeSQLORM.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EntityName, LoggingOptions } from "
|
|
1
|
+
import type { EntityName, LoggingOptions } from "..";
|
|
2
2
|
import type { EntitySchema } from "@mikro-orm/core/metadata/EntitySchema";
|
|
3
3
|
import type { AnyEntity, EntityClass, EntityClassGroup } from "@mikro-orm/core/typings";
|
|
4
4
|
import type { QueryBuilder } from "@mikro-orm/knex/query";
|