The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { Retry } from "@distilled.cloud/prisma"; |
| 2 | import { |
| 3 | type GetDatabasesResponse, |
| 4 | type GetProjectBranchesResponse, |
| 5 | type GetProjectDatabasesResponse, |
| 6 | deleteDatabase, |
| 7 | getDatabases, |
| 8 | getDatabase, |
| 9 | getProject, |
| 10 | getProjectBranches, |
| 11 | getProjectDatabases, |
| 12 | updateDatabase, |
| 13 | createDatabase, |
| 14 | } from "@distilled.cloud/prisma/management"; |
| 15 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 16 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 17 | import * as ProviderLayer from "alchemy/Local/ProviderLayer"; |
| 18 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 19 | import * as Provider from "alchemy/Provider"; |
| 20 | import { Resource } from "alchemy/Resource"; |
| 21 | import * as Data from "effect/Data"; |
| 22 | import * as Effect from "effect/Effect"; |
| 23 | import type * as Path from "effect/Path"; |
| 24 | import type { ChildProcessSpawner } from "effect/process/ChildProcessSpawner"; |
| 25 | import * as Redacted from "effect/Redacted"; |
| 26 | import * as Schedule from "effect/Schedule"; |
| 27 | import type { Scope } from "effect/Scope"; |
| 28 | import { extractConnectionSecrets } from "./Client.ts"; |
| 29 | import { desiredBranchId } from "./internal/Branches.ts"; |
| 30 | import { |
| 31 | hasCanonicalConnectionSecrets, |
| 32 | mergeConnectionSecrets, |
| 33 | recoverDatabaseConnectionSecrets, |
| 34 | } from "./internal/DatabaseSecrets.ts"; |
| 35 | import { DEV_TIMESTAMP, attrOrString, devId } from "./internal/DevStub.ts"; |
| 36 | import { |
| 37 | type ObservedProjectDatabase, |
| 38 | type ObservedSource, |
| 39 | narrowDatabaseSource, |
| 40 | } from "./internal/Observed.ts"; |
| 41 | import { PrismaPaginationError } from "./internal/Pagination.ts"; |
| 42 | import { closePrismaDevDatabase, ensurePrismaDevDatabase } from "./internal/PrismaDevDatabase.ts"; |
| 43 | import { |
| 44 | concreteIdsChanged, |
| 45 | isInputObject, |
| 46 | isPrismaDevId, |
| 47 | resolveProjectId, |
| 48 | unresolvedProjectIdOf, |
| 49 | } from "./internal/Refs.ts"; |
| 50 | import type { Project } from "./Project.ts"; |
| 51 | import type { Providers } from "./Providers.ts"; |
| 52 | import type { |
| 53 | DatabaseSourceInput, |
| 54 | PrismaDatabaseRegionId, |
| 55 | PrismaRegionId, |
| 56 | PrismaSecretConnection, |
| 57 | } from "./Types.ts"; |
| 58 | |
| 59 | export class DatabaseConflict extends Data.TaggedError("DatabaseConflict")<{ |
| 60 | readonly message: string; |
| 61 | readonly cause?: unknown; |
| 62 | }> {} |
| 63 | |
| 64 | export class DatabaseInvalidProps extends Data.TaggedError("DatabaseInvalidProps")<{ |
| 65 | readonly message: string; |
| 66 | readonly cause?: unknown; |
| 67 | }> {} |
| 68 | |
| 69 | export class DatabaseOperationFailed extends Data.TaggedError("DatabaseOperationFailed")<{ |
| 70 | readonly message: string; |
| 71 | readonly cause?: unknown; |
| 72 | }> {} |
| 73 | |
| 74 | export interface DatabaseDev { |
| 75 | /** |
| 76 | * Local provider used by `alchemy dev`. |
| 77 | * |
| 78 | * @default "@prisma/dev" |
| 79 | */ |
| 80 | provider?: "@prisma/dev"; |
| 81 | /** |
| 82 | * Stable local server name. |
| 83 | */ |
| 84 | name?: string; |
| 85 | /** |
| 86 | * Local storage mode for the database server. |
| 87 | * |
| 88 | * @default "stateful" |
| 89 | */ |
| 90 | persistenceMode?: "stateless" | "stateful"; |
| 91 | /** |
| 92 | * HTTP control port for the local server. |
| 93 | */ |
| 94 | port?: number; |
| 95 | /** |
| 96 | * Direct Postgres port for the local database. |
| 97 | */ |
| 98 | databasePort?: number; |
| 99 | /** |
| 100 | * Direct Postgres port for the local shadow database. |
| 101 | */ |
| 102 | shadowDatabasePort?: number; |
| 103 | /** |
| 104 | * Enable local provider debug logging. |
| 105 | * |
| 106 | * @default false |
| 107 | */ |
| 108 | debug?: boolean; |
| 109 | /** |
| 110 | * Connection timeout in milliseconds for pending database clients. |
| 111 | */ |
| 112 | databaseConnectTimeoutMillis?: number; |
| 113 | /** |
| 114 | * Idle timeout in milliseconds for active database clients. |
| 115 | */ |
| 116 | databaseIdleTimeoutMillis?: number; |
| 117 | /** |
| 118 | * Connection timeout in milliseconds for pending shadow database clients. |
| 119 | */ |
| 120 | shadowDatabaseConnectTimeoutMillis?: number; |
| 121 | /** |
| 122 | * Idle timeout in milliseconds for active shadow database clients. |
| 123 | */ |
| 124 | shadowDatabaseIdleTimeoutMillis?: number; |
| 125 | /** |
| 126 | * Optional shell command to run after the local database is ready. |
| 127 | */ |
| 128 | migrate?: string; |
| 129 | /** |
| 130 | * Working directory for the migration command. |
| 131 | */ |
| 132 | migrateCwd?: string; |
| 133 | /** |
| 134 | * Maximum time to wait for the migration command before terminating it. |
| 135 | * Must be a positive finite number. |
| 136 | * |
| 137 | * @default 900 |
| 138 | */ |
| 139 | migrateTimeoutSeconds?: number; |
| 140 | } |
| 141 | |
| 142 | export interface DatabaseProps { |
| 143 | /** |
| 144 | * Project ID or `project.projectId` output that owns this database. |
| 145 | */ |
| 146 | project: string | Project; |
| 147 | /** |
| 148 | * Database display name. If omitted, Alchemy generates a stable physical |
| 149 | * name so interrupted creates can be recovered without duplicating a |
| 150 | * database. Explicit names cannot be combined with branch attachment during |
| 151 | * initial creation because the Management API creates the database before it |
| 152 | * attaches the branch and exposes no idempotency key. |
| 153 | */ |
| 154 | name?: string; |
| 155 | /** |
| 156 | * Region for the database. `"inherit"` uses the project's default region, |
| 157 | * or the default database's region when the project has none. |
| 158 | * |
| 159 | * @default "us-east-1" |
| 160 | */ |
| 161 | region?: PrismaDatabaseRegionId; |
| 162 | /** |
| 163 | * Standalone Prisma.Database resources cannot be the project's default |
| 164 | * database because the Management API cannot demote or promote an existing |
| 165 | * database, making the resource impossible to destroy safely. Use |
| 166 | * Prisma.Project to manage the project-owned default database. |
| 167 | * |
| 168 | * @default false |
| 169 | */ |
| 170 | isDefault?: false; |
| 171 | /** |
| 172 | * Optional source database/backup descriptor for clone or restore creation. |
| 173 | */ |
| 174 | source?: DatabaseSourceInput; |
| 175 | /** |
| 176 | * Branch ID to attach the database to. Mutually exclusive with |
| 177 | * branchGitName. Every Prisma database belongs to a Branch: omit both |
| 178 | * fields to let the Management API attach it to the project's default |
| 179 | * Branch, which Alchemy then leaves unmanaged. |
| 180 | */ |
| 181 | branchId?: string; |
| 182 | /** |
| 183 | * Branch git name to attach the database to (the Branch is created when it |
| 184 | * does not exist). Mutually exclusive with branchId. Omit both fields to |
| 185 | * attach to the project's default Branch. |
| 186 | */ |
| 187 | branchGitName?: string; |
| 188 | /** |
| 189 | * Stable identity of this declaration on the Prisma platform, unique per |
| 190 | * branch. A rename in the Console does not change it. After lost state, the |
| 191 | * provider finds the database by it instead of creating a second one, and |
| 192 | * `--adopt` (or `adopt(true)`) takes it back over, because a logical ID alone |
| 193 | * does not prove which stack owns it. Changing it updates the database in place. |
| 194 | * @default the resource's fully qualified logical ID, e.g. `"db"` or `"App/Db"` |
| 195 | */ |
| 196 | logicalId?: string; |
| 197 | /** |
| 198 | * Local database settings for `alchemy dev`. Set to `false` to keep only |
| 199 | * placeholder IDs. |
| 200 | */ |
| 201 | dev?: false | DatabaseDev; |
| 202 | /** |
| 203 | * Rotate the adopted database's default connection to recover its one-time |
| 204 | * credentials. Prisma revokes the previous key on a best-effort basis and |
| 205 | * rotation may interrupt existing consumers, so adoption leaves credentials |
| 206 | * unset unless explicitly opted in. |
| 207 | * |
| 208 | * @default false |
| 209 | */ |
| 210 | rotateCredentialsOnAdopt?: boolean; |
| 211 | } |
| 212 | |
| 213 | export interface Database extends Resource< |
| 214 | "Prisma.Database", |
| 215 | DatabaseProps, |
| 216 | { |
| 217 | /** |
| 218 | * Prisma database ID. |
| 219 | */ |
| 220 | databaseId: string; |
| 221 | /** |
| 222 | * Prisma database display name. |
| 223 | */ |
| 224 | databaseName: string; |
| 225 | /** |
| 226 | * Project ID that owns the database. |
| 227 | */ |
| 228 | projectId: string; |
| 229 | /** |
| 230 | * Current Prisma database status. |
| 231 | */ |
| 232 | status: string; |
| 233 | /** |
| 234 | * Prisma Postgres region ID, when available. |
| 235 | */ |
| 236 | region: string | null; |
| 237 | /** |
| 238 | * Whether this is the project's default database. |
| 239 | */ |
| 240 | isDefault: boolean; |
| 241 | /** |
| 242 | * Branch ID attached to the database, or null when unassigned. |
| 243 | */ |
| 244 | branchId: string | null; |
| 245 | /** |
| 246 | * Default connection ID for the database. |
| 247 | */ |
| 248 | defaultConnectionId: string | null; |
| 249 | /** |
| 250 | * ISO timestamp when the database was created. |
| 251 | */ |
| 252 | createdAt: string; |
| 253 | /** |
| 254 | * Direct Postgres connection string, redacted in state. |
| 255 | */ |
| 256 | directConnectionString: Redacted.Redacted<string> | undefined; |
| 257 | /** |
| 258 | * Pooled Postgres connection string, redacted in state. |
| 259 | */ |
| 260 | pooledConnectionString: Redacted.Redacted<string> | undefined; |
| 261 | /** |
| 262 | * Accelerate connection string, redacted in state. |
| 263 | */ |
| 264 | accelerateConnectionString: Redacted.Redacted<string> | undefined; |
| 265 | /** |
| 266 | * Direct database host, when returned by Prisma. |
| 267 | */ |
| 268 | host: string | null | undefined; |
| 269 | /** |
| 270 | * Direct database username, when returned by Prisma. |
| 271 | */ |
| 272 | user: string | null | undefined; |
| 273 | /** |
| 274 | * Direct database password, redacted in state. |
| 275 | */ |
| 276 | password: Redacted.Redacted<string> | undefined; |
| 277 | /** |
| 278 | * Logical ID recorded on the database, or null when none is set. |
| 279 | */ |
| 280 | logicalId: string | null; |
| 281 | }, |
| 282 | never, |
| 283 | Providers |
| 284 | > {} |
| 285 | |
| 286 | /** |
| 287 | * A Prisma Postgres database inside a Prisma project. |
| 288 | * |
| 289 | * Standalone `Prisma.Database` resources cannot be the project's default |
| 290 | * database. Use `Prisma.Project` when the project should own a default |
| 291 | * database. Project, region, and source changes require replacement; display |
| 292 | * name and branch attachment can converge in place. Destroying this resource |
| 293 | * deletes its database and data. |
| 294 | * |
| 295 | * ### Creating a Database |
| 296 | * **Example:** Database in a project |
| 297 | * ```typescript |
| 298 | * const project = yield* Prisma.Project("app", { createDatabase: false }); |
| 299 | * const database = yield* Prisma.Database("db", { |
| 300 | * project, |
| 301 | * region: "us-east-1", |
| 302 | * }); |
| 303 | * ``` |
| 304 | * |
| 305 | * **Example:** Database attached to a preview branch |
| 306 | * ```typescript |
| 307 | * const database = yield* Prisma.Database("preview-db", { |
| 308 | * project, |
| 309 | * branchId: preview.branchId, |
| 310 | * }); |
| 311 | * ``` |
| 312 | * |
| 313 | * @resource |
| 314 | * @product Postgres |
| 315 | */ |
| 316 | export const Database = Resource<Database>("Prisma.Database"); |
| 317 | |
| 318 | const createName = (id: string, name: string | undefined) => |
| 319 | name === undefined ? createPhysicalName({ id }) : Effect.succeed(name); |
| 320 | |
| 321 | // Distilled emits the cursor-paginated list operations as plain ops, so |
| 322 | // callers walk `pagination` themselves (see `src/Neon/Project.ts`). |
| 323 | const listProjectDatabases = (projectId: string) => |
| 324 | Effect.gen(function* () { |
| 325 | const databases: GetProjectDatabasesResponse["data"][number][] = []; |
| 326 | let cursor: string | undefined; |
| 327 | while (true) { |
| 328 | const page = yield* getProjectDatabases( |
| 329 | cursor === undefined ? { projectId, limit: 100 } : { projectId, limit: 100, cursor }, |
| 330 | ); |
| 331 | databases.push(...page.data); |
| 332 | const nextCursor = page.pagination.nextCursor; |
| 333 | if (!page.pagination.hasMore) break; |
| 334 | if (nextCursor === null) { |
| 335 | return yield* new PrismaPaginationError({ |
| 336 | message: |
| 337 | "Invalid Prisma Management API pagination response from getProjectDatabases: hasMore was true without a non-empty nextCursor", |
| 338 | }); |
| 339 | } |
| 340 | cursor = nextCursor; |
| 341 | } |
| 342 | return databases; |
| 343 | }); |
| 344 | |
| 345 | const listAllDatabases = ( |
| 346 | filter: { projectId?: string; logicalId?: string; branchId?: string } = {}, |
| 347 | ) => |
| 348 | Effect.gen(function* () { |
| 349 | const databases: GetDatabasesResponse["data"][number][] = []; |
| 350 | let cursor: string | undefined; |
| 351 | while (true) { |
| 352 | const page = yield* getDatabases(cursor === undefined ? filter : { ...filter, cursor }); |
| 353 | databases.push(...page.data); |
| 354 | const nextCursor = page.pagination.nextCursor; |
| 355 | if (!page.pagination.hasMore) break; |
| 356 | if (nextCursor === null) { |
| 357 | return yield* new PrismaPaginationError({ |
| 358 | message: |
| 359 | "Invalid Prisma Management API pagination response from getDatabases: hasMore was true without a non-empty nextCursor", |
| 360 | }); |
| 361 | } |
| 362 | cursor = nextCursor; |
| 363 | } |
| 364 | return databases; |
| 365 | }); |
| 366 | |
| 367 | const findDatabaseByName = (projectId: string, name: string) => |
| 368 | listProjectDatabases(projectId).pipe( |
| 369 | Effect.flatMap((databases) => { |
| 370 | const matches = databases.filter((database) => database.name === name); |
| 371 | return matches.length > 1 |
| 372 | ? Effect.fail( |
| 373 | new DatabaseConflict({ |
| 374 | message: `Prisma project '${projectId}' has multiple databases named '${name}'; refusing to select one arbitrarily.`, |
| 375 | }), |
| 376 | ) |
| 377 | : Effect.succeed(matches[0]); |
| 378 | }), |
| 379 | ); |
| 380 | |
| 381 | const findDatabaseByLogicalId = Effect.fn(function* ( |
| 382 | projectId: string, |
| 383 | logicalId: string, |
| 384 | props: { branchId?: string; branchGitName?: string }, |
| 385 | ) { |
| 386 | const branch = yield* desiredBranchId(projectId, props); |
| 387 | if (!branch.resolved) return undefined; |
| 388 | const databases = yield* listAllDatabases({ |
| 389 | projectId, |
| 390 | logicalId, |
| 391 | branchId: branch.id, |
| 392 | }); |
| 393 | return databases.find( |
| 394 | (database) => database.logicalId === logicalId && database.branchId === branch.id, |
| 395 | ); |
| 396 | }); |
| 397 | |
| 398 | const logicalIdTaken = ( |
| 399 | logicalId: string, |
| 400 | branchId: string | null, |
| 401 | projectId: string, |
| 402 | cause: unknown, |
| 403 | ) => |
| 404 | new Error( |
| 405 | `Prisma database logical ID '${logicalId}' is already used by another database on branch '${branchId}' in project '${projectId}'. Logical IDs are unique per branch; choose a different logicalId or remove it from the other database.`, |
| 406 | { cause }, |
| 407 | ); |
| 408 | |
| 409 | class GeneratedDatabaseNotVisible extends Data.TaggedError("GeneratedDatabaseNotVisible")<{ |
| 410 | readonly message: string; |
| 411 | }> {} |
| 412 | |
| 413 | const generatedDatabaseRecoverySchedule = Schedule.max([ |
| 414 | Schedule.exponential("250 millis"), |
| 415 | Schedule.recurs(6), |
| 416 | ]); |
| 417 | |
| 418 | const recoverGeneratedDatabaseAfterConflict = (projectId: string, name: string) => |
| 419 | findDatabaseByName(projectId, name).pipe( |
| 420 | Effect.flatMap((database) => |
| 421 | database |
| 422 | ? Effect.succeed(database) |
| 423 | : Effect.fail( |
| 424 | new GeneratedDatabaseNotVisible({ |
| 425 | message: `Generated Prisma database '${name}' already exists but is not visible yet.`, |
| 426 | }), |
| 427 | ), |
| 428 | ), |
| 429 | Effect.retry({ |
| 430 | while: (error) => error instanceof GeneratedDatabaseNotVisible, |
| 431 | schedule: generatedDatabaseRecoverySchedule, |
| 432 | }), |
| 433 | ); |
| 434 | |
| 435 | const findDefaultDatabase = (projectId: string) => |
| 436 | listProjectDatabases(projectId).pipe( |
| 437 | Effect.flatMap((databases) => { |
| 438 | const matches = databases.filter((database) => database.isDefault); |
| 439 | return matches.length > 1 |
| 440 | ? Effect.fail( |
| 441 | new DatabaseConflict({ |
| 442 | message: `Prisma project '${projectId}' has multiple default databases; refusing to select one arbitrarily.`, |
| 443 | }), |
| 444 | ) |
| 445 | : Effect.succeed(matches[0]); |
| 446 | }), |
| 447 | ); |
| 448 | |
| 449 | const resolveDatabaseRegion = Effect.fn(function* ( |
| 450 | projectId: string, |
| 451 | region: PrismaDatabaseRegionId | undefined, |
| 452 | ) { |
| 453 | if (region !== "inherit") { |
| 454 | return (region ?? "us-east-1") as PrismaRegionId; |
| 455 | } |
| 456 | const project = yield* getProject({ id: projectId }); |
| 457 | if (project.data.defaultRegion !== null) { |
| 458 | return project.data.defaultRegion as PrismaRegionId; |
| 459 | } |
| 460 | const database = yield* findDefaultDatabase(projectId); |
| 461 | const inherited = database?.region?.id; |
| 462 | if (inherited === undefined) { |
| 463 | return yield* new DatabaseOperationFailed({ |
| 464 | message: `Cannot resolve Prisma database region 'inherit' because project '${projectId}' has no default region and no default database region. Create or promote a default database first, or specify an explicit region.`, |
| 465 | }); |
| 466 | } |
| 467 | return inherited as PrismaRegionId; |
| 468 | }); |
| 469 | |
| 470 | const stripDatabaseIdPrefix = (databaseId: string) => |
| 471 | databaseId.startsWith("db_") ? databaseId.slice(3) : databaseId; |
| 472 | |
| 473 | const normalizeDatabaseSource = ( |
| 474 | source: DatabaseSourceInput | { readonly type: "unknown" } | undefined, |
| 475 | ) => { |
| 476 | if (source === undefined || source.type === "empty") { |
| 477 | return { type: "empty" as const }; |
| 478 | } |
| 479 | if (source.type === "unknown") return { type: "unknown" as const }; |
| 480 | return source.type === "database" |
| 481 | ? { |
| 482 | type: "database" as const, |
| 483 | databaseId: stripDatabaseIdPrefix(source.databaseId), |
| 484 | } |
| 485 | : { |
| 486 | type: "backup" as const, |
| 487 | databaseId: stripDatabaseIdPrefix(source.databaseId), |
| 488 | backupId: source.backupId, |
| 489 | }; |
| 490 | }; |
| 491 | |
| 492 | const sourceMatches = (observed: ObservedSource | null, desired: DatabaseSourceInput | undefined) => |
| 493 | deepEqual( |
| 494 | normalizeDatabaseSource(narrowDatabaseSource(observed)), |
| 495 | normalizeDatabaseSource(desired), |
| 496 | ); |
| 497 | |
| 498 | const desiredSourcesMatch = ( |
| 499 | left: DatabaseSourceInput | undefined, |
| 500 | right: DatabaseSourceInput | undefined, |
| 501 | ) => deepEqual(normalizeDatabaseSource(left), normalizeDatabaseSource(right)); |
| 502 | |
| 503 | const branchIdForGitName = (projectId: string, gitName: string) => |
| 504 | getProjectBranches({ projectId, gitName, limit: 2 }).pipe( |
| 505 | Effect.map((response: GetProjectBranchesResponse) => response.data), |
| 506 | Effect.flatMap((branches) => |
| 507 | branches.length > 1 |
| 508 | ? Effect.fail( |
| 509 | new DatabaseConflict({ |
| 510 | message: `Prisma project '${projectId}' has multiple branches named '${gitName}'; refusing to select one arbitrarily.`, |
| 511 | }), |
| 512 | ) |
| 513 | : Effect.succeed(branches[0]?.id), |
| 514 | ), |
| 515 | ); |
| 516 | |
| 517 | const attrsFrom = ( |
| 518 | database: ObservedProjectDatabase, |
| 519 | secrets: PrismaSecretConnection, |
| 520 | ): Database["Attributes"] => ({ |
| 521 | databaseId: database.id, |
| 522 | databaseName: database.name, |
| 523 | projectId: database.project.id, |
| 524 | status: database.status, |
| 525 | region: database.region?.id ?? null, |
| 526 | isDefault: database.isDefault, |
| 527 | branchId: database.branchId, |
| 528 | defaultConnectionId: database.defaultConnectionId, |
| 529 | createdAt: database.createdAt, |
| 530 | directConnectionString: secrets.directConnectionString, |
| 531 | pooledConnectionString: secrets.pooledConnectionString, |
| 532 | accelerateConnectionString: secrets.accelerateConnectionString, |
| 533 | host: secrets.host, |
| 534 | user: secrets.user, |
| 535 | password: secrets.password, |
| 536 | logicalId: database.logicalId ?? null, |
| 537 | }); |
| 538 | |
| 539 | const branchNeedsSync = Effect.fn(function* ( |
| 540 | projectId: string, |
| 541 | database: ObservedProjectDatabase, |
| 542 | props: DatabaseProps, |
| 543 | ) { |
| 544 | if (props.branchId !== undefined && !isPrismaDevId(props.branchId)) { |
| 545 | return database.branchId !== props.branchId; |
| 546 | } |
| 547 | if (props.branchGitName === undefined) { |
| 548 | // No attachment requested: the Management API attaches every database to |
| 549 | // a Branch (the project default when omitted) and rejects detaching, so |
| 550 | // the observed attachment is left alone. |
| 551 | return false; |
| 552 | } |
| 553 | const branchId = yield* branchIdForGitName(projectId, props.branchGitName); |
| 554 | return branchId === undefined || branchId !== database.branchId; |
| 555 | }); |
| 556 | |
| 557 | const branchAttachment = (props: DatabaseProps) => |
| 558 | props.branchId !== undefined && !isPrismaDevId(props.branchId) |
| 559 | ? { |
| 560 | branchId: props.branchId, |
| 561 | branchGitName: undefined, |
| 562 | } |
| 563 | : props.branchGitName !== undefined |
| 564 | ? { |
| 565 | branchId: undefined, |
| 566 | branchGitName: props.branchGitName, |
| 567 | } |
| 568 | : { |
| 569 | branchId: undefined, |
| 570 | branchGitName: undefined, |
| 571 | }; |
| 572 | |
| 573 | const validateDatabaseProps = (props: DatabaseProps) => |
| 574 | Effect.gen(function* () { |
| 575 | if ((props as { isDefault?: boolean }).isDefault === true) { |
| 576 | return yield* new DatabaseInvalidProps({ |
| 577 | message: |
| 578 | "Prisma.Database cannot manage a default database because the Management API has no safe demotion or promote-existing operation, so the resource could never be destroyed. Use Prisma.Project for the project-owned default database.", |
| 579 | }); |
| 580 | } |
| 581 | if (props.branchId !== undefined && props.branchGitName !== undefined) { |
| 582 | return yield* new DatabaseInvalidProps({ |
| 583 | message: "branchId and branchGitName are mutually exclusive.", |
| 584 | }); |
| 585 | } |
| 586 | if ((props.branchId as unknown) === null || (props.branchGitName as unknown) === null) { |
| 587 | return yield* new DatabaseInvalidProps({ |
| 588 | message: |
| 589 | "Every Prisma database belongs to a Branch; the Management API rejects detaching (null). Omit both branchId and branchGitName to attach to the project's default branch, or provide one of them.", |
| 590 | }); |
| 591 | } |
| 592 | }); |
| 593 | |
| 594 | const ProviderLive = () => |
| 595 | Provider.effect( |
| 596 | Database, |
| 597 | Effect.gen(function* () { |
| 598 | return { |
| 599 | stables: ["databaseId"], |
| 600 | list: () => |
| 601 | listAllDatabases().pipe( |
| 602 | Effect.map((databases) => |
| 603 | // Default databases are project-owned and the API rejects |
| 604 | // direct deletion. Project.list/delete owns their teardown; |
| 605 | // exposing them here would make unsafe nuke retry forever. |
| 606 | databases |
| 607 | .filter((database) => !database.isDefault) |
| 608 | .map((database) => attrsFrom(database, {})), |
| 609 | ), |
| 610 | ), |
| 611 | diff: Effect.fn(function* ({ id, fqn, olds, news, output }) { |
| 612 | if (!isInputObject(news)) return undefined; |
| 613 | if ( |
| 614 | isResolved(news.rotateCredentialsOnAdopt) && |
| 615 | news.rotateCredentialsOnAdopt === true && |
| 616 | olds.rotateCredentialsOnAdopt !== true |
| 617 | ) { |
| 618 | return { action: "update" } as const; |
| 619 | } |
| 620 | if ((news as { isDefault?: unknown }).isDefault === true) { |
| 621 | return yield* new DatabaseInvalidProps({ |
| 622 | message: |
| 623 | "Prisma.Database cannot manage a default database because the Management API has no safe demotion or promote-existing operation. Use Prisma.Project for the project-owned default database.", |
| 624 | }); |
| 625 | } |
| 626 | if (isPrismaDevId(output?.databaseId)) { |
| 627 | return { action: "update" } as const; |
| 628 | } |
| 629 | const oldProjectId = output?.projectId ?? unresolvedProjectIdOf(olds.project); |
| 630 | const newProjectId = isResolved(news.project) |
| 631 | ? unresolvedProjectIdOf(news.project) |
| 632 | : undefined; |
| 633 | const desiredRegionInput = isResolved(news.region) |
| 634 | ? (news.region ?? "us-east-1") |
| 635 | : undefined; |
| 636 | const regionProjectId = newProjectId ?? oldProjectId; |
| 637 | const desiredRegion = |
| 638 | desiredRegionInput === "inherit" |
| 639 | ? regionProjectId |
| 640 | ? yield* resolveDatabaseRegion(regionProjectId, desiredRegionInput) |
| 641 | : undefined |
| 642 | : desiredRegionInput; |
| 643 | const observedRegion = output ? output.region : (olds.region ?? "us-east-1"); |
| 644 | const desiredIsDefault = isResolved(news.isDefault) |
| 645 | ? (news.isDefault ?? false) |
| 646 | : undefined; |
| 647 | const observedIsDefault = output?.isDefault ?? olds.isDefault ?? false; |
| 648 | |
| 649 | // A default database cannot be deleted from its old project after a |
| 650 | // cross-project replacement. Block before creating anything until |
| 651 | // another database has been promoted in the original project. |
| 652 | if (observedIsDefault && concreteIdsChanged(oldProjectId, newProjectId)) { |
| 653 | return { action: "update" } as const; |
| 654 | } |
| 655 | |
| 656 | // Prisma has no API operation that directly demotes the current |
| 657 | // default database. Do not schedule a doomed create-first |
| 658 | // replacement: reconcile will fail before mutation until another |
| 659 | // database has been promoted and this one is observed as nondefault. |
| 660 | if (desiredIsDefault === false && observedIsDefault) { |
| 661 | return { action: "update" } as const; |
| 662 | } |
| 663 | if ( |
| 664 | concreteIdsChanged(oldProjectId, newProjectId) || |
| 665 | (desiredRegion !== undefined && desiredRegion !== observedRegion) || |
| 666 | (desiredIsDefault !== undefined && desiredIsDefault !== observedIsDefault) || |
| 667 | (isResolved(news.source) && !desiredSourcesMatch(news.source, olds.source)) |
| 668 | ) { |
| 669 | // A stable explicit name in the same project collides with the |
| 670 | // old generation, so it must go before the replacement is created. |
| 671 | const deleteFirst = |
| 672 | !concreteIdsChanged(oldProjectId, newProjectId) && |
| 673 | (isResolved(news.name) |
| 674 | ? news.name !== undefined && |
| 675 | (!output || (yield* createName(id, news.name)) === output.databaseName) |
| 676 | : true); |
| 677 | return { action: "replace", deleteFirst } as const; |
| 678 | } |
| 679 | if ( |
| 680 | isResolved(news.logicalId) && |
| 681 | (news.logicalId ?? fqn) !== (output ? output.logicalId : (olds.logicalId ?? fqn)) |
| 682 | ) { |
| 683 | return { action: "update" } as const; |
| 684 | } |
| 685 | if (!isResolved(news.name)) return undefined; |
| 686 | const desiredName = yield* createName(id, news.name); |
| 687 | const observedName = output?.databaseName ?? (yield* createName(id, olds.name)); |
| 688 | // Omitting both branch fields leaves the observed attachment |
| 689 | // unmanaged (every database belongs to a Branch; detaching is not |
| 690 | // an API operation), so only an explicit target can mismatch. |
| 691 | let branchMismatch = false; |
| 692 | if (isResolved(news.branchId) && news.branchId !== undefined) { |
| 693 | branchMismatch = |
| 694 | !isPrismaDevId(news.branchId) && |
| 695 | (output?.branchId ?? olds.branchId ?? null) !== news.branchId; |
| 696 | } else if (isResolved(news.branchGitName) && news.branchGitName !== undefined) { |
| 697 | if (output && newProjectId !== undefined) { |
| 698 | const desiredBranchId = yield* branchIdForGitName(newProjectId, news.branchGitName); |
| 699 | branchMismatch = desiredBranchId === undefined || desiredBranchId !== output.branchId; |
| 700 | } else { |
| 701 | branchMismatch = news.branchGitName !== olds.branchGitName; |
| 702 | } |
| 703 | } |
| 704 | if (desiredName !== observedName || branchMismatch) { |
| 705 | return { action: "update" } as const; |
| 706 | } |
| 707 | return undefined; |
| 708 | }), |
| 709 | read: Effect.fn(function* ({ id, fqn, output, olds, previous }) { |
| 710 | const databaseId = isPrismaDevId(output?.databaseId) ? undefined : output?.databaseId; |
| 711 | let generatedIdentityMatch = false; |
| 712 | let database = databaseId |
| 713 | ? yield* getDatabase({ databaseId }).pipe( |
| 714 | Effect.map((response) => response.data), |
| 715 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 716 | ) |
| 717 | : undefined; |
| 718 | if (!database && databaseId === undefined) { |
| 719 | const projectId = unresolvedProjectIdOf(olds.project); |
| 720 | if (projectId) { |
| 721 | database = yield* findDatabaseByLogicalId(projectId, olds.logicalId ?? fqn, olds); |
| 722 | // A logical ID alone does not prove ownership: another |
| 723 | // declaration, stage, or stack on the branch can hold it. Only |
| 724 | // the generated name, which embeds this instance's ID, does. |
| 725 | generatedIdentityMatch = |
| 726 | database !== undefined && |
| 727 | olds.name === undefined && |
| 728 | database.name === (yield* createName(id, undefined)); |
| 729 | } |
| 730 | // An explicit logical ID is the only identity. A derived one falls |
| 731 | // back to the name for databases created before logical IDs existed. |
| 732 | if (!database && projectId && olds.logicalId === undefined) { |
| 733 | const name = yield* createName(id, olds.name); |
| 734 | database = yield* findDatabaseByName(projectId, name); |
| 735 | generatedIdentityMatch = database !== undefined && olds.name === undefined; |
| 736 | if (!database && olds.name === undefined && (olds.isDefault ?? false)) { |
| 737 | database = yield* findDefaultDatabase(projectId); |
| 738 | } |
| 739 | } |
| 740 | } |
| 741 | if (!database) return undefined; |
| 742 | if (databaseId === undefined && !sourceMatches(database.source, olds.source)) { |
| 743 | return yield* new DatabaseConflict({ |
| 744 | message: `Prisma database '${database.name}' has immutable source ${JSON.stringify(database.source)} but ${JSON.stringify(olds.source ?? { type: "empty" })} was requested; refusing to adopt a database that cannot converge.`, |
| 745 | }); |
| 746 | } |
| 747 | const cachedSecrets = output?.databaseId === database.id ? output : undefined; |
| 748 | const attrs = attrsFrom(database, { |
| 749 | directConnectionString: cachedSecrets?.directConnectionString, |
| 750 | pooledConnectionString: cachedSecrets?.pooledConnectionString, |
| 751 | accelerateConnectionString: cachedSecrets?.accelerateConnectionString, |
| 752 | host: cachedSecrets?.host, |
| 753 | user: cachedSecrets?.user, |
| 754 | password: cachedSecrets?.password, |
| 755 | }); |
| 756 | // Only a declaration assigns a logical ID, so a match is this database. |
| 757 | // The generation a replacement is replacing is ours too. |
| 758 | return databaseId === undefined && |
| 759 | !generatedIdentityMatch && |
| 760 | database.id !== previous?.databaseId |
| 761 | ? Unowned(attrs) |
| 762 | : attrs; |
| 763 | }), |
| 764 | reconcile: Effect.fn(function* ({ id, fqn, news, olds, output }) { |
| 765 | yield* validateDatabaseProps(news); |
| 766 | const projectId = yield* resolveProjectId(news.project); |
| 767 | const region = yield* resolveDatabaseRegion(projectId, news.region); |
| 768 | const name = yield* createName(id, news.name); |
| 769 | const databaseId = isPrismaDevId(output?.databaseId) ? undefined : output?.databaseId; |
| 770 | let database: ObservedProjectDatabase | undefined = databaseId |
| 771 | ? yield* getDatabase({ databaseId }).pipe( |
| 772 | Effect.map((response) => response.data), |
| 773 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 774 | ) |
| 775 | : undefined; |
| 776 | const logicalId = news.logicalId ?? fqn; |
| 777 | if (!database) { |
| 778 | database = yield* findDatabaseByLogicalId(projectId, logicalId, news); |
| 779 | } |
| 780 | if (!database && news.logicalId === undefined && news.name === undefined) { |
| 781 | database = yield* findDatabaseByName(projectId, name); |
| 782 | } |
| 783 | |
| 784 | let secrets: PrismaSecretConnection = {}; |
| 785 | let recoverCreateSecrets = false; |
| 786 | const attach = branchAttachment(news); |
| 787 | if (!database) { |
| 788 | if ( |
| 789 | news.name !== undefined && |
| 790 | (news.branchId !== undefined || news.branchGitName !== undefined) |
| 791 | ) { |
| 792 | return yield* new DatabaseInvalidProps({ |
| 793 | message: `Cannot safely create explicitly named Prisma database '${name}' with a branch attachment. The Management API creates the database before attaching the branch and exposes no idempotency key, so a failed response cannot be distinguished from a foreign database. Omit name to use Alchemy's recoverable physical identity, or wait for an atomic Management API operation.`, |
| 794 | }); |
| 795 | } |
| 796 | let createAttach: { |
| 797 | branchId: string | undefined; |
| 798 | branchGitName: string | undefined; |
| 799 | } = attach; |
| 800 | // The API refuses logicalId together with branchGitName on create. |
| 801 | // When the branch does not exist yet, create it through |
| 802 | // branchGitName and set the logical ID in a follow-up update. |
| 803 | let createLogicalId: string | undefined = logicalId; |
| 804 | if (attach.branchGitName !== undefined) { |
| 805 | const branchId = yield* branchIdForGitName(projectId, attach.branchGitName); |
| 806 | if (branchId === undefined) { |
| 807 | createLogicalId = undefined; |
| 808 | } else { |
| 809 | createAttach = { branchId, branchGitName: undefined }; |
| 810 | } |
| 811 | } |
| 812 | const result = yield* createDatabase({ |
| 813 | projectId, |
| 814 | name, |
| 815 | region, |
| 816 | isDefault: news.isDefault ?? false, |
| 817 | ...(news.source === undefined ? {} : { source: news.source }), |
| 818 | branchId: createAttach.branchId, |
| 819 | branchGitName: createAttach.branchGitName, |
| 820 | ...(createLogicalId === undefined ? {} : { logicalId: createLogicalId }), |
| 821 | }).pipe( |
| 822 | // A replayed create would make a second database; the retry |
| 823 | // policy cannot see the request, so opt out explicitly. |
| 824 | Retry.none, |
| 825 | Effect.map((response) => ({ |
| 826 | database: response.data, |
| 827 | secrets: extractConnectionSecrets(response.data.connections[0]), |
| 828 | recoverSecrets: true, |
| 829 | })), |
| 830 | Effect.catchTag("Conflict", (conflict) => |
| 831 | Effect.gen(function* () { |
| 832 | const taken = |
| 833 | createLogicalId === undefined |
| 834 | ? undefined |
| 835 | : yield* findDatabaseByLogicalId(projectId, createLogicalId, createAttach); |
| 836 | if (taken) { |
| 837 | return yield* Effect.fail( |
| 838 | logicalIdTaken(logicalId, taken.branchId, projectId, conflict), |
| 839 | ); |
| 840 | } |
| 841 | if (news.logicalId !== undefined) { |
| 842 | return yield* new DatabaseConflict({ |
| 843 | message: `A Prisma database named '${name}' already exists in project '${projectId}' without logical ID '${logicalId}'. Refusing to take it over; choose a different name.`, |
| 844 | cause: conflict, |
| 845 | }); |
| 846 | } |
| 847 | return yield* news.name === undefined |
| 848 | ? recoverGeneratedDatabaseAfterConflict(projectId, name).pipe( |
| 849 | Effect.map((database) => ({ |
| 850 | database, |
| 851 | secrets: {}, |
| 852 | // The generated physical name is owned by this |
| 853 | // resource instance. A conflict after the POST can |
| 854 | // be a lost successful response, so recover the |
| 855 | // write-only default credentials below. |
| 856 | recoverSecrets: true, |
| 857 | })), |
| 858 | ) |
| 859 | : Effect.fail( |
| 860 | new DatabaseConflict({ |
| 861 | message: `A Prisma database named '${name}' appeared after the adoption check. Refusing to take it over; rerun with adoption enabled if it is the intended database.`, |
| 862 | }), |
| 863 | ); |
| 864 | }), |
| 865 | ), |
| 866 | ); |
| 867 | database = result.database; |
| 868 | secrets = result.secrets; |
| 869 | recoverCreateSecrets = result.recoverSecrets; |
| 870 | } |
| 871 | |
| 872 | if (database.project.id !== projectId) { |
| 873 | return yield* new DatabaseInvalidProps({ |
| 874 | message: database.isDefault |
| 875 | ? `Cannot move default Prisma database '${database.name}' from project '${database.project.id}' to '${projectId}' because the old default cannot be deleted. Promote another database in the original project first, then retry the move.` |
| 876 | : `Prisma database '${database.name}' belongs to project '${database.project.id}', not requested project '${projectId}'. Refusing to claim convergence; replace the database.`, |
| 877 | }); |
| 878 | } |
| 879 | if (database.region?.id !== region) { |
| 880 | return yield* new DatabaseConflict({ |
| 881 | message: `Prisma database '${database.name}' is in immutable region '${database.region?.id ?? "unknown"}', not requested region '${region}'. Refusing to claim convergence; replace the database.`, |
| 882 | }); |
| 883 | } |
| 884 | if (!sourceMatches(database.source, news.source)) { |
| 885 | return yield* new DatabaseConflict({ |
| 886 | message: `Prisma database '${database.name}' has immutable source ${JSON.stringify(database.source)}, not requested source ${JSON.stringify(news.source ?? { type: "empty" })}. Refusing to claim convergence; replace the database.`, |
| 887 | }); |
| 888 | } |
| 889 | if (database.isDefault === true && (news.isDefault ?? false) === false) { |
| 890 | return yield* new DatabaseConflict({ |
| 891 | message: `Cannot demote default Prisma database '${database.name}' directly because the Management API has no demotion operation. Promote another database in project '${projectId}' first, then retry this deployment.`, |
| 892 | }); |
| 893 | } |
| 894 | |
| 895 | const ownedGeneratedIdentity = news.name === undefined && database.name === name; |
| 896 | |
| 897 | const desired = { ...news, name }; |
| 898 | const needsPatch = |
| 899 | database.name !== name || (yield* branchNeedsSync(projectId, database, desired)); |
| 900 | if (needsPatch) { |
| 901 | // Omitted branch props preserve the attachment; null is rejected. |
| 902 | database = (yield* updateDatabase({ |
| 903 | databaseId: database.id, |
| 904 | name, |
| 905 | branchId: attach.branchId, |
| 906 | branchGitName: attach.branchGitName, |
| 907 | })).data; |
| 908 | } |
| 909 | if (database.logicalId !== logicalId) { |
| 910 | const { branchId } = database; |
| 911 | // The API refuses to rebind a logical ID; it must be cleared first. |
| 912 | if (database.logicalId) { |
| 913 | database = (yield* updateDatabase({ databaseId: database.id, logicalId: null })).data; |
| 914 | } |
| 915 | // The API refuses logicalId in the same request as a branch |
| 916 | // move, so it is set only after the move above. |
| 917 | database = (yield* updateDatabase({ |
| 918 | databaseId: database.id, |
| 919 | logicalId, |
| 920 | }).pipe( |
| 921 | Effect.catchTag("Conflict", (conflict) => |
| 922 | Effect.fail(logicalIdTaken(logicalId, branchId, projectId, conflict)), |
| 923 | ), |
| 924 | )).data; |
| 925 | } |
| 926 | |
| 927 | const persistedSecrets = output?.databaseId === database.id ? output : undefined; |
| 928 | const knownSecrets = mergeConnectionSecrets(secrets, { |
| 929 | directConnectionString: persistedSecrets?.directConnectionString, |
| 930 | pooledConnectionString: persistedSecrets?.pooledConnectionString, |
| 931 | accelerateConnectionString: persistedSecrets?.accelerateConnectionString, |
| 932 | host: persistedSecrets?.host, |
| 933 | user: persistedSecrets?.user, |
| 934 | password: persistedSecrets?.password, |
| 935 | }); |
| 936 | if ( |
| 937 | recoverCreateSecrets || |
| 938 | (ownedGeneratedIdentity && !hasCanonicalConnectionSecrets(knownSecrets)) || |
| 939 | olds !== undefined || |
| 940 | news.rotateCredentialsOnAdopt === true |
| 941 | ) { |
| 942 | const recovered = yield* recoverDatabaseConnectionSecrets(database, knownSecrets); |
| 943 | database = recovered.database; |
| 944 | return attrsFrom(database, recovered.secrets); |
| 945 | } |
| 946 | return attrsFrom(database, knownSecrets); |
| 947 | }), |
| 948 | delete: Effect.fn(function* ({ output }) { |
| 949 | if (isPrismaDevId(output.databaseId)) return; |
| 950 | const database = yield* getDatabase({ |
| 951 | databaseId: output.databaseId, |
| 952 | }).pipe( |
| 953 | Effect.map((response) => response.data), |
| 954 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 955 | ); |
| 956 | if (!database) return; |
| 957 | if (database.isDefault) { |
| 958 | return yield* new DatabaseConflict({ |
| 959 | message: `Cannot delete default Prisma database '${database.name ?? output.databaseId}' directly. Promote another database first, or delete the owning Prisma.Project so the API can remove its project-owned default database.`, |
| 960 | }); |
| 961 | } |
| 962 | yield* deleteDatabase({ |
| 963 | databaseId: output.databaseId, |
| 964 | }).pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 965 | }), |
| 966 | }; |
| 967 | }), |
| 968 | ); |
| 969 | |
| 970 | type PrismaDevDatabaseRequirements = ChildProcessSpawner | Path.Path | Scope; |
| 971 | |
| 972 | const ProviderLocal = () => |
| 973 | Provider.succeed<Database, never, never, never, PrismaDevDatabaseRequirements>(Database, { |
| 974 | stables: ["databaseId"], |
| 975 | list: () => Effect.succeed([]), |
| 976 | diff: Effect.fn(function* () { |
| 977 | return { action: "update" } as const; |
| 978 | }), |
| 979 | read: Effect.fn(function* ({ output }) { |
| 980 | return output; |
| 981 | }), |
| 982 | reconcile: Effect.fn(function* ({ id, fqn, news, output }) { |
| 983 | const databaseId = output?.databaseId ?? devId("database", id); |
| 984 | const local = yield* ensurePrismaDevDatabase(databaseId, news.dev); |
| 985 | return { |
| 986 | databaseId, |
| 987 | databaseName: news.name ?? id, |
| 988 | projectId: attrOrString(news.project, "projectId") ?? devId("project", id), |
| 989 | status: "ready", |
| 990 | region: news.region ?? "us-east-1", |
| 991 | isDefault: news.isDefault ?? false, |
| 992 | branchId: news.branchId ?? null, |
| 993 | defaultConnectionId: devId("connection", id), |
| 994 | createdAt: output?.createdAt ?? DEV_TIMESTAMP, |
| 995 | directConnectionString: local?.directConnectionString, |
| 996 | pooledConnectionString: local?.pooledConnectionString, |
| 997 | accelerateConnectionString: local?.accelerateConnectionString, |
| 998 | host: local?.host, |
| 999 | user: local?.user, |
| 1000 | password: local?.password, |
| 1001 | logicalId: news.logicalId ?? fqn, |
| 1002 | } satisfies Database["Attributes"]; |
| 1003 | }), |
| 1004 | delete: Effect.fn(function* ({ output }) { |
| 1005 | yield* closePrismaDevDatabase(output.databaseId); |
| 1006 | }), |
| 1007 | }); |
| 1008 | |
| 1009 | export const DatabaseProvider = () => |
| 1010 | ProviderLayer.dual(Database, { |
| 1011 | local: () => ProviderLocal(), |
| 1012 | live: () => ProviderLive(), |
| 1013 | }); |