Repository navigation
Releases
v1.3.1
Patch Changes
-
22bc6e1:
maskLiteralsAndCommentskeeps a line break that is inside a quoted string or identifier, as it already did inside a comment. It replaced one with a space, so line numbers counted in the masked text were off after a multi-line literal. -
7e80320: On ClickHouse, a string literal matched against a pattern that is an expression is now written
materialize('…'):lit(path).startsWith($.Prefix),lit(text).contains($.Word)andlit(text).like($.Pattern)failed on ClickHouse 26.2 with "Function 'like' doesn't support search with non-constant needles in constant haystack". The same server does not match an empty string against'%%', which an empty literal ran into:lit("").contains($.Word),startsWithandendsWithare now writtenWord = '', which is what they mean. A column on the left, or a pattern that is a string, compiles as before.The SQL of such an expression changes, so a table whose DDL holds one (a
MATERIALIZEDcolumn, an index or sorting key written this way) shows that definition as changed in the next migration. A constant built by a function, such aslower(lit("A")).startsWith($.Name), is not rewritten and still fails on 26.2. -
27de404:
splitTerminalClausesnow finds aSETTINGSorFORMATclause that followsALLor a*wildcard.SELECT a, count() FROM t GROUP BY ALL FORMAT JSON,ALTER TABLE t DROP PARTITION ALL SETTINGS mutations_sync = 2andSELECT * FORMAT JSONcame back whole, clause included, becauseALLand*were always read as wanting an operand after them. They are now read by what precedes them:SELECT ALL x,UNION ALL SELECTanda * bstill take an operand.
v1.3.0
Minor Changes
- df5537b:
MySQL.asBoolean(condition): a condition as a boolean value, to select it orseta column from it, as Postgres'sasBoolean. It is written((c) IS TRUE), so a condition MySQL evaluates to NULL reads asfalserather than failing the boolean codec. MySQL and MariaDB only; another dialect refuses it in the type and at compile.
v1.2.0
Minor Changes
- f8fd28d: MySQL and MariaDB
ORDER BYandLIMITon a single-table UPDATE or DELETE:deleteFrom(table).where(...).orderBy(["id", "asc"]).limit(20000)writesDELETE FROM t WHERE ... ORDER BY ... LIMIT 20000, andupdate(table)takes the same two clauses, for chunked deletes that keep each transaction small (loop untilDb.runWritereports feweraffectedRowsthan the limit).orderBytakes[column, direction]tuples of the table's columns or a callback of[expression, direction]pairs;limit(n)writesnas a literal, as a query's limit, and a negative or fractional literal is a type error, such a value at run time anInvalidArgumentsfailure. Both add the newWriteLimitClauseto the write's params, so compiling it for Postgres, SQLite, D1 or ClickHouse is a type error, and the compile refuses it as aQueryBuilderDefect; besideupdate(...).from(...), a multi-table write MySQL refuses them on, they are a defect too. Tenant scope is unchanged: the WHERE decides it, and a subquery in the ORDER BY counts as a read. New:Dialect.clauses.writeOrderLimit, and theWriteLimitClauseandWriteOrderBySpectypes.
v1.1.0
Minor Changes
-
05fbd7a: MySQL and MariaDB generated columns:
MySQL.column(type, { generated: { as, stored? } })declares aGENERATED ALWAYS AS (<as>) STORED | VIRTUALcolumn.asis SQL, or a DSL callback that may read the row's columns. The column is computed, as a ClickHouseMATERIALIZEDone is: an insert row, an update SET oronDuplicateKeyUpdatethat writes it is a type error and refused at runtime,excludedAllskips it, andtableSchemas(table).insert/.updateleave it out; selects read it. It works onexternal: truetables, where it only marks the column computed, so an insert into a table another tool owns no longer sends a column MySQL refuses.On an owned table the DDL writes
`col` <type> GENERATED ALWAYS AS (<expr>) STORED|VIRTUALwith noNOT NULL(MariaDB refuses it there) and no default, so declareMySQL.nullable(...)unless the expression cannot be NULL. Definition problems: adefault,defaultExpr,defaultFnoronUpdatebeside it (also a type error), an emptyas, a generated primary key or tenant column, and, for a callback only, one that reads itself, a generated column declared after it, or a nullable column into a non-nullable type. A stringasis not checked.effect-orm generatecreates and adds such columns (a new generated oneAFTERthe column before it), andMODIFYs a changed expression or type, and a base column made STORED (which needsconfirm_data_loss) or a STORED one made base (which keeps its values). A column made VIRTUAL, or a VIRTUAL one made STORED or base, is dropped and added back in oneALTER TABLE, in its place and with its indexes around it; to or from base needsconfirm_data_loss, and a VIRTUAL column made base under a UNIQUE key is refused as unsupported. The ops are ordered around what generated columns read: base columns are added first and generated ones dropped first, and the generated columns reading a column that is renamed or dropped and added back (including ones renamed or replaced themselves) are dropped before it, last declared first, and added back after in declaration order.MySQL.ComputedColumnsOfandMySQL.GeneratedColumnare new types, andMysqlSchemaTabletakes the computed columns as a new last type parameter.MysqlColumnEntityhas an optionalgenerated: { expr, stored, reads? }(reads: the columns a callback read), absent on other columns, so existing snapshots keep their ids.MysqlMigrationOphas areplace_columnop, andadd_columnan optionalafter.
v1.0.0
Major Changes
- 6708ad8: 1.0.0. The package follows semantic versioning from here: a breaking change to a documented export is a major release. Every export of every entry is named in the API reference (
docs/reference.md), andbun run testnow fails when one is not; before, only the four dialect entries were checked. The Alpha notice is gone from the README and the docs site.package.jsondeclaresengines.node >= 20.19.0, the oldest Node the build was run on.
Minor Changes
-
2d2fe62: ClickHouse names are quoted when they need to be. The ClickHouse dialect wrote every identifier bare, so a select key such as
"p-95"or"by service"was a syntax error, a key namednullordered by the literal, and a key built from input was SQL:{ "x FROM system.users --": $.Name }compiled toevents.Name AS x FROM system.users --. A plain name (letters, digits,_, dots for a Nested column) is still bare, so existing SQL does not change; any other is written in backticks with`and\escaped. That covers select keys, GROUP BY and ORDER BY keys, column names of an external table, source and join aliases, and CTE names. As a select key, an alias or a CTE name, the words ClickHouse reads as something else there are quoted too (all,cube,distinct,false,inf,infinity,nan,not,null,recursive,rollup,select,top,true); a column of such a name is still read bare, so a table's DDL does not change, andgeneratedoes not recreate a materialized view whose SELECT differs from its snapshot only by those backticks. A select key with a dot is quoted too, so selecting a Nested column by name (.select("Events.Name")) works: it used to writeAS Events.Name, a syntax error. A ClickHouse table name is still written as given, since an external table's name may be a table function or a subquery;Dialect.rawTableNamessays so.A name that spells the reserved param marker
__PARAM_is escaped on ClickHouse and refused withInvalidLiteralon the other dialects. On Postgres it used to be rewritten into the placeholder's text (AS "$1").contains("")is written with one wildcard (LIKE '%') instead of two. It means the same, and ClickHouse 26.2 turns aLEFT JOINfiltered byLIKE '%%'on the joined table into an inner join, losing the unmatched rows. -
2fcf943: MySQL and MariaDB upserts:
insertInto(table).values(rows).onDuplicateKeyUpdate({ set })writesINSERT ... ON DUPLICATE KEY UPDATE.settakes the formsonConflictDoUpdate's does: a record of values, params or expressions, a callback($, excluded) => ({ ... })of the existing and proposed rows,excluded(columns)orexcludedAll(except?). MySQL reads the proposed row through a row alias,VALUES (...) AS excluded(MySQL 8.0.19+); MariaDB readsVALUES(col). (For MySQL before 8.0.19, spreadmysqlDialectwithclauses.onDuplicateKey: "valuesFunction".) It fires on any unique key and takes no target orwhere, soexcludedAllleaves out the table's declared primary key and itstenantColumn, and a bareexcludedAll()on a table with no declared key is aQueryBuilderDefectasking forexcept. On a table with atenantColumnthe insert is"cross-tenant". A proposed-row column the SET reads but no row writes joins the insert withDEFAULTcells, as Postgres'sexcludedholds the default.valuesrows only; withselect, on a table namedexcludedon MySQL, or on another dialect, compiling is aQueryBuilderDefect.onConflictDoUpdate/onConflictDoNothingon MySQL now nameonDuplicateKeyUpdate/onDuplicateKeyDoNothingin their errors, and the reverse on Postgres and SQLite. New:Dialect.clauses.onDuplicateKey, and theOnDuplicateKeyUpdatetype.onDuplicateKeyDoNothing()skips a row that conflicts on any unique key, on MySQL and MariaDB. It writesON DUPLICATE KEY UPDATE col = table.colon the first written column, notINSERT IGNORE:IGNOREalso turns truncation, NOT NULL and foreign key errors into warnings and stores or drops the row, while these still fail. A skipped row counts as 1 affected row with mysql2's defaultCLIENT_FOUND_ROWS, 0 without it. It keeps the inserted rows' tenant scope, since the statement writes no existing row; it is still an UPDATE of the matched row, so aBEFORE UPDATEtrigger runs, and thenaffectedRowsis 2 andinsertIdthe matched row's id. -
f69f39c:
Db.runWriteruns an insert, update or delete and returns aWriteResult:affectedRows, and for an insertinsertId, the key of the row it wrote. It is how MySQL, which has noRETURNING(and MariaDB, whoseRETURNINGthe builder does not write), reads anAUTO_INCREMENTkey; it reads@effect/sql-mysql2,@effect/sql-pg, PGlite, node:sqlite and D1 results, and refuses a ClickHouse write before sending it.layerTesttakes aTestWriteReply({ affectedRows, insertId? }) to answer one.MySQL and MariaDB constraint failures are now refined like the other dialects':
refineConstraintsreads the server's error number, so a foreign key (1451, 1452), NOT NULL (1048, 1364) or CHECK (3819, MariaDB 4025) failure becomesForeignKeyViolation,NotNullViolationorCheckViolation, with the key, constraint, table or column the message names. Before, only a duplicate key was refined, and without names. A MySQLDatabaseErrornow also carries the server'ssqlStateand its error number aserrorCode. Names are read from the server's whole message and anchored where the server writes them, so a duplicated value quoted in the message cannot name the key. A Node error name (EPIPE,EBUSY) is no longer read as a SQLSTATE.
Patch Changes
-
6955a28:
effect-orm --versionandch-bench --versionprint the package version.effect-ormnames a command it does not have (unknown command "frobnicate") before it looks for a config file; it used to report thateffect-orm.config.tscould not be imported. -
e972080:
/clickhouse-httpno longer returns the rows of a query that failed. ClickHouse answers200with the first block of rows, so a timeout, a memory limit or any exception after that arrives inside the body. On servers before 25.11 (25.8 LTS among them) the client read the rows sent so far as the whole result:sql.unsafe(...)succeeded with 900,000 of 2,000,000 rows, and.streamended normally. On 25.11 and later it failed, but as "the response is not valid JSON" or "the stream failed", with the server's code lost, so a timeout was not aStatementTimeoutError.Queries now send
http_write_exception_in_output_format=1, and the client reads the exception wherever the server puts it: anexceptionkey besidedata, a JSONEachRow exception line, the__exception__block (tagged or not), or the text after the rows of a compressed reply. The statement fails with the server's reason and message; a stream fails after the rows before the exception. A statement whose200carriesX-ClickHouse-Exception-Code(a command with progress headers on) fails too; it used to succeed. A body that cannot be read to the end is aConnectionError, not anUnknownError. Needs ClickHouse 23.9 or later. Areadonly = 1user, who cannot change settings, sets both built-in settings insettingsto the server's current values (http_write_exception_in_output_formatis1before 25.11 and0from it).Bound values:
nullbinds as NULL (it was the textnull), an array holding a null isArray(Nullable(T))(its nulls were the type's default), and abigintbinds as the narrowest ofInt64,UInt64,Int128,UInt256andInt256that holds it (2^64 - 1 arrived as -1). An array's element type is read from all of its elements, nested arrays included. -
b35749b: MariaDB: an integer literal in a
unionAllbranch keeps its value beside a DECIMAL in another branch. MariaDB 11.4 sizes an integer literal one digit short when a union branch is a derived table, which is howmariadbDialectwrites branches, and cut it down to fit:lit(97)in one branch and aDECIMAL(5,4)in the other came back9.9999. A selected integer literal is now writtenCAST(n AS SIGNED) + 0on MariaDB, which has the digits. MySQL is unaffected and unchanged.
v0.11.0
Minor Changes
-
528e59d: SQLite query features, typed end to end, so hand-written SQLite statements can move to the builder:
- Window functions on SQLite and Postgres:
over(expr, windowSpec(...))withlead,lag(offset and fallback),rowNumber,rank,denseRank,firstValue,lastValue, and a newrangeBetweenframe (also on ClickHouse).leadandlagdecode NULL past the partition's edge. - Table-valued sources:
SQLite.jsonEachandSQLite.jsonTreeinfrom,innerJoin/leftJoin/crossJoin(also as a callback over the earlier sources' columns) andupdate(...).from, with typedkey/valuecolumns and the JSON bound as one parameter.SQLite.jsonRows(rows, columns)is a typed query over a JS array, forinsertInto(...).select(...)andupdate(...).from(...). A join's ON callback now also reads the earlier joins under their aliases. update(table).from(source, alias):UPDATE ... FROMon SQLite and Postgres, refused in the type elsewhere.scalar(query): a one-column query as a value, for a correlated SET or a select.selectNoFrom(fn): a SELECT of values with no FROM, for a conditionalINSERT ... SELECT.- SQLite functions:
iif,caseWhen,ifnull,nullif,cast,concat,trim/ltrim/rtrim,substr,replace,instr,abs,round,greatest/least,jsonExtract,json_,jsonSet,jsonGroupArray,jsonGroupObject,julianday,date,datetime,strftime,unixepoch;coalescetakes a plain fallback. - FTS5:
SQLite.fts5TableandSQLite.fts5.match/snippet/highlight/bm25. SQLite.runSync(storage, query, params?)runs a query or write synchronously on Durable Object storage (ctx.storage.sql).Database.batch([...])(andDb.batch) runs a list of statements atomically: one D1 batch on D1, a transaction elsewhere, returning each statement's rows.- A
wherethat proves a FROM column not NULL now narrows it for a laterselect, as it did for joined columns. - A comparison accepts a nullable expression on its right (
o.rowid.eq(h.head)withh.headan aggregate).
Fix: in an UPDATE or DELETE, a target column used inside a subquery (a correlated
subqueryExpr,scalarorexists) is now qualified with the table name. It was written bare, so it bound to the subquery's own column of the same name and the condition always held.firstValueandlastValuedecode as nullable (a frame can be empty).runSynctakes an optional fourth argument,RunSyncOptions. - Window functions on SQLite and Postgres:
Patch Changes
- eccc9c2: The package homepage and README now link to the new docs site at https://effect-orm.maple.dev.
- 7b01f01: Tested against Effect 4.1.2. The peer range stays
effect ^4.0.6, and the docs' pinned install examples now use 4.1.2.
v0.10.0
Minor Changes
-
28ee8b8: A new
/mysqlentry compiles the shared query builder for MySQL 8.0.17+ (mysqlDialect) and MariaDB 10.6+ (mariadbDialect), for@effect/sql-mysql2(#53). It writes backtick identifiers and positional?bindings (up to 65,535 per statement), escapes\in string literals, and writesOFFSETwithoutLIMITwith MySQL's largest row count. It has MySQL column types and codecs for what mysql2 sends (text,longtext,varchar(n), the integer types,bigintwithin 2^53,double,decimal(p, s)as exact text,boolean,datetimeasDATETIME(3)in UTC,date,blob,varbinary(n),json(schema)) and MySQL functions (count,countDistinct,countIf,sum,avg,min,max,lower,upper,length,coalesce), refused for another dialect in the type.forUpdateandforSharecompile for MySQL, with MariaDB'sLOCK IN SHARE MODE; the type refusesforNoKeyUpdateandforKeySharethere. RETURNING, ON CONFLICT, DISTINCT ON and ILIKE are refused at compile time. A transaction's isolation level and access mode go in the statement that starts it (SET TRANSACTION …; START TRANSACTION READ ONLY).contains,startsWithandendsWithcompare bytes, so they stay case-sensitive under a case-insensitive collation. A JSON column is compared withCAST(? AS JSON)on MySQL. A selected small integer or numeric param is cast, as MySQL 8.4 can read it as an ORDER BY position inside a derived table. The fuzzer runs every property on MySQL 8.4 and MariaDB 11.4, over prepared statements and the text protocol Cloudflare Hyperdrive uses; see docs/mysql.md for what MySQL does differently.Breaking, for a custom
Dialect:clauses.offsetRequiresLimit: trueis nowclauses.limitForOffset: "-1": the LIMIT to write, which MySQL needs to be its largest row count.clauses.lockingis aLockingSupport({ strengths, of, shareSyntax? }), nottrue: Postgres's is every strength withof.likeIgnoresCase: trueis nowlikeCase: "ascii-insensitive", beside"sensitive"(the default) and MySQL's"collation".integerComparesFraction: trueis nowfractionComparableIntegers, the integer column types that compare with a fraction (SQLite's is["integer"]).
New optional
Dialectfields:castType(the CAST target for a selected param's column type),concat,comparisonCastandclauses.selectedNumberCast.MysqlOnlyandLockingSupportare exported from every dialect entry. -
91c6ee5:
MySQL.table(name, { columns, primaryKey, indexes, tenantColumn, casing })declares a MySQL or MariaDB table with its DDL, asSQLite.tabledoes: the value is still a queryTable, withddlandproblemsbeside it.MySQL.column(type, { name, default, defaultExpr, unique, defaultFn, onUpdate }),MySQL.indexandMySQL.uniqueIndexgo with it, and{ external: true, columns }declares a table another tool owns. A literal default on aTEXT,BLOBorJSONcolumn is written as an expression,DEFAULT ('…');MySQL.dateTimeNowis thedefaultExprfor adatetime. A definition records a problem for aTEXT,BLOBorJSONcolumn in a key, index or UNIQUE constraint, a nullable primary key column, a key past InnoDB's 3072 bytes, a name past 64 characters, and index names that collide./schemaaddsmysqlEntitiesOf,renderMysqlSchema(CREATE TABLE IF NOT EXISTS … ENGINE=InnoDB DEFAULT CHARSET=utf8mb4andCREATE [UNIQUE] INDEX),diffMysqlSchemas,MysqlMigrationOp,renderMysqlOp,renderMysqlMigrationSql, the MySQL entity schemas andMysqlSnapshot.effect-orm generatewithdialect: "mysql"writes the next migration in the drizzle-kit 1.0 folder layout, one statement per--> statement-breakpoint, altering tables in place:ADD,DROP,MODIFYandCHANGE COLUMN,DROP/ADD PRIMARY KEY,RENAME TABLE, and index and UNIQUE changes. effect-orm does not apply MySQL migrations yet:/migraterefuses a MySQL folder,verify --schemaa MySQL config, and--from-drizzlea MySQL snapshot. A new fuzzer applies migrations between random schemas to seeded rows on MySQL 8.4 and MariaDB 11.4 and comparesinformation_schemawith a fresh create.
v0.8.0
Minor Changes
- ec94fd2:
Db.afterCommit(effect)queues work, such as an SMS or an HTTP call, to run after the outermost transaction commits, and never after a rollback. It delegates to Effect'sSqlClient.afterCommitand, likerequireTransaction, addsTransactionto the requirements, so queueing outside a transaction does not compile. A failing hook does not fail the committed transaction: its cause goes to theErrorReporters in context and to an error log, and the next hook still runs. - 2ca58aa: Require Effect 4.0.6 (
effect ^4.0.6peer). Effect now fails a transaction whose COMMIT failed
with aSqlErrorinstead of dying;transactionstill reports it asTransactionCommitFailed.
ClickhouseHttpClientnames its driver"clickhouse-http"(SqlClient.driver), and Effect's own
statement span is now named after the database (db.namespace) rather thansql.execute. - d8bae8c: Add the
/sqlitequery entry with SQLite codecs, functions and positional bindings. Use
sqliteDialectwith an Effect SQLite SqlClient, ord1Dialectfor Cloudflare D1's binding limit
and explicit refusal of interactive transactions.timestampstores SQLite's own
YYYY-MM-DD HH:MM:SS.SSSUTC text, so it compares correctly with whatstrftimewrites;LIKE
escapes with\as on every dialect; text with U+0000 and integers past 2^53 are refused rather
than silently changed. - 8eb7200:
effect-orm generatesupportsdialect: "sqlite". It diffsSQLite.tabledefinitions against
the migrations folder and writes<timestamp>_<name>/migration.sqlplussnapshot.json, the
drizzle-kit 1.0 layout that Alchemy's D1 resource applies.ALTER TABLEadds, drops and renames
where SQLite allows it; other column, primary key and UNIQUE changes rebuild the table. Renames
need aconfirm_renamehint.generate --baseline --from-drizzleadopts a drizzle-kit 1.0
SQLite folder. Snapshots gain asqlitedialect./migraterefuses SQLite folders for now. - b4b84c3:
SQLite.table(name, { columns, primaryKey, indexes })declares a SQLite table with its DDL:
NOT NULLfrom the column type, single and composite primary keys, literal and expression
defaults (SQLite.timestampNowfor atimestampcolumn), unique columns, and named indexes and
unique indexes.sqliteEntitiesOfand
renderSqliteSchemafrom/schemacheck a schema and write itsCREATE TABLEand
CREATE INDEXstatements.table(name, columns, options?)and
table(name, { external: true, columns })stay query-only.
Patch Changes
- a3bd763: On ClickHouse, a
unionAllordered by a numeric column whose branches may differ in type (Id + 1
andId - 1, or aUInt32and anInt64column) no longer fails with "Data types Variant/Dynamic
are not allowed in ORDER BY keys". The union's ORDER BY sorts such a column by
CAST(x AS Nullable(Float64)), accurateCastOrNull(x, 'Int128'), which keeps integers past 2^53 in exact order; the
values themselves are not converted.
v0.7.2
Patch Changes
- 36499ea: An arithmetic expression passed as an argument keeps its parentheses:
$.a.sub($.b.add(1))compiles toa - (b + 1), nota - b + 1. Chains still follow SQL precedence as documented ($.a.sub(1).div(2)isa - 1 / 2); passing the group as an argument is how to group. - 0bf4dbc: On ClickHouse, an array or map compared against a column is cast to the column's type:
$.Ids.eq([0, 4294967296])writesCAST([0, 4294967296] AS Array(Nullable(Int64))). Uncast, ClickHouse inferred the literal's element type from its values (Array(UInt64)here) and could refuse the comparison withILLEGAL_TYPE_OF_ARGUMENT. - 1aee63f: ClickHouse number literals read back as exactly the value you passed. A subnormal float (
5e-324) was a syntax error and is now written from its bits; a whole number past 2^53 (44812297868494010) was written as its shortest decimal, which ClickHouse parses as a different integer, soWHERE x = valuecould miss the row — it is now written as the double's exact integer value. - 362e880: A bare
select()over a subquery or union (CH.fromQuery(inner, "w").select(),CH.fromUnion(union, "u").select()) selects every alias the source selects, as its type already said. It died withQueryBuilderDefect: select() is required, because the derived source has no column list until its own SELECT is evaluated. - 4f690ed: Two Postgres values the server typed wrong from context now compile correctly. A
param.of(type)selected on its own is writtenCAST($n AS <type>), so a boolean or array comes back as itself instead of text that fails to decode. A fractional value compared with an integer column binds as$n::numericinstead of failing withinvalid input syntax for type bigint. Nothing else is cast: whole numbers, params compared with columns, inserts andrealcolumns keep untyped placeholders (and their indexes).param.ofalso no longer confuses two types that share a codec (int8andfloat8). - ed8f7b4: Values that cannot become SQL fail compilation with a
QueryBuilderError(InvalidLiteral) instead of throwing: a bigint compared against a non-integer column, a non-stringlike/notLike/ilikepattern,lit()of anything but a string or number (it wrote[object Object]), a non-numeric arithmetic operand, an invalidDate, and an unparseable string or invalidDatefor a Postgres timestamp. A non-expression in aselectrecord is aQueryBuilderDefectnaming the alias, like a malformedorderBy.
v0.7.1
Patch Changes
- 8e74459: Refuse values with no SQL literal instead of writing
String(value). A value compared against, or passed to, an expression with no column type (adefineFnresult,untypedExpr, an untypeddynamicColumn) used to be written raw when it was not a string, number, boolean or date: an array or object from a request became part of the SQL (toFloat64OrNull(x) > 1) OR (1=1). It now fails compilation with aQueryBuilderError(InvalidLiteral).nullis written asNULLand a bigint as its digits, as before.