yggio-prisma
v0.0.20
Published
A Prisma Client extension whose query engine is the yggio expression plan: what a database can answer is pushed into the query, the rest runs natively over the rows it returns
Readme
yggio-prisma
A Prisma Client extension whose query engine is the yggio plan. A plan's text
is read by the core's parser; what the database can answer exactly is pushed
into findMany arguments, and the residual runs natively over the rows they
return, landed once under the model's typed struct field - a decimal at its
column's scale, a UUID, an instant at its unit. The documentation page is
Prisma.
| | |
| --- | --- |
| Install | npm install yggio-prisma yggio - yggio is a peer at the exact version, @prisma/client (>=5) an optional peer: nothing of it is imported, the extension is a plain object |
| Prisma | $extends from Prisma 5; $use in Prisma 5 and 6; tested against 7.10.1 |
| Doors | yggioExtension(options) for prisma.$extends: model.plan(text, params?) on every model, yggioWhere(text, params?) under any operation's where; yggioMiddleware(options), the marker filter for $use |
| By hand | compilePlan(plan, model, { yggio, params?, provider?, insensitive?, field? }) -> { args, residual, complete, pushed, columns }; modelField(model, yggio, columns?, provider?); landRows(model, rows, yggio, columns?); runPlan(landedRows, residual, field, yggio); filterRows(rows, filter, model, columns, yggio) |
| Arrow over MySQL | modelArrowReader(model, rows, yggio, { field?, batchSize? }) - a model's rows as Arrow batches cast onto a Field by the core; writeModel(delegate, source, model, yggio, { mode?, batchSize?, key?, client? }) - an Arrow source through createMany or upsert in batches; mysqlDatatype, mysqlColumn, mysqlModel, fieldModel, prismaSchema - the MySQL type map, both ways (MySQL) |
| Refusals | PlanRefused, an Error naming what it refuses |
Install
npm install yggio-prisma yggio @prisma/clientyggio is a peer at the exact version and is never imported: every door
takes it as an argument, so the application loads the addon once and hands
it over. @prisma/client is an optional peer, needed only for a generated
client; a MySQL application adds its driver adapter
(@prisma/adapter-mariadb). The package carries dist/ (ESM and CommonJS,
declarations) and its sources; npm pack builds it first (prepack).
The extension
import * as yggio from 'yggio'
import { yggioExtension, yggioWhere } from 'yggio-prisma'
const db = prisma.$extends(yggioExtension({ yggio, models: [TRADE], provider: 'postgresql' }))
// findMany with what pushes, then the residual natively.
const totals = await db.trade.plan(
'select venue, sum(quantity) as total from trade where price > :floor group by venue order by total desc',
{ floor: 10 },
)
// The marker filter: compiled where the operation runs, its keys beside any Prisma filter of the call.
const buys = await db.trade.findMany({ where: { ...yggioWhere("side = 'BUY' and venue like 'X%'"), tradable: true } })| Option | Is |
| --- | --- |
| yggio | the yggio module as the caller loaded it |
| models | a list of DMMF models, or Prisma.dmmf itself ({ datamodel: { models, enums } }), whose enums give each enum column its values; a model is found by the delegate's $name, case aside |
| provider | the datasource provider word - sqlite, postgresql, cockroachdb, mongodb, mysql, sqlserver; text equality pushes exactly under the first four alone; another word is refused |
| insensitive | true pushes ilike as mode: 'insensitive', only for a database that takes that mode |
| marker | the where key yggioWhere writes, $yggio by default; pass the same name as yggioWhere's third argument |
Prisma 7's own Prisma.dmmf keeps no isRequired, isList or nativeType,
and no enum's members: hand each model with them, as the schema states them,
and each enum column its values (Object.values(Side)). A model without
isRequired lands every column nullable, and no null test and no order push;
an enum column without values pushes no equality and no in.
plan answers the rows as Prisma answered them where nothing remains or the
residual is a filter alone, else one object per native output row keyed by the
plan's output columns. The pushed where sits beside the caller's at the top
level, a key both state joined by AND, so a unique key stays where
findUnique, update, delete and upsert read it. A marker filter Prisma
answers whole runs on any operation; a residual filter runs over findMany
rows alone.
The middleware
prisma.$use(yggioMiddleware({ yggio, models: Prisma.dmmf }))
const buys = await prisma.trade.findMany({ where: yggioWhere("side = 'BUY' and venue like 'X%'") })The same marker filter over { model, action, args } and next; middleware
adds no model method, so it has no plan.
Pushdown
| Plan | Prisma | Condition |
| --- | --- | --- |
| col = v, <>, <, <=, >, >= (either side) | { col: { equals \| not \| lt \| lte \| gt \| gte: v } } | a literal or parameter, not null; equality on every type but Json, an enum's where it states its values; ranges on Int, BigInt, Float, Decimal, DateTime alone |
| col in (...), not col in (...) | { in }, { notIn } | every item a non-null literal or parameter |
| col between a and b | { gte: a, lte: b } | a range type, each bound as its comparison pushes |
| text col = v, col in (...) | equals, in, checked again | under mysql, sqlserver or no provider, whose default collations fold case and accents (MySQL's pads trailing spaces); <>, not and not in over text stay whole. Exact under sqlite, postgresql, cockroachdb, mongodb |
| col = v, col in (...) no row can equal | { in: [] }, the item dropped | an enum value that is no member, a fraction on Int or BigInt; the equality checked again, <> left to the residual |
| col > 1.5, >=, <, <= on Int, BigInt | { gte: 2 }, { lte: 1 } | the whole bound inside the fraction |
| a DateTime bound between two milliseconds | the millisecond outside it - floored for >, >=, raised for <, <=; = the range around it - checked again | a native type of more than three fractional digits; <> and in stay |
| col is null, col is not null | { equals: null }, { not: null } | the model states the column optional |
| col like 'X%', '%X', '%X%', 'X' | startsWith, endsWith, contains, equals | a String column that is not @db.Uuid, no _, no escape, % at the ends alone; pushed to prune and checked again natively, since a database's LIKE may fold case |
| col ilike ... | the same, mode: 'insensitive' | insensitive: true; checked again |
| a or b | OR: [...] | every branch pushes |
| not a | NOT, notIn | a pushes exactly |
| conjuncts on one column | one object | their keys differ and none states mode; else AND: [...] |
| order by col [desc] [nulls first] | orderBy: [{ col: 'asc' \| 'desc' }], { col: { sort, nulls } } on an optional column, nulls: 'last' unless stated | every key a bare column of a range type or Boolean whose nullability the model states, no alias of that name, no grouping; one key that does not push keeps the whole order |
| limit, offset | take, skip | the filter pushed whole with nothing to check again, the order pushed or absent, no group by, having or aggregate |
| select a, b | select: { a: true, b: true, ...what the residual reads } | no star; bare columns with no alias push whole, computed projections and aliases stay; a plan reading no column selects the id |
| group by, having, aggregates, exclude | - | the residual, behind the pushed where |
| from | - | absent or the model's name |
A text column pushes equality, in and like alone, a UUID column equality
and in: a database collation orders text by locale, where the native orders
by code units. Every literal or parameter a pushed filter compares is
converted by the column, in the core: a Decimal at its scale as text, a
DateTime a Date from a Date, an ISO text or an epoch count, a Float a
float, a BigInt a bigint, a UUID canonical.
The residual
The residual is the plan less what pushed, its parameters bound and every
literal or parameter its where compares typed by the datatype of the term it
meets (price > 2.5 on a decimal128 is a decimal comparison). A residual
that is a filter alone keeps the rows Prisma answered, untouched; any other
answers the native output. A plan Prisma answers whole answers its rows as
Prisma typed them - a Decimal a Prisma.Decimal.
Types
| Prisma type | yggio datatype | Back from a native run |
| --- | --- | --- |
| String | utf8; uuid under @db.Uuid | string, a UUID lower case and hyphenated |
| Int | int32; uint32 under @db.UnsignedInt, @db.UnsignedMediumInt, @db.Oid | number |
| BigInt | int64; uint64 under @db.UnsignedBigInt | bigint |
| Float | float64 | number |
| Decimal | decimal(p,s) under @db.Decimal(p,s), the core's narrowest width for the digits, else decimal128(38,18) | string, the canonical text ('12.5') |
| Boolean | boolean | boolean |
| DateTime | datetime64(ms, UTC); datetime64(us, UTC) past three fractional digits | Date, floored to the millisecond |
| Json | utf8, the JSON text | string, the JSON text |
| Bytes | binary | Buffer |
| an enum | utf8 | string |
| a list | serie<T> | an array |
A Decimal no native type states the precision and scale of lands as
decimal128(38,18): a value past 18 fractional digits or 20 integral ones
fails the residual run (decimal has more fractional digits than the field
allows, decimal coefficient exceeds 38 digits).
An aggregate answers by its own datatype: count a bigint, a sum over
integers or decimals a decimal's text, avg a number. A column is nullable
unless the model states it required; relations are left out.
Refusals
- A section that is not a read:
create, a write, a join. fromnaming anything but the model, a location, or a plan.- A parameter the call does not give; a literal a column cannot hold
(
id = 'abc',u = -1on an unsigned column) - a fraction meeting an integer column is none: it bounds the range or matches nothing. - A Prisma type with no yggio datatype; an unknown model; a
providerthat is no datasource provider. yggioWheretext holding anything but awhereclause, or no text.- A residual marker filter under any operation but
findMany, or besidetake,skip,cursorordistinct, which would cut rows before it runs.
MySQL
The rows of any Field of the addon live in MySQL under one type map,
src/mysql.ts, read in both directions. Every instant is UTC: a DATETIME is the wall clock
Prisma writes and reads in UTC, a TIMESTAMP is UTC by MySQL's definition.
| MySQL column | Lands as | A column of a Field | Written as |
| --- | --- | --- | --- |
| TINYINT(1), BIT(1) | boolean | boolean | Boolean |
| TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT, each UNSIGNED | int8 .. uint64 | every integer width | Int @db.TinyInt .. BigInt @db.UnsignedBigInt |
| FLOAT, DOUBLE | float32, float64 | float32, float64 | Float @db.Float, Float |
| DECIMAL(p,s), the default DECIMAL(65,30) | decimal(p,s), the core's narrowest width for the digits | a decimal at its precision and scale (decimal 38 and 18) to 65 digits and scale 30; bigdecimal refused | Decimal @db.Decimal(p,s) |
| DATETIME(n), TIMESTAMP(n) | datetime64(s) at 0 digits, ms to 3, us to 6, UTC | datetime64(unit, zone) | DateTime @db.DateTime(0 \| 3 \| 6); a nanosecond column at six, sent as a Date floored to the millisecond - no cast cuts it |
| DATE, TIME(n) | date32, time(unit) (time32/time64, the core's width) | date32, date64, time32, time64 | DateTime @db.Date, @db.Time(n) |
| VARCHAR(n), CHAR(n), TEXT | utf8 | text; a code (mic, ccy, lei, ...) and timezone | String @db.Text, the key and an indexed column @db.VarChar(191); @db.VarChar(n), @db.Char(n); a code @db.VarChar(64) |
| BINARY(16); BINARY(n), VARBINARY(n), BLOB | uuid; fixed_binary(n), sized_binary(n), binary | uuid; fixed_binary, sized_binary, binary | Bytes @db.Binary(16); @db.Binary(n), @db.VarBinary(n), Bytes |
| JSON | utf8, the text; the map, struct or serie the generated model states | map, struct, serie | Json |
| ENUM | the kind a generated model states; else the kind its name spells (Side is side) where every member is the kind's, as the core reads them; else utf8 | side, state, marketdatakind, marketdatatype, timeinforce | none generated: a kind is Int (an INT of its code, as yggio-mysql lays it out), its datatype the kind |
Under every other provider, or none, a MySQL native spelling is read as the
Prisma type's own default (@db.TinyInt is int32, @db.Date an instant).
fieldModel(field, { key?, indexes? }) is the model of a field as the
addon states it, a kind an Int of its code as yggio-mysql lays it out, and
prismaSchema(models) renders the schema of models - never edited by hand.
Each column is read off its DataType - family, precision, scale, unit,
widths - never off its text. Each model is keyed by the one column its
field's SORT:by names (rowKey), else by the key the caller states:
the key a merge upserts by. Each model is indexed by what its field
declares (rowIndexes): one @@index over the columns its PARTITION:by
marks - an identity entry, never a transform such as months(timestamp) -
then the keys its SORT:by names, none where that is the key itself; and
every row holding crossuuid gains (crossuuid), the element's one
secondary key, which InnoDB reads as (crossuuid, uuid).
MySQL indexes no TEXT, so an indexed text column is VARCHAR(191), as a
key is; an index over a JSON or BLOB column is refused by name.
mysql/schema.prisma is the exchange's schema - one trade model over a
plain field (tests/support.ts's TRADE_FIELD), which the mysql suite
holds equal to prismaSchema([fieldModel(...)]) - and
mysql/prisma.config.ts reads the server from MYSQL_URL.
// The rows a model answered, as Arrow under its field: landed under the model, cast by the core.
const field = yggio.Field.from('trade: struct<uuid: uuid not null, code: utf8 not null, price: decimal128(18,4), timestamp: datetime64(us, UTC) not null> not null')
const model = fieldModel(field, { key: 'uuid' })
const reader = modelArrowReader(model, await prisma.trade.findMany(), yggio, { field })
// An Arrow source into the model: 500 rows a createMany, or one upsert per row by the key under merge.
await writeModel(prisma.trade, trades.intoArrowReader(), model, yggio, { mode: 'merge', client: prisma })A refusal names the model, the rows of the batch and, in the core's words,
the column and the row (trade rows 0..500: ...price...; a stream's
trade rows from 500: ...). Through Prisma an instant crosses as a Date,
to the millisecond, both ways - the Date floors a nanosecond source, which
the generated model lands as it is; writeModel sends skipDuplicates:
false, so skippedRows is 0 against Prisma and counts only a delegate
answering a short count; a DATE or TIME as a Date too, landed as
the day or the clock. overwrite empties the model at its first createMany,
once that batch is cast and spelled, in one $transaction with it where a
client is given. scripts/check_mysql_interop.py at the repository root
runs the exchange against a real MySQL in both directions (the Node half
mysql/roundtrip.test.ts, npm run mysql:roundtrip), refused by name where
none is reachable. Against MYSQL_URL it runs prisma db push --force-reset,
which drops every table of that database, so it refuses a database not named
yggio or ending in _yggio_interop; the container it starts takes a plain
db push. db push supports MySQL 8.4 only. Apache Doris is refused by
name: create its tables with yggio's DDL (the native route's
connection.writeSerie), because Prisma's push needs MySQL system variables
Doris lacks.
Tests
npm test generates the integration client (prisma generate into
tests/generated/), runs every suite against the addon beside this package -
the integration one over an embedded database file through Prisma's driver adapter - then
tsc --noEmit. npm run mysql:generate generates the MySQL client the exchange drives (pretest
generates it too, so the round trip type-checks with no server), and
npm run mysql:roundtrip is the exchange's Node half, which MYSQL_URL
must name a server for.
