aboutsummaryrefslogtreecommitdiff
path: root/test/js/third_party/prisma/helper.ts
blob: ae11ede20cdc72bd7bc8d05dbd46bf71b1c64f8b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import path from "path";
import { bunExe, bunEnv } from "harness";
import fs from "fs";
const cwd = import.meta.dir;

export async function generateClient(type: string) {
  generate(type);

  // This should run the first time on a fresh db
  try {
    migrate(type);
  } catch (err: any) {
    if (err.message.indexOf("Environment variable not found:") !== -1) throw err;
  }

  return (await import(`./prisma/${type}/client`)).PrismaClient;
}
export function migrate(type: string) {
  const result = Bun.spawnSync(
    [
      bunExe(),
      "x",
      "prisma",
      "migrate",
      "dev",
      "--name",
      "init",
      "--schema",
      path.join(cwd, "prisma", type, "schema.prisma"),
    ],
    {
      cwd,
      env: {
        ...bunEnv,
        NODE_ENV: undefined,
      },
    },
  );
  if (!result.success) throw new Error(result.stderr.toString("utf8"));
}

export function generate(type: string) {
  const schema = path.join(cwd, "prisma", type, "schema.prisma");

  const content = fs
    .readFileSync(schema)
    .toString("utf8")
    // only affect linux
    .replace(
      "%binaryTargets%",
      process.platform === "win32" || process.platform === "darwin"
        ? ""
        : 'binaryTargets = ["native", "debian-openssl-1.1.x", "debian-openssl-3.0.x", "linux-musl", "linux-musl-openssl-3.0.x"]',
    );

  fs.writeFileSync(schema, content);

  const result = Bun.spawnSync([bunExe(), "prisma", "generate", "--schema", schema], {
    cwd,
    env: {
      ...bunEnv,
      NODE_ENV: undefined,
    },
  });
  if (!result.success) throw new Error(result.stderr.toString("utf8"));
}