prisma / migrate

Issues for Prisma Migrate are now tracked at prisma/prisma. This repo was used to track issues for Prisma Migrate Experimental and is now deprecated.
https://www.prisma.io/docs/concepts/components/prisma-migrate
Apache License 2.0
766 stars 22 forks source link

No such table : test_XX when testing nexus-prisma #638

Closed asaadawey closed 3 years ago

asaadawey commented 4 years ago

Bug description

I have followed the documentation step by step of how to integrate testing with prisma and nexus But the code stops at execSync code block which has command

       execSync(`${prismaBinary} migrate up --create-db --experimental`, {
         env: {
           ...process.env,
           DATABASE_URL: databaseUrl,
         },
       });

How to reproduce

Just following this documentation https://nexusjs.org/docs/getting-started/tutorial/chapter-testing-your-api AND https://nexusjs.org/docs/getting-started/tutorial/chapter-testing-with-prisma

Here is my code

helpers.ts

import { PrismaClient } from "@prisma/client";
import { ServerInfo } from "apollo-server";
import { execSync } from "child_process";
import getPort, { makeRange } from "get-port";
import { GraphQLClient } from "graphql-request";
import { nanoid } from "nanoid";
import path from "path";
import { join } from "path";
import { Client } from "pg";
import { server } from "../src/server";
type TestContext = {
  client: GraphQLClient;
  db: PrismaClient;
};
export function createTestContext(): TestContext {
  let ctx = {} as TestContext;
  const graphqlCtx = graphqlTestContext();
  const prismaCtx = prismaTestContext();
  beforeEach(async () => {
    const client = await graphqlCtx.before();
    const db = await prismaCtx.before();
    Object.assign(ctx, {
      client,
      db,
    });
  });
  afterEach(async () => {
    await graphqlCtx.after();
    await prismaCtx.after();
  });
  return ctx;
}
function graphqlTestContext() {
  let serverInstance: ServerInfo | null = null;
  return {
    async before() {
      const port = await getPort({ port: makeRange(4000, 6000) });
      serverInstance = await server.listen({ port });
      return new GraphQLClient(`http://localhost:${port}`);
    },
    async after() {
      serverInstance?.server.close();
    },
  };
}
function prismaTestContext() {
  const prismaBinary = path.join(
    __dirname,
    '..',
    'node_modules',
    '.bin',
    'prisma'
  )
  let schema = "";
  let databaseUrl = "";
  let prismaClient: null | PrismaClient = null;
  return {
     async before() {
       // Generate a unique schema identifier for this test context
       schema = `test_${nanoid()}`;
       // Generate the pg connection string for the test schema
       databaseUrl = `postgresql://postgres:123456@localhost:5432/test?schema=${schema}`;
       // Set the required environment variable to contain the connection string
       // to our database test schema
       process.env.DATABASE_URL = databaseUrl;
       let a =process.env
      //  execSync(`${prismaBinary} migrate save --experimental`,{   
      //    env: {
      //   ...process.env,
      //   DATABASE_URL: databaseUrl,
      //    }
      // })
       // Run the migrations to ensure our schema has the required structure
       execSync(`${prismaBinary} migrate up --create-db --experimental`, {
         env: {
           ...process.env,
           DATABASE_URL: databaseUrl,
         },
       });
       // Construct a new Prisma Client connected to the generated Postgres schema
       prismaClient = new PrismaClient();
       return prismaClient;
     },
     async after() {
       // Drop the schema after the tests have completed
       const client = new Client({
         connectionString: databaseUrl,
       });
       await client.connect();
       await client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`);
       await client.end();
       // Release the Prisma Client connection
       await prismaClient?.$disconnect();
     },
   };
 }

run command :

jest

schema.prisma

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["connectOrCreate"]
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model accountTypes {
  id                       Int        @default(dbgenerated()) @id
  PARENT_ACCOUNT_TYPE_ID   Int?
  ACCOUNT_TYPE_NAME        String     @unique
  ACCOUNT_TYPE_DESCRIPTION String?
  BALANCE_TYPE             String
  ACCOUNT_TYPE_CODE_MIN    String?
  ACCOUNT_TYPE_CODE_MAX    String?
  IS_ACTIVE                Boolean?
  CREATED_BY               String?
  MODIFIED_BY              String?
  CREATED_ON               DateTime?
  MODIFIED_ON              DateTime?
  AMOUNT                   Float?
  accounts                 accounts[]
}

model accountingTransactions {
  id                  Int               @default(dbgenerated()) @id
  JOURNAL_ID          Int?
  ACCOUNT_ID          Int?
  ORGANIZATION_ID     Int?
  BRANCH_ID           Int?
  CREDIT_DEBIT        String?
  REFERENCE_NUMBER    String?
  POST_DATE           DateTime?
  CURRENCY            DateTime?
  AMOUNT              Float?
  IS_ACTIVE           Boolean?
  CREATED_BY          String?
  MODIFIED_BY         String?
  CREATED_ON          DateTime?         @default(now())
  MODIFIED_ON         DateTime?
  TRANSACTION_TYPE_ID Int?
  accounts            accounts?         @relation(fields: [ACCOUNT_ID], references: [id])
  journals            journals?         @relation(fields: [JOURNAL_ID], references: [id])
  transactionTypes    transactionTypes? @relation(fields: [TRANSACTION_TYPE_ID], references: [id])
}

model accounts {
  id                     Int                      @default(dbgenerated()) @id
  ACCOUNT_TYPE_ID        Int
  ORGANIZATION_ID        Int?
  BRANCH_ID              Int?
  PARENT_ACCOUNT_ID      Int?
  ACCOUNT_NAME           String
  ACCOUNT_DESCRIPTION    String?
  OPENING_BALANCE        Float
  DEBIT                  Float                    @default(0)
  CREDIT                 Float                    @default(0)
  CURRENT_BALANCE        Float                    @default(0)
  IS_ACTIVE              Boolean?
  CREATED_BY             String?
  MODIFIED_BY            String?
  CREATED_ON             DateTime?
  MODIFIED_ON            DateTime?
  accountTypes           accountTypes             @relation(fields: [ACCOUNT_TYPE_ID], references: [id])
  accounts               accounts?                @relation("accountsToaccounts_PARENT_ACCOUNT_ID", fields: [PARENT_ACCOUNT_ID], references: [id])
  accountingTransactions accountingTransactions[]
  other_accounts         accounts[]               @relation("accountsToaccounts_PARENT_ACCOUNT_ID")
  feeTypes               feeTypes[]
  receiptFeeTypes        receiptFeeTypes[]
}

model companies {
  id                             Int           @default(dbgenerated()) @id
  CONTACT_ID                     Int
  ORGANIZATION_ID                Int?
  COMPANY_TYPE                   String?
  COMMERCIAL_LICENSE_NUMBER      String?
  COMMERCIAL_LICENSE_ISSUE_DATE  DateTime?
  COMMERCIAL_LICENSE_EXPIRY_DATE DateTime?
  TRN                            String?
  FAX                            String?
  DATE_OF_ESTABLISHMENT          DateTime?
  WEBSITE                        String?
  PO_BOX                         String?
  SPOC_NAME_EN                   String?
  SPOC_NAME_AR                   String?
  IS_ACTIVE                      Boolean?
  CREATED_BY                     String?
  MODIFIED_BY                    String?
  CREATED_ON                     DateTime?
  MODIFIED_ON                    DateTime?
  contacts                       contacts      @relation(fields: [CONTACT_ID], references: [id])
  salesOrders                    salesOrders[]
}

model contactTypes {
  id                       Int        @id
  CONTACT_TYPE_NAME        String     @unique
  CONTACT_TYPE_DESCRIPTION String?
  IS_ACTIVE                Boolean?
  CREATED_BY               String?
  MODIFIED_BY              String?
  CREATED_ON               DateTime?
  MODIFIED_ON              DateTime?
  contacts                 contacts[]
}

Error 👍

Error: Failure during a migration command: Connector error. (error: Error querying the database: No such table: test_w01GCpwP9mErWsdDrZf3E._Migration
   0: migration_core::api::ListMigrations
             at migration-engine\core\src\api.rs:118)

Expected behavior

To have working integration test

Prisma information

"nexus-plugin-prisma": "^0.19.0" "dependencies": { "@nexus/schema": "^0.15.0", "apollo-server": "^2.13.0", "bcrypt": "5.0.0", "dotenv": "^8.1.0", "graphql-middleware": "^4.0.2", "graphql-shield": "7.3.6", "jsonwebtoken": "8.5.1", "nexus-plugin-prisma": "^0.19.0" }, "devDependencies": { "@types/bcrypt": "3.0.0", "@types/dotenv": "^8.2.0", "@types/eslint": "^7.2.0", "@types/jest": "^26.0.13", "@types/jsonwebtoken": "8.5.0", "@types/node": "^14.10.2", "@types/prettier": "^2.0.0", "@types/rimraf": "^3.0.0", "@typescript-eslint/eslint-plugin": "^4.0.1", "@typescript-eslint/parser": "^4.0.1", "cross-env": "^7.0.2", "dotenv-cli": "^4.0.0", "eslint": "^7.8.1", "eslint-config-prettier": "^6.10.1", "graphql-request": "1.8.2", "husky": ">=4.3.0", "jest": "^26.2.2", "jest-environment-node": "^26.2.0", "lint-staged": ">=10.4.0", "nanoid": "^3.1.12", "npm-run-all": "^4.1.5", "prettier": "^2.1.2", "rimraf": "^3.0.0", "ts-jest": "^26.1.4", "ts-node": "^9.0.0", "ts-node-dev": "1.0.0-pre.63", "typescript": "4.0.3", "typesync": "^0.7.0" },

Environment & setup

tomhoule commented 4 years ago

Thanks for reporting this Are you using MySQL on windows?

tomhoule commented 3 years ago

Thanks for taking the time to report this issue!

We've recently released a Prisma Migrate Preview (2.1.3.0 release notes), which has quite a few changes compared to the previous experimental version. We believe this issue is no longer relevant in this new version, so we are closing this.

We would encourage you to try out Prisma Migrate Preview. If you come across this or any other issue in the preview version, please feel free to open a new issue in prisma/prisma. For general feedback on Prisma Migrate Preview, feel free to chime in on this issue.