medz / prisma-dart

Prisma Client Dart is an auto-generated type-safe ORM. It uses Prisma Engine as the data access layer and is as consistent as possible with the Prisma Client JS/TS APIs.
https://prisma.pub
BSD 3-Clause "New" or "Revised" License
436 stars 29 forks source link

PrismaClientInitializationError: P1003 The SQLite database file (sqlite.db) does not exist #401

Open TanaseHagi opened 2 weeks ago

TanaseHagi commented 2 weeks ago

An error occurs when using sqlite database provider.

prisma db push will push the database in prisma folder, next to the schemas, but when connecting with the client, it tries to read the database from the root folder.

I made a proof of concept

version 5.0.3

medz commented 2 weeks ago

@TanaseHagi I think this issue should be added to FQA. The root cause of this problem is the difference between the base directory of Prisma CLI and the real working directory of Dart Runtime.

Prisma CLI chooses <project>/prisma/ as the base directory. No matter where the url of your .env or datasource configuration is located, the CLI is based on the schema.prisma directory.

And Dart usually requires AOT compilation, which will cause a situation. We don't need the prisma directory. Usually the path in the environment variable is based on PWD. This is a conventional rule.

So Prisma CLI is a special case, and the recommended way to make it compatible is to set directUrl:

schema:

datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
// Why need directUrl ?
// The Prisma CLI tool uses the file URL relative to the prisma directory when it is configured at runtime. The Dart runtime uses PWD
directUrl = env("DIRECT_DATABASE_URL")
}

.env

DATABASE_URL="file:./prisma/dev.db" # Dart rintime using
DIRECT_DATABASE_URL="file:./dev.db" # Prisma CLI using

This is to make it compatible with this situation.

You can see this solution in the demo at https://github.com/medz/prisma-dart/tree/main/examples/with_sqlite.

medz commented 2 weeks ago

Maybe, I can make an enhancement tool to find the schema.prisma file from PWD, and when setting the database to SQLite connection string, if the schema.prisma file is found, reset the database connection URL.

But I don't want to do this. If you try to compile a Node project into a runnable JS or single file and move it out of the project directory, you will find that you will face the same problem.

medz commented 2 weeks ago

The official approach of Prisma is to look for the schema.prisma file and then rewrite the path to SQLite. But I have always thought this is a misleading feature. Ideally, the URL written in .env should be based on the location of .env to be consistent. But .env is usually in string format KV format.

The general practice is to use PWD as the base directory once you encounter the path configured by the environment variable. But Prisma CLI is a special case.