@prisma-next/family-sql 0.16.0-dev.3 → 0.16.0-dev.30
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/README.md +1 -1
- package/dist/control.d.mts +1 -1
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +24 -15
- package/dist/control.mjs.map +1 -1
- package/dist/diff.d.mts +1 -1
- package/dist/migration.d.mts +1 -1
- package/dist/psl-infer.d.mts +3 -5
- package/dist/psl-infer.d.mts.map +1 -1
- package/dist/psl-infer.mjs +11 -8
- package/dist/psl-infer.mjs.map +1 -1
- package/dist/{types-6JMCRorL.d.mts → types-DhAmOoxA.d.mts} +11 -4
- package/dist/{types-6JMCRorL.d.mts.map → types-DhAmOoxA.d.mts.map} +1 -1
- package/package.json +21 -21
- package/src/core/control-instance.ts +7 -8
- package/src/core/migrations/contract-to-schema-ir.ts +22 -9
- package/src/core/migrations/types.ts +10 -3
- package/src/core/psl-contract-infer/name-transforms.ts +0 -12
- package/src/core/psl-contract-infer/printer-config.ts +2 -3
- package/src/core/psl-contract-infer/relation-inference.ts +23 -1
- package/src/exports/psl-infer.ts +1 -2
package/dist/diff.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as NativeTypeNormalizer, o as arraysEqual } from "./control-adapter-CW7FdxeS.mjs";
|
|
2
|
-
import { n as CodecControlHooks } from "./types-
|
|
2
|
+
import { n as CodecControlHooks } from "./types-DhAmOoxA.mjs";
|
|
3
3
|
import { t as SqlSchemaDiffFn } from "./schema-differ-C8OHo1V5.mjs";
|
|
4
4
|
import { DiffSubjectGranularity, SchemaDiffIssue, VerifierIssueCategory, VerifyDatabaseSchemaResult } from "@prisma-next/framework-components/control";
|
|
5
5
|
import { Contract, ControlPolicy } from "@prisma-next/contract/types";
|
package/dist/migration.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as SqlMigrationPlanOperation, w as SqlPlanTargetDetails } from "./types-
|
|
1
|
+
import { f as SqlMigrationPlanOperation, w as SqlPlanTargetDetails } from "./types-DhAmOoxA.mjs";
|
|
2
2
|
import { Contract } from "@prisma-next/contract/types";
|
|
3
3
|
import { SqlStorage } from "@prisma-next/sql-contract/types";
|
|
4
4
|
import { Migration } from "@prisma-next/migration-tools/migration";
|
package/dist/psl-infer.d.mts
CHANGED
|
@@ -30,18 +30,16 @@ declare function toEnumMemberName(value: string): string;
|
|
|
30
30
|
declare function pluralize(word: string): string;
|
|
31
31
|
declare function deriveRelationFieldName(fkColumns: readonly string[], referencedTableName: string): string;
|
|
32
32
|
declare function deriveBackRelationFieldName(childModelName: string, isOneToOne: boolean): string;
|
|
33
|
-
declare function toNamedTypeName(columnName: string): string;
|
|
34
33
|
//#endregion
|
|
35
34
|
//#region src/core/psl-contract-infer/printer-config.d.ts
|
|
36
|
-
type
|
|
35
|
+
type PslTypeReference = {
|
|
37
36
|
readonly name: string;
|
|
38
37
|
readonly args?: readonly string[];
|
|
39
38
|
};
|
|
40
39
|
type PslTypeResolution = {
|
|
41
|
-
readonly pslType:
|
|
40
|
+
readonly pslType: PslTypeReference;
|
|
42
41
|
readonly nativeType: string;
|
|
43
42
|
readonly typeParams?: Record<string, unknown>;
|
|
44
|
-
readonly nativeTypeAttribute?: PslNativeTypeAttribute;
|
|
45
43
|
} | {
|
|
46
44
|
readonly unsupported: true;
|
|
47
45
|
readonly nativeType: string;
|
|
@@ -115,5 +113,5 @@ declare function inferRelations(tables: Record<string, SqlTableIR>, modelNameMap
|
|
|
115
113
|
*/
|
|
116
114
|
declare function buildChildRelationField(fieldName: string, parentModelName: string, fk: SqlForeignKeyIR, optional: boolean, relationName?: string, hostTable?: SqlTableIR): RelationField;
|
|
117
115
|
//#endregion
|
|
118
|
-
export { type DefaultMappingOptions, type DefaultMappingResult, type EnumInfo, type InferredRelations, type
|
|
116
|
+
export { type DefaultMappingOptions, type DefaultMappingResult, type EnumInfo, type InferredRelations, type PslPrinterOptions, type PslTypeMap, type PslTypeReference, type PslTypeResolution, type RelationField, buildChildRelationField, deriveBackRelationFieldName, deriveRelationFieldName, inferRelations, mapDefault, parseRawDefault, pluralize, toEnumMemberName, toEnumName, toFieldName, toModelName };
|
|
119
117
|
//# sourceMappingURL=psl-infer.d.mts.map
|
package/dist/psl-infer.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"psl-infer.d.mts","names":[],"sources":["../src/core/psl-contract-infer/default-mapping.ts","../src/core/psl-contract-infer/name-transforms.ts","../src/core/psl-contract-infer/printer-config.ts","../src/core/psl-contract-infer/raw-default-parser.ts","../src/core/psl-contract-infer/relation-inference.ts"],"mappings":";;;UAOiB;WACN,qBAAqB,SAAS;WAC9B,8BAA8B;;KAG7B;WAAkC;;WAAiC;;iBAE/D,WACd,eAAe,eACf,UAAU,wBACT;;;KCXE;WACM;WACA;;iBA4DK,YAAY,oBAAoB;iBAqBhC,YAAY,qBAAqB;iBAqBjC,WAAW,qBAAqB;;;;;;;iBA6BhC,iBAAiB;iBAOjB,UAAU;iBAIV,wBACd,8BACA;iBAec,4BAA4B,wBAAwB
|
|
1
|
+
{"version":3,"file":"psl-infer.d.mts","names":[],"sources":["../src/core/psl-contract-infer/default-mapping.ts","../src/core/psl-contract-infer/name-transforms.ts","../src/core/psl-contract-infer/printer-config.ts","../src/core/psl-contract-infer/raw-default-parser.ts","../src/core/psl-contract-infer/relation-inference.ts"],"mappings":";;;UAOiB;WACN,qBAAqB,SAAS;WAC9B,8BAA8B;;KAG7B;WAAkC;;WAAiC;;iBAE/D,WACd,eAAe,eACf,UAAU,wBACT;;;KCXE;WACM;WACA;;iBA4DK,YAAY,oBAAoB;iBAqBhC,YAAY,qBAAqB;iBAqBjC,WAAW,qBAAqB;;;;;;;iBA6BhC,iBAAiB;iBAOjB,UAAU;iBAIV,wBACd,8BACA;iBAec,4BAA4B,wBAAwB;;;KCpKxD;WACD;WACA;;KAGC;WAEG,SAAS;WACT;WACA,aAAa;;WAGb;WACA;;UAGE;EACf,QAAQ,oBAAoB,cAAc,0BAA0B;;UAGrD;WACN,WAAW;WACX,aAAa;;UAGP;WACN,SAAS;WACT,iBAAiB;WACjB,WAAW;WACX,mBAAmB,oBAAoB,wBAAwB;;KAG9D;WACD;WACA;;;;;;WAMA;;;;;;WAMA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;WAEA;;;;iBCvBK,gBACd,oBACA,sBACC;;;KCrBS;WACD,kBAAkB,6BAA6B;;iBAG1C,eACd,QAAQ,eAAe,aACvB,cAAc,8BACb;;;;;;;;;;;;;;;;;;;iBAiJa,wBACd,mBACA,yBACA,IAAI,iBACJ,mBACA,uBACA,YAAY,aACX"}
|
package/dist/psl-infer.mjs
CHANGED
|
@@ -150,12 +150,6 @@ function deriveBackRelationFieldName(childModelName, isOneToOne) {
|
|
|
150
150
|
const base = childModelName.charAt(0).toLowerCase() + childModelName.slice(1);
|
|
151
151
|
return isOneToOne ? base : pluralize(base);
|
|
152
152
|
}
|
|
153
|
-
function toNamedTypeName(columnName) {
|
|
154
|
-
let name;
|
|
155
|
-
if (hasSeparators(columnName)) name = snakeToPascalCase(columnName);
|
|
156
|
-
else name = columnName.charAt(0).toUpperCase() + columnName.slice(1);
|
|
157
|
-
return escapeIfNeeded(name);
|
|
158
|
-
}
|
|
159
153
|
//#endregion
|
|
160
154
|
//#region src/core/psl-contract-infer/raw-default-parser.ts
|
|
161
155
|
const NEXTVAL_PATTERN = /^nextval\s*\(/i;
|
|
@@ -302,6 +296,11 @@ function detectOneToOne(fk, table) {
|
|
|
302
296
|
const uniqueCols = [...unique.columns].sort();
|
|
303
297
|
if (uniqueCols.length === fkCols.length && uniqueCols.every((c, i) => c === fkCols[i])) return true;
|
|
304
298
|
}
|
|
299
|
+
for (const index of table.indexes) {
|
|
300
|
+
if (!index.unique || index.partial || index.columns === void 0) continue;
|
|
301
|
+
const indexCols = [...index.columns].sort();
|
|
302
|
+
if (indexCols.length === fkCols.length && indexCols.every((c, i) => c === fkCols[i])) return true;
|
|
303
|
+
}
|
|
305
304
|
return false;
|
|
306
305
|
}
|
|
307
306
|
function deriveRelationName(fk, childRelationFieldName, parentModelName, isSelfRelation) {
|
|
@@ -330,7 +329,11 @@ function deriveRelationName(fk, childRelationFieldName, parentModelName, isSelfR
|
|
|
330
329
|
function buildChildRelationField(fieldName, parentModelName, fk, optional, relationName, hostTable) {
|
|
331
330
|
const onDelete = fk.onDelete && fk.onDelete !== DEFAULT_ON_DELETE ? fk.onDelete : void 0;
|
|
332
331
|
const onUpdate = fk.onUpdate && fk.onUpdate !== DEFAULT_ON_UPDATE ? fk.onUpdate : void 0;
|
|
333
|
-
const index = hostTable && !isBackedByColumnKeys(fk.columns, backingIndexColumnKeys(
|
|
332
|
+
const index = hostTable && !isBackedByColumnKeys(fk.columns, backingIndexColumnKeys({
|
|
333
|
+
indexes: hostTable.indexes.filter((i) => i.where === void 0),
|
|
334
|
+
uniques: hostTable.uniques,
|
|
335
|
+
primaryKey: hostTable.primaryKey
|
|
336
|
+
})) ? false : void 0;
|
|
334
337
|
return {
|
|
335
338
|
fieldName,
|
|
336
339
|
typeName: parentModelName,
|
|
@@ -360,6 +363,6 @@ function addRelationField(map, tableName, field) {
|
|
|
360
363
|
else map.set(tableName, [field]);
|
|
361
364
|
}
|
|
362
365
|
//#endregion
|
|
363
|
-
export { buildChildRelationField, deriveBackRelationFieldName, deriveRelationFieldName, inferRelations, mapDefault, parseRawDefault, pluralize, toEnumMemberName, toEnumName, toFieldName, toModelName
|
|
366
|
+
export { buildChildRelationField, deriveBackRelationFieldName, deriveRelationFieldName, inferRelations, mapDefault, parseRawDefault, pluralize, toEnumMemberName, toEnumName, toFieldName, toModelName };
|
|
364
367
|
|
|
365
368
|
//# sourceMappingURL=psl-infer.mjs.map
|
package/dist/psl-infer.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"psl-infer.mjs","names":[],"sources":["../src/core/psl-contract-infer/default-mapping.ts","../src/core/psl-contract-infer/name-transforms.ts","../src/core/psl-contract-infer/raw-default-parser.ts","../src/core/psl-contract-infer/relation-inference.ts"],"sourcesContent":["import type { ColumnDefault } from '@prisma-next/contract/types';\n\nconst DEFAULT_FUNCTION_ATTRIBUTES: Readonly<Record<string, string>> = {\n 'autoincrement()': '@default(autoincrement())',\n 'now()': '@default(now())',\n};\n\nexport interface DefaultMappingOptions {\n readonly functionAttributes?: Readonly<Record<string, string>>;\n readonly fallbackFunctionAttribute?: ((expression: string) => string | undefined) | undefined;\n}\n\nexport type DefaultMappingResult = { readonly attribute: string } | { readonly comment: string };\n\nexport function mapDefault(\n columnDefault: ColumnDefault,\n options?: DefaultMappingOptions,\n): DefaultMappingResult {\n switch (columnDefault.kind) {\n case 'literal':\n return { attribute: `@default(${formatLiteralValue(columnDefault.value)})` };\n case 'function': {\n const attribute =\n options?.functionAttributes?.[columnDefault.expression] ??\n DEFAULT_FUNCTION_ATTRIBUTES[columnDefault.expression] ??\n options?.fallbackFunctionAttribute?.(columnDefault.expression);\n return attribute\n ? { attribute }\n : { comment: `// Raw default: ${columnDefault.expression.replace(/[\\r\\n]+/g, ' ')}` };\n }\n }\n}\n\nfunction formatLiteralValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n\n switch (typeof value) {\n case 'boolean':\n case 'number':\n return String(value);\n case 'string':\n return quoteString(value);\n default:\n return quoteString(JSON.stringify(value));\n }\n}\n\nfunction quoteString(str: string): string {\n return `\"${escapeString(str)}\"`;\n}\n\nfunction escapeString(str: string): string {\n return JSON.stringify(str).slice(1, -1);\n}\n","import pluralizeLib from 'pluralize';\n\nconst PSL_RESERVED_WORDS = new Set(['model', 'enum', 'types', 'type', 'generator', 'datasource']);\n\nconst IDENTIFIER_PART_PATTERN = /[A-Za-z0-9]+/g;\n\ntype NameResult = {\n readonly name: string;\n readonly map?: string;\n};\n\nfunction hasSeparators(input: string): boolean {\n return /[^A-Za-z0-9]/.test(input);\n}\n\nfunction extractIdentifierParts(input: string): string[] {\n return input.match(IDENTIFIER_PART_PATTERN) ?? [];\n}\n\nfunction createSyntheticIdentifier(input: string): string {\n let hash = 2166136261;\n\n for (const char of input) {\n hash ^= char.codePointAt(0) ?? 0;\n hash = Math.imul(hash, 16777619);\n }\n\n return `x${(hash >>> 0).toString(16)}`;\n}\n\nfunction sanitizeIdentifierCharacters(input: string): string {\n const sanitized = input.replace(/[^\\w]/g, '');\n return sanitized.length > 0 ? sanitized : createSyntheticIdentifier(input);\n}\n\nfunction capitalize(word: string): string {\n return word.charAt(0).toUpperCase() + word.slice(1);\n}\n\nfunction snakeToPascalCase(input: string): string {\n const parts = extractIdentifierParts(input);\n if (parts.length === 0) {\n return capitalize(sanitizeIdentifierCharacters(input));\n }\n return parts.map(capitalize).join('');\n}\n\nfunction snakeToCamelCase(input: string): string {\n const parts = extractIdentifierParts(input);\n if (parts.length === 0) {\n return sanitizeIdentifierCharacters(input);\n }\n const [firstPart = input, ...rest] = parts;\n return firstPart.charAt(0).toLowerCase() + firstPart.slice(1) + rest.map(capitalize).join('');\n}\n\nfunction needsEscaping(name: string): boolean {\n return PSL_RESERVED_WORDS.has(name.toLowerCase()) || /^\\d/.test(name);\n}\n\nfunction escapeName(name: string): string {\n return `_${name}`;\n}\n\nfunction escapeIfNeeded(name: string): string {\n return needsEscaping(name) ? escapeName(name) : name;\n}\n\nexport function toModelName(tableName: string): NameResult {\n let name: string;\n\n if (hasSeparators(tableName)) {\n name = snakeToPascalCase(tableName);\n } else {\n name = tableName.charAt(0).toUpperCase() + tableName.slice(1);\n }\n\n if (needsEscaping(name)) {\n const escaped = escapeName(name);\n return { name: escaped, map: tableName };\n }\n\n if (name !== tableName) {\n return { name, map: tableName };\n }\n\n return { name };\n}\n\nexport function toFieldName(columnName: string): NameResult {\n let name: string;\n\n if (hasSeparators(columnName)) {\n name = snakeToCamelCase(columnName);\n } else {\n name = columnName.charAt(0).toLowerCase() + columnName.slice(1);\n }\n\n if (needsEscaping(name)) {\n const escaped = escapeName(name);\n return { name: escaped, map: columnName };\n }\n\n if (name !== columnName) {\n return { name, map: columnName };\n }\n\n return { name };\n}\n\nexport function toEnumName(pgTypeName: string): NameResult {\n let name: string;\n\n if (hasSeparators(pgTypeName)) {\n name = snakeToPascalCase(pgTypeName);\n } else {\n name = pgTypeName.charAt(0).toUpperCase() + pgTypeName.slice(1);\n }\n\n if (needsEscaping(name)) {\n const escaped = escapeName(name);\n return { name: escaped, map: pgTypeName };\n }\n\n if (name !== pgTypeName) {\n return { name, map: pgTypeName };\n }\n\n return { name };\n}\n\nconst VALID_IDENTIFIER_PATTERN = /^[A-Za-z_]\\w*$/;\n\n/**\n * PSL member name for a native-enum value. The value itself always prints\n * explicitly (`member = \"value\"`), so the returned name never needs a map:\n * a value that already is a valid, non-reserved identifier is kept verbatim\n * (case included); anything else is camelCased/escaped like a field name.\n */\nexport function toEnumMemberName(value: string): string {\n if (VALID_IDENTIFIER_PATTERN.test(value) && !needsEscaping(value)) {\n return value;\n }\n return escapeIfNeeded(snakeToCamelCase(value));\n}\n\nexport function pluralize(word: string): string {\n return pluralizeLib.plural(word);\n}\n\nexport function deriveRelationFieldName(\n fkColumns: readonly string[],\n referencedTableName: string,\n): string {\n if (fkColumns.length === 1) {\n const [col = referencedTableName] = fkColumns;\n const stripped = col.replace(/_id$/i, '').replace(/Id$/, '');\n\n if (stripped.length > 0 && stripped !== col) {\n return escapeIfNeeded(snakeToCamelCase(stripped));\n }\n return escapeIfNeeded(snakeToCamelCase(referencedTableName));\n }\n\n return escapeIfNeeded(snakeToCamelCase(referencedTableName));\n}\n\nexport function deriveBackRelationFieldName(childModelName: string, isOneToOne: boolean): string {\n const base = childModelName.charAt(0).toLowerCase() + childModelName.slice(1);\n return isOneToOne ? base : pluralize(base);\n}\n\nexport function toNamedTypeName(columnName: string): string {\n let name: string;\n\n if (hasSeparators(columnName)) {\n name = snakeToPascalCase(columnName);\n } else {\n name = columnName.charAt(0).toUpperCase() + columnName.slice(1);\n }\n\n return escapeIfNeeded(name);\n}\n","import type { ColumnDefault } from '@prisma-next/contract/types';\n\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst NOW_FUNCTION_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP)$/i;\nconst CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\\s*\\(\\s*\\)$/i;\nconst TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\\s+(?:with|without)\\s+time\\s+zone)?$/i;\nconst TEXT_CAST_SUFFIX = /::text$/i;\nconst NOW_LITERAL_PATTERN = /^'now'$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst NULL_PATTERN = /^NULL(?:::.+)?$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst JSON_CAST_SUFFIX = /::jsonb?$/i;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n\nfunction canonicalizeTimestampDefault(expr: string): string | undefined {\n if (NOW_FUNCTION_PATTERN.test(expr)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(expr)) return 'clock_timestamp()';\n\n if (!TIMESTAMP_CAST_SUFFIX.test(expr)) return undefined;\n\n let inner = expr.replace(TIMESTAMP_CAST_SUFFIX, '').trim();\n if (inner.startsWith('(') && inner.endsWith(')')) {\n inner = inner.slice(1, -1).trim();\n }\n\n if (NOW_FUNCTION_PATTERN.test(inner)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(inner)) return 'clock_timestamp()';\n\n inner = inner.replace(TEXT_CAST_SUFFIX, '').trim();\n if (NOW_LITERAL_PATTERN.test(inner)) return 'now()';\n\n return undefined;\n}\n\nexport function parseRawDefault(\n rawDefault: string,\n nativeType?: string,\n): ColumnDefault | undefined {\n const trimmed = rawDefault.trim();\n const normalizedType = nativeType?.toLowerCase();\n\n if (NEXTVAL_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'autoincrement()' };\n }\n\n const canonicalTimestamp = canonicalizeTimestampDefault(trimmed);\n if (canonicalTimestamp) {\n return { kind: 'function', expression: canonicalTimestamp };\n }\n\n if (UUID_PATTERN.test(trimmed) || UUID_OSSP_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (NULL_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: null };\n }\n\n if (TRUE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: true };\n }\n\n if (FALSE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: false };\n }\n\n if (NUMERIC_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: Number(trimmed) };\n }\n\n const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n if (stringMatch?.[1] !== undefined) {\n const unescaped = stringMatch[1].replace(/''/g, \"'\");\n if (normalizedType === 'json' || normalizedType === 'jsonb') {\n if (JSON_CAST_SUFFIX.test(trimmed)) {\n return { kind: 'function', expression: trimmed };\n }\n try {\n return { kind: 'literal', value: JSON.parse(unescaped) };\n } catch {\n // Fall through to the string form for malformed/non-JSON values.\n }\n }\n return { kind: 'literal', value: unescaped };\n }\n\n return { kind: 'function', expression: trimmed };\n}\n","import {\n backingIndexColumnKeys,\n isBackedByColumnKeys,\n} from '@prisma-next/sql-contract/foreign-key-materialization';\nimport type { SqlForeignKeyIR, SqlTableIR } from '@prisma-next/sql-schema-ir/types';\nimport { deriveBackRelationFieldName, deriveRelationFieldName, pluralize } from './name-transforms';\nimport type { RelationField } from './printer-config';\n\nconst DEFAULT_ON_DELETE = 'noAction';\nconst DEFAULT_ON_UPDATE = 'noAction';\n\nconst REFERENTIAL_ACTION_PSL: Record<string, string> = {\n noAction: 'NoAction',\n restrict: 'Restrict',\n cascade: 'Cascade',\n setNull: 'SetNull',\n setDefault: 'SetDefault',\n};\n\nexport type InferredRelations = {\n readonly relationsByTable: ReadonlyMap<string, readonly RelationField[]>;\n};\n\nexport function inferRelations(\n tables: Record<string, SqlTableIR>,\n modelNameMap: ReadonlyMap<string, string>,\n): InferredRelations {\n const relationsByTable = new Map<string, RelationField[]>();\n\n const fkCountByPair = new Map<string, number>();\n for (const table of Object.values(tables)) {\n for (const fk of table.foreignKeys) {\n const pairKey = `${table.name}→${fk.referencedTable}`;\n fkCountByPair.set(pairKey, (fkCountByPair.get(pairKey) ?? 0) + 1);\n }\n }\n\n const usedFieldNames = new Map<string, Set<string>>();\n for (const table of Object.values(tables)) {\n const names = new Set<string>();\n for (const col of Object.values(table.columns)) {\n names.add(col.name);\n }\n usedFieldNames.set(table.name, names);\n }\n\n for (const table of Object.values(tables)) {\n for (const fk of table.foreignKeys) {\n const childTableName = table.name;\n const parentTableName = fk.referencedTable;\n const childUsed = usedFieldNames.get(childTableName) as Set<string>;\n const childModelName = modelNameMap.get(childTableName) ?? childTableName;\n const parentModelName = modelNameMap.get(parentTableName) ?? parentTableName;\n const pairKey = `${childTableName}→${parentTableName}`;\n const isSelfRelation = childTableName === parentTableName;\n const needsRelationName = (fkCountByPair.get(pairKey) as number) > 1 || isSelfRelation;\n\n const isOneToOne = detectOneToOne(fk, table);\n\n const childRelFieldName = resolveUniqueFieldName(\n deriveRelationFieldName(fk.columns, parentTableName),\n childUsed,\n parentModelName,\n );\n const relationName = needsRelationName\n ? deriveRelationName(fk, childRelFieldName, parentModelName, isSelfRelation)\n : undefined;\n const childOptional = fk.columns.some(\n (columnName) => table.columns[columnName]?.nullable ?? false,\n );\n\n const childRelField = buildChildRelationField(\n childRelFieldName,\n parentModelName,\n fk,\n childOptional,\n relationName,\n table,\n );\n\n addRelationField(relationsByTable, childTableName, childRelField);\n childUsed.add(childRelFieldName);\n\n const parentUsed = usedFieldNames.get(parentTableName) ?? new Set();\n usedFieldNames.set(parentTableName, parentUsed);\n\n const backRelFieldName = resolveUniqueFieldName(\n deriveBackRelationFieldName(childModelName, isOneToOne),\n parentUsed,\n childModelName,\n );\n\n const backRelField: RelationField = {\n fieldName: backRelFieldName,\n typeName: childModelName,\n optional: isOneToOne,\n list: !isOneToOne,\n relationName,\n };\n\n addRelationField(relationsByTable, parentTableName, backRelField);\n parentUsed.add(backRelFieldName);\n }\n }\n\n return { relationsByTable };\n}\n\nfunction detectOneToOne(fk: SqlForeignKeyIR, table: SqlTableIR): boolean {\n const fkCols = [...fk.columns].sort();\n\n if (table.primaryKey) {\n const pkCols = [...table.primaryKey.columns].sort();\n if (pkCols.length === fkCols.length && pkCols.every((c, i) => c === fkCols[i])) {\n return true;\n }\n }\n\n for (const unique of table.uniques) {\n const uniqueCols = [...unique.columns].sort();\n if (uniqueCols.length === fkCols.length && uniqueCols.every((c, i) => c === fkCols[i])) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction deriveRelationName(\n fk: SqlForeignKeyIR,\n childRelationFieldName: string,\n parentModelName: string,\n isSelfRelation: boolean,\n): string {\n if (fk.name) {\n return fk.name;\n }\n if (isSelfRelation) {\n return `${childRelationFieldName.charAt(0).toUpperCase() + childRelationFieldName.slice(1)}${pluralize(parentModelName)}`;\n }\n return fk.columns.join('_');\n}\n\n/**\n * Builds the child-side {@link RelationField} for a single foreign key:\n * `typeName` is the parent model name, `fields`/`references` are the FK's raw\n * columns, and `onDelete`/`onUpdate` are normalized to their PSL spelling.\n * Exported so a caller resolving a foreign key against a model outside\n * `tables` (e.g. a cross-space reference into another contract) can reuse the\n * same normalization instead of duplicating it.\n *\n * `hostTable` is the table the FK is declared on (i.e. `table`, not the\n * referenced parent) — its own indexes/uniques/primary key are what a\n * backing index for this FK would be. When none of them exactly match the\n * FK's source columns (in order), `index: false` is stamped so the emitted\n * `@relation` opts out of the framework's default derived backing-index\n * expectation, matching what `db verify` will find live. Passing the table\n * is optional so existing single-FK callers (e.g. cross-space resolution\n * before a host table reference is threaded through) can omit it and keep\n * the framework default.\n */\nexport function buildChildRelationField(\n fieldName: string,\n parentModelName: string,\n fk: SqlForeignKeyIR,\n optional: boolean,\n relationName?: string,\n hostTable?: SqlTableIR,\n): RelationField {\n const onDelete = fk.onDelete && fk.onDelete !== DEFAULT_ON_DELETE ? fk.onDelete : undefined;\n const onUpdate = fk.onUpdate && fk.onUpdate !== DEFAULT_ON_UPDATE ? fk.onUpdate : undefined;\n const index =\n hostTable && !isBackedByColumnKeys(fk.columns, backingIndexColumnKeys(hostTable))\n ? false\n : undefined;\n\n return {\n fieldName,\n typeName: parentModelName,\n referencedTableName: fk.referencedTable,\n optional,\n list: false,\n relationName,\n fkName: fk.name,\n fields: fk.columns,\n references: fk.referencedColumns,\n onDelete: onDelete ? REFERENTIAL_ACTION_PSL[onDelete] : undefined,\n onUpdate: onUpdate ? REFERENTIAL_ACTION_PSL[onUpdate] : undefined,\n index,\n };\n}\n\nfunction resolveUniqueFieldName(\n desired: string,\n usedNames: ReadonlySet<string>,\n fallbackSuffix: string,\n): string {\n if (!usedNames.has(desired)) {\n return desired;\n }\n\n const withSuffix = `${desired}${fallbackSuffix}`;\n if (!usedNames.has(withSuffix)) {\n return withSuffix;\n }\n\n let counter = 2;\n while (usedNames.has(`${desired}${counter}`)) {\n counter++;\n }\n return `${desired}${counter}`;\n}\n\nfunction addRelationField(\n map: Map<string, RelationField[]>,\n tableName: string,\n field: RelationField,\n): void {\n const existing = map.get(tableName);\n if (existing) {\n existing.push(field);\n } else {\n map.set(tableName, [field]);\n }\n}\n"],"mappings":";;;AAEA,MAAM,8BAAgE;CACpE,mBAAmB;CACnB,SAAS;AACX;AASA,SAAgB,WACd,eACA,SACsB;CACtB,QAAQ,cAAc,MAAtB;EACE,KAAK,WACH,OAAO,EAAE,WAAW,YAAY,mBAAmB,cAAc,KAAK,EAAE,GAAG;EAC7E,KAAK,YAAY;GACf,MAAM,YACJ,SAAS,qBAAqB,cAAc,eAC5C,4BAA4B,c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;EACA,QAAQ,GAAG;EACX,QAAQ,GAAG;EACX,YAAY,GAAG;EACf,UAAU,WAAW,uBAAuB,YAAY,KAAA;EACxD,UAAU,WAAW,uBAAuB,YAAY,KAAA;EACxD;CACF;AACF;AAEA,SAAS,uBACP,SACA,WACA,gBACQ;CACR,IAAI,CAAC,UAAU,IAAI,OAAO,GACxB,OAAO;CAGT,MAAM,aAAa,GAAG,UAAU;CAChC,IAAI,CAAC,UAAU,IAAI,UAAU,GAC3B,OAAO;CAGT,IAAI,UAAU;CACd,OAAO,UAAU,IAAI,GAAG,UAAU,SAAS,GACzC;CAEF,OAAO,GAAG,UAAU;AACtB;AAEA,SAAS,iBACP,KACA,WACA,OACM;CACN,MAAM,WAAW,IAAI,IAAI,SAAS;CAClC,IAAI,UACF,SAAS,KAAK,KAAK;MAEnB,IAAI,IAAI,WAAW,CAAC,KAAK,CAAC;AAE9B"}
|
|
1
|
+
{"version":3,"file":"psl-infer.mjs","names":[],"sources":["../src/core/psl-contract-infer/default-mapping.ts","../src/core/psl-contract-infer/name-transforms.ts","../src/core/psl-contract-infer/raw-default-parser.ts","../src/core/psl-contract-infer/relation-inference.ts"],"sourcesContent":["import type { ColumnDefault } from '@prisma-next/contract/types';\n\nconst DEFAULT_FUNCTION_ATTRIBUTES: Readonly<Record<string, string>> = {\n 'autoincrement()': '@default(autoincrement())',\n 'now()': '@default(now())',\n};\n\nexport interface DefaultMappingOptions {\n readonly functionAttributes?: Readonly<Record<string, string>>;\n readonly fallbackFunctionAttribute?: ((expression: string) => string | undefined) | undefined;\n}\n\nexport type DefaultMappingResult = { readonly attribute: string } | { readonly comment: string };\n\nexport function mapDefault(\n columnDefault: ColumnDefault,\n options?: DefaultMappingOptions,\n): DefaultMappingResult {\n switch (columnDefault.kind) {\n case 'literal':\n return { attribute: `@default(${formatLiteralValue(columnDefault.value)})` };\n case 'function': {\n const attribute =\n options?.functionAttributes?.[columnDefault.expression] ??\n DEFAULT_FUNCTION_ATTRIBUTES[columnDefault.expression] ??\n options?.fallbackFunctionAttribute?.(columnDefault.expression);\n return attribute\n ? { attribute }\n : { comment: `// Raw default: ${columnDefault.expression.replace(/[\\r\\n]+/g, ' ')}` };\n }\n }\n}\n\nfunction formatLiteralValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n\n switch (typeof value) {\n case 'boolean':\n case 'number':\n return String(value);\n case 'string':\n return quoteString(value);\n default:\n return quoteString(JSON.stringify(value));\n }\n}\n\nfunction quoteString(str: string): string {\n return `\"${escapeString(str)}\"`;\n}\n\nfunction escapeString(str: string): string {\n return JSON.stringify(str).slice(1, -1);\n}\n","import pluralizeLib from 'pluralize';\n\nconst PSL_RESERVED_WORDS = new Set(['model', 'enum', 'types', 'type', 'generator', 'datasource']);\n\nconst IDENTIFIER_PART_PATTERN = /[A-Za-z0-9]+/g;\n\ntype NameResult = {\n readonly name: string;\n readonly map?: string;\n};\n\nfunction hasSeparators(input: string): boolean {\n return /[^A-Za-z0-9]/.test(input);\n}\n\nfunction extractIdentifierParts(input: string): string[] {\n return input.match(IDENTIFIER_PART_PATTERN) ?? [];\n}\n\nfunction createSyntheticIdentifier(input: string): string {\n let hash = 2166136261;\n\n for (const char of input) {\n hash ^= char.codePointAt(0) ?? 0;\n hash = Math.imul(hash, 16777619);\n }\n\n return `x${(hash >>> 0).toString(16)}`;\n}\n\nfunction sanitizeIdentifierCharacters(input: string): string {\n const sanitized = input.replace(/[^\\w]/g, '');\n return sanitized.length > 0 ? sanitized : createSyntheticIdentifier(input);\n}\n\nfunction capitalize(word: string): string {\n return word.charAt(0).toUpperCase() + word.slice(1);\n}\n\nfunction snakeToPascalCase(input: string): string {\n const parts = extractIdentifierParts(input);\n if (parts.length === 0) {\n return capitalize(sanitizeIdentifierCharacters(input));\n }\n return parts.map(capitalize).join('');\n}\n\nfunction snakeToCamelCase(input: string): string {\n const parts = extractIdentifierParts(input);\n if (parts.length === 0) {\n return sanitizeIdentifierCharacters(input);\n }\n const [firstPart = input, ...rest] = parts;\n return firstPart.charAt(0).toLowerCase() + firstPart.slice(1) + rest.map(capitalize).join('');\n}\n\nfunction needsEscaping(name: string): boolean {\n return PSL_RESERVED_WORDS.has(name.toLowerCase()) || /^\\d/.test(name);\n}\n\nfunction escapeName(name: string): string {\n return `_${name}`;\n}\n\nfunction escapeIfNeeded(name: string): string {\n return needsEscaping(name) ? escapeName(name) : name;\n}\n\nexport function toModelName(tableName: string): NameResult {\n let name: string;\n\n if (hasSeparators(tableName)) {\n name = snakeToPascalCase(tableName);\n } else {\n name = tableName.charAt(0).toUpperCase() + tableName.slice(1);\n }\n\n if (needsEscaping(name)) {\n const escaped = escapeName(name);\n return { name: escaped, map: tableName };\n }\n\n if (name !== tableName) {\n return { name, map: tableName };\n }\n\n return { name };\n}\n\nexport function toFieldName(columnName: string): NameResult {\n let name: string;\n\n if (hasSeparators(columnName)) {\n name = snakeToCamelCase(columnName);\n } else {\n name = columnName.charAt(0).toLowerCase() + columnName.slice(1);\n }\n\n if (needsEscaping(name)) {\n const escaped = escapeName(name);\n return { name: escaped, map: columnName };\n }\n\n if (name !== columnName) {\n return { name, map: columnName };\n }\n\n return { name };\n}\n\nexport function toEnumName(pgTypeName: string): NameResult {\n let name: string;\n\n if (hasSeparators(pgTypeName)) {\n name = snakeToPascalCase(pgTypeName);\n } else {\n name = pgTypeName.charAt(0).toUpperCase() + pgTypeName.slice(1);\n }\n\n if (needsEscaping(name)) {\n const escaped = escapeName(name);\n return { name: escaped, map: pgTypeName };\n }\n\n if (name !== pgTypeName) {\n return { name, map: pgTypeName };\n }\n\n return { name };\n}\n\nconst VALID_IDENTIFIER_PATTERN = /^[A-Za-z_]\\w*$/;\n\n/**\n * PSL member name for a native-enum value. The value itself always prints\n * explicitly (`member = \"value\"`), so the returned name never needs a map:\n * a value that already is a valid, non-reserved identifier is kept verbatim\n * (case included); anything else is camelCased/escaped like a field name.\n */\nexport function toEnumMemberName(value: string): string {\n if (VALID_IDENTIFIER_PATTERN.test(value) && !needsEscaping(value)) {\n return value;\n }\n return escapeIfNeeded(snakeToCamelCase(value));\n}\n\nexport function pluralize(word: string): string {\n return pluralizeLib.plural(word);\n}\n\nexport function deriveRelationFieldName(\n fkColumns: readonly string[],\n referencedTableName: string,\n): string {\n if (fkColumns.length === 1) {\n const [col = referencedTableName] = fkColumns;\n const stripped = col.replace(/_id$/i, '').replace(/Id$/, '');\n\n if (stripped.length > 0 && stripped !== col) {\n return escapeIfNeeded(snakeToCamelCase(stripped));\n }\n return escapeIfNeeded(snakeToCamelCase(referencedTableName));\n }\n\n return escapeIfNeeded(snakeToCamelCase(referencedTableName));\n}\n\nexport function deriveBackRelationFieldName(childModelName: string, isOneToOne: boolean): string {\n const base = childModelName.charAt(0).toLowerCase() + childModelName.slice(1);\n return isOneToOne ? base : pluralize(base);\n}\n","import type { ColumnDefault } from '@prisma-next/contract/types';\n\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst NOW_FUNCTION_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP)$/i;\nconst CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\\s*\\(\\s*\\)$/i;\nconst TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\\s+(?:with|without)\\s+time\\s+zone)?$/i;\nconst TEXT_CAST_SUFFIX = /::text$/i;\nconst NOW_LITERAL_PATTERN = /^'now'$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst NULL_PATTERN = /^NULL(?:::.+)?$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst JSON_CAST_SUFFIX = /::jsonb?$/i;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n\nfunction canonicalizeTimestampDefault(expr: string): string | undefined {\n if (NOW_FUNCTION_PATTERN.test(expr)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(expr)) return 'clock_timestamp()';\n\n if (!TIMESTAMP_CAST_SUFFIX.test(expr)) return undefined;\n\n let inner = expr.replace(TIMESTAMP_CAST_SUFFIX, '').trim();\n if (inner.startsWith('(') && inner.endsWith(')')) {\n inner = inner.slice(1, -1).trim();\n }\n\n if (NOW_FUNCTION_PATTERN.test(inner)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(inner)) return 'clock_timestamp()';\n\n inner = inner.replace(TEXT_CAST_SUFFIX, '').trim();\n if (NOW_LITERAL_PATTERN.test(inner)) return 'now()';\n\n return undefined;\n}\n\nexport function parseRawDefault(\n rawDefault: string,\n nativeType?: string,\n): ColumnDefault | undefined {\n const trimmed = rawDefault.trim();\n const normalizedType = nativeType?.toLowerCase();\n\n if (NEXTVAL_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'autoincrement()' };\n }\n\n const canonicalTimestamp = canonicalizeTimestampDefault(trimmed);\n if (canonicalTimestamp) {\n return { kind: 'function', expression: canonicalTimestamp };\n }\n\n if (UUID_PATTERN.test(trimmed) || UUID_OSSP_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (NULL_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: null };\n }\n\n if (TRUE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: true };\n }\n\n if (FALSE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: false };\n }\n\n if (NUMERIC_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: Number(trimmed) };\n }\n\n const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n if (stringMatch?.[1] !== undefined) {\n const unescaped = stringMatch[1].replace(/''/g, \"'\");\n if (normalizedType === 'json' || normalizedType === 'jsonb') {\n if (JSON_CAST_SUFFIX.test(trimmed)) {\n return { kind: 'function', expression: trimmed };\n }\n try {\n return { kind: 'literal', value: JSON.parse(unescaped) };\n } catch {\n // Fall through to the string form for malformed/non-JSON values.\n }\n }\n return { kind: 'literal', value: unescaped };\n }\n\n return { kind: 'function', expression: trimmed };\n}\n","import {\n backingIndexColumnKeys,\n isBackedByColumnKeys,\n} from '@prisma-next/sql-contract/foreign-key-materialization';\nimport type { SqlForeignKeyIR, SqlTableIR } from '@prisma-next/sql-schema-ir/types';\nimport { deriveBackRelationFieldName, deriveRelationFieldName, pluralize } from './name-transforms';\nimport type { RelationField } from './printer-config';\n\nconst DEFAULT_ON_DELETE = 'noAction';\nconst DEFAULT_ON_UPDATE = 'noAction';\n\nconst REFERENTIAL_ACTION_PSL: Record<string, string> = {\n noAction: 'NoAction',\n restrict: 'Restrict',\n cascade: 'Cascade',\n setNull: 'SetNull',\n setDefault: 'SetDefault',\n};\n\nexport type InferredRelations = {\n readonly relationsByTable: ReadonlyMap<string, readonly RelationField[]>;\n};\n\nexport function inferRelations(\n tables: Record<string, SqlTableIR>,\n modelNameMap: ReadonlyMap<string, string>,\n): InferredRelations {\n const relationsByTable = new Map<string, RelationField[]>();\n\n const fkCountByPair = new Map<string, number>();\n for (const table of Object.values(tables)) {\n for (const fk of table.foreignKeys) {\n const pairKey = `${table.name}→${fk.referencedTable}`;\n fkCountByPair.set(pairKey, (fkCountByPair.get(pairKey) ?? 0) + 1);\n }\n }\n\n const usedFieldNames = new Map<string, Set<string>>();\n for (const table of Object.values(tables)) {\n const names = new Set<string>();\n for (const col of Object.values(table.columns)) {\n names.add(col.name);\n }\n usedFieldNames.set(table.name, names);\n }\n\n for (const table of Object.values(tables)) {\n for (const fk of table.foreignKeys) {\n const childTableName = table.name;\n const parentTableName = fk.referencedTable;\n const childUsed = usedFieldNames.get(childTableName) as Set<string>;\n const childModelName = modelNameMap.get(childTableName) ?? childTableName;\n const parentModelName = modelNameMap.get(parentTableName) ?? parentTableName;\n const pairKey = `${childTableName}→${parentTableName}`;\n const isSelfRelation = childTableName === parentTableName;\n const needsRelationName = (fkCountByPair.get(pairKey) as number) > 1 || isSelfRelation;\n\n const isOneToOne = detectOneToOne(fk, table);\n\n const childRelFieldName = resolveUniqueFieldName(\n deriveRelationFieldName(fk.columns, parentTableName),\n childUsed,\n parentModelName,\n );\n const relationName = needsRelationName\n ? deriveRelationName(fk, childRelFieldName, parentModelName, isSelfRelation)\n : undefined;\n const childOptional = fk.columns.some(\n (columnName) => table.columns[columnName]?.nullable ?? false,\n );\n\n const childRelField = buildChildRelationField(\n childRelFieldName,\n parentModelName,\n fk,\n childOptional,\n relationName,\n table,\n );\n\n addRelationField(relationsByTable, childTableName, childRelField);\n childUsed.add(childRelFieldName);\n\n const parentUsed = usedFieldNames.get(parentTableName) ?? new Set();\n usedFieldNames.set(parentTableName, parentUsed);\n\n const backRelFieldName = resolveUniqueFieldName(\n deriveBackRelationFieldName(childModelName, isOneToOne),\n parentUsed,\n childModelName,\n );\n\n const backRelField: RelationField = {\n fieldName: backRelFieldName,\n typeName: childModelName,\n optional: isOneToOne,\n list: !isOneToOne,\n relationName,\n };\n\n addRelationField(relationsByTable, parentTableName, backRelField);\n parentUsed.add(backRelFieldName);\n }\n }\n\n return { relationsByTable };\n}\n\nfunction detectOneToOne(fk: SqlForeignKeyIR, table: SqlTableIR): boolean {\n const fkCols = [...fk.columns].sort();\n\n if (table.primaryKey) {\n const pkCols = [...table.primaryKey.columns].sort();\n if (pkCols.length === fkCols.length && pkCols.every((c, i) => c === fkCols[i])) {\n return true;\n }\n }\n\n for (const unique of table.uniques) {\n const uniqueCols = [...unique.columns].sort();\n if (uniqueCols.length === fkCols.length && uniqueCols.every((c, i) => c === fkCols[i])) {\n return true;\n }\n }\n\n for (const index of table.indexes) {\n if (!index.unique || index.partial || index.columns === undefined) {\n continue;\n }\n const indexCols = [...index.columns].sort();\n if (indexCols.length === fkCols.length && indexCols.every((c, i) => c === fkCols[i])) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction deriveRelationName(\n fk: SqlForeignKeyIR,\n childRelationFieldName: string,\n parentModelName: string,\n isSelfRelation: boolean,\n): string {\n if (fk.name) {\n return fk.name;\n }\n if (isSelfRelation) {\n return `${childRelationFieldName.charAt(0).toUpperCase() + childRelationFieldName.slice(1)}${pluralize(parentModelName)}`;\n }\n return fk.columns.join('_');\n}\n\n/**\n * Builds the child-side {@link RelationField} for a single foreign key:\n * `typeName` is the parent model name, `fields`/`references` are the FK's raw\n * columns, and `onDelete`/`onUpdate` are normalized to their PSL spelling.\n * Exported so a caller resolving a foreign key against a model outside\n * `tables` (e.g. a cross-space reference into another contract) can reuse the\n * same normalization instead of duplicating it.\n *\n * `hostTable` is the table the FK is declared on (i.e. `table`, not the\n * referenced parent) — its own indexes/uniques/primary key are what a\n * backing index for this FK would be. When none of them exactly match the\n * FK's source columns (in order), `index: false` is stamped so the emitted\n * `@relation` opts out of the framework's default derived backing-index\n * expectation, matching what `db verify` will find live. Passing the table\n * is optional so existing single-FK callers (e.g. cross-space resolution\n * before a host table reference is threaded through) can omit it and keep\n * the framework default.\n */\nexport function buildChildRelationField(\n fieldName: string,\n parentModelName: string,\n fk: SqlForeignKeyIR,\n optional: boolean,\n relationName?: string,\n hostTable?: SqlTableIR,\n): RelationField {\n const onDelete = fk.onDelete && fk.onDelete !== DEFAULT_ON_DELETE ? fk.onDelete : undefined;\n const onUpdate = fk.onUpdate && fk.onUpdate !== DEFAULT_ON_UPDATE ? fk.onUpdate : undefined;\n const index =\n hostTable &&\n !isBackedByColumnKeys(\n fk.columns,\n // Only indexes the inferrer actually emits can back the FK in the\n // emitted contract: partial indexes (and expression indexes, which\n // carry no column tuple) are not emitted yet, so\n // they must not suppress the explicit `index: false`.\n backingIndexColumnKeys({\n indexes: hostTable.indexes.filter((i) => i.where === undefined),\n uniques: hostTable.uniques,\n primaryKey: hostTable.primaryKey,\n }),\n )\n ? false\n : undefined;\n\n return {\n fieldName,\n typeName: parentModelName,\n referencedTableName: fk.referencedTable,\n optional,\n list: false,\n relationName,\n fkName: fk.name,\n fields: fk.columns,\n references: fk.referencedColumns,\n onDelete: onDelete ? REFERENTIAL_ACTION_PSL[onDelete] : undefined,\n onUpdate: onUpdate ? REFERENTIAL_ACTION_PSL[onUpdate] : undefined,\n index,\n };\n}\n\nfunction resolveUniqueFieldName(\n desired: string,\n usedNames: ReadonlySet<string>,\n fallbackSuffix: string,\n): string {\n if (!usedNames.has(desired)) {\n return desired;\n }\n\n const withSuffix = `${desired}${fallbackSuffix}`;\n if (!usedNames.has(withSuffix)) {\n return withSuffix;\n }\n\n let counter = 2;\n while (usedNames.has(`${desired}${counter}`)) {\n counter++;\n }\n return `${desired}${counter}`;\n}\n\nfunction addRelationField(\n map: Map<string, RelationField[]>,\n tableName: string,\n field: RelationField,\n): void {\n const existing = map.get(tableName);\n if (existing) {\n existing.push(field);\n } else {\n map.set(tableName, [field]);\n }\n}\n"],"mappings":";;;AAEA,MAAM,8BAAgE;CACpE,mBAAmB;CACnB,SAAS;AACX;AASA,SAAgB,WACd,eACA,SACsB;CACtB,QAAQ,cAAc,MAAtB;EACE,KAAK,WACH,OAAO,EAAE,WAAW,YAAY,mBAAmB,cAAc,KAAK,EAAE,GAAG;EAC7E,KAAK,YAAY;GACf,MAAM,YACJ,SAAS,qBAAqB,cAAc,eAC5C,4BAA4B,cAAc,eAC1C,SAAS,4BAA4B,cAAc,UAAU;GAC/D,OAAO,YACH,EAAE,UAAU,IACZ,EAAE,SAAS,mBAAmB,cAAc,WAAW,QAAQ,YAAY,GAAG,IAAI;EACxF;CACF;AACF;AAEA,SAAS,mBAAmB,OAAwB;CAClD,IAAI,UAAU,MACZ,OAAO;CAGT,QAAQ,OAAO,OAAf;EACE,KAAK;EACL,KAAK,UACH,OAAO,OAAO,KAAK;EACrB,KAAK,UACH,OAAO,YAAY,KAAK;EAC1B,SACE,OAAO,YAAY,KAAK,UAAU,KAAK,CAAC;CAC5C;AACF;AAEA,SAAS,YAAY,KAAqB;CACxC,OAAO,IAAI,aAAa,GAAG,EAAE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C,UAAU,IAAI,UAAU,GAC3B,OAAO;CAGT,IAAI,UAAU;CACd,OAAO,UAAU,IAAI,GAAG,UAAU,SAAS,GACzC;CAEF,OAAO,GAAG,UAAU;AACtB;AAEA,SAAS,iBACP,KACA,WACA,OACM;CACN,MAAM,WAAW,IAAI,IAAI,SAAS;CAClC,IAAI,UACF,SAAS,KAAK,KAAK;MAEnB,IAAI,IAAI,WAAW,CAAC,KAAK,CAAC;AAE9B"}
|
|
@@ -274,9 +274,9 @@ interface SqlMigrationPlannerPlanOptions {
|
|
|
274
274
|
* or `null` for reconciliation flows that have no prior contract.
|
|
275
275
|
*
|
|
276
276
|
* Required at every call site so the structural fact "I have a prior
|
|
277
|
-
* contract / I don't" is visible in the type. `migration plan` reads
|
|
278
|
-
*
|
|
279
|
-
* the parsed value; `db update` / `db init` reconcile against the
|
|
277
|
+
* contract / I don't" is visible in the type. `migration plan` reads the
|
|
278
|
+
* predecessor's contract from the snapshot store by its storage hash and
|
|
279
|
+
* passes the parsed value; `db update` / `db init` reconcile against the
|
|
280
280
|
* live schema and pass `null`. Strategies that
|
|
281
281
|
* need from/to column-shape comparisons (unsafe type change, nullability
|
|
282
282
|
* tightening) use this to decide whether to emit `dataTransform`
|
|
@@ -286,6 +286,13 @@ interface SqlMigrationPlannerPlanOptions {
|
|
|
286
286
|
* plan's `describe()` as `fromContract?.storage.storageHash ?? null`.
|
|
287
287
|
*/
|
|
288
288
|
readonly fromContract: Contract<SqlStorage> | null;
|
|
289
|
+
/**
|
|
290
|
+
* POSIX-relative path from the migration package dir to
|
|
291
|
+
* `migrations/snapshots`, e.g. `'../../snapshots'`. Threaded straight
|
|
292
|
+
* into the produced plan's `renderTypeScript()` metadata so the
|
|
293
|
+
* scaffold's contract-snapshot imports point at the deduplicated store.
|
|
294
|
+
*/
|
|
295
|
+
readonly snapshotsImportPath: string;
|
|
289
296
|
/**
|
|
290
297
|
* Active framework components participating in this composition.
|
|
291
298
|
* Each component is target-bound so SQL targets can dispatch
|
|
@@ -410,4 +417,4 @@ interface CreateSqlMigrationPlanOptions<TTargetDetails> {
|
|
|
410
417
|
}
|
|
411
418
|
//#endregion
|
|
412
419
|
export { SqlPlannerSuccessResult as A, SqlMigrationRunnerSuccessValue as C, SqlPlannerConflictLocation as D, SqlPlannerConflictKind as E, SqlPlannerFailureResult as O, SqlMigrationRunnerResult as S, SqlPlannerConflict as T, SqlMigrationRunner as _, FieldEvent as a, SqlMigrationRunnerExecuteOptions as b, SqlControlAdapterDescriptor as c, SqlMigrationPlanContractInfo as d, SqlMigrationPlanOperation as f, SqlMigrationPlannerPlanOptions as g, SqlMigrationPlanner as h, ExpandNativeTypeInput as i, StorageTypePlanResult as j, SqlPlannerResult as k, SqlControlExtensionDescriptor as l, SqlMigrationPlanOperationTarget as m, CodecControlHooks as n, FieldEventContext as o, SqlMigrationPlanOperationStep as p, CreateSqlMigrationPlanOptions as r, ResolveIdentityValueInput as s, AnyRecord as t, SqlMigrationPlan as u, SqlMigrationRunnerErrorCode as v, SqlPlanTargetDetails as w, SqlMigrationRunnerFailure as x, SqlMigrationRunnerExecuteCallbacks as y };
|
|
413
|
-
//# sourceMappingURL=types-
|
|
420
|
+
//# sourceMappingURL=types-DhAmOoxA.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-
|
|
1
|
+
{"version":3,"file":"types-DhAmOoxA.d.mts","names":[],"sources":["../src/core/migrations/types.ts"],"mappings":";;;;;;;;;;KAkCY,YAAY,SAAS;UAEhB,sBAAsB;WAC5B,qBAAqB,0BAA0B;;;;;UAMzC;WACN;WACA;WACA,aAAa;;;;;;;;;UAUP;WACN;WACA;WACA,aAAa;;;;;;;;;;;;;;;;KAiBZ;;;;;;;;;;;;;UAcK;WACN;WACA;WACA;WACA,aAAa;WACb,WAAW;WACX,aAAa;WACb,WAAW;;UAGL,kBAAkB;;;;;;;;;EASjC,sBAAsB;aACX;aACA,cAAc;aACd,UAAU,SAAS;aACnB,QAAQ;aACR;aACA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;UAGjD,mCAAmC;EAClD,kBAAkB,WAAW,0BAA0B;EACvD,qBAAqB,WAAW,0BAA0B;;UAG3C,iCAAiC;WACvC,MAAM,iBAAiB;WACvB,QAAQ;;;;;;;;WAQR;;;;;WAKA,qBAAqB,SAAS;;;;;WAK9B,QAAQ;WACR;WACA;WACA,YAAY,mCAAmC;WAC/C,UAAU;;;;;WAKV,kBAAkB;;;;;;;WAOlB,qBAAqB,cAAc;;;;;WAKnC,yBAAyB;;KAGxB;UAYK,kCAAkC;WACxC,MAAM;WACN,OAAO;;UAGD,uCAAuC;KAE5C,2BAA2B,OACrC,gCACA;UAGe,mBAAmB;;;;;;;;;;;;;;EAclC,QAAQ;aACG,QAAQ;aACR,iBAAiB,cAAc,iCAAiC;MACvE,QAAQ;;;;;;;;;;;EAYZ,oBACE,SAAS,iCAAiC,kBACzC,QAAQ;;UAGI,8BAA8B;WACpC;;;;WAIA;WACA,SAAS;WACT,aAAa;WACb,qBAAqB,0BAA0B;;;;;;WAM/C;WACA,OAAO"}
|
package/package.json
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/family-sql",
|
|
3
|
-
"version": "0.16.0-dev.
|
|
3
|
+
"version": "0.16.0-dev.30",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"description": "SQL family descriptor for Prisma Next",
|
|
8
8
|
"dependencies": {
|
|
9
|
-
"@prisma-next/contract": "0.16.0-dev.
|
|
10
|
-
"@prisma-next/emitter": "0.16.0-dev.
|
|
11
|
-
"@prisma-next/framework-components": "0.16.0-dev.
|
|
12
|
-
"@prisma-next/migration-tools": "0.16.0-dev.
|
|
13
|
-
"@prisma-next/operations": "0.16.0-dev.
|
|
14
|
-
"@prisma-next/sql-contract": "0.16.0-dev.
|
|
15
|
-
"@prisma-next/sql-contract-emitter": "0.16.0-dev.
|
|
16
|
-
"@prisma-next/sql-contract-ts": "0.16.0-dev.
|
|
17
|
-
"@prisma-next/sql-operations": "0.16.0-dev.
|
|
18
|
-
"@prisma-next/sql-relational-core": "0.16.0-dev.
|
|
19
|
-
"@prisma-next/sql-runtime": "0.16.0-dev.
|
|
20
|
-
"@prisma-next/sql-schema-ir": "0.16.0-dev.
|
|
21
|
-
"@prisma-next/utils": "0.16.0-dev.
|
|
9
|
+
"@prisma-next/contract": "0.16.0-dev.30",
|
|
10
|
+
"@prisma-next/emitter": "0.16.0-dev.30",
|
|
11
|
+
"@prisma-next/framework-components": "0.16.0-dev.30",
|
|
12
|
+
"@prisma-next/migration-tools": "0.16.0-dev.30",
|
|
13
|
+
"@prisma-next/operations": "0.16.0-dev.30",
|
|
14
|
+
"@prisma-next/sql-contract": "0.16.0-dev.30",
|
|
15
|
+
"@prisma-next/sql-contract-emitter": "0.16.0-dev.30",
|
|
16
|
+
"@prisma-next/sql-contract-ts": "0.16.0-dev.30",
|
|
17
|
+
"@prisma-next/sql-operations": "0.16.0-dev.30",
|
|
18
|
+
"@prisma-next/sql-relational-core": "0.16.0-dev.30",
|
|
19
|
+
"@prisma-next/sql-runtime": "0.16.0-dev.30",
|
|
20
|
+
"@prisma-next/sql-schema-ir": "0.16.0-dev.30",
|
|
21
|
+
"@prisma-next/utils": "0.16.0-dev.30",
|
|
22
22
|
"arktype": "^2.2.2",
|
|
23
23
|
"pluralize": "^8.0.0"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
|
-
"@prisma-next/driver-postgres": "0.16.0-dev.
|
|
27
|
-
"@prisma-next/psl-parser": "0.16.0-dev.
|
|
28
|
-
"@prisma-next/psl-printer": "0.16.0-dev.
|
|
29
|
-
"@prisma-next/sql-contract-psl": "0.16.0-dev.
|
|
30
|
-
"@prisma-next/test-utils": "0.16.0-dev.
|
|
31
|
-
"@prisma-next/tsconfig": "0.16.0-dev.
|
|
32
|
-
"@prisma-next/tsdown": "0.16.0-dev.
|
|
26
|
+
"@prisma-next/driver-postgres": "0.16.0-dev.30",
|
|
27
|
+
"@prisma-next/psl-parser": "0.16.0-dev.30",
|
|
28
|
+
"@prisma-next/psl-printer": "0.16.0-dev.30",
|
|
29
|
+
"@prisma-next/sql-contract-psl": "0.16.0-dev.30",
|
|
30
|
+
"@prisma-next/test-utils": "0.16.0-dev.30",
|
|
31
|
+
"@prisma-next/tsconfig": "0.16.0-dev.30",
|
|
32
|
+
"@prisma-next/tsdown": "0.16.0-dev.30",
|
|
33
33
|
"@types/pluralize": "^0.0.33",
|
|
34
34
|
"tsdown": "0.22.8",
|
|
35
35
|
"typescript": "5.9.3",
|
|
@@ -41,7 +41,6 @@ import type {
|
|
|
41
41
|
LowererContext,
|
|
42
42
|
SqlExecuteRequest,
|
|
43
43
|
} from '@prisma-next/sql-relational-core/ast';
|
|
44
|
-
import { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';
|
|
45
44
|
import type { SqlSchemaIRNode, SqlTableIR } from '@prisma-next/sql-schema-ir/types';
|
|
46
45
|
import { blindCast } from '@prisma-next/utils/casts';
|
|
47
46
|
import { ifDefined } from '@prisma-next/utils/defined';
|
|
@@ -350,9 +349,9 @@ interface DescriptorWithStorageTypes {
|
|
|
350
349
|
function buildSqlTypeMetadataRegistry(options: {
|
|
351
350
|
readonly target: DescriptorWithStorageTypes;
|
|
352
351
|
readonly adapter: DescriptorWithStorageTypes & { readonly targetId: string };
|
|
353
|
-
readonly
|
|
352
|
+
readonly extensions: readonly DescriptorWithStorageTypes[];
|
|
354
353
|
}): SqlTypeMetadataRegistry {
|
|
355
|
-
const { target, adapter,
|
|
354
|
+
const { target, adapter, extensions } = options;
|
|
356
355
|
const registry = new Map<string, SqlTypeMetadata>();
|
|
357
356
|
const targetId = adapter.targetId;
|
|
358
357
|
const descriptors = [target, adapter, ...extensions];
|
|
@@ -384,7 +383,7 @@ interface CrossSpaceFkView {
|
|
|
384
383
|
readonly id: string;
|
|
385
384
|
readonly contractSpace?: {
|
|
386
385
|
readonly contractJson?: {
|
|
387
|
-
readonly
|
|
386
|
+
readonly extensions?: Readonly<Record<string, unknown>>;
|
|
388
387
|
readonly storage?: {
|
|
389
388
|
readonly namespaces?: Readonly<Record<string, unknown>>;
|
|
390
389
|
};
|
|
@@ -402,7 +401,7 @@ function buildTransitiveDependsOnMap(
|
|
|
402
401
|
): Map<string, Set<string>> {
|
|
403
402
|
const directDeps = new Map<string, readonly string[]>();
|
|
404
403
|
for (const ext of extensions) {
|
|
405
|
-
const packs = ext.contractSpace?.contractJson?.
|
|
404
|
+
const packs = ext.contractSpace?.contractJson?.extensions;
|
|
406
405
|
const deps = packs !== null && typeof packs === 'object' ? Object.keys(packs) : [];
|
|
407
406
|
directDeps.set(ext.id, deps);
|
|
408
407
|
}
|
|
@@ -499,7 +498,7 @@ export function createSqlFamilyInstance<TTargetId extends string>(
|
|
|
499
498
|
const adapter = stack.adapter as unknown as SqlControlAdapterDescriptor<TTargetId> &
|
|
500
499
|
DescriptorWithStorageTypes;
|
|
501
500
|
const extensions =
|
|
502
|
-
stack.
|
|
501
|
+
stack.extensions as unknown as readonly (SqlControlExtensionDescriptor<TTargetId> &
|
|
503
502
|
DescriptorWithStorageTypes)[];
|
|
504
503
|
|
|
505
504
|
// Descriptor self-consistency check.
|
|
@@ -533,7 +532,7 @@ export function createSqlFamilyInstance<TTargetId extends string>(
|
|
|
533
532
|
const typeMetadataRegistry = buildSqlTypeMetadataRegistry({
|
|
534
533
|
target,
|
|
535
534
|
adapter,
|
|
536
|
-
|
|
535
|
+
extensions: extensions,
|
|
537
536
|
});
|
|
538
537
|
|
|
539
538
|
// Lazily construct the control adapter on first use, then memoize it.
|
|
@@ -1112,7 +1111,7 @@ export function createSqlFamilyInstance<TTargetId extends string>(
|
|
|
1112
1111
|
}
|
|
1113
1112
|
|
|
1114
1113
|
for (const index of table.indexes) {
|
|
1115
|
-
const name = index.name
|
|
1114
|
+
const name = index.name;
|
|
1116
1115
|
const label = index.unique ? `unique index ${name}` : `index ${name}`;
|
|
1117
1116
|
children.push(
|
|
1118
1117
|
new SchemaTreeNode({
|
|
@@ -276,17 +276,30 @@ function convertUnique(unique: UniqueConstraint, tableName: string): SqlUniqueIR
|
|
|
276
276
|
};
|
|
277
277
|
}
|
|
278
278
|
|
|
279
|
-
function convertIndex(
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
279
|
+
function convertIndex(
|
|
280
|
+
index: Index,
|
|
281
|
+
tableName: string,
|
|
282
|
+
tableColumns: readonly string[],
|
|
283
|
+
): SqlIndexIRInput {
|
|
284
|
+
const base = {
|
|
285
|
+
name: index.name,
|
|
286
|
+
prefix: index.prefix,
|
|
287
|
+
where: index.where,
|
|
288
|
+
unique: index.unique,
|
|
289
|
+
partial: index.where !== undefined,
|
|
284
290
|
// Carried so the derived index node compares type/options against the
|
|
285
291
|
// introspected side (the legacy walk read them from the contract).
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
292
|
+
type: index.type,
|
|
293
|
+
options: index.options,
|
|
294
|
+
annotations: undefined,
|
|
295
|
+
// An expression index's chains cover every column of its table — the
|
|
296
|
+
// opaque expression is never parsed, so this deterministic
|
|
297
|
+
// over-approximation keeps drops ordered without a SQL parser.
|
|
298
|
+
dependsOn: flatColumnDependsOn(tableName, index.columns ?? tableColumns),
|
|
289
299
|
};
|
|
300
|
+
return index.expression !== undefined
|
|
301
|
+
? { ...base, expression: index.expression }
|
|
302
|
+
: { ...base, columns: index.columns ?? [] };
|
|
290
303
|
}
|
|
291
304
|
|
|
292
305
|
/**
|
|
@@ -399,7 +412,7 @@ function convertTable(
|
|
|
399
412
|
// the object→own-column `dependsOn` edge like any other index.
|
|
400
413
|
foreignKeys: table.foreignKeys.map((fk) => convertForeignKey(fk, storage)),
|
|
401
414
|
uniques: table.uniques.map((u) => convertUnique(u, name)),
|
|
402
|
-
indexes: table.indexes.map((i) => convertIndex(i, name)),
|
|
415
|
+
indexes: table.indexes.map((i) => convertIndex(i, name, Object.keys(table.columns))),
|
|
403
416
|
...ifDefined('checks', checks),
|
|
404
417
|
});
|
|
405
418
|
}
|
|
@@ -334,9 +334,9 @@ export interface SqlMigrationPlannerPlanOptions {
|
|
|
334
334
|
* or `null` for reconciliation flows that have no prior contract.
|
|
335
335
|
*
|
|
336
336
|
* Required at every call site so the structural fact "I have a prior
|
|
337
|
-
* contract / I don't" is visible in the type. `migration plan` reads
|
|
338
|
-
*
|
|
339
|
-
* the parsed value; `db update` / `db init` reconcile against the
|
|
337
|
+
* contract / I don't" is visible in the type. `migration plan` reads the
|
|
338
|
+
* predecessor's contract from the snapshot store by its storage hash and
|
|
339
|
+
* passes the parsed value; `db update` / `db init` reconcile against the
|
|
340
340
|
* live schema and pass `null`. Strategies that
|
|
341
341
|
* need from/to column-shape comparisons (unsafe type change, nullability
|
|
342
342
|
* tightening) use this to decide whether to emit `dataTransform`
|
|
@@ -346,6 +346,13 @@ export interface SqlMigrationPlannerPlanOptions {
|
|
|
346
346
|
* plan's `describe()` as `fromContract?.storage.storageHash ?? null`.
|
|
347
347
|
*/
|
|
348
348
|
readonly fromContract: Contract<SqlStorage> | null;
|
|
349
|
+
/**
|
|
350
|
+
* POSIX-relative path from the migration package dir to
|
|
351
|
+
* `migrations/snapshots`, e.g. `'../../snapshots'`. Threaded straight
|
|
352
|
+
* into the produced plan's `renderTypeScript()` metadata so the
|
|
353
|
+
* scaffold's contract-snapshot imports point at the deduplicated store.
|
|
354
|
+
*/
|
|
355
|
+
readonly snapshotsImportPath: string;
|
|
349
356
|
/**
|
|
350
357
|
* Active framework components participating in this composition.
|
|
351
358
|
* Each component is target-bound so SQL targets can dispatch
|
|
@@ -169,15 +169,3 @@ export function deriveBackRelationFieldName(childModelName: string, isOneToOne:
|
|
|
169
169
|
const base = childModelName.charAt(0).toLowerCase() + childModelName.slice(1);
|
|
170
170
|
return isOneToOne ? base : pluralize(base);
|
|
171
171
|
}
|
|
172
|
-
|
|
173
|
-
export function toNamedTypeName(columnName: string): string {
|
|
174
|
-
let name: string;
|
|
175
|
-
|
|
176
|
-
if (hasSeparators(columnName)) {
|
|
177
|
-
name = snakeToPascalCase(columnName);
|
|
178
|
-
} else {
|
|
179
|
-
name = columnName.charAt(0).toUpperCase() + columnName.slice(1);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
return escapeIfNeeded(name);
|
|
183
|
-
}
|
|
@@ -1,17 +1,16 @@
|
|
|
1
1
|
import type { ColumnDefault } from '@prisma-next/contract/types';
|
|
2
2
|
import type { DefaultMappingOptions } from './default-mapping';
|
|
3
3
|
|
|
4
|
-
export type
|
|
4
|
+
export type PslTypeReference = {
|
|
5
5
|
readonly name: string;
|
|
6
6
|
readonly args?: readonly string[];
|
|
7
7
|
};
|
|
8
8
|
|
|
9
9
|
export type PslTypeResolution =
|
|
10
10
|
| {
|
|
11
|
-
readonly pslType:
|
|
11
|
+
readonly pslType: PslTypeReference;
|
|
12
12
|
readonly nativeType: string;
|
|
13
13
|
readonly typeParams?: Record<string, unknown>;
|
|
14
|
-
readonly nativeTypeAttribute?: PslNativeTypeAttribute;
|
|
15
14
|
}
|
|
16
15
|
| {
|
|
17
16
|
readonly unsupported: true;
|
|
@@ -123,6 +123,16 @@ function detectOneToOne(fk: SqlForeignKeyIR, table: SqlTableIR): boolean {
|
|
|
123
123
|
}
|
|
124
124
|
}
|
|
125
125
|
|
|
126
|
+
for (const index of table.indexes) {
|
|
127
|
+
if (!index.unique || index.partial || index.columns === undefined) {
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const indexCols = [...index.columns].sort();
|
|
131
|
+
if (indexCols.length === fkCols.length && indexCols.every((c, i) => c === fkCols[i])) {
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
126
136
|
return false;
|
|
127
137
|
}
|
|
128
138
|
|
|
@@ -170,7 +180,19 @@ export function buildChildRelationField(
|
|
|
170
180
|
const onDelete = fk.onDelete && fk.onDelete !== DEFAULT_ON_DELETE ? fk.onDelete : undefined;
|
|
171
181
|
const onUpdate = fk.onUpdate && fk.onUpdate !== DEFAULT_ON_UPDATE ? fk.onUpdate : undefined;
|
|
172
182
|
const index =
|
|
173
|
-
hostTable &&
|
|
183
|
+
hostTable &&
|
|
184
|
+
!isBackedByColumnKeys(
|
|
185
|
+
fk.columns,
|
|
186
|
+
// Only indexes the inferrer actually emits can back the FK in the
|
|
187
|
+
// emitted contract: partial indexes (and expression indexes, which
|
|
188
|
+
// carry no column tuple) are not emitted yet, so
|
|
189
|
+
// they must not suppress the explicit `index: false`.
|
|
190
|
+
backingIndexColumnKeys({
|
|
191
|
+
indexes: hostTable.indexes.filter((i) => i.where === undefined),
|
|
192
|
+
uniques: hostTable.uniques,
|
|
193
|
+
primaryKey: hostTable.primaryKey,
|
|
194
|
+
}),
|
|
195
|
+
)
|
|
174
196
|
? false
|
|
175
197
|
: undefined;
|
|
176
198
|
|
package/src/exports/psl-infer.ts
CHANGED
|
@@ -22,13 +22,12 @@ export {
|
|
|
22
22
|
toEnumName,
|
|
23
23
|
toFieldName,
|
|
24
24
|
toModelName,
|
|
25
|
-
toNamedTypeName,
|
|
26
25
|
} from '../core/psl-contract-infer/name-transforms';
|
|
27
26
|
export type {
|
|
28
27
|
EnumInfo,
|
|
29
|
-
PslNativeTypeAttribute,
|
|
30
28
|
PslPrinterOptions,
|
|
31
29
|
PslTypeMap,
|
|
30
|
+
PslTypeReference,
|
|
32
31
|
PslTypeResolution,
|
|
33
32
|
RelationField,
|
|
34
33
|
} from '../core/psl-contract-infer/printer-config';
|