Skip to main content

knex_dart 1.4.0 copy "knex_dart: ^1.4.0" to clipboard
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() and QueryBuilder.then. Both were never implemented — they throw UnimplementedError unconditionally on every driver. On most drivers the QueryBuilder returned by db('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), or db.execute(qb) for method-agnostic dispatch.
  • Client.transaction(), Transaction and TransactionConfig. This explicit-transaction-object API was never implemented either — every driver override throws UnimplementedError — and will be removed in a future major version. Use the callback API instead, e.g. KnexPostgres.trx((trx) async { ... }), or Client.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 from parity_test.dart entirely, based on a stale comment claiming mssql wasn't reachable via the core harness — it is). Client.offsetPlaceholders (used when inlining a Raw value 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) from parameterPlaceholder itself 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 @pN too. SchemaCompiler._inlineBindings (used for CREATE VIEW/materialized-view bodies, which can't take bound parameters in most dialects) gained the matching @pN recognition 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 a RECURSIVE keyword T-SQL has no grammar for, and .forUpdate()/.forShare() refused to compile at all. In detail:

    • .returning() now compiles to OUTPUT inserted.*/OUTPUT deleted.*, positioned per verb (after the column list on INSERT, after SET on UPDATE, after the target table on DELETE). KnexDialect.mssql gained SqlCapability.returning accordingly, so dialect_unsupported_returning no longer warns on correct code.
    • .forUpdate()/.forShare() compile to the with (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 to select top (n), and .limit() on an UPDATE to update top (n) (previously dropped outright).
    • .update().join(...) compiles to T-SQL's UPDATE ... 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/except leave 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 its lock component after join, 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. A top (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, since inserted/deleted expose the target table's columns directly; inserted.[users].[id] is two qualifiers for one column.
    • .offset() without an .orderBy() gets the ordinal sort order 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 an order by 1 prefix 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 $N placeholder corruption in subqueries, lateral joins, WHERE EXISTS, UNION, and CTEs once binding counts reached double digits (was renumbering $11 as $101).
  • Ragged multi-row INSERT (rows with different keys) now fills missing cells with DEFAULT instead of misaligning columns; SQLite-family dialects refuse rather than emit invalid SQL for this case.
  • UPDATE/DELETE no longer drop a preceding WITH (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's ON DUPLICATE KEY UPDATE merge form now correctly lowercases values(...).
  • 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; added orWhereIn, leftOuterJoin/rightOuterJoin/outerJoin, and list-based groupBy.

Schema compiler

  • table.primary(), table.unique(), and table.index() declared inside createTable() are no longer silently dropped — folded inline into the CREATE TABLE statement where required (SQLite-family) or emitted as proper deferred ALTER TABLE statements otherwise.
  • Foreign keys declared inside createTable() (both .references().inTable() and fluent table.foreign()) were silently dropped entirely on SQLite/turso/d1; now folded inline into the CREATE TABLE statement.
  • alterTable().primary(), dropPrimary(), dropForeign(), and alterTable().foreign() now correctly refuse on SQLite/turso/d1 (which can't ALTER 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.) in TableBuilder.
  • Redshift increments()/bigIncrements() now emit IDENTITY(1,1) instead of Postgres's SERIAL, which Redshift doesn't support.
  • Redshift index()/dropIndex() now refuse (Redshift has no CREATE 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 WatchableClient contract for drivers that support reactive query streams.
  • Exported the doc snippet runtime helpers used by the docs site and playground through the public knex_dart API.
  • 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 / QueryExecutionContext pipeline 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 KnexQuery for dialect-only SQL generation via KnexQuery.forDialect(...) and KnexQuery.forClient(...).
  • Added schema parity APIs in SchemaBuilder and SchemaCompiler, including: createTableLike, hasTable, hasColumn, renameView, view/materialized-view operations, schema operations, extension operations, and schema.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 MSSQL LIMIT/OFFSET SQL generation.
  • Internal workspace refactor: core package moved under packages/knex_dart with no user-facing import path change.

1.1.0 #

  • Added filesystem/config migration source support via fromConfig().
  • Added auto-registration of JsonSchemaAdapter for fromSchema(...).
  • 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.
6
likes
150
points
963
downloads

Documentation

API reference

Publisher

verified publishermahawarkartikey.in

Weekly Downloads

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.

Repository (GitHub)
View/report issues
Contributing

Topics

#sql #query-builder #database #orm #knex

License

MIT (license)

Dependencies

collection, knex_dart_capabilities, logging, meta, universal_io

More

Packages that depend on knex_dart