knex_dart 1.4.0
knex_dart: ^1.4.0 copied to clipboard
A Dart SQL query builder inspired by Knex.js. Use driver packages (knex_dart_postgres, knex_dart_mysql, knex_dart_sqlite) to connect to databases.
1.4.0 #
Supersedes the unreleased 1.3.2, 1.3.3 and 1.3.4 entries, which were written but never tagged or published — 1.3.1 is the last release, so everything below lands on top of it in one go.
Fixed: MSSQL .update() with .join() wrote every row in the table #
Compiling a join-filtered UPDATE for mssql dropped the join entirely, leaving
an unconditional UPDATE with no FROM and no WHERE:
db('users').join('orders', 'users.id', 'orders.user_id')
.update({'active': false});
// emitted: update [users] set [active] = @p0 <- every row
In a join-filtered update the join is the filter, so removing it left nothing
to constrain the statement. It compiled to valid SQL, executed successfully and
reported no error; the only signal was an affected-row count nobody checks on
an update. The join clause was gated on a MySQL-family check — correct for
Postgres and SQLite, which genuinely have no JOIN on UPDATE and where
knex.js also drops it — but mssql was swept into the same branch even though
T-SQL expresses it as UPDATE ... FROM ... JOIN, which knex.js's own mssql
compiler emits. It now compiles to that form.
This was never a working feature that regressed: mssql .update().join() had
never emitted a join. It is listed first because of the consequence, not
because of a regression.
Known limitation: Migrator.latest() takes no lock #
Two overlapping latest() calls against the same tracking table can both read
the same "pending" snapshot and each run the same migration's up(), applying
its DDL/DML twice. KnexMigrationLockException exists but is never thrown.
This is a design gap rather than a new bug — it is documented on latest() and
pinned by a test — but it affects anyone running migrations from more than one
instance at boot, so it belongs here rather than only in a doc comment.
Deprecated #
QueryBuilder.execute()andQueryBuilder.then. Both were never implemented — they throwUnimplementedErrorunconditionally on every driver. On most drivers theQueryBuilderreturned bydb('table')/db.queryBuilder()is bound to a dialect-only client used purely for SQL compilation, not the driver's executing client (SQLite is the exception, though fixing it there would still bypass the wrapper's interceptor pipeline). Use the driver wrapper's own methods instead:db.select(qb)/db.insert(qb)/db.update(qb)/db.delete(qb), ordb.execute(qb)for method-agnostic dispatch.Client.transaction(),TransactionandTransactionConfig. This explicit-transaction-object API was never implemented either — every driver override throwsUnimplementedError— and will be removed in a future major version. Use the callback API instead, e.g.KnexPostgres.trx((trx) async { ... }), orClient.runInTransaction().
Both are deprecation-only: no behavior changed.
MSSQL compile parity #
-
MSSQL query compilation now emits
@p0,@p1, … numbered parameter placeholders, matching knex.js's mssql client exactly, instead of the generic?used for other positional-placeholder dialects. This was the single largest source of divergence in a newly-enabled MSSQL compile-parity sweep (previously excluded fromparity_test.dartentirely, based on a stale comment claiming mssql wasn't reachable via the core harness — it is).Client.offsetPlaceholders(used when inlining aRawvalue or subquery into a query that already has prior bindings, so nested placeholders continue the running numbered sequence) now derives the active numbered-placeholder prefix ($or@p) fromparameterPlaceholderitself instead of only recognizing$N, so mssql gets the same renumbering correctness Postgres already had — including the$11→$101-style collision guard from 1.3.1, now covering@pNtoo.SchemaCompiler._inlineBindings(used forCREATE VIEW/materialized-view bodies, which can't take bound parameters in most dialects) gained the matching@pNrecognition branch. No breaking change to the public query-builder API;.toSQL()output for mssql queries with bindings changes shape (placeholder text and parameter passing), which downstream code inspecting compiled SQL text directly should account for. -
MSSQL: closed eight compile-parity gaps that the same sweep surfaced. Two were silently producing wrong results rather than merely divergent SQL:
.update().join(...)dropped the join entirely, turning a join-filtered UPDATE into an unconditional one that wrote to every row of the table; and.returning()dropped its columns with only a log line, so callers got nothing back. Two more were emitting SQL that SQL Server rejects outright: recursive CTEs carried aRECURSIVEkeyword T-SQL has no grammar for, and.forUpdate()/.forShare()refused to compile at all. In detail:.returning()now compiles toOUTPUT inserted.*/OUTPUT deleted.*, positioned per verb (after the column list on INSERT, after SET on UPDATE, after the target table on DELETE).KnexDialect.mssqlgainedSqlCapability.returningaccordingly, sodialect_unsupported_returningno longer warns on correct code..forUpdate()/.forShare()compile to thewith (UPDLOCK)/with (HOLDLOCK)FROM-clause table hints instead of throwing..skipLocked()/.noWait()have no table-hint equivalent and are dropped, and.forNoKeyUpdate()/.forKeyShare()still refuse — all three matching knex.js..limit(n)without an offset compiles toselect top (n), and.limit()on an UPDATE toupdate top (n)(previously dropped outright)..update().join(...)compiles to T-SQL'sUPDATE ... FROM ... JOIN.- Recursive CTEs emit a plain
WITH; T-SQL doesn't distinguish recursive from non-recursive CTEs and rejects the keyword. - The jsonb key-existence operators (
?,?|,?&) are no longer backslash-escaped. The escape is now keyed off whether a dialect actually uses?as its placeholder, rather than a hardcoded Postgres-family list. - Wrapped
union/unionAll/intersect/exceptleave the base select unparenthesized, and the OFFSET/FETCH keywords are lowercase.
Four of these deliberately diverge from knex.js, because matching it would emit a statement SQL Server rejects or silently return wrong rows:
- The lock hint attaches to the table (
from [t] with (UPDLOCK) inner join ...). knex.js orders itslockcomponent afterjoin, which trails the hint off the end of an ON condition where T-SQL won't accept it. .limit(n)on a set operation keeps the trailing OFFSET/FETCH form. Atop (n)prefix — what knex.js emits — bounds only the first branch, so one branch loses rows while the other returns everything.- A qualified
.returning(['users.id'])drops the table qualifier, sinceinserted/deletedexpose the target table's columns directly;inserted.[users].[id]is two qualifiers for one column. .offset()without an.orderBy()gets the ordinal sortorder by 1. T-SQL defines OFFSET/FETCH as a tail of the ORDER BY clause rather than a clause in its own right, so the unsorted form knex.js emits is a syntax error — confirmed against a real SQL Server, not inferred from the grammar..toSQL()output for mssql queries using.offset()without an explicit sort therefore gains anorder by 1prefix on the clause. Pagination without an ORDER BY returns an arbitrary page in any case, so the imposed sort removes nothing a caller could have relied on.
1.3.1 #
Correctness fixes surfaced by an adversarial knex.js-vs-knex-dart comparison
review and a new differential schema-DDL parity harness (test/parity/).
No breaking changes and no new public API — every item below is a bug fix to
existing behavior.
Query compiler
.onConflict().merge().where(...)no longer silently drops the WHERE clause; MySQL now correctly refuses this combination instead of emitting wrong SQL.- Fixed
$Nplaceholder corruption in subqueries, lateral joins,WHERE EXISTS,UNION, and CTEs once binding counts reached double digits (was renumbering$11as$101). - Ragged multi-row
INSERT(rows with different keys) now fills missing cells withDEFAULTinstead of misaligning columns; SQLite-family dialects refuse rather than emit invalid SQL for this case. UPDATE/DELETEno longer drop a precedingWITH(CTE) clause.- Fixed dotted/qualified column names in aggregate
GROUP BY/array forms. .onConflict().ignore()now refuses on dialects that don't support it instead of emitting broken SQL; MySQL'sON DUPLICATE KEY UPDATEmerge form now correctly lowercasesvalues(...).- Postgres-family
?(jsonb key-existence) operator no longer leaks a stray backslash into the emitted SQL. where(column, null)now has correct null-shorthand semantics; addedorWhereIn,leftOuterJoin/rightOuterJoin/outerJoin, and list-basedgroupBy.
Schema compiler
table.primary(),table.unique(), andtable.index()declared insidecreateTable()are no longer silently dropped — folded inline into theCREATE TABLEstatement where required (SQLite-family) or emitted as proper deferredALTER TABLEstatements otherwise.- Foreign keys declared inside
createTable()(both.references().inTable()and fluenttable.foreign()) were silently dropped entirely on SQLite/turso/d1; now folded inline into theCREATE TABLEstatement. alterTable().primary(),dropPrimary(),dropForeign(), andalterTable().foreign()now correctly refuse on SQLite/turso/d1 (which can'tALTER TABLE ADD/DROP CONSTRAINT) instead of emitting invalid SQL.- turso and d1 were falling through to Postgres-shaped SQL for almost every
schema operation — most dialect-dispatch checks compared
driverName == 'sqlite' || 'sqlite3'literally instead of using the family-aware helper that already covered turso/d1. Affected:dropUnique,dropIndex, primary-key folding, foreign-key folding, and every column type mapping (increments, booleans, datetimes, JSON, etc.) inTableBuilder. - Redshift
increments()/bigIncrements()now emitIDENTITY(1,1)instead of Postgres'sSERIAL, which Redshift doesn't support. - Redshift
index()/dropIndex()now refuse (Redshift has noCREATE INDEX/DROP INDEX) instead of emitting SQL Redshift rejects at execution time. enu()(enum) values containing a single quote are now correctly escaped.- Custom constraint/index names passed to
unique()/dropIndex()are no longer ignored.
Verified against real Postgres, MySQL, SQLite, and turso (sqld) instances,
and against a real CockroachDB and local D1 instance for the two dialects
without a live driver in this repo. See tool/parity/README.md for the
differential harness this was built and checked against.
1.3.0 #
- Added the public
WatchableClientcontract for drivers that support reactive query streams. - Exported the doc snippet runtime helpers used by the docs site and playground
through the public
knex_dartAPI. - Added executable doc snippet runtime support and regression coverage for snippet wrapping and dialect validation.
- Documentation updates for runnable snippets and SQLite reactive examples.
1.2.1 #
- Improved query compilation hot paths by replacing timestamp/random UID generation with per-isolate counters.
- Avoided enum string splitting when resolving compiled query methods.
- Documented the public
QueryInterceptor/QueryExecutionContextpipeline used by live driver wrappers for tracing, metrics, logging, and policy hooks. - Added a compiled-query interceptor path so driver wrappers can avoid compiling the same query twice when interceptors are installed.
- No SQL escaping, binding, identifier wrapping, or generated SQL semantics changed in this release.
1.2.0 #
- Added
KnexQueryfor dialect-only SQL generation viaKnexQuery.forDialect(...)andKnexQuery.forClient(...). - Added schema parity APIs in
SchemaBuilderandSchemaCompiler, including:createTableLike,hasTable,hasColumn,renameView, view/materialized-view operations, schema operations, extension operations, andschema.raw(...). - Improved cross-dialect schema SQL generation for MSSQL and MySQL-family paths
(dialect-specific
dropTableIfExists,renameTable, and fulltext alter support). - Improved query compilation behavior for function-style subqueries, analytic
OVER(...)handling, and MSSQLLIMIT/OFFSETSQL generation. - Internal workspace refactor: core package moved under
packages/knex_dartwith no user-facing import path change.
1.1.0 #
- Added filesystem/config migration source support via
fromConfig(). - Added auto-registration of
JsonSchemaAdapterforfromSchema(...). - Added
Client.runInTransaction(...)hook and integrated migrator transaction path. - Added lateral joins API (
joinLateral,leftJoinLateral,crossJoinLateral). - Added and published supporting packages:
knex_dart_capabilities(0.1.0)knex_dart_lint(0.1.0)
- Documentation updates for migrations and optional dialect lint tooling.
1.0.0 #
- Initial stable release.
- SQL query builder core: SELECT, INSERT, UPDATE, DELETE.
- WHERE clauses, JOINs, aggregates, ORDER BY, GROUP BY, HAVING, LIMIT, OFFSET.
- Raw queries, CTEs, UNIONs, INTERSECTs, EXCEPTs, subqueries.
- JSON operators, full-text search, upserts (
onConflict().merge()). - Schema builder: createTable, alterTable, dropTable, foreign keys, indexes.
- Dialect-aware SQL generation (PostgreSQL
$1, MySQL/SQLite?). - 551+ tests passing with >85% coverage.
- Driver packages published separately:
knex_dart_postgres,knex_dart_mysql,knex_dart_sqlite.