Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ yarn add -D effect-prisma-generator

### Effect version support

The generator supports both **Effect v3** and **Effect v4 (beta)** from a single package. It detects the `effect` version installed in your project and emits matching code, so you don't need a special install:
The generator supports **Effect v4** and **Effect v3** from a single package. It detects the `effect` version installed in your project and emits matching code, so you don't need a special install:

- **Effect v3** → uses `Context.Tag` and the auto-generated `PrismaService.Default` layer.
- **Effect v4** → uses `Context.Service` and exposes `PrismaService.layer`.
- **Effect v3** → uses `Context.Tag` and the auto-generated `PrismaService.Default` layer.

> Effect v4 is still in beta and its APIs may shift between releases, so v4 output is considered experimental.
The examples in this README use Effect v4.

If detection ever picks the wrong major (or `effect` can't be resolved — in which case it defaults to v3), set it explicitly in the generator block:
If detection ever picks the wrong major (or `effect` can't be resolved — in which case it defaults to v4), set it explicitly in the generator block:

```prisma
generator effect {
Expand Down Expand Up @@ -95,7 +95,7 @@ import { PrismaService } from "../../prisma/generated/effect";

### 1. Provide the Layer

Initialize the `PrismaClient` and provide it to the generated `PrismaService` layer as a `PrismaClientService`. The layer accessor depends on your Effect version: `PrismaService.Default` on v3, `PrismaService.layer` on v4.
Initialize the `PrismaClient` and provide it to the generated `PrismaService` layer as a `PrismaClientService`. The layer accessor depends on your Effect version: `PrismaService.layer` on v4, `PrismaService.Default` on v3.

```typescript
import { Effect, Layer } from "effect";
Expand All @@ -104,7 +104,7 @@ import { PrismaService, PrismaClientService } from "~prisma/effect";
// ... in your program
const prisma = new PrismaClient({ adapter });
const PrismaLayer = Layer.provide(
PrismaService.Default, // on Effect v4, use PrismaService.layer
PrismaService.layer, // on Effect v3, use PrismaService.Default
Layer.succeed(PrismaClientService, prisma),
);
```
Expand All @@ -123,7 +123,7 @@ import { withAccelerate } from "@prisma/extension-accelerate";

const prisma = new PrismaClient().$extends(withAccelerate());
const PrismaLayer = Layer.provide(
PrismaService.Default, // on Effect v4, use PrismaService.layer
PrismaService.layer, // on Effect v3, use PrismaService.Default
layerFromPrismaClient(prisma),
);
```
Expand Down
12 changes: 6 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ type EffectMajor = 3 | 4;

// Extract the supported EffectMajor from a version-ish string ("4.0.0-beta.83",
// "^3.19", "10"). Reads the first run of digits as the major, so multi-digit
// majors parse correctly; only a leading major of 4+ selects v4. Anything that
// doesn't parse to >= 4 — including malformed values — falls back to v3, the
// long-standing stable line.
// majors parse correctly; a leading major below 4 selects v3, 4 and up select
// v4. Values with no major at all fall back to v4, the current stable line.
function majorOf(version: string): EffectMajor {
return Number(version.match(/\d+/)?.[0]) >= 4 ? 4 : 3;
const major = Number(version.match(/\d+/)?.[0]);
return major < 4 ? 3 : 4;
}

// Resolve the consuming project's installed `effect` major version. Returns
Expand All @@ -56,7 +56,7 @@ function resolveEffectMajor(searchPaths: string[]): EffectMajor | undefined {

// Decide which effect major to target: an explicit `effectVersion` config wins,
// otherwise auto-detect from the consumer's installed `effect`, otherwise fall
// back to v3.
// back to v4.
function determineEffectMajor(
configVersion: string | string[] | undefined,
searchPaths: string[],
Expand All @@ -67,7 +67,7 @@ function determineEffectMajor(
if (typeof explicit === "string" && explicit.trim() !== "") {
return majorOf(explicit);
}
return resolveEffectMajor(searchPaths) ?? 3;
return resolveEffectMajor(searchPaths) ?? 4;
}

// Prisma passes generator config values as strings (or string arrays for
Expand Down
93 changes: 93 additions & 0 deletions tests/effectVersion.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { afterAll, describe, expect, it } from "@effect/vitest";
import { execFileSync } from "child_process";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";

// Runs the built generator in a throwaway project outside this repo, so the
// only `effect` it can find is the one the fixture installs (or none at all).
// Checks which major the emitted code targets.
const generator = path.resolve("../dist/index.js");
const prismaBin = path.resolve("../node_modules/.bin/prisma");
const fixtures: string[] = [];

const generate = (options: {
installedEffect?: string;
effectVersion?: string;
}) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "epg-effect-version-"));
fixtures.push(dir);
if (options.installedEffect !== undefined) {
const pkgDir = path.join(dir, "node_modules", "effect");
fs.mkdirSync(pkgDir, { recursive: true });
fs.writeFileSync(
path.join(pkgDir, "package.json"),
JSON.stringify({ name: "effect", version: options.installedEffect }),
);
}
const effectVersionLine =
options.effectVersion === undefined
? ""
: `\n effectVersion = "${options.effectVersion}"`;
fs.writeFileSync(
path.join(dir, "schema.prisma"),
`datasource db {
provider = "sqlite"
}

generator effect {
provider = "node ${JSON.stringify(generator).slice(1, -1)}"
output = "./generated/effect.ts"
clientImportPath = "./client"${effectVersionLine}
}

model User {
id Int @id
}
`,
);
execFileSync(prismaBin, ["generate", "--schema", "schema.prisma"], {
cwd: dir,
stdio: "pipe",
});
const source = fs.readFileSync(
path.join(dir, "generated", "effect.ts"),
"utf8",
);
if (source.includes("static readonly layer = Layer.effect(")) {
return 4;
}
if (source.includes(`import { Service } from "effect/Effect"`)) {
return 3;
}
throw new Error("generated code matches neither effect v3 nor v4");
};

describe("effect version detection", () => {
afterAll(() => {
for (const dir of fixtures) {
fs.rmSync(dir, { recursive: true, force: true });
}
});

it("emits v3 code when effect 3 is installed", () => {
expect(generate({ installedEffect: "3.19.0" })).toBe(3);
});

it("emits v4 code when effect 4 is installed", () => {
expect(generate({ installedEffect: "4.1.0" })).toBe(4);
});

it("emits v4 code when effect cannot be resolved", () => {
expect(generate({})).toBe(4);
});

it("emits v4 code when the installed version cannot be parsed", () => {
expect(generate({ installedEffect: "not-a-version" })).toBe(4);
});

it("lets effectVersion override the installed effect", () => {
expect(generate({ installedEffect: "4.1.0", effectVersion: "3" })).toBe(3);
expect(generate({ installedEffect: "3.19.0", effectVersion: "4" })).toBe(4);
});
});
Loading