Repository: Quramy/prisma-fabbrica
Pull request #53 (2022-11-28 15:33:04)

CONTRIBUTING.md add migrate:test
CONTRIBUTING.mdの手順に従い、動作確認をしようとしたところ
```sh
The table `main.User` does not exist in the current database.
```

テーブルが存在していないため、test通過できない状態だったため
CONTRIBUTING.mdに、migrate:testの実行手順を追記しました。

```sh
Test Suites: 3 passed, 3 total
Tests:       9 passed, 9 total
Snapshots:   0 total
Time:        1.494 s, estimated 2 s
```

実行後はtest通過することを確認できています。

認識齟齬、問題などないかレビューお願いいたします。


Patch:
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a79768b..77f1749 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -5,5 +5,6 @@
 ```sh
 $ npm ci
 $ npm run bootstrap
+$ npm run migrate:test
 $ npm test
 ```
diff --git a/examples/example-prj/package.json b/examples/example-prj/package.json
index 1aed7ea..8ef36ea 100644
--- a/examples/example-prj/package.json
+++ b/examples/example-prj/package.json
@@ -1,7 +1,7 @@
 {
   "private": true,
   "name": "example-prj",
-  "version": "0.2.1",
+  "version": "0.2.0",
   "scripts": {
     "bootstrap": "npm run generate",
     "clean": "echo nothing to do",
diff --git a/package-lock.json b/package-lock.json
index a416a38..aba7ca4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -25,7 +25,7 @@
       }
     },
     "examples/example-prj": {
-      "version": "0.2.1",
+      "version": "0.2.0",
       "dependencies": {
         "@prisma/client": "4.6.1",
         "@types/uuid": "8.3.4",
@@ -6775,7 +6775,7 @@
     },
     "packages/prisma-fabbrica": {
       "name": "@quramy/prisma-fabbrica",
-      "version": "0.2.1",
+      "version": "0.2.0",
       "license": "MIT",
       "dependencies": {
         "@prisma/generator-helper": "^4.2.0",
@@ -6834,7 +6834,7 @@
       }
     },
     "packages/ts-compile-testing": {
-      "version": "0.2.1",
+      "version": "0.2.0",
       "devDependencies": {
         "@prisma/client": "4.6.1",
         "@prisma/internals": "4.6.1",
diff --git a/packages/prisma-fabbrica/package.json b/packages/prisma-fabbrica/package.json
index 768b601..1553bd6 100644
--- a/packages/prisma-fabbrica/package.json
+++ b/packages/prisma-fabbrica/package.json
@@ -1,6 +1,6 @@
 {
   "name": "@quramy/prisma-fabbrica",
-  "version": "0.2.1",
+  "version": "0.2.0",
   "description": " Prisma generator for model factories",
   "main": "./lib/index.js",
   "types": "./lib/index.d.ts",
diff --git a/packages/prisma-fabbrica/src/scalar/types.ts b/packages/prisma-fabbrica/src/scalar/types.ts
index ce8b1e3..65668f0 100644
--- a/packages/prisma-fabbrica/src/scalar/types.ts
+++ b/packages/prisma-fabbrica/src/scalar/types.ts
@@ -12,7 +12,7 @@ export interface ScalarFieldValueGenerator {
   Int: (options: ScalarFieldGenerateOptions) => number;
   Float: (options: ScalarFieldGenerateOptions) => number;
   BigInt: (options: ScalarFieldGenerateOptions) => bigint;
-  Decimal: (options: ScalarFieldGenerateOptions) => any;
+  Decimal: (options: ScalarFieldGenerateOptions) => unknown;
   DateTime: (options: ScalarFieldGenerateOptions) => Date;
   Bytes: (options: ScalarFieldGenerateOptions) => Buffer;
   Json: (options: ScalarFieldGenerateOptions) => any;
diff --git a/packages/prisma-fabbrica/src/templates/index.ts b/packages/prisma-fabbrica/src/templates/index.ts
index e699c46..654c22d 100644
--- a/packages/prisma-fabbrica/src/templates/index.ts
+++ b/packages/prisma-fabbrica/src/templates/index.ts
@@ -20,7 +20,10 @@ function filterRequiredFields(inputType: DMMF.InputType) {
 }
 
 function isScalarOrEnumField(field: DMMF.SchemaArg) {
-  return field.inputTypes.every(cit => cit.location === "enumTypes" || cit.location === "scalar");
+  return (
+    field.inputTypes.length === 1 &&
+    field.inputTypes.every(cit => cit.location === "enumTypes" || cit.location === "scalar")
+  );
 }
 
 function isInputObjectTypeField(field: DMMF.SchemaArg) {
@@ -28,9 +31,7 @@ function isInputObjectTypeField(field: DMMF.SchemaArg) {
 }
 
 function filterRequiredScalarOrEnumFields(inputType: DMMF.InputType) {
-  return filterRequiredFields(inputType)
-    .filter(inputType => !inputType.isNullable)
-    .filter(isScalarOrEnumField);
+  return filterRequiredFields(inputType).filter(isScalarOrEnumField);
 }
 
 function filterRequiredInputObjectTypeField(inputType: DMMF.InputType) {
@@ -93,8 +94,6 @@ export const scalarFieldType = (
     throw new Error("Invalid call. This function is allowed for only scalar field.");
   }
   switch (inputType.type) {
-    case "Null":
-      return ast.literalTypeNode(ast.null());
     case "Boolean":
       return ast.keywordTypeNode(ts.SyntaxKind.BooleanKeyword);
     case "String":
@@ -103,15 +102,17 @@ export const scalarFieldType = (
     case "Float":
       return ast.keywordTypeNode(ts.SyntaxKind.NumberKeyword);
     case "BigInt":
-      return template.typeNode`bigint | number`();
+      return ast.keywordTypeNode(ts.SyntaxKind.BigIntKeyword);
     case "Decimal":
-      return template.typeNode`Prisma.Decimal | Prisma.DecimalJsLike | string`();
+      return template.typeNode`Prisma.Decimal`();
     case "DateTime":
       return template.typeNode`Date`();
     case "Bytes":
       return template.typeNode`Buffer`();
     case "Json":
-      return template.typeNode`Prisma.InputJsonValue`();
+      // FIXME Is the folloing type right?
+      // return template.typeNode`Prisma.Json`();
+      return ast.keywordTypeNode(ts.SyntaxKind.AnyKeyword);
     default:
       throw new Error(`Unknown scalar type "${inputType.type}" for ${model.name}.${fieldName} .`);
   }
@@ -122,9 +123,7 @@ export const argInputType = (model: DMMF.Model, fieldName: string, inputType: DM
     if (inputType.location === "scalar") {
       return scalarFieldType(model, fieldName, inputType);
     } else if (inputType.location === "enumTypes") {
-      return inputType.namespace === "model"
-        ? ast.typeReferenceNode(ast.identifier(inputType.type as string))
-        : template.typeNode`Prisma.${() => ast.identifier(inputType.type as string)}`();
+      return ast.typeReferenceNode(ast.identifier(inputType.type as string));
     } else if (inputType.location === "outputObjectTypes" || inputType.location === "inputObjectTypes") {
       return ast.typeReferenceNode(
         template.expression<ts.Identifier>`Prisma.${() => ast.identifier(inputType.type as string)}`(),
@@ -227,12 +226,11 @@ export const autoGenerateModelScalarsOrEnumsFieldArgs = (
   field: DMMF.SchemaArg,
   enums: DMMF.SchemaEnum[],
 ) =>
-  // Note: In Json sclar filed, inputTypes[0].location is not scalar but enumType
-  field.inputTypes[field.inputTypes.length - 1].location === "scalar"
+  field.inputTypes[0].location === "scalar"
     ? template.expression`
         scalarFieldValueGenerator.SCALAR_TYPE({ modelName: MODEL_NAME, fieldName: FIELD_NAME, isId: IS_ID, isUnique: IS_UNIQUE, seq })
       `({
-        SCALAR_TYPE: ast.identifier(field.inputTypes[field.inputTypes.length - 1].type as string),
+        SCALAR_TYPE: ast.identifier(field.inputTypes[0].type as string),
         MODEL_NAME: ast.stringLiteral(model.name),
         FIELD_NAME: ast.stringLiteral(field.name),
         IS_ID:
@@ -382,22 +380,18 @@ export function getSourceFile({
   document: DMMF.Document;
   prismaClientModuleSpecifier?: string;
 }) {
-  const modelEnums = [
+  const enums = [
     ...new Set(
       document.schema.inputObjectTypes.prisma
         .filter(iOT => iOT.name.endsWith("CreateInput"))
         .flatMap(filterEnumFields)
-        .flatMap(field =>
-          field.inputTypes
-            .filter(inputType => inputType.namespace === "model")
-            .map(inputType => inputType.type as string),
-        ),
+        .map(field => field.inputTypes[0].type as string),
     ),
   ];
   const modelNames = document.datamodel.models.map(m => m.name);
   const statements = [
     ...modelNames.map(modelName => importStatement(modelName, prismaClientModuleSpecifier)),
-    ...modelEnums.map(enumName => importStatement(enumName, prismaClientModuleSpecifier)),
+    ...enums.map(enumName => importStatement(enumName, prismaClientModuleSpecifier)),
     ...header(prismaClientModuleSpecifier).statements,
     modelFieldDefinitions(document.datamodel.models),
     ...document.datamodel.models


Test patch:
diff --git a/packages/prisma-fabbrica/src/templates/modelScalarOrEnumFields.test.ts b/packages/prisma-fabbrica/src/templates/modelScalarOrEnumFields.test.ts
index be18312..c7401cb 100644
--- a/packages/prisma-fabbrica/src/templates/modelScalarOrEnumFields.test.ts
+++ b/packages/prisma-fabbrica/src/templates/modelScalarOrEnumFields.test.ts
@@ -24,26 +24,12 @@ describe(modelScalarOrEnumFields, () => {
           boolField: boolean;
           strField: string;
           floatField: number;
-          bigIntField: (bigint | number);
+          bigIntField: bigint;
           bytesField: Buffer;
           dateTimeField: Date;
         }
       `,
     },
-    {
-      pattern: "Nullable field",
-      datamodel: `
-        model TestModel {
-          id            Int @id
-          nullableField String?
-        }
-      `,
-      expected: `
-        type TestModelScalarOrEnumFields = {
-          id: number;
-        }
-      `,
-    },
     {
       pattern: "Complex id",
       datamodel: `
diff --git a/packages/ts-compile-testing/fixtures/field-variation/__generated__/fabbrica/index.ts b/packages/ts-compile-testing/fixtures/field-variation/__generated__/fabbrica/index.ts
index ed2da5a..e7ed38c 100644
--- a/packages/ts-compile-testing/fixtures/field-variation/__generated__/fabbrica/index.ts
+++ b/packages/ts-compile-testing/fixtures/field-variation/__generated__/fabbrica/index.ts
@@ -1,6 +1,5 @@
 import { User } from "./../client";
 import { ComplexIdModel } from "./../client";
-import { FieldTypePatternModel } from "./../client";
 import { Role } from "./../client";
 import { Prisma } from "./../client";
 import type { PrismaClient } from "./../client";
@@ -18,9 +17,6 @@ const modelFieldDefinitions: ModelWithFields[] = [{
     }, {
         name: "ComplexIdModel",
         fields: []
-    }, {
-        name: "FieldTypePatternModel",
-        fields: []
     }];
 type UserScalarOrEnumFields = {
     id: string;
@@ -149,94 +145,3 @@ function defineComplexIdModelFactoryInternal({ defaultData: defaultDataResolver
 export function defineComplexIdModelFactory(args: ComplexIdModelFactoryDefineOptions = {}) {
     return defineComplexIdModelFactoryInternal(args);
 }
-type FieldTypePatternModelScalarOrEnumFields = {
-    id: number;
-    requiredInt: number;
-    requiredStr: string;
-    requiredBool: boolean;
-    requiredFlaot: number;
-    requiredDecimal: (Prisma.Decimal | Prisma.DecimalJsLike | string);
-    requiredJson: Prisma.JsonNullValueInput | Prisma.InputJsonValue;
-    requriedBytes: Buffer;
-    requiredBigInt: (bigint | number);
-};
-type FieldTypePatternModelFactoryDefineInput = {
-    id?: number;
-    requiredInt?: number;
-    nullableInt?: number | null;
-    requiredStr?: string;
-    nullableStr?: string | null;
-    requiredBool?: boolean;
-    nullableBool?: boolean | null;
-    requiredFlaot?: number;
-    nullableFloat?: number | null;
-    requiredDecimal?: (Prisma.Decimal | Prisma.DecimalJsLike | string);
-    nullableDecimal?: (Prisma.Decimal | Prisma.DecimalJsLike | string) | null;
-    requiredJson?: Prisma.JsonNullValueInput | Prisma.InputJsonValue;
-    nullableJson?: Prisma.NullableJsonNullValueInput | Prisma.InputJsonValue;
-    requriedBytes?: Buffer;
-    nullableBytes?: Buffer | null;
-    requiredBigInt?: (bigint | number);
-    nullableBigInt?: (bigint | number) | null;
-};
-type FieldTypePatternModelFactoryDefineOptions = {
-    defaultData?: Resolver<FieldTypePatternModelFactoryDefineInput, BuildDataOptions>;
-};
-function autoGenerateFieldTypePatternModelScalarsOrEnums({ seq }: {
-    readonly seq: number;
-}): FieldTypePatternModelScalarOrEnumFields {
-    return {
-        id: scalarFieldValueGenerator.Int({ modelName: "FieldTypePatternModel", fieldName: "id", isId: true, isUnique: false, seq }),
-        requiredInt: scalarFieldValueGenerator.Int({ modelName: "FieldTypePatternModel", fieldName: "requiredInt", isId: false, isUnique: false, seq }),
-        requiredStr: scalarFieldValueGenerator.String({ modelName: "FieldTypePatternModel", fieldName: "requiredStr", isId: false, isUnique: false, seq }),
-        requiredBool: scalarFieldValueGenerator.Boolean({ modelName: "FieldTypePatternModel", fieldName: "requiredBool", isId: false, isUnique: false, seq }),
-        requiredFlaot: scalarFieldValueGenerator.Float({ modelName: "FieldTypePatternModel", fieldName: "requiredFlaot", isId: false, isUnique: false, seq }),
-        requiredDecimal: scalarFieldValueGenerator.Decimal({ modelName: "FieldTypePatternModel", fieldName: "requiredDecimal", isId: false, isUnique: false, seq }),
-        requiredJson: scalarFieldValueGenerator.Json({ modelName: "FieldTypePatternModel", fieldName: "requiredJson", isId: false, isUnique: false, seq }),
-        requriedBytes: scalarFieldValueGenerator.Bytes({ modelName: "FieldTypePatternModel", fieldName: "requriedBytes", isId: false, isUnique: false, seq }),
-        requiredBigInt: scalarFieldValueGenerator.BigInt({ modelName: "FieldTypePatternModel", fieldName: "requiredBigInt", isId: false, isUnique: false, seq })
-    };
-}
-function defineFieldTypePatternModelFactoryInternal({ defaultData: defaultDataResolver }: FieldTypePatternModelFactoryDefineOptions) {
-    const seqKey = {};
-    const getSeq = () => getSequenceCounter(seqKey);
-    const screen = createScreener("FieldTypePatternModel", modelFieldDefinitions);
-    const build = async (inputData: Partial<Prisma.FieldTypePatternModelCreateInput> = {}) => {
-        const seq = getSeq();
-        const requiredScalarData = autoGenerateFieldTypePatternModelScalarsOrEnums({ seq });
-        const resolveValue = normalizeResolver<FieldTypePatternModelFactoryDefineInput, BuildDataOptions>(defaultDataResolver ?? {});
-        const defaultData = await resolveValue({ seq });
-        const defaultAssociations = {};
-        const data: Prisma.FieldTypePatternModelCreateInput = { ...requiredScalarData, ...defaultData, ...defaultAssociations, ...inputData };
-        return data;
-    };
-    const buildList = (inputData: number | Partial<Prisma.FieldTypePatternModelCreateInput>[]) => {
-        const list = typeof inputData === "number" ? [...new Array(inputData).keys()].map(() => ({})) : inputData;
-        return Promise.all(list.map(data => build(data)));
-    };
-    const pickForConnect = (inputData: FieldTypePatternModel) => ({
-        id: inputData.id
-    });
-    const create = async (inputData: Partial<Prisma.FieldTypePatternModelCreateInput> = {}) => {
-        const data = await build(inputData).then(screen);
-        return await getClient<PrismaClient>().fieldTypePatternModel.create({ data });
-    };
-    const createList = (inputData: number | Partial<Prisma.FieldTypePatternModelCreateInput>[]) => {
-        const list = typeof inputData === "number" ? [...new Array(inputData).keys()].map(() => ({})) : inputData;
-        return Promise.all(list.map(data => create(data)));
-    };
-    const createForConnect = (inputData: Partial<Prisma.FieldTypePatternModelCreateInput> = {}) => create(inputData).then(pickForConnect);
-    return {
-        _factoryFor: "FieldTypePatternModel" as const,
-        build,
-        buildList,
-        buildCreateInput: build,
-        pickForConnect,
-        create,
-        createList,
-        createForConnect,
-    };
-}
-export function defineFieldTypePatternModelFactory(args: FieldTypePatternModelFactoryDefineOptions = {}) {
-    return defineFieldTypePatternModelFactoryInternal(args);
-}
diff --git a/packages/ts-compile-testing/fixtures/field-variation/schema.prisma b/packages/ts-compile-testing/fixtures/field-variation/schema.prisma
index ed96db1..7e33e7f 100644
--- a/packages/ts-compile-testing/fixtures/field-variation/schema.prisma
+++ b/packages/ts-compile-testing/fixtures/field-variation/schema.prisma
@@ -31,23 +31,3 @@ model ComplexIdModel {
   lastName  String
   @@id([firstName, lastName])
 }
-
-model FieldTypePatternModel {
-  id              Int @id
-  requiredInt     Int
-  nullableInt     Int?
-  requiredStr     String
-  nullableStr     String?
-  requiredBool    Boolean
-  nullableBool    Boolean?
-  requiredFlaot   Float
-  nullableFloat   Float?
-  requiredDecimal Decimal
-  nullableDecimal Decimal?
-  requiredJson    Json
-  nullableJson    Json?
-  requriedBytes   Bytes
-  nullableBytes   Bytes?
-  requiredBigInt  BigInt
-  nullableBigInt  BigInt?
-}
diff --git a/packages/ts-compile-testing/package.json b/packages/ts-compile-testing/package.json
index 55a7b5b..51f630f 100644
--- a/packages/ts-compile-testing/package.json
+++ b/packages/ts-compile-testing/package.json
@@ -1,7 +1,7 @@
 {
   "private": true,
   "name": "ts-compile-testing",
-  "version": "0.2.1",
+  "version": "0.2.0",
   "scripts": {
     "clean": "rimraf \"fixtures/*/__generated__/client\" \"fixtures/*/dmmf.json\"",
     "pretest": "ts-node scripts/generateFixtures.ts",
diff --git a/packages/ts-compile-testing/scripts/generateFixtures.ts b/packages/ts-compile-testing/scripts/generateFixtures.ts
index d68922e..d3257ea 100644
--- a/packages/ts-compile-testing/scripts/generateFixtures.ts
+++ b/packages/ts-compile-testing/scripts/generateFixtures.ts
@@ -13,6 +13,8 @@ async function main() {
   for (const fixtureDir of dirs) {
     const schemaPath = path.resolve(fixturesDir, fixtureDir, "schema.prisma");
     if (!existsSync(schemaPath)) continue;
+    const { stdout } = await exec(`npx prisma generate --schema=${schemaPath}`);
+    process.stdout.write(stdout);
     const schemaContents = await fs.readFile(schemaPath, "utf8");
     const dmmfDocument = await getDMMF({
       datamodel: schemaContents,
@@ -22,8 +24,6 @@ async function main() {
       JSON.stringify(dmmfDocument, null, 2),
       "utf8",
     );
-    const { stdout } = await exec(`npx prisma generate --schema=${schemaPath}`);
-    process.stdout.write(stdout);
   }
 }