CodeVetter · Repo Unpack · Behavior traces
prisma/prisma
Three flows dominate. Process startup wires telemetry, a CLI engine, and a host runtime, then dispatches one mounted command. Contract emit is offline: config, source provider, enrichment, canonical JSON, and a dts pair. A Postgres query stays lazy until first use, then compiles middleware, lowers SQL, encodes codecs, checks the marker, and streams decoded rows. db update is the persistence path: prepare a control client, pre-plan destructive work, and only then introspect, plan, and apply.
- Startup order is bin.ts calling runOrmCli(process); runOrmCli calling resolveTelemetryHooks then createOrmCli().run(argv.slice(2), runtimeFromProcess(proc), hooks). A throw before a command exists is caught by reportStartupFailure, which writes a single stderr line and returns exit code 1.
- createOrmCli builds the engine with name prisma, version from the CLI package.json, commandFamilies [ormCommandFamily], groups BIN_GROUPS, and commands BIN_COMMANDS. BIN_COMMANDS is createBinCommands(createControlClient), so db and migration commands close over the real control client while tests can inject a double.
- runtimeFromProcess copies stdout, stderr, stdin, cwd, env, TTY flags, Node version, platform, and arch; registers SIGINT and SIGTERM; sets loadConfig to loadOrmConfig; sets managementApi.baseUrl to https://api.prisma.io; and installs runPackageManager as the package-manager capability. The engine, not the bin, owns signal policy.
- contract emit handler order: resolve optional --output-path against ctx.cwd; call executeContractEmit with config, cwd, controlProgressReporter, and AbortSignal; surface validationWarning; build an EmitDocument with hashes and files; return ok(ctx.present(...)). The command factory injects executeContractEmitOperation as the dependency.
- Inside executeContractEmit the ordered steps are: require config.contract and source.load; getEmittedArtifactPaths; queueEmitByOutput; createControlStack(config); source.load(sourceContext); validateProviderResult; family.create plus assertFrameworkComponentsCompatible; enrichContract; serializeContract; deserializeContract; emitter emit with the project import-specifier resolver.
- Emitter emit order is requireToOneRelationNullability, canonicalizeContractToObject (schemaVersion 1 plus the target serializer), JSON.stringify of the canonical object with a _generated banner, generateContractDts, and prettier format (typescript parser, singleQuote, semi, printWidth 100).
- postgres() query startup order: resolveContract; resolveOptionalPostgresBinding; createSqlExecutionStack({ target: postgresTarget, adapter: postgresAdapter, driver: postgresDriver, extensions }); createExecutionContext; buildPostgresStaticContext for the sql Proxy, raw tag, enums, and native enums. ormBuilder delegates query, execute, and connection to getRuntime().
- getRuntime order on first use: instantiateExecutionStack; driverDescriptor.create({ cursor: { disabled: true } }); if a binding exists, connectDriver in the background; construct PostgresRuntimeImpl with context, adapter, driver, verifyMarker, and middleware. A later call after close() throws DRIVER.NOT_CONNECTED. connectDriver turns a url into a Pool and connects the driver once.
- Row execution order on SqlRuntimeBase: query calls queryAgainstQueryable; that calls ensureCodecRegistryValidated, prepareQueryExecution, buildDecodeContext, and streamRows. prepareQueryExecution ends in prepareOperation. For a query plan, prepareOperation calls compilePlan (runBeforeCompileChain), lowerToDraft (lowerSqlPlan), the before-hook mutator, and encodeDraftParams. streamRows calls setupDriverExecution (verifyMarker), runQueryWithMiddleware, queryable.query({ sql, params }), and decodeRow, checking the abort signal between rows.
- withTransaction order: runtime.connection(), connection.transaction(), invoke the callback with a guarded query/execute surface, set invalidated in a finally, then transaction.commit(). A callback throw triggers rollback; if rollback throws, the connection is destroy()ed and the error is RUNTIME.TRANSACTION_ROLLBACK_FAILED with the original as cause. A failed commit attempts rollback and destroys the connection if that also fails. The connection is release()d when it was not destroyed.
- db update handler starts with prepareMigrationRun({ config, cwd, db, commandName: 'db update', createClient }). The operation layer then either returns the destructive-change refusal from a plan-mode executeRun or calls executeRun in the requested mode with the consented plan hash.
- Non-CI telemetry order: resolveGating against env and the user config file; if no installationId, write the first-run notice that names DO_NOT_TRACK, PRISMA_DISABLE_TELEMETRY, and enableTelemetry; return an onSettled hook. The hook calls ensureInstallationId if needed and runTelemetry, which returns immediately with spawned true, gated-off, ci, or fork-failed. Failures are swallowed.