GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Releases · prisma/orm

Releases · prisma/orm

v8.0.0-rc.25

v8.0.0-rc.25 Pre-release
Pre-release
@github-actions github-actions released this 23 Nov 09:32
v8.0.0-rc.25
e023771
This commit was created on GitHub.com and signed with GitHub’s verified signature.
GPG key ID: B5690EEEBB952194
Verified
Learn about vigilant mode.

v8.0.0-rc.25

A database can now record how it may change and what data it protects, and the CLI refuses a migration or update that breaks those rules. MariaDB gets a client of its own, and MySQL gains the ORM's aggregates. Int, BigInt, Float, Decimal, String, Boolean, Bytes and Json are convenience types on every database. SQL clients run nested transactions with tx.transaction(callback), and an ORM write inside a transaction is atomic. On PostgreSQL and SQLite, a changed @@map, @map or enum stored value is planned as a rename. Nested writes gain onConflict, variants of a polymorphic model, a disconnect that applies its criteria, and update and delete of one related row. prisma orm init --target takes any target package by name.

The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them. The examples write the ORM client as db.orm.public.<Model>, the PostgreSQL form; on SQLite, MySQL and MariaDB it is db.orm.<Model>. After upgrading, run prisma contract emit once: the generated contract.d.ts now imports from one module of the target package, SQL contracts record two new capabilities, and MySQL and MariaDB contracts gain aggregate types.

Breaking changes

  • pg and @types/pg are peer dependencies. @prisma/orm-postgres, @prisma/orm-target-postgres and @prisma/orm-extension-supabase no longer install their own copy of pg and @types/pg. Add "pg": "^8.22.0" to your dependencies and "@types/pg": "^8.20.0" to your dev dependencies before you install the upgrade. This fixes a Pool from your own pg not being accepted by the client when the two @types/pg versions differed. See pg-is-a-peer-dependency in the app recipe and the extension recipe, and extension-importing-pg-peers-it in the extension recipe. (#31060)

  • temporal-polyfill must be 1.0.8 or later. Every database package that requires temporal-polyfill as a peer dependency now requires ^1.0.8, where it required ^1.0.4. A project or extension package that pins an older 1.0.x version updates it. See temporal-polyfill-peer-range-moves-to-1-0-8 in the app recipe and the extension recipe. (#31045)

  • PostgreSQL connections no longer set lc_monetary=C. This lets a pooled Prisma Postgres URL connect. If you use money columns, run SHOW lc_monetary as the application's role, outside Prisma. If it is not C, POSIX or en_US, run ALTER ROLE <role> SET lc_monetary = 'C' before you deploy the upgrade; otherwise a money read fails with RUNTIME.LC_MONETARY_NOT_C. Under a locale with no or three fraction digits, writes made before the change are stored wrong, so make the change first. See postgres-lc-monetary-not-set in the app recipe. (#31081)

  • The config type is PrismaConfig. The type defineConfig returns is renamed from PrismaNextConfig to PrismaConfig, with no alias. The language server's diagnostic PRISMA_NEXT_INTERPRETATION_FAILED is now PRISMA_INTERPRETATION_FAILED. See config-type-renamed-to-prisma-config in the app recipe and the extension recipe. (#31062)

    Before:

    import type { PrismaNextConfig } from '@prisma/orm-toolchain/cli/config-types';
    const config: PrismaNextConfig<'sql', 'postgres'> = defineConfig({ /* ... */ });

    After:

    import type { PrismaConfig } from '@prisma/orm-toolchain/cli/config-types';
    const config: PrismaConfig<'sql', 'postgres'> = defineConfig({ /* ... */ });
  • Generated files import from the module the target package names. A generated contract.d.ts now imports all its types from one module, such as @prisma/orm-postgres/contract-types; run prisma contract emit to regenerate it. A config that you assemble from the framework's own defineConfig, not a target package's, must set contract.typesModule and migrations.module, or commands fail with CONFIG.CONTRACT_TYPES_MODULE_MISSING and CONFIG.MIGRATION_MODULE_MISSING. Control API callers pass typesModule to emit and renderContractDts, and the projectDir option is gone. @prisma/orm-toolchain/publish-surface and its two sub-entries are removed. Extension authors: the emitter, migration renderer and MySQL config factory take the module names too. See contract-types-import-from-the-target-package, hand-assembled-config-names-generated-file-modules, control-api-takes-types-module and toolchain-publish-surface-entrypoints-removed in the app recipe, and target-package-names-generated-file-modules, extension-config-names-generated-file-modules, family-imports-are-import-requirements, migration-renderer-takes-the-migration-module, emitter-takes-the-types-module, mysql-config-components-carry-family-and-modules, control-api-takes-types-module, component-type-import-module-is-not-a-literal-type and toolchain-publish-surface-entrypoints-removed in the extension recipe. (#31078)

  • On PostgreSQL and SQLite, a changed stored name is planned as a rename. When a model, field or enum member keeps its name and only its @@map, @map or stored value changes, migration plan and db update now rename the table or column, or replace the stored value, without asking. A script that passed --delete for such a change now fails with CLI.CONSENT_UNUSED; remove the flag. To get an empty table under the new name, remove the model in one migration and add it back in the next. Swaps, chains and takeovers of table and column names are refused with MIGRATION.PLANNING_FAILED, and so are enum members that swap stored values or take the stored value of a removed member; make them in two migrations: the first moves every name involved to a name nothing uses, and the second moves them to the final names. Chains of enum stored values are planned. A table that still has the lowered name an earlier release gave a model with no @@map is renamed to the model name; add @@map to keep the old name. MySQL and MongoDB plan these changes as before. See sql-stored-name-change-is-a-rename, sql-stored-name-delete-is-unused, sql-stored-name-empty-table, sql-stored-name-swaps-refused and sql-lowered-table-names-renamed in the app recipe. Extension authors who call the SQL family's statement planning see schema-tables-same-name, plan-statements-plans-stored-name-renames, subjects-of-calls-storage-renames and stored-value-keep-data-edit-removed in the extension recipe. (#31088)

    Before:

    prisma migration plan --name move-users --delete User

    After:

    prisma migration plan --name move-users
  • sql.String(n) is now sql.Varchar(n), and PostgreSQL's jsonColumn is plainJsonColumn. sql.String(n) still works as a deprecated alias that warns with PSL_DEPRECATED_SCALAR_NAME, in PSL and as type.sql.String(n) in TypeScript. The PostgreSQL column helper jsonColumn is removed; import plainJsonColumn. No contract changes. See psl-renamed-sql-string, ts-renamed-sql-string and ts-renamed-postgres-json-column-helper in the app recipe, and ts-postgres-explicit-json-type in the extension recipe. (#31065)

    Before:

    model Label {
      id   Int            @id
      name sql.String(50)
    }

    After:

    model Label {
      id   Int             @id
      name sql.Varchar(50)
    }
  • On MongoDB, Int64 is now Int64BigInt. Int64 still works in PSL as a deprecated alias that warns. In a TypeScript contract, type.Int64() is removed; write type.BigInt() or type.Int64BigInt(). No contract changes. See psl-renamed-mongo-int64 and ts-removed-mongo-int64-helper in the app recipe and the [extension recipe](https://github.com/prisma/...

Read more
Assets 2
Loading

Uh oh!

There was an error while loading. Please reload this page.

All reactions

v8.0.0-rc.24

v8.0.0-rc.24 Pre-release
Pre-release
@github-actions github-actions released this 16 Nov 17:00
v8.0.0-rc.24
17385f2
This commit was created on GitHub.com and signed with GitHub’s verified signature.
GPG key ID: B5690EEEBB952194
Verified
Learn about vigilant mode.

v8.0.0-rc.24

MongoDB gets the convenience date and time types, and Date becomes a calendar date. A MongoDB TypeScript contract names a field's type with type.X(), as PSL does, and MongoDB clients can prepare a query. MongoDB plans check documents before a validator change and ask about type changes that can lose values. SQL clients take transaction isolation levels and callback timeouts. The CLI manages MariaDB, and answers Prisma 7 commands such as prisma migrate dev with what to run instead. Nested create() and update() gain arrays of operations and filtered updateAll and deleteAll, and db.raw.sql embeds builder queries.

The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them. The app recipe opens with the order to do the steps in. After upgrading, run prisma contract emit once, so a contract that an extension such as Supabase stamps with its version matches the installed package (contract-artifacts-restamp in the app recipe).

Breaking changes

  • On MongoDB, Date is a calendar date. Date is now stored as a BSON date at midnight UTC and read as a string such as "2024-02-29". DateTime is what Date was: an instant read as a JavaScript Date. DateTime(as: temporal), Time and Duration are new. Rewrite Date to DateTime in MongoDB schemas with the script the app recipe ships; the contract does not change. A field you miss still compiles, but @onCreate(now()) on it then writes today's date at midnight UTC and loses the time. temporal-polyfill is now a required peer dependency of @prisma/orm-mongo and @prisma/orm-target-mongo; a project that installs with Yarn, or with npm and legacy-peer-deps, adds it to its dependencies. See mongo-date-is-a-calendar-date, temporal-polyfill-is-a-peer-dependency-of-mongo and temporal-polyfill-with-legacy-peer-deps in the app recipe. (#30989)

    Before:

    model Order {
      id     ObjectId @id @map("_id")
      paidAt Date
    }

    After:

    model Order {
      id     ObjectId @id @map("_id")
      paidAt DateTime
    }
  • A MongoDB TypeScript contract names a field's type with type.X(). field.objectId(), field.string(), field.date(), field.vector(), field.scalar(codecId) and the other MongoDB field helpers are removed. Write field.scalar(type.X()), where type comes from the defineContract callback, as PSL names the type. The app recipe ships a script that rewrites them; the contract does not change. MongoDB PSL gains Vector and Vector(length), and a type that takes no arguments, written with one, such as String(5), is now refused. Extension authors whose extension has its own MongoDB codec add a type constructor under authoring.type. See mongo-fields-take-a-type in the app recipe and the extension recipe. (#30959)

    Before:

    fields: {
      _id: field.objectId(),
      embedding: field.vector({ typeParams: { length: 3 } }),
      raw: field.scalar('mongo/bson@1'),
    }

    After:

    fields: {
      _id: field.scalar(type.ObjectId()),
      embedding: field.scalar(type.Vector(3)),
      raw: field.scalar(type.Bson()),
    }
  • MongoDB plans rewrite the documents a schema change touches. A validator change that migration plan or db update writes now checks every document first, and the apply stops with MIGRATION.PRECHECK_FAILED while a document does not fit the new validator. A field type change that can lose values is now a question, answered with --convert or --delete, as on SQL. A new required field is filled with a temporary value in the documents that lack it, unless --backfill names it. Existing migration.ts files are unchanged. See mongo-validator-change-checks-documents, mongo-type-change-is-asked and mongo-new-required-field-gets-temporary-value in the app recipe. (#30970)

  • MySQL no longer sets every session to READ COMMITTED. A callback transaction with no isolation level now uses the server or session default. If your code relied on READ COMMITTED, pass transactionOptions: { isolationLevel: 'ReadCommitted' } to the MySQL client, or pass it to transaction(callback, options). Transactions the ORM opens for its own writes still use READ COMMITTED. Extension authors forward the isolation options through their SQL transaction wrappers. See mysql-explicit-isolation-default in the app recipe and forward-sql-transaction-options in the extension recipe. (#30990)

  • @prisma/orm-postgres/migration no longer exports the free functions createExtension and dataTransform. Neither could be called correctly from a migration.ts. Call the methods on the migration class instead: this.createExtension({ extension: 'btree_gist' }) and this.dataTransform(endContract, name, { check, run }). The migration's ops.json does not change. See create-extension-not-exported and data-transform-not-exported in the app recipe. (#30988)

  • Prisma 7 commands fail with CLI.V7_COMMAND. prisma generate, validate, format, studio, db pull, db push, db seed, db execute and the six prisma migrate commands now fail with CLI.V7_COMMAND instead of CLI.COMMAND_MOVED, still with exit code 2. The error names the Prisma 8 commands to run instead, or links the CLI docs when Prisma 8 has none, and says how to install Prisma 7's CLI as @prisma/prisma7 to keep running the old command. The toolchain now requires @prisma/[email protected]; a project that depends on it itself moves to 0.10.0. See prisma-7-commands-answer-v7-command and engine-pin-moves-to-0-10-0 in the app recipe. (#31027)

  • The CLI's --json output lists planner warnings under plannerWarnings. db update --json and db init --json list the planner's warnings under plannerWarnings instead of warnings, as migration plan --json does. See planner-warnings-json-field in the app recipe. (#30970)

  • Raw SQL parts can hold a statement. The parts of RawExpr and RawQueryAst can now hold a SelectAst, InsertAst, UpdateAst or DeleteAst. Code that walks parts and treats every non-string part as an expression must handle the four statement kinds. See raw-parts-hold-statement-asts in the app recipe and the extension recipe. (#30991)

  • PostgreSQL: a statement on a pg client that lost its connection is refused. A statement on a pooled connection, on a held connection, and in a transaction or savepoint, including its BEGIN, COMMIT, ROLLBACK and savepoint statements, and before each later step of a cursor, now rejects with DRIVER.NOT_CONNECTED and the message "Postgres connection is no longer usable." when its pg client lost its connection: the client emitted error or end after the driver first used it, a driver gave up on it, or pg marks it ended or broken. Before, the statement was sent to the client. On a driver given one pg.Client that has already lost its connection, a query, and the start of a transaction or held connection, were already refused at 8.0.0-rc.23 with "Postgres connection lost or closed. Create a new client to reconnect.", and still are; the new message comes on a connection or transaction taken before the loss. The driver keeps this state for the client object, so code that recovers a lost connection by patching the same pg client, for example by replacing its query method, stops working: release the client and take a new one from the pool, or create a new pg.Client. (#31012)

  • Extension authors: runtime transactions carry an AbortSignal. Runtime connection and activity wrappers take RuntimeTransactionOptions and forward them unchanged, and every hand-written RuntimeTransaction, test doubles included, exposes a signal. See runtime-transaction-signal in the extension recipe. (#31012)...

Read more
Assets 2
Loading

Uh oh!

There was an error while loading. Please reload this page.

NetLancer, marr-cloud, dev-garcia, and bubu94 reacted with thumbs up emoji
All reactions
  • 👍 4 reactions
4 people reacted

v8.0.0-rc.23

v8.0.0-rc.23 Pre-release
Pre-release
@github-actions github-actions released this 06 Nov 18:13
v8.0.0-rc.23
557c0d4
This commit was created on GitHub.com and signed with GitHub’s verified signature.
GPG key ID: B5690EEEBB952194
Verified
Learn about vigilant mode.

v8.0.0-rc.23

MongoDB indexes carry their names, and migrations create and drop each index by its name. On PostgreSQL, Int, BigInt, Float, Decimal, String, Boolean and Bytes become convenience types, and SQLite and MySQL get the convenience date and time types. The pgvector, PostGIS, ParadeDB and citext packs find their extension through the search path, so db sign adopts a Supabase database. MySQL gets ORM writes. mongo() takes extension packs, and supabase() takes the options postgres() takes. Prisma ORM no longer refuses to start when it is loaded from more than one copy.

The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them. The app recipe opens with the order to do the steps in. After upgrading, run prisma contract emit once, so a contract that an extension such as Supabase stamps with its version matches the installed package (contract-artifacts-restamp in the app recipe).

Breaking changes

  • MongoDB indexes carry their names. Every index of a MongoDB contract records the name MongoDB stores it under, so every MongoDB contract with an index gets a new storage hash. An index written without a name is named after its keys, such as email_1, the name earlier releases already gave it in the database, so no database changes. Migrations create and drop each index by that name, and an operation id names the index, as in index.users.create(email_1). Two indexes of one collection that would get one name, such as a unique and a sparse index on email, are refused; name one of them. A contract read with prisma6Schema() names each index as Prisma 6 did, such as User_email_key. Run prisma contract emit, run the script the app recipe ships to name the indexes of your migration snapshots, then run prisma db sign or plan a migration, which has no operations. Extension authors: MongoIndex, MongoSchemaIndex and their input types take a required name, CreateIndexCall and DropIndexCall take the index's name and options, and code that calls buildMongoContractFromDefinition calls nameIndexes first. See mongo-contracts-record-index-names, mongo-unnamed-indexes-with-one-name-refused, mongo-prisma6-index-names and mongo-index-operations-by-name in the app recipe, and mongo-index-name-required, mongo-index-calls-take-name and mongo-build-refusal-index-name-duplicate in the extension recipe. (#30952)

    Before:

    createIndex('users', [{ field: 'email', direction: 1 }], { unique: true }),

    After:

    createIndex('users', [{ field: 'email', direction: 1 }], { name: 'email_1', unique: true }),
  • The Prisma 6 MongoDB reader keeps indexes as Prisma 6 wrote them. prisma6Schema() no longer merges indexes. Two indexes of one model with the same fields and the same written sort are refused with PSL.PRISMA6_MONGO_INDEX_ALREADY_EXISTS, as Prisma 6 refuses them. A unique and a plain index on the same keys that Prisma 6 accepts are both kept, so the contract gets a new storage hash; run prisma db sign again. Prisma 8 PSL and TypeScript still merge identical and redundant indexes. Extension authors: the MongoDB contract builder no longer merges indexes, BuildRefusal has the kind indexDuplicate again, and mergeRedundantIndexes merges before building. See mongo-prisma6-indexes-as-prisma6-reads-them in the app recipe, and mongo-build-refusal-index-duplicate-restored in the extension recipe. (#30921)

  • The pgvector, PostGIS, ParadeDB and citext packs find their extension through the search path. Each pack declares its extension in the unbound namespace, so db sign and db verify accept the extension in any schema on the connection's search path, such as Supabase's extensions. A project that composes one of these packs runs prisma contract emit, which writes the pack's new migration, and then prisma db migrate, which applies it without changing the database. An application may no longer declare an extension that a composed pack declares; remove its own extension vector {} block or extension('vector') handle. Extension authors: a pack declares its Postgres extension in the unbound namespace, or the configuration is refused with CONTRACT.PACK_CONTRIBUTION_INVALID. See pack-extension-found-on-search-path and remove-pack-extension-declaration in the app recipe, and pack-declares-extension-unbound in the extension recipe. (#30956)

  • mongo() and mongoStatic() refuse a contract whose extension packs they are not given. They take an extensions option, as postgres() does. A MongoDB project whose prisma.config.ts composes extension packs passes each pack's runtime descriptor to mongo({ extensions }) and mongoStatic({ extensions }); otherwise they fail with RUNTIME.MISSING_EXTENSION_PACK. A MongoDB contract.json must have "target"; every contract prisma contract emit writes has it. Extension authors: createMongoExecutionContext checks the contract against the stack, a MongoDB descriptor declares each codec once as a codec descriptor instead of in a codecs() slot, and mongoStandardCodecs and buildStandardCodecRegistry are removed. See mongo-client-takes-extensions and mongo-contract-requires-target in the app recipe, and mongo-execution-context-checks-contract-requirements, mongo-codecs-declared-once and mongo-standard-codecs-removed in the extension recipe. (#30943)

    Before:

    export const db = mongo({ contract, url });

    After:

    import myPack from 'my-mongo-pack/runtime';
    
    export const db = mongo({ contract, url, extensions: [myPack] });
  • supabase() and postgres() check their database input when they are called. A wrong input fails with RUNTIME.BINDING_INVALID at once, not on the first query. Passing both url and pg to supabase() fails; before, pg won silently. An empty url, or one that is not postgres:// or postgresql://, fails; before, an empty one connected with the PG* environment variables or to localhost. null as pg, url or binding fails, even beside another input, so leave the option out instead. A binding of an unknown kind fails. supabase() refuses a pg.Client with the message "Supabase takes a pg.Pool or a url, not a pg.Client". See supabase-one-binding-input and postgres-checks-database-input in the app recipe. (#30920)

    Before:

    postgres({ contract, url: process.env['DATABASE_URL'] ?? null });

    After:

    const url = process.env['DATABASE_URL'];
    postgres({ contract, ...(url === undefined ? {} : { url }) });
  • On PostgreSQL, seven scalar type names are deprecated, and two column helpers are renamed. SmallInt, BigIntNumber, Numeric, UnboundedInt, Real, VarChar and VarBit still work but report the warning PSL_DEPRECATED_SCALAR_NAME. Write the convenience type that gives the same type instead, such as String(storage: varchar, length: 12) for VarChar(12); the contract does not change. The same TypeScript helpers, such as type.VarChar(...), are deprecated too. The column helpers int8Column and numericColumn are renamed int8BigIntColumn and numericStringColumn, and the old names are removed. Extension authors: postgresScalarAuthoringTypes, postgresNativeAuthoringTypes and postgresScalarAndNativeTypeConstructors are replaced by postgresScalarTypes and postgresExplicitTypes. See psl-renamed-postgres-scalar-types, ts-renamed-postgres-scalar-helpers and ts-renamed-postgres-column-helpers in the app recipe, and the same ids plus ts-renamed-postgres-type-groupings in the extension recipe. (#30942)

    Before:

    model Account {
      id     Int          @id
      visits SmallInt
      price  Numeric(10, 2)
      code   VarChar(12)
    }

    After:

    model Account {
      id     Int                                  @id
      visits Int(storage: int2)
      price  Decimal(precision: 10, scale: 2)
      code   String(storage: varchar, length: 12)
    }
  • **temporal-polyfill is a peer dependency...

Read more
Assets 2
Loading

Uh oh!

There was an error while loading. Please reload this page.

All reactions

v8.0.0-rc.22

v8.0.0-rc.22 Pre-release
Pre-release
@github-actions github-actions released this 30 Oct 13:48
v8.0.0-rc.22
4f70a33
This commit was created on GitHub.com and signed with GitHub’s verified signature.
GPG key ID: B5690EEEBB952194
Verified
Learn about vigilant mode.

v8.0.0-rc.22

On PostgreSQL, DateTime, Date, Time and the new Duration are convenience types whose defaults read a JavaScript Date or a string, with no Temporal polyfill. Value objects move into the storage plane, so changing one is a migration, and Postgres checks value object and discriminator columns. MongoDB's query builder, raw lane, ORM and runtime take an execution context, as SQL's do, and a MongoDB client creates its driver from the execution stack. A contract can declare the Postgres extensions it needs, so db sign adopts a database that uses pgvector, PostGIS, ParadeDB or the new citext pack. The Prisma 7 reader now reads every Postgres @db.* type Prisma 7 accepts. MySQL gets ORM and SQL builder reads. Prisma ORM refuses to run from two installed copies, and connect() on a client is safe to call again.

The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them. The app recipe opens with the order to do the steps in. After upgrading, run prisma contract emit once, so a contract that an extension such as Supabase stamps with its version matches the installed package (contract-artifacts-restamp in the app recipe).

Breaking changes

  • On PostgreSQL, DateTime, Date and Time are convenience types with new defaults. Each is named for what a field means and becomes one explicit type, chosen by its optional as, storage and precision arguments. At its default, DateTime is a timestamptz(3) column read as a JavaScript Date, Date reads a string such as "2024-02-29", Time reads a string such as "09:30:00", and the new Duration reads an ISO 8601 duration such as "P1M". Until now the three names read Temporal values. To keep a field as it is, rename DateTime to TimestamptzTemporal, Date to DateTemporal and Time to TimeTemporal; in TypeScript, call type.TimestamptzTemporal(...), type.DateTemporal() and type.TimeTemporal(...). temporal.CreatedAt and temporal.UpdatedAt are now built on the new DateTime, and their String and JsDate variants are removed. A contract read by prisma7Schema(...) now reads a Prisma 7 DateTime field as a Date, as Prisma 7 did, so run prisma db sign after re-emitting it. On PostgreSQL and MySQL, a column read as a Date, such as MySQL's DateTime, refuses a default with digits below a millisecond. The rest of this change is PostgreSQL only: SQLite, MySQL and MongoDB keep their date and time types. contract infer and contract print now write the convenience types: a timestamptz(3) column is DateTime, a timestamptz column DateTime(precision: 6), a timestamp(3) column DateTime(storage: timestamp), date is Date, time is Time and interval is Duration. So a contract you infer again reads a timestamptz field as a Date, where it read an ISO 8601 string, and drops its microseconds; add as: string, as in DateTime(as: string, precision: 6), to keep the string. See psl-date-time-types-are-convenience-types, ts-date-time-helpers-are-convenience-types, temporal-type-aliases-on-datetime, prisma7-schema-reads-dates and date-default-below-a-millisecond in the app recipe. (#30847)

    Before:

    model Event {
      id      Int      @id
      at      DateTime
      day     Date
      opensAt Time(0)
    }

    After, to keep each field and its contract:

    model Event {
      id      Int                 @id
      at      TimestamptzTemporal
      day     DateTemporal
      opensAt TimeTemporal(0)
    }
  • Value objects are storage entities, and Postgres checks their columns. A contract keeps its value objects at storage.namespaces.<ns>.entries.valueObject, and a field names one by its storage coordinate, so changing a value object changes the storage hash and is a migration. On SQL, a discriminator column names a value set of its variants' values, and a discriminator field is typed by those values, such as 'bug' | 'feature'. On a managed Postgres table, the contract derives a check for each value object column and each discriminator column; the next migration plan adds them, and db migrate fails on a row that does not fit. A contract.json that keeps valueObjects in the domain plane is refused with CONTRACT.VALIDATION_FAILED. The app recipe ships a script that rewrites every contract, snapshot and migration that names one; run it, then sign each database before you re-emit. Extension authors: ValueObjectTypesFromDomain is now ValueObjectTypesFromStorage, FieldTypesFromDomain takes the storage namespaces as a sixth argument, ValueObjectFieldType is renamed ValueObjectReference, and a Postgres codec descriptor declares jsonType. See value-objects-in-storage, value-object-types-from-storage, postgres-value-object-checks and discriminator-typed-by-variant-values in the app recipe, and mongo-result-shapes-read-storage, postgres-check-expression-types-move, field-types-read-storage-value-objects, value-object-reference-type and postgres-codec-json-type in the extension recipe. (#30869)

  • MongoDB's query builder, raw lane, ORM and runtime take an execution context. mongoQuery, mongoRaw and mongoOrm take { context } instead of { contract }, as sql({ context }) and the SQL ORM do. A context comes from mongoStatic({ contract }) or mongo({ contract }), which validate the contract once. mongoOrm takes { context, runtime } and no longer takes executor, enums or mutationDefaults. createMongoRuntime takes { context, adapter, driver }. buildMongoEnums, MongoEnumAccessors, MongoOrmEnums and ORM.MUTATION_DEFAULTS_MISSING are removed. Extension authors: createSqlExecutionStack(...) returns SqlExecutionStackWithDriver, whose driver is always set, only when given a driver. See mongo-query-takes-context, mongo-orm-takes-context and mongo-runtime-takes-adapter in the app recipe, and the same ids plus sql-stack-with-driver-requires-driver in the extension recipe. (#30865)

    Before:

    import { mongoQuery } from '@prisma/orm-mongo/query-builder';
    const query = mongoQuery({ contract });
    const raw = mongoRaw({ contract });

    After:

    import mongoStatic from '@prisma/orm-mongo/static';
    const { query, raw } = mongoStatic({ contract });
  • A MongoDB driver is created from its descriptor. createMongoDriver and MongoDriverImpl are no longer exported. Put the runtime driver descriptor, the default export of @prisma/orm-mongo/driver/runtime, on the execution stack, create the driver from the stack, and connect it. An application that calls mongo({ contract, url }) sees no difference. Extension authors: MongoDriver gains connect(binding), and code that only sends commands takes the new MongoQueryable. See mongo-driver-from-runtime-descriptor in the app recipe, and mongo-driver-from-runtime-descriptor and mongo-driver-connect in the extension recipe. (#30906)

    Before:

    import { createMongoDriver } from '@prisma/orm-mongo/driver';
    const driver = await createMongoDriver(url, dbName);

    After:

    import mongoRuntimeDriver from '@prisma/orm-mongo/driver/runtime';
    const stack = createMongoExecutionStack({ target, adapter, driver: mongoRuntimeDriver });
    const driver = stack.driver.create();
    await driver.connect({ kind: 'url', url, dbName });
  • The pgvector, PostGIS and ParadeDB packs declare their Postgres extension, and contract emit writes each pack's files. Each pack's contract now declares its extension, and its head no longer requires an install invariant. prisma contract emit writes each composed pack's head ref, contract snapshot and migrations under migrations/<space-id>/, as migration plan already did: commit them, then run prisma db migrate on each database to move the pack's marker. db sign now refuses a contract space whose head requires an invariant its marker does not record, with MIGRATION.SIGN_INVARIANTS_MISSING. Extension authors: declare a pack's extension in its contract instead of installing it with installExtension(...) and an invariant. See contract-emit-pins-pack-files and packs-declare-their-postgres-extension in the app recipe, and declare-postgres-extension-in-pack-contract in the extension recipe. (#30902)

  • **Prisma ORM refuses to ru...

Read more
Assets 2
Loading

Uh oh!

There was an error while loading. Please reload this page.

ussfranck and AlexGalhardo reacted with thumbs up emoji djibrillitalien-bot reacted with laugh emoji dev-garcia reacted with hooray emoji marr-cloud and lsolano2707 reacted with rocket emoji
All reactions
  • 👍 2 reactions
  • 😄 1 reaction
  • 🎉 1 reaction
  • 🚀 2 reactions
6 people reacted

v8.0.0-rc.21

v8.0.0-rc.21 Pre-release
Pre-release
@wmadden-electric wmadden-electric released this 30 Oct 12:58
v8.0.0-rc.21
fad17c1
This commit was created on GitHub.com and signed with GitHub’s verified signature.
GPG key ID: B5690EEEBB952194
Verified
Learn about vigilant mode.

v8.0.0-rc.21

migration plan and db update can rename or delete an enum value on Postgres and SQLite, and update the rows that hold it. MongoDB contracts written in TypeScript, PSL or Prisma 6 now build through one builder and follow the same rules. A closed client's members report the failure through the promise or result they return. MySQL gets its first public packages, which can plan and apply migrations. PostgreSQL's date and time types now name the kind of value they read, and the text date and time types read ISO 8601 on every server. Field presets are removed: each is written with a type constructor or type alias that stores the same contract. When a database is at a contract outside the migration graph, db migrate explains why and gives recoveries that work, none of which resets the database. The upgrade guides for rc.18 and rc.19 now work on real projects.

The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them. After upgrading, run prisma contract emit once, so a contract that an extension such as Supabase stamps with its version matches the installed package (contract-artifacts-restamp in the app recipe).

Breaking changes

  • A client member that returns a promise or a result rejects instead of throwing at the call. On postgres(), sqlite(), a supabase() role-bound client and a transaction, query, execute, prepare, transaction, ORM calls and a prepared statement's query and execute now report a closed client, a failed connection or an ended transaction through what they return. The promise rejects, or the result rejects when it is awaited or read. Error codes and messages do not change. So .catch(handle) and Promise.allSettled now see the error, but a try/catch around a call without await no longer catches it: add await. db.runtime() still throws at the call, and so does a mistake in the call itself. Extension authors: lazyActivitySource and delegatingActivitySource now reject from startActivity and planContentHash when their source throws. See client-members-reject-instead-of-throwing in the app recipe, and client-members-reject-instead-of-throwing and lazy-activity-source-rejects in the extension recipe. (#30840)

    Before:

    try {
      db.transaction(work); // threw at the call after close(), so the catch ran
    } catch (error) {
      handle(error);
    }

    After:

    try {
      await db.transaction(work); // the returned promise rejects; await it to catch the error
    } catch (error) {
      handle(error);
    }
  • Removing an enum value is now asked about, like removing a model or a field. On Postgres and SQLite, when the contract removes an enum member or changes the value it stores, migration plan and db update ask what the change means and rewrite the rows that hold the old value. A script that runs without a terminal fails with CLI.CONSENT_REQUIRED until you answer with --rename Status.ARCHIVED:Status.RETIRED or --delete Status.ARCHIVED. Before, Postgres failed at apply when a row held the old value, and SQLite planned nothing. Native Postgres enums (pg.enum(...)) are unchanged. Extension authors: renames and migration subjects gain an enumValue kind, and three optional fields let a target say how to keep the data a removed value would lose. See removed-enum-value-questions in the app recipe, and enum-value-rename-statement and rows-holding-value-and-keep-data-edit in the extension recipe. (#30849)

  • MongoDB contract type names and mongoContract options change. mongoContract(schemaPath, options) now requires options.target, the MongoDB target pack; a config written with defineConfig from @prisma/orm-mongo/config needs no change. The type of the object you pass to defineContract is renamed from ContractDefinition to ContractInput, as in SQL. MongoModelDefinition is removed: write ContractModel<MongoModelStorage>. Extension authors: loadContractSource no longer takes onWarning and returns { contract, warnings }, and a failed emit carries sourceWarnings. See mongo-contract-target-option, mongo-contract-input and mongo-model-definition-removed in the app recipe, and the same ids plus contract-source-warnings in the extension recipe. (#30846)

    Before:

    import type { ContractDefinition } from '@prisma/orm-mongo/contract-builder';
    
    const contract = mongoContract('./prisma/schema.prisma');

    After:

    import type { ContractInput } from '@prisma/orm-mongo/contract-builder';
    import mongoTargetPack from '@prisma/orm-mongo/target/pack';
    
    const contract = mongoContract('./prisma/schema.prisma', { target: mongoTargetPack });
  • Every MongoDB contract source applies the same rules, so some contracts are now refused. defineContract now refuses what PSL refused: a discriminator that is optional, a list or not text; a variant value the discriminator cannot hold; a listed variant no model declares; and a variant stored in another collection than its base. Every source refuses an index MongoDB would refuse, a value object field typed by an undeclared enum, and a variant field that overwrites or restates a base field differently. PSL also refuses a duplicate index in one collection. Some contracts are newly accepted, such as an optional field that a type alias or generator fills. A Prisma 6 schema with two identical indexes in one collection now gives one index, so its storage hash changes: run prisma contract emit, then prisma db sign. See mongo-ts-polymorphism-rules, mongo-index-shape-rules, mongo-value-object-enum-check, mongo-newly-accepted and mongo-prisma6-merged-indexes in the app recipe and the extension recipe. (#30846)

  • close() closes the client's runtime even when you passed in the pool, and a SQLite file that cannot be opened is a connection error. When you pass your own pg.Pool or pg.Client to postgres() or supabase(), close() now also closes the client's runtime, so a runtime captured with db.runtime() before close() refuses new work. Your pool or client stays open; end it yourself. A SQLite database file that cannot be opened, such as a missing directory or a file that is not a database, is now a SqlConnectionError instead of a SqlQueryError. See close-ends-the-client-not-your-pool and sqlite-open-failure-is-a-connection-error in the app recipe. (#30833)

  • Each target names where its contract markers live. verifyContractSpaces takes a required markerLocation. Extension authors: SqlControlAdapter, MongoControlAdapter and ControlFamilyInstance gain a required markerLocation, SqlControlAdapter gains an optional holdMarkerLock, and SqlPlanTargetDetails.schema is optional, with SQLite operations no longer carrying schema: 'main'. See verify-contract-spaces-marker-location in the app recipe, and verify-contract-spaces-marker-location, control-adapter-marker-location, control-adapter-hold-marker-lock and plan-target-details-schema-optional in the extension recipe. (#30841)

  • PostgreSQL date and time types that read more than one kind of value are renamed. In PSL, Timestamptz becomes TimestamptzTemporal, Timestamp becomes TimestampTemporal and Interval becomes IntervalParts; the old names are errors. In TypeScript, type.Timestamptz(...), type.Timestamp(...) and type.Interval(...) are renamed the same way, and intervalColumn(...) becomes intervalPartsColumn(...). Each new name reads the same value with the same codec, so the contract and its hashes do not change. @db.Timestamp and @db.Timestamptz in a Prisma 7 schema are not affected. An IntervalParts(p) column is now typed as PgInterval, the { months, days, micros } object it reads, instead of a string. The string types Timestamp, Timestamptz, Time and Interval are no longer exported from @prisma/orm-postgres/target/codec-types, so remove them from imports, including those in migration snapshots' contract.d.ts. Temporal fields are now typed with the...

Read more
Assets 2
Loading

Uh oh!

There was an error while loading. Please reload this page.

marr-cloud reacted with rocket emoji
All reactions
  • 🚀 1 reaction
1 person reacted

v8.0.0-rc.20

v8.0.0-rc.20 Pre-release
Pre-release
@github-actions github-actions released this 22 Oct 18:09
v8.0.0-rc.20
10b7bed
This commit was created on GitHub.com and signed with GitHub’s verified signature.
GPG key ID: B5690EEEBB952194
Verified
Learn about vigilant mode.

v8.0.0-rc.20

ORM commands run on @prisma/cli-engine 0.9.0, so a piped command prints tab-separated data lines and JSON needs --json. A type alias in PSL can set @default, @onCreate and @onUpdate, and the contract stores each column's real type instead of the alias name. Postgres migrations can rename, move and remove namespaces, and can change a relation's actions or a primary key. A failed migration check now names the object it expected.

The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them.

Breaking changes

  • A piped ORM command prints data lines, not JSON, unless you pass --json. The ORM toolchain now requires @prisma/cli-engine 0.9.0, up from 0.7.0, the engine the prisma CLI ships since 8.0.0-rc.25. This engine picks the output format from flags only. When stdout is a pipe, a file, $(…), a CI log or an agent, a command used to print JSON. It now prints the human output on stderr and plain data lines on stdout. Add --json to every script, CI step or program that reads JSON from prisma contract …, prisma db …, prisma migration … or prisma orm init. A project that depends on @prisma/cli-engine itself moves to 0.9.0. Data lines are a stable interface: fields are tab-separated in a documented order, and new fields are only added at the end. For example, migration list prints space, name, from, to and operation count, one line per migration. db init, db update, db verify, db schema and migration ref delete print nothing on stdout; read their exit code, or pass --json. See piped-output-needs-json and engine-pin-moves-to-0-9-0 in the app recipe and the extension recipe. (#30835)

    Before:

    prisma migration status | jq '.envelope.result'

    After:

    prisma migration status --json | jq '.envelope.result'
    prisma migration list | cut -f2   # or read the data lines: one migration name per line
  • The contract stores a column's type, not the type alias it was written with. A column typed by a types {} alias now stores the alias's codec and parameters itself, and the contract no longer has the alias in storage.types. Every contract that uses an alias gets a new storage hash. A stored contract whose columns still name an alias in typeRef no longer loads. Run the app recipe's script, which rewrites stored contracts and migration snapshots, then run prisma contract emit, then prisma db sign against every database. The database does not change. In the TypeScript builder, the types key is removed and field.namedType(...) takes only an enum: write an alias as a constant field.column(type.VarChar(64)). The Supabase extension's contract changes hash for the same reason, so sign a Supabase database too. See stored-contracts-expand-type-aliases, ts-types-key-removed and supabase-contract-expanded in the app recipe. Extension authors run the same script from the package root and re-emit the bundled contract. A contract space that registers a database type writes it under databaseTypes instead of types. ColumnTypeDescriptor.typeRef, StorageColumn.typeRef and ExecutionContext.types are removed. See stored-contracts-expand-type-aliases, types-key-is-database-types and column-type-ref-removed in the extension recipe. (#30819)

    Before:

    const types = { Embedding1536: type.pgvector.Vector(1536) } as const;
    const Post = model('Post', {
      fields: { embedding: field.namedType(types.Embedding1536).optional() },
    });
    return { types, models: { Post } };

    After:

    const Embedding1536 = field.column(type.pgvector.Vector(1536));
    const Post = model('Post', {
      fields: { embedding: Embedding1536.optional() },
    });
    return { models: { Post } };
  • A SQL builder insert must include every column the database requires. In db.sql.<namespace>.<table>.insert(rows), leaving out a column that is not nullable and has no default is now a type error that names the column. Such an insert used to compile and then fail in the database. A value typed T | undefined for such a column is an error too; check it before the insert. In ORM create and upsert, a field that is not nullable, has no default and generates a value only on update, such as one with @onUpdate(...) and no @onCreate(...), is now required. See sql-builder-insert-required-columns and orm-create-on-update-only-field in the app recipe, and sql-builder-insert-required-columns in the extension recipe. (#30830)

    Before:

    // User.displayName is `String` with no default; this compiled, then failed in the database
    db.sql.public.user.insert([{ email: '[email protected]', kind: 'admin' }]);

    After:

    db.sql.public.user.insert([{ email: '[email protected]', kind: 'admin', displayName: 'Admin' }]);
  • MongoDB enum members and discriminator values are written in the syntax of their data type. A MongoDB PSL enum member is read as a value of its codec's data type, as on SQL, so a quoted member is text. A quoted member on a type that does not take text is refused with PSL_VALUE_TYPE_INCOMPATIBLE: write numbers, NaN and the infinities unquoted, and dates and binary values with their tags. An Int32 or Int64 member written with a fraction, such as 1.0, is refused; write 1. A @@discriminator field must be required and hold one value, on SQL and MongoDB alike. When an enum types a discriminator, each @@base value must be one of its members. A value the receiving type refuses now reports PSL_VALUE_REFUSED. A Decimal128 value with leading zeros in contract.json, such as "007.5", is refused when the contract loads; re-emit the contract. See mongo-quoted-enum-members, mongo-integer-enum-members-with-a-fraction, discriminator-optional-or-list, discriminator-base-value-not-a-member, psl-value-refused-code and decimal128-spelling in the app recipe. Extension authors: AuthoringEntityContext takes dataTypes in place of dataTypeLookup, the readWrittenValueForCodec hook is removed, and an enum block needs writtenValues. See entity-context-data-types and enum-block-members-written-values in the extension recipe. (#30832)

    Before:

    enum Ratio {
      @@type("mongo/double@1")
      Unknown = "NaN"
      Half    = 0.5
    }

    After:

    enum Ratio {
      @@type("mongo/double@1")
      Unknown = NaN
      Half    = 0.5
    }
  • Supabase runs every role operation through forRole(binding), and its pg option takes a pool only. SupabaseRuntime no longer has queryWithRole, executeWithRole, preparedQueryWithRole or preparedExecuteWithRole. Call runtime.forRole(binding) once and use its query, execute and connection members. The pg option of supabase() takes a pg.Pool; a pg.Client fails with SUPABASE.CONFIG_INVALID. db.close() does not end a pool you pass in. RoleBoundDb, ServiceRoleDb and the transaction context gain enums and nativeEnums, so test doubles of them must add those members. After db.close(), a query on any role-bound client rejects with DRIVER.NOT_CONNECTED "Runtime is closed", and close() waits for open role transactions. See supabase-for-role-replaces-with-role-methods, supabase-role-types-gain-members, supabase-pg-takes-a-pool and supabase-close-waits-for-work in the app recipe. Extension authors: SqlRuntimeBase.acquireRawConnection() now follows the close rule of connection(), and a runtime that shares its driver is built with ownsDriver: false. See supabase-for-role-replaces-with-role-methods, supabase-role-types-gain-members, supabase-pg-takes-a-pool and raw-connection-obeys-close in the extension recipe. (#30828)

    Before:

    const rows = await runtime.queryWithRole(plan, { role: 'anon' }).toArray();
    const db = await supabase({ contract, pg: new Client({ connectionString }), jwtSecret });

    After:

    const rows = await runtime.forRole({ role: 'anon' }).query(plan).toArray();
    const db = await supabase({ contract, pg: new Pool({ connectionString }), jwtSecret });
  • A removed Postgres namespace is asked about, and accessWidening is renamed accessChanges. When the cont...

Read more
Assets 2
Loading

Uh oh!

There was an error while loading. Please reload this page.

Heliodex reacted with hooray emoji Heliodex reacted with heart emoji
All reactions
  • 🎉 1 reaction
  • ❤️ 1 reaction
1 person reacted

v8.0.0-rc.19

v8.0.0-rc.19 Pre-release
Pre-release
@github-actions github-actions released this 21 Oct 16:42
v8.0.0-rc.19
1e98c69
This commit was created on GitHub.com and signed with GitHub’s verified signature.
GPG key ID: B5690EEEBB952194
Verified
Learn about vigilant mode.

v8.0.0-rc.19

@default now means a database default, and values the client generates are written @onCreate(...) and @onUpdate(...). Every default is stored in one form owned by its column's data type, so date, time and bytes defaults are written with tags. Clients take the contract as a typed value, can render any plan as SQL without a database, and run each ORM call as one activity that middleware and the cache can see. A column of any database type can be declared with Raw(sql`...`), and Prisma 7 schemas with Unsupported(...) fields now load.

The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them.

Breaking changes

  • Client generators are written @onCreate(...) and @onUpdate(...), and @default means a database default. @default(uuid()), @default(cuid(2)), @default(ulid()) and @default(nanoid()) are refused with PSL_GENERATOR_IN_DEFAULT. Write @onCreate(uuid()) and so on instead. The app recipe ships a script that rewrites your Prisma 8 schema files. The contract does not change, so there is nothing to re-emit, sign or migrate. @default(now()) and @default(autoincrement()) are unchanged. contract print now writes generated values as @onCreate(...) and @onUpdate(...). See client-functions-move-from-default-to-on-create and contract-print-writes-generator-attributes in the app recipe. (#30780)

    Before:

    model Post {
      id   String @id @default(uuid(7))
      slug String @default(nanoid(12))
    }

    After:

    model Post {
      id   String @id @onCreate(uuid(7))
      slug String @onCreate(nanoid(12))
    }
  • A client takes the contract as a typed value. The contractJson option and the type argument on the client call are removed from postgres(), postgresServerless(), sqlite(), supabase(), mongo(), postgresStatic(), sqliteStatic(), mongoStatic() and mongoQuery(). Turn the emitted JSON into a value once with contractFromJson<Contract>(contractJson) from the facade's /static entry, and pass { contract }. The app recipe ships a script that moves your source files; move test files by hand. The *OptionsWithContract and *OptionsWithContractJson types are replaced by PostgresOptions<Contract> and the matching types of the other facades. See client-takes-contract-value in the app recipe. (#30748)

    Before:

    export const db = postgres<Contract>({ contractJson, url: process.env['DATABASE_URL']! });

    After:

    import { contractFromJson } from '@prisma/orm-postgres/static';
    
    export const contract = contractFromJson<Contract>(contractJson);
    export const db = postgres({ contract, url: process.env['DATABASE_URL']! });
  • Date, time, interval and bytes defaults are written with tags, and each default has one stored form. contract emit refuses a quoted date, time, interval or bytes default and names the tag to write. A bytea default takes hexadecimal, not base64. A PostgreSQL contract that stores a default in another form than its column's type gives, such as "1.5" on numeric(10,2), is refused by the CLI: run prisma contract emit, then prisma db sign. On SQLite, datetime and JSON columns get their own data types; run the app recipe's script before the next CLI command, because the CLI refuses the old contract. Reading a value that its column's type cannot hold now throws RUNTIME.DECODE_FAILED. A SQLite DateTime text with no UTC offset is read as UTC. Run prisma db sign against every database after the upgrade. See date-time-interval-and-bytes-defaults-use-tags, sqlite-contracts-name-datetime-and-json-data-types, postgres-defaults-stored-in-another-spelling, prisma7-datetime-default-finer-than-column, stored-values-a-column-type-does-not-hold, sqlite-datetime-without-offset-read-as-utc, text-array-min-max-return-arrays and sign-databases-after-data-type-values in the app recipe. (#30750)

    Before:

    at      DateTime @default("2024-01-01T00:00:00Z")
    day     Date     @default("2024-03-15")
    payload Bytes    @default("AQID")

    After:

    at      DateTime @default(timestamptz`2024-01-01T00:00:00Z`)
    day     Date     @default(date`2024-03-15`)
    payload Bytes    @default(bytea`\x010203`)
  • @noCheck is removed, and a list that allows null elements is written T?[]. A stored contract with a noCheck key no longer loads. First run the app recipe's script, which rewrites stored contracts and migration snapshots, then run prisma db sign against every database. Then replace T[] @noCheck(elementNotNull) with T?[] and delete @noCheck(membership); in TypeScript, use .many({ elementsNullable: true }). A contract read from a Prisma 7 schema now types list elements as T | null, and the Supabase extension's four text[] columns allow null elements; both change the storage hash, so sign your databases. See stored-contracts-drop-nocheck, psl-nocheck-removed, ts-nocheck-method-removed, prisma7-lists-allow-null-elements and supabase-contract-lists-allow-null-elements in the app recipe. Extension authors run the same script from the extension package root, then re-emit the bundled contract; see stored-contracts-drop-nocheck, psl-nocheck-removed and ts-nocheck-method-removed in the extension recipe. (#30741)

    Before:

    tags String[] @noCheck(elementNotNull)

    After:

    tags String?[]
  • Type-constructor arguments are values. A quoted number, such as VarChar("255") or Timestamp("3"), is refused with PSL_VALUE_TYPE_INCOMPATIBLE; write the number without quotes. On Postgres a whole number written with a fraction, such as VarChar(255.0), is refused too, and so is a number the type cannot hold. The same applies to a field preset's precision, such as temporal.timestamp("3"). See type-constructor-arguments-are-values in the app recipe. (#30801)

    Before:

    name VarChar("255")

    After:

    name VarChar(255)
  • Enum members are values of their data type. A PSL enum member is read as a value of the enum codec's data type, as a @default is. A quoted member is refused on a codec whose type is not text, such as pg/numeric@1 or pg/int8@1; write numbers unquoted and dates and times with their tag. Enums typed by pg/jsonb@1, pg/timetz@1, pg/enum@1, arktype/json@1, pg/vector@1 or pg/geometry@1 are refused; use a text enum, or a native enum instead of pg/enum@1. Members of a pg/numeric@1, pg/interval@1 or mongo/decimal128@1 enum compare as values, so 0.5 and 0.50 are duplicates. Columns of more enum codecs are now typed as the union of their members; re-emit the contract. See psl-enum-members-read-by-the-cast-rule, more-codecs-refused-for-enums, enum-members-compare-by-their-data-type and enum-columns-typed-by-member-literals in the app recipe. (#30790)

    Before:

    enum Ratio {
      @@type("pg/numeric@1")
      Half  = "0.5"
    }

    After:

    enum Ratio {
      @@type("pg/numeric@1")
      Half  = 0.5
    }
  • Generator arguments are checked, and a generator must fit its column. An argument uuid, cuid or nanoid does not take, such as uuid(5), is now refused, in Prisma 8 PSL with PSL_INVALID_GENERATOR_ARGUMENT and in a Prisma 7 schema with PSL.PRISMA7_UNKNOWN_DEFAULT; it used to be read as something else. A number with a fraction, such as nanoid(8.0), is refused too. A generator on a Postgres column too short for what it writes, such as VarChar(5) @onCreate(uuid()), is refused when the contract is built instead of failing at the first insert. A SQL @@discriminator that is not text has a new message. See prisma7-default-function-arguments-checked, generator-function-argument-diagnostics, generator-function-argument-with-fraction, generator-fits-column and discriminator-must-be-text in the app recipe. (#30792)

  • Re-emit contract.d.ts, and expect more precise types from defineContract. prisma contract emit writes field and column types as generics applied to the contract, so a SQL contract.d.ts emitted by an earlier release no longer compiles; re-emit it. A contract built with defineContract now gets the same ORM types as an emitted one: typed include rows, aggregates, query operations, parameterized types such as Varchar<50>, ...

Read more
Assets 2
Loading

Uh oh!

There was an error while loading. Please reload this page.

All reactions

7.10.1

7.10.1 Latest
Latest
@wmadden-electric wmadden-electric released this 19 Oct 08:13
7.10.1
97ea359
This commit was created on GitHub.com and signed with GitHub’s verified signature.
GPG key ID: B5690EEEBB952194
Verified
Learn about vigilant mode.

Prisma ORM 7.10.1 is a patch release. It fixes a bug where a nested interactive transaction could make later, unrelated transactions run inside the wrong transaction. It also updates dependencies that had security advisories.

Fixes

Prisma Client: nested $transaction no longer changes the options object you pass in

If you passed the same options object to a nested tx.$transaction(...) and later to a top-level prisma.$transaction(...), the nested call wrote the outer transaction's id into that object. Every later top-level transaction that used the object was then treated as nested inside that old transaction:

  • if the old transaction had committed, the new one failed with P2028;
  • if the old transaction was still open, the new one silently ran as a savepoint inside another request's transaction.
const TX_OPTIONS = { timeout: 30_000, maxWait: 10_000 }

await prisma.$transaction(async (tx) => {
  await tx.$transaction(async (inner) => { /* ... */ }, TX_OPTIONS)
})

// Before 7.10.1, this call could fail with P2028 or join another transaction.
await prisma.$transaction(async (tx) => { /* ... */ }, TX_OPTIONS)

Prisma Client no longer modifies the options object. (#30368, thanks @lazerg)

Prisma Migrate: refuse a shadow database that is the main database

Prisma Migrate now refuses to run with error P3025 when the shadow database URL points at the same database as the main database URL. Before, prisma migrate diff --from-migrations with that setup dropped the real schema, rebuilt it from the migrations, and reported an empty diff. (prisma/prisma-engines#5851)

MariaDB adapter: updated to mariadb 3.5.4

@prisma/adapter-mariadb now depends on mariadb 3.5.4, which fixes several security advisories in 3.5.3. The adapter no longer rewrites IPv6 hosts in connection strings, because mariadb 3.5.4 accepts them as written. IPv6 connection strings keep working without changes. (#30668)

Dependency updates

Dependencies with security advisories were updated: mysql2, fast-uri, deepmerge-ts, mariadb and source-map-js. (#30314, #30189, #30668)

Contributors

  • @lazerg
lazerg
Assets 2
Loading

Uh oh!

There was an error while loading. Please reload this page.

dev-garcia, marr-cloud, NetLancer, xerzo, Apogee2024, spaghetttti, and jsomville reacted with thumbs up emoji
All reactions
  • 👍 7 reactions
7 people reacted

v8.0.0-rc.18

v8.0.0-rc.18 Pre-release
Pre-release
@github-actions github-actions released this 14 Oct 16:52
v8.0.0-rc.18
34f77c2
This commit was created on GitHub.com and signed with GitHub’s verified signature.
GPG key ID: B5690EEEBB952194
Verified
Learn about vigilant mode.

v8.0.0-rc.18

Raw SQL in a contract is now always a sql literal or value, a full-text index can span several weighted fields and is searched from the ORM by naming it, and middleware observes each statement and transaction as an activity. PSL gains mixins, the SQL ORM gains whereUnique and firstOrThrow, and MongoDB migrations carry out --rename.

The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them.

Breaking changes

  • Raw SQL in a contract is a sql literal. In PSL, @@index(where:), @@index(expression:), @@fullTextIndex(where:), @@check(expression:) and a policy's using and withCheck take a sql literal, and a quoted string is refused with PSL_VALUE_TYPE_INCOMPATIBLE. The app recipe ships a script that rewrites every .prisma file. In a TypeScript contract the same fields take a sql value, and a string does not compile; migration files keep strings. A text with shared indentation, blank lines at its ends or CRLF line breaks is stored as its canonical text, which changes the storage hash once. See raw-sql-is-a-sql-literal, builder-raw-sql-is-a-sql-value, psl-storage-hash-may-change-once and ts-storage-hash-may-change-once in the app recipe. (#30550, #30558)

    Before:

    @@index([email], where: "(archived_at IS NULL)", name: "users_email_active")

    After:

    @@index([email], where: sql`(archived_at IS NULL)`, name: "users_email_active")
  • Middleware hooks are activity hooks. The runtime runs every statement and transaction as an activity. beforeQuery and beforeExecute become beforeEncode; interceptQuery and interceptExecute become intercept.onQuery and intercept.onExecute; afterQuery and afterExecute become activityEnded; afterTransaction becomes activityFinalized. RuntimeMiddlewareContext is now ActivityContext, and ctx.planExecutionId is replaced by activity.id. activityEnded also fires for a statement the caller stopped reading and for one that failed before it ran, so a metrics middleware checks result.outcome. See middleware-hooks-are-activity-hooks and every-started-statement-is-ended-and-finalized in the app recipe, and statement-runners-replace-middleware-runners in the extension recipe. (#30703)

    Before:

    async afterQuery(plan, result, ctx) {
      if (result.latencyMs > 250) ctx.log.warn({ sql: plan.sql, rowCount: result.rowCount });
    },

    After:

    async beforeEncode(plan, ctx) {
      ctx.state(statementSql)['sql'] = plan.sql;
    },
    async activityEnded(activity, result, ctx) {
      if (result.kind !== 'statement' || result.latencyMs <= 250) return;
      ctx.log.warn({
        sql: ctx.state(statementSql)['sql'],
        ...(result.returns === 'rows' ? { rowCount: result.rowCount } : {}),
      });
    },
  • A full-text index is stored as data. @@fullTextIndex and fullTextIndex store an index of type fullText with its columns, weight groups and language, not a SQL expression. The schema source does not change, but the index's generated name and the storage hash do: re-emit the contract and run prisma migration plan, which renames the index in place. Avoid db update for a large index, because it drops and rebuilds it. See re-emit-contracts-with-a-full-text-index in the app recipe and render-full-text-index-document-takes-a-definition in the extension recipe. (#30562)

    Before:

    { "expression": "to_tsvector('english', \"title\")", "name": "post_title_search_724b05e5", "type": "gin" }

    After:

    { "columns": ["title"], "name": "post_title_search_e0dd1131", "options": { "language": "english", "weightGroups": [["title"]] }, "type": "fullText" }
  • A base model lists its variants by discriminator value. In contract.json and contract.d.ts, a polymorphic base's variants is keyed by discriminator value, and each entry names the variant model and its namespace. A contract in the previous form is refused with CONTRACT.VALIDATION_FAILED. Re-emit the contract and rewrite variants in the snapshots under migrations/snapshots/; the storage hash does not change. See re-emit-contracts-with-polymorphic-models and read-variants-by-discriminator-value in the app recipe. (#30696)

    Before:

    "variants": { "Bug": { "value": "bug" }, "Feature": { "value": "feature" } }

    After:

    "variants": { "bug": { "model": "Bug", "namespace": "public" }, "feature": { "model": "Feature", "namespace": "public" } }
  • The SQL ORM client accepts only field names. Every name passed to the SQL ORM client must be a field of the model, or of the variant the collection is narrowed to; any other name, including a column name that differs from its field name, throws ORM.FIELD_UNKNOWN. Rows no longer carry a column no field maps. See orm-refuses-names-that-are-not-fields in the app recipe. (#30667)

    Before:

    await db.orm.Post.where({ user_id: 1 }).all();

    After:

    await db.orm.Post.where({ userId: 1 }).all();
  • The query fragment types are renamed, and a fragment is made from the model's root collection. Fragment is now QueryFragment and FieldFragment is now DeclaredFieldsFragment. collection.fragment(body) throws ORM.ARGUMENT_INVALID on a collection with chained calls, which it used to ignore; chain on the collection directly, or move the calls into the fragment's body. See fragment-types-are-renamed and fragment-is-made-from-the-root-collection in the app recipe. (#30652, #30673)

    Before:

    const recentSummary = db.orm.public.Post.orderBy((p) => p.id.desc()).fragment((posts) =>
      posts.select('id', 'title'),
    );

    After:

    const recentSummary = db.orm.public.Post.fragment((posts) =>
      posts.orderBy((p) => p.id.desc()).select('id', 'title'),
    );
  • migration plan asks before a lossy type change, and writes placeholders only when asked. On Postgres and SQLite, a type change that can lose values fails with CLI.CONSENT_REQUIRED where nobody can answer, until --convert <Model.field> (write the conversion yourself) or --delete <Model.field> (accept the database's cast) answers it. A new required field gets a temporary value in existing rows; pass --backfill <Model.field> to fill them yourself. In a hand-written Postgres migration.ts, alterColumnType takes type and using directly instead of an options object. See lossy-type-changes-ask, placeholders-only-when-asked and postgres-alter-column-type-plain-options in the app recipe. (#30695)

  • Removing a field from a MongoDB model asks first. The plan now removes the field from every document that holds it, and migration plan and db update ask about it; add --delete <Model>.<field>, or --rename if the field was renamed, to scripts and CI. A MongoDB plan's preview writes db.getCollection("users") where it wrote db.users, and node migration.ts uses the config that owns the migration. See mongo-removed-field-asks, mongo-preview-get-collection and migration-ts-finds-its-config in the app recipe. (#30691)

  • A Prisma 7 schema's @ignore and @@ignore objects stay in the contract. prisma7Schema() keeps their columns, tables, keys and indexes in storage, so a schema that uses them gets a new storage hash, and a schema that loaded only because they were dropped can be refused. Emit the contract, then sign each database, or plan a migration first if Prisma 8 already manages your migrations. See prisma7-ignore-keeps-storage in the app recipe. (#30672)

  • Top-level PSL declarations belong to the default namespace. A top-level declaration and one inside namespace public { … } on Postgres share one set of names, so the same name declared both ways is PSL_DUPLICATE_DECLARATION, and a top-level declarati...

Read more
Assets 2
Loading

Uh oh!

There was an error while loading. Please reload this page.

lord007tn reacted with rocket emoji
All reactions
  • 🚀 1 reaction
1 person reacted

v8.0.0-rc.17

v8.0.0-rc.17 Pre-release
Pre-release
@github-actions github-actions released this 08 Oct 13:01
v8.0.0-rc.17
b44e43b
This commit was created on GitHub.com and signed with GitHub’s verified signature.
GPG key ID: B5690EEEBB952194
Verified
Learn about vigilant mode.

v8.0.0-rc.17

Migrations no longer lose data without being told to: prisma migration plan and prisma db update ask about each model or field a plan would drop, answered with --delete or with the new --rename, which keeps the rows. The ORM client gains row locks, apply and scope are renamed to with and fragment, and db.enums holds each member as a query returns it.

The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them.

Breaking changes

  • --confirm no longer consents to data loss. prisma migration plan and prisma db update ask one question for each model, field or table a plan would lose data from, before they write or apply anything. Answer with --delete <subject> to let the data go, or --rename <old>:<new> to keep it. db update also asks before an operation that widens who can read or write a model's rows, such as dropping a row-level-security policy, answered with --allow <Model>. Where nobody can answer, the command fails with CLI.CONSENT_REQUIRED, whose nextActions give the flags. Replace each --confirm in scripts and CI. See migration-plan-refuses-data-loss and db-update-confirm-no-longer-consents in the app recipe. (#30648)

    Before:

    prisma db update --confirm appdb

    After:

    prisma db update --delete Legacy --rename User.name:User.fullName
  • destructive now means data loss. Dropping an index, a constraint, a check, a default or a native enum type, Postgres setNotNull, and type changes that keep every value are now widening operations, and no longer ask for consent. A migration.ts no database has applied yet writes a different ops.json and migrationHash when run again. See non-data-drops-are-widening and destructive-means-data-loss in the app recipe. (#30638, #30648)

  • The control API answers questions through a callback. executeMigrationPlanCommand, executeDbUpdate and the control client's dbUpdate require an answerQuestions callback, and lose consent. acceptDataLoss: true no longer covers access widening; pass acceptAccessWidening: true too. The errors MIGRATION.DESTRUCTIVE_CHANGES and MIGRATION.CONSENT_PLAN_MISMATCH are no longer raised. See control-api-answer-questions and consent-errors-removed in the app recipe. (#30648)

  • The collection method apply is now with, and scope is now fragment. A reusable function from a collection to a collection is a query fragment, made with db.orm.fragment(...) or collection.fragment(...) and run with collection.with(...). The types Scope, FieldScope and ScopeFacts are now Fragment, FieldFragment and FragmentFacts. This applies to the SQL ORM client only. See collection-apply-is-now-with and orm-scope-is-now-fragment in the app recipe. (#30635, #30647)

    Before:

    const postSummary = db.orm.public.Post.scope((posts) => posts.select('id', 'title').include('user'));
    const posts = await db.orm.public.Post.apply(notDeleted).apply(postSummary).all();

    After:

    const postSummary = db.orm.public.Post.fragment((posts) => posts.select('id', 'title').include('user'));
    const posts = await db.orm.public.Post.with(notDeleted).with(postSummary).all();
  • db.enums holds each member as a query returns it. A member whose codec stores another form in contract.json changes: a bigint member is a bigint, a date member a Date or a Temporal value, a byte member a Uint8Array, and a NaN or infinite float member a number. has(), nameOf() and ordinalOf() now find a value read from the database. Remove conversions your code applied to these members, and re-emit the contract. Code that builds the MongoDB ORM itself with mongoOrm() or createMongoCollection() must pass the enum accessors. See db-enums-members-hold-read-values and mongo-orm-takes-enum-accessors in the app recipe. (#30628)

    Before:

    // Level is @@type("pg/int8@1") with Low = "1"
    db.enums.public.Level.members.Low; // "1"

    After:

    db.enums.public.Level.members.Low; // 1n
  • Enum members and values must be written as the database stores them. A Postgres numeric or inet enum member written in a form Postgres prints differently, such as "01.5" or "10.0.0.1/32", is refused, and the message says what to write. Enums can no longer use codecs whose values never equal a member: pg/timestamp-string@1, pg/timestamptz-string@1, pg/bytea@1, pg/tsquery@1, pg/json@1, and on MongoDB mongo/json@1 and mongo/bson@1, plus PSL enums on BSON types the collection validator cannot list. See ts-enum-members-written-as-stored, psl-enum-members-written-as-stored, enum-codecs-refused, enum-json-codec-refused and psl-enum-bson-types-refused in the app recipe. (#30628)

    Before:

    enum Ratio {
      @@type("pg/numeric@1")
      Half = "01.5"
    }

    After:

    enum Ratio {
      @@type("pg/numeric@1")
      Half = "1.5"
    }
  • Contracts from a Prisma 7 schema state the constraint names Prisma 7 chose. prisma7Schema(...) now writes the name of each primary key and foreign key whose Prisma 7 name differs from the one Prisma 8 derives. A contract with such a constraint gets a new storage hash: re-emit, then sign the database, plan a migration or run db update, depending on who manages it. See prisma7-schema-states-constraint-names in the app recipe. (#30606)

  • The CHECK constraint on an enum list column compares in the column's own type. The constraint's expression and name change, so re-emit and apply a migration that replaces it. See enum-list-check-compares-in-column-type in the app recipe. (#30628)

  • Each foreign key in contract.json names the index that backs it. A new index field on each foreign key says whether an index, the primary key or a unique constraint serves its lookups, so every SQL contract with a foreign key gets a new storage hash. Re-emit, then follow migration plan's advice: write an empty migration with prisma migration new --from <hash>, or run prisma db sign on a database you manage with db init or db update. Two related changes can alter your database: a partial index, or an index with a non-default type or options, no longer counts as a relation's backing index, so migration plan creates one beside it; and an unnamed @@index on exactly the columns of a unique constraint or the primary key is left out of the contract, so migration plan drops it. To keep the database as it is, write index: "<name>" on the relation, or give the plain index a name. See foreign-keys-name-their-backing-index, partial-or-typed-index-no-longer-backs-a-foreign-key and unnamed-index-on-unique-columns-left-out in the app recipe. (#30561)

    author User @relation(fields: [authorId], references: [id], index: "post_author_live")
  • MongoDB PSL writes an index's sort direction as sort(field, direction). The old field(sort: Desc) form is no longer accepted in @@index, @@unique and @@textIndex. The database index does not change. See mongo-index-sort-function in the app recipe. (#30636)

    Before:

    @@index([createdAt(sort: Desc), authorId])

    After:

    @@index([sort(createdAt, Desc), authorId])
  • Extension authors: migration planners take statements and report what they lose. A planner's plan(...) takes required statements and origin, and its success result carries appliedStatements, dataLoss and accessWidening. ControlFamilyInstance requires storageNameOf. plannerSuccess takes appliedStatements and the subjects lists. See the planner entries in the extension recipe. (#30638, [#30648](https://github.com/prisma/orm/pull...

Read more
Assets 2
Loading

Uh oh!

There was an error while loading. Please reload this page.

All reactions
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.