prisma / prisma

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
https://www.prisma.io
Apache License 2.0
39.89k stars 1.56k forks source link

All tables missing in build only #24845

Closed zimonitrome closed 4 months ago

zimonitrome commented 4 months ago

Bug description

I have a SolidStart webapp with AuthJS and Prisma that runs fine in dev, but in build it fails and throws the following error:

The table `main.<tablename here>` does not exist in the current database..

I found the recent issue: https://github.com/prisma/prisma/issues/24779 And tried upgrading to 5.18.0-integration-fix-config-dir-client.5 but still got the same error.

It probably has to do with SQLite integration. Similar issue found here without reproduction: https://github.com/prisma/prisma/issues/10633#issuecomment-1570048865

How to reproduce

  1. npm init solid@latest
  2. Select the following options: Solid-Start: Yes, TypeScript: Yes, template: "with-prisma"
  3. cd into project folder
  4. npm install
  5. npx prisma generate
  6. npx prisma migrate dev
  7. npm run dev
  8. Open "localhost:3000". Interact with the site. Register a user, login, logout. Observe correct behavior.
  9. npm run build
  10. node .output/server/index.mjs
  11. Open "localhost:3000". Interact with the site. Register a user, login, logout. Observe it's impossible. Error: Invalidprisma.user.findUnique()invocation: The tablemain.Userdoes not exist in the current database.

Expected behavior

Expected to work in build as it does in dev.

Prisma information

datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id            String          @id @default(cuid())
  name          String?
  email         String?         @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  // Optional for WebAuthn support
  Authenticator Authenticator[]

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model Account {
  id                String  @id @default(cuid())
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String?
  access_token      String?
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String?
  session_state     String?

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model VerificationToken {
  identifier String
  token      String
  expires    DateTime

  @@unique([identifier, token])
}

// Optional for WebAuthn support
model Authenticator {
  credentialID         String  @unique
  userId               String
  providerAccountId    String
  credentialPublicKey  String
  counter              Int
  credentialDeviceType String
  credentialBackedUp   Boolean
  transports           String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@id([userId, credentialID])
}
import DiscordProvider from "@auth/core/providers/discord";
import GithubProvider from "@auth/core/providers/github";
import { SolidAuthConfig } from "@solid-mediakit/auth/";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
import { Adapter } from "@auth/core/adapters";

const prisma = new PrismaClient();

export const authOptions: SolidAuthConfig = {
  providers: [
    DiscordProvider({
      clientId: process.env.DISCORD_CLIENT_ID as string,
      clientSecret: process.env.DISCORD_CLIENT_SECRET as string
    }),
    GithubProvider({
      clientId: process.env.GITHUB_CLIENT_ID as string,
      clientSecret: process.env.GITHUB_CLIENT_SECRET as string
    })
  ],
  adapter: PrismaAdapter(prisma) as Adapter,
  basePath: "/api/auth"
};

and

import { getSession } from "@solid-mediakit/auth";
import { cache } from "@solidjs/router";
import { getWebRequest } from "vinxi/server";
import { authOptions } from "./auth";

export const getUserSession = cache(async () => {
    "use server"
    const request = getWebRequest();
    const session = await getSession(request, authOptions);
    return session;
  }, "user");

But it could be any code using prisma through the normal client also.

Environment & setup

Prisma Version

prisma                  : 5.16.2
@prisma/client          : 5.16.2
Computed binaryTarget   : windows
Operating System        : win32
Architecture            : x64
Node.js                 : v21.6.1
Query Engine (Node-API) : libquery-engine 34ace0eb2704183d2c05b60b52fba5c43c13f303 (at node_modules\@prisma\engines\query_engine-windows.dll.node)
Schema Engine           : schema-engine-cli 34ace0eb2704183d2c05b60b52fba5c43c13f303 (at node_modules\@prisma\engines\schema-engine-windows.exe)
Schema Wasm             : @prisma/prisma-schema-wasm 5.16.0-24.34ace0eb2704183d2c05b60b52fba5c43c13f303
Default Engines Hash    : 34ace0eb2704183d2c05b60b52fba5c43c13f303
Studio                  : 0.502.0
zimonitrome commented 4 months ago

This happens whenever I try to query anything in the database. I looked into the compiled code which does something like:

p = new PrismaClient();

This object seems nice and correct. I can console.log it and see all definitions. p.session and p.user and all other tables exist and I can print those as well. But whenever I await p.user.findFirst() or do any other query operation, I get the above error that The tablemain.Userdoes not exist in the current database..

I have tried manually setting the URL in dev and build. If I set it incorrectly it lists another error, that the db could not be found. So it seems like it can locate the db file, it has the definitions, but actually reading the db file or finding the corresponding definitions fail.

I have obviously migrated and re-migrated my db, but still nothing helps.

zimonitrome commented 4 months ago

This is really weird because previous versions of the repo that were seemingly working are all now giving the same error.

Posting this here for my own sanity since it seems relevant:

https://github.com/prisma/prisma/issues/10633#issuecomment-1570048865

zimonitrome commented 4 months ago

Turns out new versions of Vinxi copies the schema to the output directory but not the db. So when searching for the Prisma files, the schema was found but not the db file.

The solution is to use an absolute path to the database (.bd) file when initializing the PrismaClient. Doing this with: const prisma = new PrismaClient({datasourceUrl: process.env.PRISMA_URL});