@quereus/quereus 2.5.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +222 -439
  2. package/dist/src/core/database.d.ts +10 -4
  3. package/dist/src/core/database.d.ts.map +1 -1
  4. package/dist/src/core/database.js +38 -11
  5. package/dist/src/core/database.js.map +1 -1
  6. package/dist/src/func/builtins/index.d.ts.map +1 -1
  7. package/dist/src/func/builtins/index.js +3 -2
  8. package/dist/src/func/builtins/index.js.map +1 -1
  9. package/dist/src/func/builtins/json-tvf.js +2 -2
  10. package/dist/src/func/builtins/json-tvf.js.map +1 -1
  11. package/dist/src/func/builtins/scalar.d.ts +2 -1
  12. package/dist/src/func/builtins/scalar.d.ts.map +1 -1
  13. package/dist/src/func/builtins/scalar.js +16 -14
  14. package/dist/src/func/builtins/scalar.js.map +1 -1
  15. package/dist/src/func/builtins/schema.d.ts.map +1 -1
  16. package/dist/src/func/builtins/schema.js +14 -21
  17. package/dist/src/func/builtins/schema.js.map +1 -1
  18. package/dist/src/planner/building/delete.d.ts.map +1 -1
  19. package/dist/src/planner/building/delete.js +4 -0
  20. package/dist/src/planner/building/delete.js.map +1 -1
  21. package/dist/src/planner/building/insert.d.ts.map +1 -1
  22. package/dist/src/planner/building/insert.js +4 -61
  23. package/dist/src/planner/building/insert.js.map +1 -1
  24. package/dist/src/planner/building/select-aggregates.d.ts +1 -1
  25. package/dist/src/planner/building/select-aggregates.d.ts.map +1 -1
  26. package/dist/src/planner/building/select-aggregates.js +62 -5
  27. package/dist/src/planner/building/select-aggregates.js.map +1 -1
  28. package/dist/src/planner/rules/subquery/rule-subquery-decorrelation.d.ts.map +1 -1
  29. package/dist/src/planner/rules/subquery/rule-subquery-decorrelation.js +30 -0
  30. package/dist/src/planner/rules/subquery/rule-subquery-decorrelation.js.map +1 -1
  31. package/dist/src/planner/validation/returning-qualifier-validator.d.ts +8 -0
  32. package/dist/src/planner/validation/returning-qualifier-validator.d.ts.map +1 -0
  33. package/dist/src/planner/validation/returning-qualifier-validator.js +63 -0
  34. package/dist/src/planner/validation/returning-qualifier-validator.js.map +1 -0
  35. package/dist/src/runtime/deferred-constraint-queue.d.ts.map +1 -1
  36. package/dist/src/runtime/deferred-constraint-queue.js +3 -0
  37. package/dist/src/runtime/deferred-constraint-queue.js.map +1 -1
  38. package/dist/src/runtime/emit/alter-table.d.ts.map +1 -1
  39. package/dist/src/runtime/emit/alter-table.js +8 -5
  40. package/dist/src/runtime/emit/alter-table.js.map +1 -1
  41. package/dist/src/runtime/emit/pragma.d.ts.map +1 -1
  42. package/dist/src/runtime/emit/pragma.js +3 -4
  43. package/dist/src/runtime/emit/pragma.js.map +1 -1
  44. package/dist/src/runtime/emit/project.d.ts.map +1 -1
  45. package/dist/src/runtime/emit/project.js +4 -1
  46. package/dist/src/runtime/emit/project.js.map +1 -1
  47. package/dist/src/runtime/emit/table-valued-function.js +2 -2
  48. package/dist/src/runtime/emit/table-valued-function.js.map +1 -1
  49. package/dist/src/schema/manager.d.ts +12 -2
  50. package/dist/src/schema/manager.d.ts.map +1 -1
  51. package/dist/src/schema/manager.js +63 -5
  52. package/dist/src/schema/manager.js.map +1 -1
  53. package/dist/src/schema/table.d.ts +2 -0
  54. package/dist/src/schema/table.d.ts.map +1 -1
  55. package/dist/src/schema/table.js.map +1 -1
  56. package/dist/src/util/key-serializer.d.ts +3 -0
  57. package/dist/src/util/key-serializer.d.ts.map +1 -1
  58. package/dist/src/util/key-serializer.js +19 -2
  59. package/dist/src/util/key-serializer.js.map +1 -1
  60. package/dist/src/util/plugin-helper.js +1 -1
  61. package/dist/src/util/plugin-helper.js.map +1 -1
  62. package/dist/src/vtab/connection.d.ts +7 -0
  63. package/dist/src/vtab/connection.d.ts.map +1 -1
  64. package/dist/src/vtab/manifest.d.ts +4 -0
  65. package/dist/src/vtab/manifest.d.ts.map +1 -1
  66. package/dist/src/vtab/memory/layer/manager.d.ts.map +1 -1
  67. package/dist/src/vtab/memory/layer/manager.js +16 -2
  68. package/dist/src/vtab/memory/layer/manager.js.map +1 -1
  69. package/dist/src/vtab/memory/layer/transaction.d.ts.map +1 -1
  70. package/dist/src/vtab/memory/layer/transaction.js +7 -1
  71. package/dist/src/vtab/memory/layer/transaction.js.map +1 -1
  72. package/dist/src/vtab/memory/module.d.ts +2 -2
  73. package/dist/src/vtab/memory/module.d.ts.map +1 -1
  74. package/dist/src/vtab/memory/module.js +2 -2
  75. package/dist/src/vtab/memory/module.js.map +1 -1
  76. package/dist/src/vtab/module.d.ts +12 -0
  77. package/dist/src/vtab/module.d.ts.map +1 -1
  78. package/dist/src/vtab/table.d.ts +8 -0
  79. package/dist/src/vtab/table.d.ts.map +1 -1
  80. package/dist/src/vtab/table.js.map +1 -1
  81. package/package.json +5 -3
package/README.md CHANGED
@@ -1,439 +1,222 @@
1
- # Quereus - A TypeScript SQL Query Processor
2
-
3
- <img src="../../docs/images/Quereus_colored_wide.svg" alt="Quereus Logo" height="150">
4
-
5
- Quereus is a feature-complete SQL query processor specifically designed for efficient in-memory data processing with a strong emphasis on the **virtual table** interface. It provides rich SQL query and constraint capabilities (joins, aggregates, subqueries, CTEs, window functions, constraints) over data sources exposed via the virtual table mechanism. Quereus features a modern type system with temporal types, JSON support, and plugin-extensible custom types. It has no persistent file storage, though one could be built as a virtual table module.
6
-
7
- ## Project Goals
8
-
9
- * **Virtual Table Centric**: Provide a robust and flexible virtual table API as the primary means of interacting with data sources. All tables are virtual tables.
10
- * **In-Memory Default**: Includes a comprehensive in-memory virtual table implementation (`MemoryTable`) with support for transactions and savepoints.
11
- * **Modern Type System**: Extensible logical/physical type separation with built-in temporal types (DATE, TIME, DATETIME), native JSON type with deep equality comparison, and plugin support for custom types. See [Type System Documentation](../../docs/types.md).
12
- * **TypeScript & Modern JS**: Leverage TypeScript's type system and modern JavaScript features and idioms.
13
- * **Async VTab Operations**: Virtual table data operations (reads/writes) are asynchronous. Cursors are implemented as async iterables.
14
- * **Cross-Platform**: Target diverse Javascript runtime environments, including Node.js, browser, and React Native. Plugin loading (via `@quereus/plugin-loader`) uses dynamic `import()` and is not compatible with React Native; use static imports for RN.
15
- * **Minimal Dependencies**: Avoid heavy external dependencies where possible.
16
- * **SQL Compatibility**: Comprehensive support for modern SQL features including joins, window functions, subqueries, CTEs, constraints, views, and advanced DML/DDL operations.
17
- * **Key-Based Addressing**: All tables are addressed by their defined Primary Key. The concept of a separate, implicit `rowid` for addressing rows is not used.
18
- * **Third Manifesto Friendly**: Embraces some of the principles of the [Third Manifesto](https://www.dcs.warwick.ac.uk/~hugh/TTM/DTATRM.pdf), such as allowing for empty keys. Utilizes algebraic planning.
19
-
20
- ## Architecture Overview
21
-
22
- Quereus is built on a modern architecture based on partially immutable PlanNodes and an Instruction-based runtime with robust attribute-based context system.
23
-
24
- 1. **SQL Input**: The process starts with a SQL query string.
25
- 2. **Parser (`src/parser`)**:
26
- * **Lexer (`lexer.ts`)**: Tokenizes the raw SQL string.
27
- * **Parser (`parser.ts`)**: Builds an Abstract Syntax Tree (AST).
28
- 3. **Planner (`src/planner`)**:
29
- * Traverses the AST to construct a tree of immutable `PlanNode` objects representing the logical query structure.
30
- * Handles Common Table Expressions (CTEs) and Subqueries by converting them into relational `PlanNode`s.
31
- * Resolves table and function references using the Schema Manager.
32
- * Performs query planning, incorporating virtual table `getBestAccessPlan` method and table schema statistics.
33
- * **Optimizer (`src/planner/optimizer`)**: Transforms logical plans into efficient physical execution plans through a rule-based optimization system. See [Optimizer Documentation](../../docs/optimizer.md) for details.
34
- 4. **Runtime (`src/runtime`)**:
35
- * **Emitters (`src/runtime/emitters.ts`, `src/runtime/emit/`)**: Translate `PlanNode`s into a graph of `Instruction` objects.
36
- * **Scheduler (`src/runtime/scheduler.ts`)**: Manages the execution flow of the `Instruction` graph.
37
- * **Instructions**: JavaScript functions that operate on `RuntimeValue`s (which can be `SqlValue` or `AsyncIterable<Row>`). Async parameters are awaited.
38
- * Invokes virtual table methods (e.g., `query` which returns `AsyncIterable<Row>`, `update`) to interact with data.
39
- * Calls User-Defined Functions (UDFs) and aggregate functions.
40
- * Handles transaction and savepoint control.
41
- 5. **Virtual Tables (`src/vtab`)**:
42
- * The core data interface. Modules implement `VirtualTableModule`.
43
- * `MemoryTable` (`vtab/memory/table.ts`) is a key implementation using `digitree`.
44
- 6. **Schema Management (`src/schema`)**: Manages schemas, tables, columns, functions.
45
- 7. **User-Defined Functions (`src/func`)**: Support for custom JS functions in SQL.
46
- 8. **Core API (`src/core`)**: `Database`, `Statement` classes.
47
-
48
- ## Source File Layout
49
-
50
- ```
51
- src/
52
- ├── core/ # Database, Statement, transactions
53
- ├── parser/ # SQL parser → AST
54
- ├── planner/ # AST PlanNode tree
55
- │ ├── building/ # Plan builders (select.ts, expression.ts, ddl.ts, ...)
56
- │ ├── nodes/ # PlanNode classes (one per node type)
57
- │ │ └── plan-node-type.ts # PlanNodeType enum — add new node types here
58
- │ ├── rules/ # Optimizer rules, by category:
59
- │ │ ├── access/ # access-path selection
60
- │ │ ├── aggregate/ # streaming aggregation
61
- │ │ ├── cache/ # CTE, IN-subquery, materialization
62
- │ │ ├── distinct/ # distinct elimination
63
- │ │ ├── join/ # join commutation, physical selection
64
- │ │ ├── predicate/ # predicate pushdown
65
- │ │ ├── retrieve/ # retrieve growth
66
- │ │ └── subquery/ # subquery decorrelation
67
- │ ├── framework/ # Optimizer framework (characteristics, passes, registry)
68
- │ ├── cost/ # Cost model (index.ts)
69
- │ ├── analysis/ # Const evaluator, constraint extractor, predicate normalizer
70
- │ ├── stats/ # Table/column statistics
71
- │ ├── validation/ # Plan validation passes
72
- │ ├── scopes/ # Name resolution scopes
73
- │ └── cache/ # Plan cache
74
- ├── runtime/
75
- │ ├── emit/ # Instruction emitters (mirrors planner/nodes/)
76
- │ ├── cache/ # Runtime caching
77
- │ └── functions/ # Runtime function dispatch
78
- ├── emit/ # Top-level emitter entry (plan → instructions)
79
- ├── schema/ # Catalog, schema manager, table/column/view/assertion defs
80
- ├── types/ # Type system (logical types, registry, temporal, JSON)
81
- ├── func/builtins/ # Built-in functions (scalar, aggregate, string, datetime, json, ...)
82
- ├── vtab/ # Virtual table framework
83
- │ └── memory/ # In-memory VTab implementation (layers, merge iterators)
84
- ├── common/ # Shared constants, errors, logger, type inference
85
- └── util/ # Miscellaneous utilities
86
-
87
- test/
88
- ├── logic/ # SQL logic tests (*.sqllogic) — primary test suite
89
- ├── plan/ # Plan-shape tests (basic/, joins/, aggregates/)
90
- ├── optimizer/ # Optimizer-specific tests
91
- ├── planner/ # Planner unit tests
92
- ├── vtab/ # VTab tests
93
- └── util/ # Test utilities
94
- ```
95
-
96
- Key relationships: each PlanNode in `planner/nodes/` has a matching emitter in `runtime/emit/`. Optimizer rules in `planner/rules/` are registered via `planner/framework/registry.ts`. Tests go in `test/logic/*.sqllogic` (SQL logic tests) or `test/plan/` (plan shape tests).
97
-
98
- ### Common Implementation Patterns
99
-
100
- **Adding a new PlanNode** (follow an existing node as template):
101
- 1. `planner/nodes/my-node.ts` — node class (e.g. copy `bloom-join-node.ts` for joins)
102
- 2. `planner/nodes/plan-node-type.ts` — add enum entry
103
- 3. `runtime/emit/my-node.ts` — matching emitter
104
- 4. `emit/emitter.ts` register emitter in the visitor
105
- 5. Tests in `test/logic/*.sqllogic` or `test/plan/`
106
-
107
- **Adding an optimizer rule:**
108
- 1. `planner/rules/<category>/rule-my-rule.ts` (copy an existing rule in the same category)
109
- 2. Register in `planner/framework/registry.ts`
110
- 3. Cost constants go in `planner/cost/index.ts`
111
-
112
- **Adding a built-in function:**
113
- 1. `func/builtins/<category>.ts` (scalar.ts, string.ts, aggregate.ts, json.ts, datetime.ts, ...)
114
- 2. Register via `func/registration.ts`
115
-
116
- All paths above are relative to `src/`.
117
-
118
- ## Quick Start
119
-
120
- ```typescript
121
- import { Database } from '@quereus/quereus';
122
-
123
- const db = new Database();
124
-
125
- // Create a table and insert data
126
- await db.exec("create table users (id integer primary key, name text, email text)");
127
- await db.exec("insert into users values (1, 'Alice', 'alice@example.com')");
128
-
129
- // Query returns objects: { id: 1, name: 'Alice', email: 'alice@example.com' }
130
- const user = await db.get("select * from users where id = ?", [1]);
131
- console.log(user.name); // "Alice"
132
-
133
- // Iterate over multiple rows
134
- for await (const row of db.eval("select * from users")) {
135
- console.log(row.name);
136
- }
137
- ```
138
-
139
- ### Reactive Patterns with Event Hooks
140
-
141
- ```typescript
142
- import { Database } from '@quereus/quereus';
143
-
144
- const db = new Database();
145
-
146
- // Subscribe to data changes at the database level
147
- db.onDataChange((event) => {
148
- console.log(`${event.type} on ${event.tableName} (module: ${event.moduleName})`);
149
- if (event.remote) {
150
- console.log('Change came from remote sync');
151
- }
152
- if (event.type === 'update') {
153
- console.log('Changed columns:', event.changedColumns);
154
- }
155
- });
156
-
157
- // Subscribe to schema changes
158
- db.onSchemaChange((event) => {
159
- console.log(`${event.type} ${event.objectType}: ${event.objectName}`);
160
- });
161
-
162
- // Events fire after commit
163
- await db.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");
164
- // Output: create table: users
165
-
166
- await db.exec("INSERT INTO users VALUES (1, 'Alice')");
167
- // Output: insert on users (module: memory)
168
- ```
169
-
170
- The database-level event system aggregates events from all modules automatically. Events are batched within transactions and delivered only after successful commit.
171
-
172
- SQL values use native JavaScript types (`string`, `number`, `bigint`, `Uint8Array`, `null`). Temporal types are ISO 8601 strings. Results stream as async iterators.
173
-
174
- See the [Usage Guide](../../docs/usage.md) for complete API reference and [Module Authoring Guide](../../docs/module-authoring.md) for event system details.
175
-
176
- ## Platform Support & Storage
177
-
178
- Quereus runs on any JavaScript runtime. For persistent storage, platform-specific plugins provide the `store` virtual table module:
179
-
180
- ### Node.js
181
-
182
- Use [`@quereus/plugin-leveldb`](../quereus-plugin-leveldb/) for LevelDB-based persistent storage with full transaction isolation. Each table becomes a subdirectory under `basePath`:
183
-
184
- ```typescript
185
- import { Database, registerPlugin } from '@quereus/quereus';
186
- import leveldbPlugin from '@quereus/plugin-leveldb/plugin';
187
-
188
- const db = new Database();
189
- await registerPlugin(db, leveldbPlugin, { basePath: './data' }); // ./data/users/, ./data/orders/, etc.
190
-
191
- await db.exec(`create table users (id integer primary key, name text) using store`);
192
-
193
- // Full transaction isolation enabled by default
194
- await db.exec('BEGIN');
195
- await db.exec(`INSERT INTO users VALUES (1, 'Alice')`);
196
- const user = await db.get('SELECT * FROM users WHERE id = 1'); // Sees uncommitted insert
197
- await db.exec('COMMIT');
198
- ```
199
-
200
- ### Browser
201
-
202
- Use [`@quereus/plugin-indexeddb`](../quereus-plugin-indexeddb/) for IndexedDB-based persistent storage with cross-tab sync and full transaction isolation. All tables share one IndexedDB database:
203
-
204
- ```typescript
205
- import { Database, registerPlugin } from '@quereus/quereus';
206
- import indexeddbPlugin from '@quereus/plugin-indexeddb/plugin';
207
-
208
- const db = new Database();
209
- await registerPlugin(db, indexeddbPlugin, { databaseName: 'myapp' }); // IndexedDB database name
210
-
211
- await db.exec(`create table users (id integer primary key, name text) using store`);
212
- ```
213
-
214
- ### React Native
215
-
216
- Use [`@quereus/plugin-react-native-leveldb`](../quereus-plugin-react-native-leveldb/) for fast LevelDB storage with full transaction isolation. Each table becomes a separate LevelDB database with a name prefix:
217
-
218
- ```typescript
219
- import { LevelDB, LevelDBWriteBatch } from 'react-native-leveldb';
220
- import { Database, registerPlugin } from '@quereus/quereus';
221
- import leveldbPlugin from '@quereus/plugin-react-native-leveldb/plugin';
222
-
223
- const db = new Database();
224
- await registerPlugin(db, leveldbPlugin, {
225
- openFn: LevelDB.open,
226
- WriteBatch: LevelDBWriteBatch,
227
- databaseName: 'myapp' // creates myapp_users, myapp_orders, etc.
228
- });
229
-
230
- await db.exec(`create table users (id integer primary key, name text) using store`);
231
- ```
232
-
233
- **Note:** React Native requires runtime polyfills and static plugin loading. See the [plugin README](../quereus-plugin-react-native-leveldb/) for setup details.
234
-
235
- **Required polyfills:**
236
- - `structuredClone` (Quereus uses it internally)
237
- - `TextEncoder` / `TextDecoder` (used by store plugins)
238
- - `Symbol.asyncIterator` (required for async-iterable support; Quereus has a Hermes workaround for AsyncGenerator iterables, but the symbol must exist)
239
-
240
- ### NativeScript
241
-
242
- Use [`@quereus/plugin-nativescript-sqlite`](../quereus-plugin-nativescript-sqlite/) for SQLite-based storage with full transaction isolation. All tables share one SQLite database file:
243
-
244
- ```typescript
245
- import { openOrCreate } from '@nativescript-community/sqlite';
246
- import { Database, registerPlugin } from '@quereus/quereus';
247
- import sqlitePlugin from '@quereus/plugin-nativescript-sqlite/plugin';
248
-
249
- const sqliteDb = openOrCreate('myapp.db'); // SQLite database file
250
- const db = new Database();
251
- await registerPlugin(db, sqlitePlugin, { db: sqliteDb });
252
-
253
- await db.exec(`create table users (id integer primary key, name text) using store`);
254
- ```
255
-
256
- See [Store Documentation](../../docs/store.md) for the storage architecture and custom backend implementation.
257
-
258
- ## Documentation
259
-
260
- * [Usage Guide](../../docs/usage.md): Complete API reference including:
261
- - Type mappings (SQL ↔ JavaScript)
262
- - Parameter binding and prepared statements
263
- - Logging via `debug` library with namespace control
264
- - Instruction tracing for performance analysis
265
- - Transaction and savepoint management
266
- * [SQL Reference Guide](../../docs/sql.md): SQL syntax (includes Declarative Schema)
267
- * [Schema Management](../../docs/schema.md): SchemaManager API, change events, key types
268
- * [Type System](../../docs/types.md): Logical/physical types, temporal types, JSON, custom types
269
- * [Functions](../../docs/functions.md): Built-in scalar, aggregate, window, and JSON functions
270
- * [Memory Tables](../../docs/memory-table.md): Built-in MemoryTable module
271
- * [Module Authoring](../../docs/module-authoring.md): Virtual table module development and event system
272
- * [Date/Time Handling](../../docs/datetime.md): Temporal parsing, functions, and ISO 8601 formats
273
- * [Runtime](../../docs/runtime.md): Instruction-based execution and opcodes
274
- * [Error Handling](../../docs/errors.md): Error types and status codes
275
- * [Plugin System](../../docs/plugins.md): Virtual tables, functions, and collations
276
- * [TODO List](../../docs/todo.md): Planned features
277
-
278
- ### Plugin Development
279
-
280
- Quereus exports all critical utilities needed for plugin and module development:
281
-
282
- * **Comparison Functions**: `compareSqlValues`, `compareRows`, `compareTypedValues`, `createTypedComparator` — Match Quereus SQL semantics in custom implementations
283
- * **Coercion Utilities**: `tryCoerceToNumber`, `coerceForAggregate` — Handle type coercion for aggregates and arithmetic
284
- * **Collation Support**: `registerCollation`, `getCollation`, built-in collations (`BINARY_COLLATION`, `NOCASE_COLLATION`, `RTRIM_COLLATION`)
285
- * **Type System**: Full access to logical types, validation, and parsing utilities
286
- * **Event Hooks**: `VTableEventEmitter` interface for mutation and schema change events — Enable reactive patterns, caching, and replication
287
- * **DDL Generation**: `generateTableDDL(tableSchema, db?)`, `generateIndexDDL(indexSchema, tableSchema, db?)` — Canonical `CREATE TABLE` / `CREATE INDEX` output from runtime schema objects. With a `Database`, matches session defaults (schema qualification, `default_column_nullability`, `default_vtab_module`/`default_vtab_args`) for readable output; without one, emits fully-qualified, explicitly-annotated DDL safe for cross-session persistence. See [Schema Management — DDL Generation](../../docs/schema.md#ddl-generation).
288
-
289
- See the [Plugin System documentation](../../docs/plugins.md#comparison-and-coercion-utilities) for complete API reference and examples.
290
-
291
- ## Key Design Decisions
292
-
293
- * **Federated / VTab-Centric**: All tables are virtual tables.
294
- * **Async Core**: Core operations are asynchronous. Cursors are `AsyncIterable<Row>`.
295
- * **Key-Based Addressing**: Rows are identified by their defined Primary Key. No separate implicit `rowid`.
296
- * **Relational Orthogonality**: Any statement that results in a relation can be used anywhere that expects a relation value, including mutating statements with RETURNING clauses.
297
- * **Declarative Schema (Optional)**: Keep using DDL normally. Optionally use order‑independent `declare schema { ... }` to describe end‑state; the engine computes diffs against current state using module‑reported catalogs and emits canonical DDL. You may auto‑apply via `apply schema` or fetch the DDL and run it yourself (enabling custom backfills). Supports seeds, imports (URL + cache), versioning, and schema hashing. Destructive changes require explicit acknowledgement.
298
- * **JavaScript Types**: Uses standard JavaScript types (`number`, `string`, `bigint`, `boolean`, `Uint8Array`, `null`) internally.
299
- * **Object-Based API**: Uses classes (`Database`, `Statement`) to represent resources with lifecycles, rather than handles.
300
- * **Transient Schema**: Schema information is primarily in-memory; persistence is not a goal. Emission of schema SQL export is supported.
301
- * **Multi-Schema Support**: Organize tables across multiple schemas with flexible search paths for modular designs.
302
- * **Bags vs Sets Distinction**: Explicit type-level distinction between relations that guarantee unique rows (sets) and those that allow duplicates (bags), enabling sophisticated optimizations and maintaining algebraic correctness in line with Third Manifesto principles.
303
- * **Attribute-Based Context System**: Robust column reference resolution using stable attribute IDs eliminates architectural fragilities and provides deterministic context lookup across plan transformations.
304
-
305
- ## Key Design Differences
306
-
307
- While Quereus supports standard SQL syntax, it has several distinctive design choices:
308
-
309
- * **Modern Type System**: Uses logical/physical type separation instead of SQLite's type affinity model. Includes native temporal types (DATE, TIME, DATETIME) and JSON type with deep equality comparison. Conversion functions (`integer()`, `date()`, `json()`) are preferred over CAST syntax. All expressions have known types at plan time, including parameters; cross-category comparisons (e.g., numeric vs text) are handled via explicit conversions rather than implicit runtime coercion. See [Type System Documentation](../../docs/types.md).
310
- * **Virtual Table Centric**: Uses `CREATE TABLE ... USING module(...)` syntax. All tables are virtual tables.
311
- * **Default NOT NULL Columns**: Following Third Manifesto principles, columns default to NOT NULL unless explicitly specified otherwise. This behavior can be controlled via `pragma default_column_nullability = 'nullable'` to restore SQL standard behavior.
312
- * **No Rowids**: All tables are addressed by their Primary Key. When no explicit PRIMARY KEY is defined, Quereus includes all columns in the primary key.
313
- * **Async API**: Core execution is asynchronous with async/await patterns throughout.
314
- * **No Triggers or Built-in Persistence**: Persistent storage can be implemented as a VTab module.
315
-
316
- ### Constraints
317
-
318
- - Row-level CHECKs that reference only the current row are enforced immediately.
319
- - Row-level CHECKs that reference other tables (e.g., via subqueries) are automatically deferred and enforced at COMMIT using the same optimized engine as global assertions. No `DEFERRABLE` or `SET CONSTRAINTS` management is required by the user.
320
- - `CREATE ASSERTION name CHECK (...)` defines database-wide invariants evaluated at COMMIT.
321
- - `FOREIGN KEY ... REFERENCES` with `ON DELETE CASCADE/SET NULL/RESTRICT` and `ON UPDATE CASCADE/SET NULL/RESTRICT`.
322
- - **`committed.tablename` pseudo-schema**: Provides read-only access to the pre-transaction (committed) state of any table. Enables transition constraints that compare current and committed state (e.g., `CREATE ASSERTION no_decrease CHECK (NOT EXISTS (SELECT 1 FROM t JOIN committed.t ct ON t.id = ct.id WHERE t.val < ct.val))`). The committed view is pinned to the transaction-start snapshot and is unaffected by savepoints.
323
- - **Determinism Enforcement**: CHECK constraints and DEFAULT values must use only deterministic expressions. Non-deterministic values (like `datetime('now')` or `random()`) must be passed via mutation context to ensure captured statements are replayable. See [Runtime Documentation](../../docs/runtime.md#determinism-validation).
324
-
325
- ### Sequential ID Generation
326
-
327
- Quereus has no built-in auto-increment or sequence objects. Instead, batch ID generation composes naturally from existing features: mutation context captures a non-deterministic seed once, a window function provides a deterministic per-row ordinal, and a scalar or table-valued function produces the final ID. For example, inserting with timestamp-derived IDs:
328
-
329
- ```sql
330
- insert into orders (id, customer_id, total)
331
- with context base_ts = epoch_ms('now')
332
- select
333
- base_ts * 1000 + row_number() over (order by c.customer_id),
334
- c.customer_id,
335
- c.total
336
- from (select customer_id, sum(price) as total from cart_items group by customer_id) c;
337
- ```
338
-
339
- The `WITH CONTEXT` boundary captures `epoch_ms('now')` as a literal, and `row_number() over (order by ...)` assigns a deterministic ordinal over a declared ordering. The entire statement is replayable. For richer formats (ULIDs, UUIDv7), register a deterministic scalar UDF that encodes `(seed, counter)` into the desired format — or use a lateral join to a deterministic TVF when multiple columns are needed per generated row.
340
-
341
- ## Current Status
342
-
343
- Quereus is a feature-complete SQL query processor with a modern planner and instruction-based runtime architecture. The engine successfully handles complex SQL workloads including joins, window functions, subqueries, CTEs, constraints, and comprehensive DML/DDL operations.
344
-
345
- **Current capabilities include:**
346
- * **Modern Type System** - Temporal types (DATE, TIME, DATETIME), JSON with deep equality, plugin-extensible custom types
347
- * **Complete JOIN support** - INNER, LEFT, RIGHT, CROSS, SEMI, and ANTI joins with proper NULL padding
348
- * **Advanced window functions** - Ranking, aggregates, and frame specifications
349
- * **Full constraint system** - NOT NULL, CHECK, FOREIGN KEY, and CREATE ASSERTION. Row-level constraints that reference other tables are automatically deferred to COMMIT. The `committed.tablename` pseudo-schema provides read-only access to pre-transaction state for transition constraints (e.g., "balance may not decrease")
350
- * **Comprehensive subqueries** - Scalar, correlated, EXISTS, and IN subqueries
351
- * **Relational orthogonality** - INSERT/UPDATE/DELETE with RETURNING can be used as table sources
352
- * **Complete set operations** - UNION, INTERSECT, EXCEPT with proper deduplication
353
- * **DIFF (symmetric difference)** - `A diff B` equals `(A except B) union (B except A)`, handy for table equality checks via `not exists(A diff B)`
354
- * **Robust transaction support** - Multi-level savepoints and rollback. See [Usage Guide](../../docs/usage.md#transactions) for details
355
- * **Rich built-in function library** - Scalar, aggregate, window, JSON, and date/time functions
356
-
357
- **Optimizer Status:**
358
-
359
- Quereus features a sophisticated rule-based query optimizer that transforms logical plans into efficient physical execution plans. The optimizer uses a single plan node hierarchy with logical-to-physical transformation, generic tree rewriting infrastructure, and comprehensive optimization rules including constant folding, intelligent caching, streaming aggregation, bloom (hash) join selection for equi-joins, and correlated subquery decorrelation (EXISTS/IN → semi/anti joins).
360
-
361
- See the [Optimizer Documentation](../../docs/optimizer.md) for architecture details and [Optimizer Conventions](../../docs/optimizer-conventions.md) for development guidelines.
362
- [TODO List](../../docs/todo.md) has remaining priorities.
363
-
364
- Recent changes:
365
- - Retrieve growth and push-down stabilized: query-based modules slide full nodes via `supports()`; index-style fallback injects supported-only fragments inside `Retrieve`, preserving residuals above.
366
- - Retrieve logical properties now expose `bindingsCount` and `bindingsNodeTypes` (visible in `query_plan().properties`) to aid verification that parameters/correlations are captured.
367
-
368
- ## Testing
369
-
370
- The tests are located in `test/*.spec.ts` and are driven by Mocha with ts-node/esm.
371
-
372
- ```bash
373
- yarn test
374
- ```
375
-
376
- Quereus employs a multi-faceted testing strategy:
377
-
378
- 1. **SQL Logic Tests (`test/logic/`)**:
379
- * Inspired by SQLite's own testing methodology.
380
- * Uses simple text files (`*.sqllogic`) containing SQL statements and their expected JSON results (using `→` marker) or expected error messages (using `-- error:` directive).
381
- * Driven by a Mocha test runner (`test/logic.spec.ts`) that executes the SQL against a fresh `Database` instance for each file.
382
- * **Configurable Diagnostics**: On unexpected failures, the test runner provides clean error messages by default with optional detailed diagnostics controlled by command line arguments:
383
- * `yarn test --verbose` - Show execution progress during tests
384
- * `yarn test --show-plan` - Include concise query plan in diagnostics
385
- * `yarn test --plan-full-detail` - Include full detailed query plan (JSON format)
386
- * `yarn test --plan-summary` - Show one-line execution path summary
387
- * `yarn test --expand-nodes node1,node2...` - Expand specific nodes in concise plan
388
- * `yarn test --max-plan-depth N` - Limit plan display depth
389
- * `yarn test --show-program` - Include instruction program in diagnostics
390
- * `yarn test --show-stack` - Include full stack trace in diagnostics
391
- * `yarn test --show-trace` - Include execution trace in diagnostics
392
- * `yarn test --trace-plan-stack` - Enable plan stack tracing in runtime
393
- * This helps pinpoint failures at the Parser, Planner, or Runtime layer while keeping output manageable.
394
- * Provides comprehensive coverage of SQL features: basic CRUD, complex expressions, all join types, window functions, aggregates, subqueries, CTEs, constraints, transactions, set operations, views, and error handling.
395
-
396
- 2. **Property-Based Tests (`test/property.spec.ts`)**:
397
- * Uses the `fast-check` library to generate a wide range of inputs for specific, tricky areas.
398
- * Focuses on verifying fundamental properties and invariants that should hold true across many different values.
399
- * Currently includes tests for:
400
- * **Collation Consistency**: Ensures `ORDER BY` results match the behavior of the `compareSqlValues` utility for `BINARY`, `NOCASE`, and `RTRIM` collations across various strings.
401
- * **Numeric Affinity**: Verifies that comparisons (`=`, `<`) in SQL handle mixed types (numbers, strings, booleans, nulls) consistently with SQLite's affinity rules, using `compareSqlValues` as the reference.
402
- * **JSON Roundtrip**: Confirms that arbitrary JSON values survive being processed by `json_quote()` and `json_extract('$')` without data loss or corruption.
403
- * **Mixed Type Arithmetic**: Checks that arithmetic on mixed types behaves consistently between SELECT and WHERE contexts.
404
- * **Parser Robustness**: Feeds random strings, SQL-like fragment mixtures, and random identifiers to the parser, asserting it either produces a valid AST or throws `QuereusError` — never unhandled exceptions.
405
- * **Expression Evaluation**: Compares random arithmetic expression trees and boolean comparisons evaluated in SQL against JS semantics.
406
- * **Comparison Properties**: Validates `compareSqlValues` maintains antisymmetry, reflexivity, and transitivity across mixed types.
407
- * **Insert/Select Roundtrip**: Tests value preservation through insert+select for INTEGER, REAL, TEXT, BLOB, and ANY column types.
408
- * **ORDER BY Determinism**: Verifies repeated ORDER BY queries on data with duplicate sort keys produce identical results.
409
-
410
- 3. **Performance Sentinels (`test/performance-sentinels.spec.ts`)**:
411
- * Micro-benchmarks with generous thresholds to catch severe performance regressions.
412
- * Currently includes sentinels for: parser throughput (simple, wide-SELECT, nested-expression), query execution (full table scan), and self-join (nested-loop baseline).
413
- * Thresholds are intentionally generous to avoid flakiness while still catching order-of-magnitude regressions.
414
-
415
- 4. **Unit Tests (`test/*.spec.ts`)**:
416
- * Dedicated unit tests for core subsystems: type system (`type-system.spec.ts`), schema manager (`schema-manager.spec.ts`), optimizer rules (`optimizer/*.spec.ts`), memory vtable (`memory-vtable.spec.ts`), utility functions (`utility-edge-cases.spec.ts`).
417
- * Integration boundary tests (`integration-boundaries.spec.ts`) verify all boundary transitions: Parser→Planner, Planner→Optimizer, Optimizer→Runtime, Runtime→VTab.
418
- * Golden plan tests (`plan/golden-plans.spec.ts`) use snapshot testing to detect unintended query plan changes.
419
-
420
- 5. **Benchmark Suite (`bench/`)**:
421
- * Standalone benchmark harness run via `yarn bench`. Measures parser, planner, execution, and mutation throughput across 18 benchmarks.
422
- * Records results to timestamped JSON files in `bench/results/` (gitignored).
423
- * `yarn bench --baseline <file>` compares against a previous result, color-codes regressions (>20% red) and improvements (>10% green), and exits non-zero on regressions.
424
-
425
- 6. **CI Integration (Planned)**:
426
- * Utilize GitHub Actions (or similar) to run test suites automatically, potentially with different configurations (quick checks, full runs, browser environment).
427
-
428
- This layered approach aims for broad coverage via the logic tests, unit tests for individual subsystems, property tests to explore edge cases, performance sentinels to guard against regressions, and a dedicated benchmark suite for tracking performance over time.
429
-
430
- ## Supported Built-in Functions
431
-
432
- * **Scalar:** `lower`, `upper`, `length`, `substr`/`substring`, `abs`, `round`, `coalesce`, `nullif`, `like`, `glob`, `typeof`
433
- * **Aggregate:** `count`, `sum`, `avg`, `min`, `max`, `group_concat`, `json_group_array`, `json_group_object`
434
- * **Window Functions:** Complete implementation with `row_number`, `rank`, `dense_rank`, `ntile` (ranking); `count`, `sum`, `avg`, `min`, `max` with OVER clause (aggregates); Full frame specification support (`ROWS BETWEEN`, `UNBOUNDED PRECEDING/FOLLOWING`); `NULLS FIRST/LAST` ordering
435
- * **Date/Time:** `date`, `time`, `datetime`, `julianday`, `strftime` (supports common formats and modifiers), `epoch_s`, `epoch_ms`, `epoch_s_frac` (Unix epoch conversions with strict parsing)
436
- * **JSON:** `json_valid`, `json_schema`, `json_type`, `json_extract`, `json_quote`, `json_array`, `json_object`, `json_insert`, `json_replace`, `json_set`, `json_remove`, `json_array_length`, `json_patch`
437
- * **Query Analysis:** `query_plan`, `scheduler_program`, `execution_trace` (debugging and performance analysis)
438
-
439
-
1
+ # Quereus - A TypeScript SQL Query Processor
2
+
3
+ <img src="../../docs/images/Quereus_colored_wide.svg" alt="Quereus Logo" height="150">
4
+
5
+ Quereus is a feature-complete SQL query processor specifically designed for efficient in-memory data processing with a strong emphasis on the **virtual table** interface. It provides rich SQL query and constraint capabilities (joins, aggregates, subqueries, CTEs, window functions, constraints) over data sources exposed via the virtual table mechanism. Quereus features a modern type system with temporal types, JSON support, and plugin-extensible custom types. It has no persistent file storage, though one could be built as a virtual table module.
6
+
7
+ ## Project Goals
8
+
9
+ * **Virtual Table Centric** provide a robust and flexible virtual table API as the primary means of interacting with data sources. All tables are virtual tables.
10
+ * **In-Memory Default** includes a comprehensive in-memory virtual table implementation (`MemoryTable`) with support for transactions and savepoints.
11
+ * **Modern Type System** extensible logical/physical type separation with built-in temporal types (DATE, TIME, DATETIME), native JSON type with deep equality comparison, and plugin support for custom types. See [Type System Documentation](../../docs/types.md).
12
+ * **TypeScript & Modern JS** leverage TypeScript's type system and modern JavaScript features and idioms.
13
+ * **Async VTab Operations** virtual table data operations (reads/writes) are asynchronous. Cursors are implemented as async iterables.
14
+ * **Cross-Platform** target diverse Javascript runtime environments, including Node.js, browser, and React Native. Plugin loading (via `@quereus/plugin-loader`) uses dynamic `import()` and is not compatible with React Native; use static imports for RN.
15
+ * **Minimal Dependencies** avoid heavy external dependencies where possible.
16
+ * **SQL Compatibility** comprehensive support for modern SQL features including joins, window functions, subqueries, CTEs, constraints, views, and advanced DML/DDL operations.
17
+ * **Key-Based Addressing** all tables are addressed by their defined Primary Key. The concept of a separate, implicit `rowid` for addressing rows is not used.
18
+ * **Third Manifesto Friendly** embraces some of the principles of the [Third Manifesto](https://www.dcs.warwick.ac.uk/~hugh/TTM/DTATRM.pdf), such as allowing for empty keys. Utilizes algebraic planning.
19
+
20
+ ## Quick Start
21
+
22
+ ```typescript
23
+ import { Database } from '@quereus/quereus';
24
+
25
+ const db = new Database();
26
+
27
+ // Create a table and insert data
28
+ await db.exec("create table users (id integer primary key, name text, email text)");
29
+ await db.exec("insert into users values (1, 'Alice', 'alice@example.com')");
30
+
31
+ // Query returns objects: { id: 1, name: 'Alice', email: 'alice@example.com' }
32
+ const user = await db.get("select * from users where id = ?", [1]);
33
+ console.log(user.name); // "Alice"
34
+
35
+ // Iterate over multiple rows
36
+ for await (const row of db.eval("select * from users")) {
37
+ console.log(row.name);
38
+ }
39
+ ```
40
+
41
+ ### Reactive Patterns with Event Hooks
42
+
43
+ ```typescript
44
+ import { Database } from '@quereus/quereus';
45
+
46
+ const db = new Database();
47
+
48
+ // Subscribe to data changes at the database level
49
+ db.onDataChange((event) => {
50
+ console.log(`${event.type} on ${event.tableName} (module: ${event.moduleName})`);
51
+ if (event.remote) {
52
+ console.log('Change came from remote sync');
53
+ }
54
+ if (event.type === 'update') {
55
+ console.log('Changed columns:', event.changedColumns);
56
+ }
57
+ });
58
+
59
+ // Subscribe to schema changes
60
+ db.onSchemaChange((event) => {
61
+ console.log(`${event.type} ${event.objectType}: ${event.objectName}`);
62
+ });
63
+
64
+ // Events fire after commit
65
+ await db.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");
66
+ // Output: create table: users
67
+
68
+ await db.exec("INSERT INTO users VALUES (1, 'Alice')");
69
+ // Output: insert on users (module: memory)
70
+ ```
71
+
72
+ The database-level event system aggregates events from all modules automatically. Events are batched within transactions and delivered only after successful commit.
73
+
74
+ SQL values use native JavaScript types (`string`, `number`, `bigint`, `Uint8Array`, `null`). Temporal types are ISO 8601 strings. Results stream as async iterators.
75
+
76
+ See the [Usage Guide](../../docs/usage.md) for complete API reference and [Module Authoring Guide](../../docs/module-authoring.md) for event system details.
77
+
78
+ ## Platform Support & Storage
79
+
80
+ Quereus runs on any JavaScript runtime. For persistent storage, platform-specific plugins provide the `store` virtual table module:
81
+
82
+ ### Node.js
83
+
84
+ Use [`@quereus/plugin-leveldb`](../quereus-plugin-leveldb/) for LevelDB-based persistent storage with full transaction isolation. Each table becomes a subdirectory under `basePath`:
85
+
86
+ ```typescript
87
+ import { Database, registerPlugin } from '@quereus/quereus';
88
+ import leveldbPlugin from '@quereus/plugin-leveldb/plugin';
89
+
90
+ const db = new Database();
91
+ await registerPlugin(db, leveldbPlugin, { basePath: './data' }); // ./data/users/, ./data/orders/, etc.
92
+
93
+ await db.exec(`create table users (id integer primary key, name text) using store`);
94
+
95
+ // Full transaction isolation enabled by default
96
+ await db.exec('BEGIN');
97
+ await db.exec(`INSERT INTO users VALUES (1, 'Alice')`);
98
+ const user = await db.get('SELECT * FROM users WHERE id = 1'); // Sees uncommitted insert
99
+ await db.exec('COMMIT');
100
+ ```
101
+
102
+ ### Browser
103
+
104
+ Use [`@quereus/plugin-indexeddb`](../quereus-plugin-indexeddb/) for IndexedDB-based persistent storage with cross-tab sync and full transaction isolation. All tables share one IndexedDB database:
105
+
106
+ ```typescript
107
+ import { Database, registerPlugin } from '@quereus/quereus';
108
+ import indexeddbPlugin from '@quereus/plugin-indexeddb/plugin';
109
+
110
+ const db = new Database();
111
+ await registerPlugin(db, indexeddbPlugin, { databaseName: 'myapp' }); // IndexedDB database name
112
+
113
+ await db.exec(`create table users (id integer primary key, name text) using store`);
114
+ ```
115
+
116
+ ### React Native
117
+
118
+ Use [`@quereus/plugin-react-native-leveldb`](../quereus-plugin-react-native-leveldb/) for fast LevelDB storage with full transaction isolation. Each table becomes a separate LevelDB database with a name prefix:
119
+
120
+ ```typescript
121
+ import { LevelDB, LevelDBWriteBatch } from 'react-native-leveldb';
122
+ import { Database, registerPlugin } from '@quereus/quereus';
123
+ import leveldbPlugin from '@quereus/plugin-react-native-leveldb/plugin';
124
+
125
+ const db = new Database();
126
+ await registerPlugin(db, leveldbPlugin, {
127
+ openFn: LevelDB.open,
128
+ WriteBatch: LevelDBWriteBatch,
129
+ databaseName: 'myapp' // creates myapp_users, myapp_orders, etc.
130
+ });
131
+
132
+ await db.exec(`create table users (id integer primary key, name text) using store`);
133
+ ```
134
+
135
+ **Note:** React Native requires runtime polyfills and static plugin loading. See the [plugin README](../quereus-plugin-react-native-leveldb/) for setup details.
136
+
137
+ **Required polyfills:**
138
+ - `structuredClone` (Quereus uses it internally)
139
+ - `TextEncoder` / `TextDecoder` (used by store plugins)
140
+ - `Symbol.asyncIterator` (required for async-iterable support; Quereus has a Hermes workaround for AsyncGenerator iterables, but the symbol must exist)
141
+
142
+ ### NativeScript
143
+
144
+ Use [`@quereus/plugin-nativescript-sqlite`](../quereus-plugin-nativescript-sqlite/) for SQLite-based storage with full transaction isolation. All tables share one SQLite database file:
145
+
146
+ ```typescript
147
+ import { openOrCreate } from '@nativescript-community/sqlite';
148
+ import { Database, registerPlugin } from '@quereus/quereus';
149
+ import sqlitePlugin from '@quereus/plugin-nativescript-sqlite/plugin';
150
+
151
+ const sqliteDb = openOrCreate('myapp.db'); // SQLite database file
152
+ const db = new Database();
153
+ await registerPlugin(db, sqlitePlugin, { db: sqliteDb });
154
+
155
+ await db.exec(`create table users (id integer primary key, name text) using store`);
156
+ ```
157
+
158
+ See [Store Documentation](../../docs/store.md) for the storage architecture and custom backend implementation.
159
+
160
+ ## Documentation
161
+
162
+ **Architecture deep dive:** [Architecture](../../docs/architecture.md) — the pipeline (parser → planner → runtime), source layout, extension patterns, design decisions, constraints model, and testing strategy. Start here if you're working on the engine itself.
163
+
164
+ **User & operator docs:**
165
+ * [Usage Guide](../../docs/usage.md) — complete API reference (type mappings, parameter binding, logging, tracing, transactions)
166
+ * [SQL Reference Guide](../../docs/sql.md) SQL syntax (includes Declarative Schema)
167
+ * [Schema Management](../../docs/schema.md) SchemaManager API, change events, key types, DDL generation
168
+ * [Type System](../../docs/types.md) — logical/physical types, temporal types, JSON, custom types
169
+ * [Functions](../../docs/functions.md) — built-in scalar, aggregate, window, and JSON functions
170
+ * [Memory Tables](../../docs/memory-table.md) built-in MemoryTable module
171
+ * [Module Authoring](../../docs/module-authoring.md) — virtual table module development and event system
172
+ * [Date/Time Handling](../../docs/datetime.md) temporal parsing, functions, and ISO 8601 formats
173
+ * [Runtime](../../docs/runtime.md) — instruction-based execution and opcodes
174
+ * [Error Handling](../../docs/errors.md) error types and status codes
175
+ * [Plugin System](../../docs/plugins.md) — virtual tables, functions, and collations
176
+ * [Optimizer](../../docs/optimizer.md) / [Optimizer Conventions](../../docs/optimizer-conventions.md)
177
+ * [TODO List](../../docs/todo.md) — planned features
178
+
179
+ ### Plugin Development
180
+
181
+ Quereus exports all critical utilities needed for plugin and module development:
182
+
183
+ * **Comparison Functions** — `compareSqlValues`, `compareRows`, `compareTypedValues`, `createTypedComparator` — match Quereus SQL semantics in custom implementations
184
+ * **Coercion Utilities** — `tryCoerceToNumber`, `coerceForAggregate` — handle type coercion for aggregates and arithmetic
185
+ * **Collation Support** `registerCollation`, `getCollation`, built-in collations (`BINARY_COLLATION`, `NOCASE_COLLATION`, `RTRIM_COLLATION`)
186
+ * **Type System** — full access to logical types, validation, and parsing utilities
187
+ * **Event Hooks** — `VTableEventEmitter` interface for mutation and schema change events; enable reactive patterns, caching, and replication
188
+ * **DDL Generation** — `generateTableDDL(tableSchema, db?)`, `generateIndexDDL(indexSchema, tableSchema, db?)` — canonical `CREATE TABLE` / `CREATE INDEX` output from runtime schema objects. With a `Database`, matches session defaults (schema qualification, `default_column_nullability`, `default_vtab_module`/`default_vtab_args`) for readable output; without one, emits fully-qualified, explicitly-annotated DDL safe for cross-session persistence. See [Schema Management — DDL Generation](../../docs/schema.md#ddl-generation).
189
+
190
+ See the [Plugin System documentation](../../docs/plugins.md#comparison-and-coercion-utilities) for complete API reference and examples.
191
+
192
+ ## Current Status
193
+
194
+ Quereus is a feature-complete SQL query processor with a modern planner and instruction-based runtime architecture. The engine successfully handles complex SQL workloads including joins, window functions, subqueries, CTEs, constraints, and comprehensive DML/DDL operations.
195
+
196
+ **Current capabilities include:**
197
+ * **Modern Type System** — temporal types (DATE, TIME, DATETIME), JSON with deep equality, plugin-extensible custom types
198
+ * **Complete JOIN support** — INNER, LEFT, RIGHT, CROSS, SEMI, and ANTI joins with proper NULL padding
199
+ * **Advanced window functions** — ranking, aggregates, and frame specifications
200
+ * **Full constraint system** — NOT NULL, CHECK, FOREIGN KEY, and CREATE ASSERTION. Row-level constraints that reference other tables are automatically deferred to COMMIT. The `committed.tablename` pseudo-schema provides read-only access to pre-transaction state for transition constraints (e.g., "balance may not decrease"). See [Architecture — Constraints](../../docs/architecture.md#constraints).
201
+ * **Comprehensive subqueries** — scalar, correlated, EXISTS, and IN subqueries
202
+ * **Relational orthogonality** — INSERT/UPDATE/DELETE with RETURNING can be used as table sources
203
+ * **Complete set operations** — UNION, INTERSECT, EXCEPT with proper deduplication
204
+ * **DIFF (symmetric difference)** — `A diff B` equals `(A except B) union (B except A)`, handy for table equality checks via `not exists(A diff B)`
205
+ * **Robust transaction support** multi-level savepoints and rollback. See [Usage Guide](../../docs/usage.md#transactions) for details
206
+ * **Rich built-in function library** — scalar, aggregate, window, JSON, and date/time functions
207
+ * **Rule-based optimizer** — constant folding, caching, streaming aggregation, bloom-join selection, and correlated subquery decorrelation. See [Architecture — Optimizer](../../docs/architecture.md#optimizer).
208
+
209
+ [TODO List](../../docs/todo.md) has remaining priorities.
210
+
211
+ ## Supported Built-in Functions
212
+
213
+ * **Scalar** — `lower`, `upper`, `length`, `substr`/`substring`, `abs`, `round`, `coalesce`, `nullif`, `like`, `glob`, `typeof`
214
+ * **Aggregate** `count`, `sum`, `avg`, `min`, `max`, `group_concat`, `json_group_array`, `json_group_object`
215
+ * **Window Functions** — complete implementation with `row_number`, `rank`, `dense_rank`, `ntile` (ranking); `count`, `sum`, `avg`, `min`, `max` with OVER clause (aggregates); full frame specification support (`ROWS BETWEEN`, `UNBOUNDED PRECEDING/FOLLOWING`); `NULLS FIRST/LAST` ordering
216
+ * **Date/Time** `date`, `time`, `datetime`, `julianday`, `strftime` (supports common formats and modifiers), `epoch_s`, `epoch_ms`, `epoch_s_frac` (Unix epoch conversions with strict parsing)
217
+ * **JSON** — `json_valid`, `json_schema`, `json_type`, `json_extract`, `json_quote`, `json_array`, `json_object`, `json_insert`, `json_replace`, `json_set`, `json_remove`, `json_array_length`, `json_patch`
218
+ * **Query Analysis** — `query_plan`, `scheduler_program`, `execution_trace` (debugging and performance analysis)
219
+
220
+ ## Testing
221
+
222
+ Tests live in `test/*.spec.ts`, driven by Mocha with ts-node/esm. Run with `yarn test`. Quereus uses SQL logic tests (primary), property-based tests, performance sentinels, unit tests, and a benchmark suite — see [Architecture — Testing Strategy](../../docs/architecture.md#testing-strategy) for details.