diff --git a/docs/storage/SINGLE_FILE_SQL_LIMITATIONS.md b/docs/storage/SINGLE_FILE_SQL_LIMITATIONS.md index 88e598a0..16fcfed0 100644 --- a/docs/storage/SINGLE_FILE_SQL_LIMITATIONS.md +++ b/docs/storage/SINGLE_FILE_SQL_LIMITATIONS.md @@ -1,231 +1,200 @@ # SingleFileDatabase SQL Support -**Applies to:** SharpCoreDB v1.8.x+ — `.scdb` single-file mode (`StorageMode.SingleFile`) +**Applies to:** SharpCoreDB 2.3.x — `.scdb` single-file mode (`DatabaseOptions.CreateSingleFileDefault()`) **and** +directory mode (`DatabaseFactory.Create`), because the two are described together below. -> **TL;DR:** Both `SingleFileDatabase` (`.scdb`) and `Database` (directory mode) share the same -> `SqlParser` engine for DML and SELECT. DDL in single-file mode uses an internal regex path that -> now covers the same core operations as directory mode, including `ALTER TABLE` with -> `ADD COLUMN`, `DROP COLUMN`, `RENAME COLUMN`, `RENAME TO`, `CREATE INDEX`, and `DROP INDEX`. -> Since issue #546 every one of those `ALTER TABLE` forms is **written to the file** — the rows are -> re-serialized in the new shape, the column block and the directory entry are rewritten, and -> `RENAME TO` moves the name-keyed blocks — so a schema change survives a reopen instead of -> reverting to the schema the file was created with. +> **How this file is kept honest:** every row in the matrices was **executed** on 2026-12-06 against both storage +> modes (same DDL, same rows, same statements; a `.scdb` file and a directory database side by side), not read off the +> parser source. Re-run the matrix before turning a ✅ into a ⛔ or the reverse. The probe found five claims in the +> previous version of this file that were **wrong**, and four engine defects that are recorded as **Verified gaps** +> below and tracked in [#580](https://github.com/MPCoreDeveloper/SharpCoreDB/issues/580) — that is why the rows carry +> the observed behaviour and not an intention. --- -## Architecture Overview +## TL;DR + +Both modes share the **same** `SqlParser` for DML and SELECT; DDL goes through each mode's own entry point (the +directory-mode `SqlParser.DDL.cs`, the single-file regex path in `DatabaseExtensions.cs`). The parity is real and +measured: `JOIN` (INNER/LEFT/RIGHT/FULL), `GROUP BY`, `HAVING`, subqueries in `FROM` and `WHERE`, aggregates, window +functions, `UNION`, `CASE`, `DISTINCT`, `LIKE`, `IN`, `BETWEEN`, `IS [NOT] NULL`, `ORDER BY`, `LIMIT`/`OFFSET`, every +`ALTER TABLE` form and `DELETE`/`UPDATE` without `WHERE` all return the same rows in both modes. + +What is **not** at parity is narrower than the previous version of this file claimed: a view cannot be queried in +either mode, `sqlite_master` answers on directory mode only, an aggregate over a column that holds a `NULL` throws on +both, and `WHERE` comparisons that meet a `NULL` disagree between the two modes — details in **Verified gaps**. + +--- -SharpCoreDB exposes one `IDatabase` interface with two concrete implementations: +## Architecture Overview -| Class | Mode | File extension | SQL engine (DML/SELECT) | SQL engine (DDL) | +| Class | Mode | Storage | SQL engine (DML/SELECT) | SQL engine (DDL) | |---|---|---|---|---| -| `Database` | Directory | `.db` folder | `SqlParser` — full featured | `SqlParser.DDL.cs` | -| `SingleFileDatabase` | Single-file | `.scdb` | `SqlParser` (shared) | Regex path in `DatabaseExtensions.cs` | +| `Database` | Directory | `/` folder | `SqlParser` (shared) | `SqlParser.DDL.cs` | +| `SingleFileDatabase` | Single-file | `.scdb` | `SqlParser` (shared) | Regex path in `DatabaseExtensions.cs` | -Both modes support the same DDL feature set for `CREATE TABLE`, `DROP TABLE`, `ALTER TABLE`, -`CREATE INDEX`, and `DROP INDEX`. The only DDL statements not yet supported in single-file mode -are `CREATE VIEW`, `CREATE TRIGGER`, and `STORAGE = COLUMNAR` hints (directory-mode only). +Both delegate column mutations (`ADD COLUMN`, `DROP COLUMN`, `RENAME COLUMN`) through the shared `ITable` interface, so +a schema change behaves the same regardless of storage backend — and, since issue #546, persists on both: the rows are +re-serialized in the new shape, the column block and the directory entry are rewritten, and `RENAME TO` moves the +name-keyed blocks, so the change survives a reopen. --- -## SQL Support Matrix +## SQL Support Matrix (measured 2026-12-06) -### DDL (CREATE / DROP / ALTER) +### DDL | Statement | Single-File | Directory | Notes | |---|---|---|---| | `CREATE TABLE` | ✅ | ✅ | Quoted identifiers supported | | `CREATE TABLE IF NOT EXISTS` | ✅ | ✅ | | -| `DROP TABLE` | ✅ | ✅ | Quoted identifiers supported | -| `DROP TABLE IF EXISTS` | ✅ | ✅ | | -| `CREATE INDEX` | ✅ | ✅ | Tracked for `IndexExists()` probes | -| `CREATE UNIQUE INDEX` | ✅ | ✅ | | +| `DROP TABLE` / `DROP TABLE IF EXISTS` | ✅ | ✅ | Quoted identifiers supported | +| `CREATE [UNIQUE] INDEX` | ✅ | ✅ | Tracked for `IndexExists()` probes | | `DROP INDEX` | ✅ | ✅ | | -| `ALTER TABLE ... RENAME TO` | ✅ | ✅ | Persisted — the name-keyed blocks move and the old name's are removed | -| `ALTER TABLE ... ADD COLUMN` | ✅ | ✅ | Persisted; reads `NOT NULL`, `UNIQUE`, `AUTO`, `PRIMARY KEY`, `COLLATE …` and `DEFAULT …`, and rejects `NOT NULL` without a default on a non-empty table | -| `ALTER TABLE ... RENAME COLUMN ... TO` | ✅ | ✅ | Persisted — updates schema, row data, unique constraints and foreign keys | -| `ALTER TABLE ... DROP COLUMN` | ✅ | ✅ | Persisted — removes the column and its value from every row | -| `CREATE TRIGGER` | ⚠️ silently ignored | ✅ | | -| `DROP TRIGGER` | ⚠️ silently ignored | ✅ | | -| `CREATE VIEW` | ❌ not supported | ✅ | | -| `STORAGE = COLUMNAR` | ❌ not supported | ✅ | Directory mode only | +| `ALTER TABLE … RENAME TO` | ✅ | ✅ | Persisted — the name-keyed blocks move | +| `ALTER TABLE … ADD COLUMN` | ✅ | ✅ | Persisted; reads `NOT NULL`, `UNIQUE`, `AUTO`, `PRIMARY KEY`, `COLLATE`, `DEFAULT`; rejects `NOT NULL` without a default on a non-empty table | +| `ALTER TABLE … RENAME COLUMN … TO` | ✅ | ✅ | Persisted — schema, rows, unique constraints and foreign keys updated | +| `ALTER TABLE … DROP COLUMN` | ✅ | ✅ | Persisted — removes the column and its value from every row | +| `CREATE VIEW` / `DROP VIEW` | ✅ accepted | ✅ accepted | The view is registered (`information_schema.tables` reports `table_type = VIEW`) but **cannot be queried**: `SELECT … FROM ` answers `Table does not exist` in both modes — gap 1 | +| `CREATE TRIGGER` / `DROP TRIGGER` | ⚠️ accepted, ignored | ⚠️ accepted, ignored | Neither mode runs a trigger; the statement does not throw | +| `STORAGE = COLUMNAR` | ⚠️ accepted, hint ignored | ✅ accepted | Single-file has one storage layout, so the hint cannot apply; the table is created normally (**verified**: it exists in both modes) | | Column types | ✅ | ✅ | INTEGER, TEXT, REAL, DECIMAL, DATETIME, BLOB, BOOLEAN, LONG, GUID/UUID, ULID | | `PRIMARY KEY`, `NOT NULL`, `AUTOINCREMENT` | ✅ | ✅ | | | `UNIQUE` column constraint | ✅ | ✅ | | | `DEFAULT` with comma-containing expressions | ✅ | ✅ | Quote-aware splitter | -| `FOREIGN KEY` | ⚠️ parsed, not enforced | ⚠️ parsed, not enforced | | -| `CHECK` constraint | ⚠️ parsed, not enforced | ⚠️ parsed, not enforced | | +| `FOREIGN KEY` | ⚠️ parsed, not enforced | ⚠️ parsed, not enforced | Reported by `GetConstraints` / `information_schema`; no referential enforcement yet | +| `CHECK` constraint | ⚠️ parsed, not enforced | ⚠️ parsed, not enforced | Same: metadata yes, enforcement no | -### Schema Introspection (FluentMigrator / migration tools) +### DML — INSERT / UPDATE / DELETE + +| Feature | Single-File | Directory | Notes | +|---|---|---|---| +| `INSERT INTO t VALUES (…)` | ✅ | ✅ | | +| `INSERT INTO t (cols) VALUES (…)` | ✅ | ✅ | | +| Multi-row `INSERT … VALUES (…), (…)` | ✅ | ✅ | | +| `UPDATE t SET col = val WHERE …` | ✅ | ✅ | | +| `UPDATE` without `WHERE` | ✅ | ✅ | Updates all rows | +| Expressions in `SET` (`col = col + 1`) | ✅ | ✅ | | +| `DELETE FROM t WHERE …` | ✅ | ✅ | | +| `DELETE FROM t` (no `WHERE`) | ✅ | ✅ | Deletes all rows | +| Parameterized queries (`@param`, `?`) | ✅ | ✅ | | +| `INSERT OR IGNORE` / `INSERT OR REPLACE` / `REPLACE INTO` | ⛔ `Unsupported SQL statement: INSERT OR` | ⛔ same | **Not supported in either mode** — the previous version of this file said ✅. `ON CONFLICT DO NOTHING` is not honoured either (the insert raises a key violation), so `SELECT` first or catch it | +| `BEGIN` / `COMMIT` / `ROLLBACK` / `SAVEPOINT` as SQL | ⛔ `Unsupported SQL statement` | ⛔ `Unsupported SQL statement` | **Not** "silently ignored": the statement is rejected in both modes. Use the API — `SharpCoreDBTransaction`, or gRPC `BeginTransaction`/`CommitTransaction`/`RollbackTransaction` — not SQL text | + +### SELECT — Query + +Identical in both modes (measured row-for-row): + +| Feature | Notes | +|---|---| +| `SELECT *`, `SELECT col1, col2` | ✅ | +| `WHERE` with `=`, `<>`, `!=`, `<`, `>`, `<=`, `>=` | ✅ — but see gap 2 when a `NULL` is involved | +| `WHERE` with `AND` / `OR` | ✅ | +| `ORDER BY col ASC/DESC` | ✅ (a `NULL` participates as a value — gap 2) | +| `LIMIT` / `OFFSET`, `LIMIT -1 OFFSET n` | ✅ | +| `INNER JOIN`, `LEFT JOIN`, `RIGHT JOIN`, `FULL OUTER JOIN` | ✅ | +| `GROUP BY`, `HAVING` | ✅ | +| Aggregates `COUNT` / `SUM` / `MIN` / `MAX` / `AVG` | ✅ — but see gap 3 for a column that contains `NULL` | +| Window functions (`ROW_NUMBER() OVER …`) | ✅ | +| `UNION` | ✅ | +| `CASE … WHEN … END` | ✅ | +| `DISTINCT`, column aliases (`AS`) | ✅ | +| `IS NULL` / `IS NOT NULL` | ✅ | +| `LIKE` / `NOT LIKE` | ✅ — case-insensitive, `%`/`_`, `NULL` never matches (covered by `SingleFileDirectoryParityTests`) | +| `IN (…)`, `BETWEEN x AND y` | ✅ — `BETWEEN` inclusive; `NOT IN` with a `NULL` differs, gap 2 | +| Subqueries in `FROM` and in `WHERE` | ✅ | +| `EXPLAIN` | ⚠️ accepted, returns **0 rows** in both modes — there is no serializable plan contract yet (issue #569) | + +### Schema introspection | Query | Single-File | Directory | Notes | |---|---|---|---| -| `PRAGMA table_info(tableName)` | ✅ | ✅ | Returns column metadata | -| `SELECT ... FROM sqlite_master WHERE type='index'` | ✅ | ✅ | Index existence checks | -| `sqlite_schema` alias | ✅ | ✅ | Synonym for `sqlite_master` | +| `PRAGMA table_info(tableName)` | ✅ | ✅ | SQLite's row shape; a primary key reports `notnull=1` | +| `SELECT … FROM information_schema.tables` | ✅ | ✅ | Includes views with `table_type = VIEW` | +| `SELECT … FROM information_schema.columns` | ✅ | ✅ | Includes a view's derived columns (issue #570) | +| `SELECT … FROM sqlite_master …` | ⛔ returns **0 rows** | ✅ | **Not** ✅ as the previous version said — gap 4 | +| `sqlite_schema` alias | ⛔ returns 0 rows | ⛔ throws `Table sqlite_schema does not exist` | Neither mode answers the alias — gap 4 | -### DML — INSERT / UPDATE / DELETE +### Verified gaps (measured 2026-12-06) -All DML is routed through the shared `SqlParser`, which means the same feature set as directory mode: - -| Feature | Supported | Notes | -|---|---|---| -| `INSERT INTO t VALUES (...)` | ✅ | | -| `INSERT INTO t (cols) VALUES (...)` | ✅ | | -| `INSERT OR IGNORE` | ✅ | | -| `INSERT OR REPLACE` | ✅ | | -| Multi-row `INSERT INTO t VALUES (...),(...)` | ✅ | | -| `UPDATE t SET col = val WHERE ...` | ✅ | | -| `UPDATE` without `WHERE` | ✅ | Updates all rows | -| Expressions in SET (`col = col + 1`) | ✅ | | -| `DELETE FROM t WHERE ...` | ✅ | | -| `DELETE FROM t` (no WHERE) | ✅ | Deletes all rows | -| Parameterized queries (`@param`, `?`) | ✅ | | +**Gap 1 — a view cannot be queried, in either mode.** `CREATE VIEW` / `DROP VIEW` are accepted and the object is +reported by `information_schema.tables` (`table_type = VIEW`) with its derived columns, but `SELECT … FROM ` +answers `Table does not exist`. A studio may list a view; it must not offer "preview" until `FROM`-expansion +lands. -### SELECT — Query +**Gap 2 — `WHERE` predicates that meet a `NULL` disagree between the modes, and both depart from SQL's three-valued +logic.** Rows: `(1, 'Ann', 30)`, `(2, 'Bob', 40)`, `(3, 'Cid', NULL)`. -All SELECT is routed through the shared `SqlParser`: - -| Feature | Supported | Notes | -|---|---|---| -| `SELECT * FROM t` | ✅ | | -| `SELECT col1, col2 FROM t` | ✅ | | -| `WHERE` with `=`, `<>`, `<`, `>`, `<=`, `>=` | ✅ | | -| `WHERE` with `AND` / `OR` | ✅ | | -| `ORDER BY col ASC/DESC` | ✅ | | -| `LIMIT` / `OFFSET` | ✅ | | -| `INNER JOIN` | ✅ | | -| `LEFT JOIN` | ✅ | | -| `RIGHT JOIN` / `FULL OUTER JOIN` | ✅ | Via EnhancedSqlParser | -| `GROUP BY` | ✅ | | -| `HAVING` | ✅ | | -| Aggregate functions (`COUNT`, `SUM`, `MIN`, `MAX`, `AVG`) | ✅ | | -| `DISTINCT` | ✅ | | -| Column aliases (`col AS alias`) | ✅ | | -| `IS NULL` / `IS NOT NULL` | ✅ | | -| `LIKE` / `NOT LIKE` | ✅ | Case-insensitive; `%` / `_` patterns; NULL never matches | -| `IN (...)` | ✅ | | -| `BETWEEN x AND y` | ✅ | Inclusive; numeric culture-independent comparison | -| Subqueries in `FROM` / `WHERE` | ✅ | Via EnhancedSqlParser | -| `EXPLAIN` | ✅ | | - -> **WHERE operator parity (v1.9.x):** single-file mode now matches directory mode for the full -> operator set, including `LIKE`, `IS NULL` / `IS NOT NULL` and `BETWEEN`. Results are -> byte-identical to directory mode (covered by `SingleFileDirectoryParityTests`). - -### Transactions - -| Feature | Supported | Notes | -|---|---|---| -| `BEGIN` / `COMMIT` / `ROLLBACK` | ⚠️ silently ignored | Single-file storage auto-flushes | -| `SAVEPOINT` | ❌ | Not supported | +| Predicate | Directory rows | Single-file rows | SQL standard | +|---|---|---|---| +| `age <> 30` | 2 (Bob **and Cid**) | 1 (Bob) | 1 | +| `age != 30` | 2 | 1 | 1 | +| `age < 40` | 2 (Ann **and Cid**) | 1 (Ann) | 1 | +| `NOT (age = 30)` | 3 (**all**) | 0 | 1 (Bob) | +| `NOT age = 30` | 0 | 0 | parenthesise the predicate | +| `age NOT IN (30)` | 2 (**incl. Cid**) | 2 (**incl. Cid**) | 1 | +| `age <> 30 AND age IS NOT NULL` | 1 | 1 | 1 | + +Practical rule today: **add `AND col IS NOT NULL`** when a predicate can meet a `NULL` — that form is identical in both +modes — and do not rely on `NOT (…)` or `NOT IN` around a nullable column until this is fixed. `IS NULL` / `IS NOT +NULL` themselves are correct in both modes. + +**Gap 3 — `SUM` / `AVG` / `MIN` / `MAX` over a column that contains a `NULL` throws.** Both modes answer +`InvalidCastException: Object cannot be cast from DBNull to other types`; `COUNT(*)` and `COUNT(col)` are fine. +Workaround: filter with `WHERE col IS NOT NULL`, or aggregate a `CAST` (`SUM(CAST(col AS INTEGER))` did not throw in +the probe — a mitigation, not a contract). + +**Gap 4 — `sqlite_master` / `sqlite_schema`.** Directory mode answers `sqlite_master`; single-file mode returns **0 +rows**. The `sqlite_schema` alias throws on directory mode and returns 0 rows on single-file. Use +`information_schema.tables` / `information_schema.columns`, which are correct on both. --- -## Practical Impact: FluentMigrator - -All typical FluentMigrator migration operations work identically against both modes: - -| FluentMigrator operation | Works in `.scdb`? | Works in `.db`? | -|---|---|---| -| `Create.Table(...)` | ✅ | ✅ | -| `Delete.Table(...)` | ✅ | ✅ | -| `Create.Index(...)` | ✅ | ✅ | -| `Delete.Index(...)` | ✅ | ✅ | -| `Alter.Table(...).AddColumn(...)` | ✅ | ✅ | -| `Alter.Table(...).AlterColumn(...)` | ✅ | ✅ | -| `Rename.Column(...).OnTable(...)` | ✅ | ✅ | -| `Insert.IntoTable(...).Row(...)` | ✅ | ✅ | -| `Update.Table(...).Set(...).Where(...)` | ✅ | ✅ | -| `Delete.FromTable(...)` | ✅ | ✅ | -| `Create.ForeignKey(...)` | ⚠️ parsed, not enforced | ⚠️ parsed, not enforced | -| Version table creation (`__SharpMigrations`) | ✅ | ✅ | -| `Delete.FromTable(...).Row(...)` | ✅ | -| `Delete.FromTable(...)` (no condition) | ✅ (v1.8+ via SqlParser) | -| `Create.Index(...)` | ⚠️ silently ignored | -| `Create.ForeignKey(...)` | ⚠️ silently ignored | -| Version table creation (`__SharpMigrations`) | ✅ | +## Practical impact: FluentMigrator + +| FluentMigrator operation | `.scdb` | directory | Notes | +|---|---|---|---| +| `Create.Table`, `Delete.Table` | ✅ | ✅ | | +| `Create.Index`, `Delete.Index` | ✅ | ✅ | Single-file records the index for `IndexExists()`; it does not create a physical index | +| `Alter.Table(...).AddColumn / AlterColumn` | ✅ | ✅ | | +| `Rename.Column(...).OnTable(...)` | ✅ | ✅ | | +| `Insert.IntoTable(...).Row(...)` | ✅ | ✅ | | +| `Update.Table(...).Set(...).Where(...)` | ✅ | ✅ | | +| `Delete.FromTable(...)` (with or without a condition) | ✅ | ✅ | | +| `Create.ForeignKey(...)` | ⚠️ parsed, not enforced | ⚠️ parsed, not enforced | | +| Version table creation (`__SharpMigrations`) | ✅ | ✅ | | --- ## Choosing the Right Mode ``` -Need COLUMNAR storage mode, Triggers, or Views? - → Use Directory mode (Database class, .db folder) - -Need encrypted portable single-file storage? - → Use SingleFile mode (SingleFileDatabase, .scdb) - → Full DDL parity with directory mode for all common operations - → Full INSERT/UPDATE/DELETE/SELECT via shared SqlParser +Need a portable, encrypted single file? → SingleFile mode (.scdb) +Need COLUMNAR/page-based storage hints? → Directory mode (the hint is accepted and ignored on .scdb) +Need a trigger to run? → neither mode runs one today +Need to query a view? → neither mode can yet (gap 1) +Need sqlite_master? → Directory mode (gap 4); information_schema works on both ``` -### Directory mode - ```csharp -var db = factory.Create("myapp", "password"); // creates myapp/ folder -db.ExecuteSQL("ALTER TABLE users RENAME COLUMN name TO full_name"); -db.ExecuteSQL("ALTER TABLE users DROP COLUMN temp_col"); +var singleFile = factory.CreateWithOptions("myapp.scdb", "password", DatabaseOptions.CreateSingleFileDefault()); +var directory = factory.Create("myapp", "password"); ``` -### Single-file mode - -```csharp -var db = factory.CreateWithOptions("myapp.scdb", "password", DatabaseOptions.CreateSingleFileDefault()); - -// All of these work identically in single-file mode: -db.ExecuteSQL("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"); -db.ExecuteSQL("ALTER TABLE users ADD COLUMN email TEXT"); -db.ExecuteSQL("ALTER TABLE users RENAME COLUMN name TO full_name"); -db.ExecuteSQL("ALTER TABLE users DROP COLUMN email"); -db.ExecuteSQL("CREATE INDEX idx_name ON users (full_name)"); - -var results = db.ExecuteQuery("SELECT * FROM users WHERE full_name LIKE 'A%' ORDER BY id LIMIT 10"); -var joined = db.ExecuteQuery("SELECT u.full_name, o.total FROM users u JOIN orders o ON u.id = o.user_id"); -``` - -### Bulk inserts: use `ExecuteBatchSQL`, because one `ExecuteSQL` per statement is quadratic +### Bulk inserts: prefer `ExecuteBatchSQL` The single-file table keeps a table's rows in **one block** and rewrites that block on every flush, so a loop of -individual `ExecuteSQL` inserts pays for the whole table on every statement — O(n²) in the row count. `ExecuteBatchSQL` -is the supported fast path: it disables auto-flush for the duration, begins a block-registry batch and flushes once per -table. - -Measured 2026-09-22 with `SharpCoreDB.Benchmarks.Comparative --scdb` (2,000 rows, `INSERT … VALUES` with 1,000 rows per -statement, median of 5, `FixedWidthInlineValueBytes` at the shipped default 24): - -| How the statements are issued | rows/s | µs/row | allocated/row | -|---|---:|---:|---:| -| `ExecuteSQL` per statement | 703 | 1,423 | 844,563 B | -| **`ExecuteBatchSQL` (one call)** | **368,535** | **2.71** | **1,444 B** | - -The batch shape is ~525× faster and allocates ~580× less, and **at that shape the single-file mode is the fastest -INSERT path in the codebase** — about 4.4× the multi-file mode's batched arm (84,263 rows/s at 3,555 B/row). It also -sits above this machine's SQLite INSERT reference on the `--pk` arm (176–199K ops/s), which is a *different* shape and -is quoted as context rather than as a like-for-like ratio. Both shapes gain from the inline capacity: going 0 → 24 moves -the batched shape 300,436 → 368,535 rows/s and the solo shape 545 → 703 rows/s. - -```csharp -// Preferred: many statements in one call — one flush per table. -db.ExecuteBatchSQL(new[] -{ - "INSERT INTO users VALUES (1, 'Alice')", - "INSERT INTO users VALUES (2, 'Bob')", -}); - -// A single multi-row INSERT … VALUES (…) , (…) statement is also batched internally. -db.ExecuteSQL("INSERT INTO users VALUES (3, 'Carol'), (4, 'Dave')"); -``` - -⚠️ One caveat that is **not** shape-dependent, and it is about **file size** rather than speed: a `.scdb` database is -**14,733,312 B whatever it holds** — measured 2026-09-23 at **1, 100, 500 and 2.000 rows**, at both inline capacities and -in both shapes. The file starts at **1.037 pages** (4.247.552 B) and the first extension adds -`max(requiredPages, currentSize / 2, minExtensionPages)`, where the **10 MiB historical minimum** is 2.560 pages at a -4 KiB page size — so 1.037 + 2.560 = 3.597 pages, and the row count never enters the sum. -`DatabaseConfig.SingleFileMinExtensionBytes` trades size for growth steps: the same 100-row database measures **6.369.280 B** at -64 KiB, because the halving term then decides (1.037 + 518 = 1.555 pages). The setting is read **per open** and is not -part of the on-disk format, so it is safe to change on an existing file. Full derivation in plan §9; pinned by -`SingleFileFileGrowthTests`. +individual `ExecuteSQL` inserts pays for the whole table on every statement — O(n²) in the row count. +`ExecuteBatchSQL` is the supported fast path (one flush per table). Measured 2026-09-22 with +`SharpCoreDB.Benchmarks.Comparative --scdb`, 2,000 rows: **703 rows/s** via one `ExecuteSQL` per statement versus +**368,535 rows/s** via `ExecuteBatchSQL` (~525× faster, ~580× less allocation). A single multi-row +`INSERT … VALUES (…), (…)` statement is batched internally too. + +One caveat that is **not** shape-dependent: a `.scdb` file is **14,733,312 B whatever it holds** (measured at 1, 100, +500 and 2,000 rows), because the first extension adds +`max(requiredPages, currentSize / 2, minExtensionPages)` with a 10 MiB historical minimum. +`DatabaseConfig.SingleFileMinExtensionBytes` trades size for growth steps (100 rows measured 6,369,280 B at 64 KiB); +it is read per open and is not part of the on-disk format. Pinned by `SingleFileFileGrowthTests`. --- @@ -233,10 +202,12 @@ part of the on-disk format, so it is safe to change on an existing file. Full de | Error | Cause | |---|---| +| `Unsupported SQL statement: BEGIN` (or `COMMIT`, `ROLLBACK`, `SAVEPOINT`, `INSERT OR`, `REPLACE INTO`) | Not part of the SQL surface — use the transaction API, or a plain `INSERT` | +| `Table '' does not exist` after a successful `CREATE VIEW` | Gap 1 — a view is registered but not queryable | +| `InvalidCastException: Object cannot be cast from DBNull to other types` from `SUM`/`AVG`/`MIN`/`MAX` | Gap 3 — the aggregated column contains a `NULL` | | `InvalidOperationException: Invalid CREATE TABLE syntax` | Malformed DDL (quoted identifiers before v1.7.2 — fixed) | -| `InvalidOperationException: Invalid DROP TABLE syntax` | Malformed DROP TABLE statement | | `InvalidOperationException: Table 'X' not found` | Table does not exist in this `.scdb` file | -| `NotSupportedException: Query not supported in single-file mode` | Non-SELECT query passed to `ExecuteQuery` | +| `NotSupportedException: Query not supported in single-file mode` | A non-`SELECT` statement was passed to `ExecuteQuery`; DDL/DML goes through `ExecuteSQL` | --- @@ -244,30 +215,27 @@ part of the on-disk format, so it is safe to change on an existing file. Full de ``` SingleFileDatabase.ExecuteSQL(sql) - ├── CREATE TABLE ──→ ExecuteCreateTableInternal() (regex, registers schema) + ├── CREATE TABLE ──→ ExecuteCreateTableInternal() (regex, registers schema) ├── DROP TABLE ──→ ExecuteDropTableInternal() (regex, removes schema) ├── CREATE/DROP INDEX ──→ ExecuteCreate/DropIndexInternal() (tracked in _indexRegistry) ├── ALTER TABLE ──→ ExecuteAlterTableInternal() (delegates to ITable methods) - └── everything else ──→ ExecuteDMLInternal() - └──→ SqlParser (shared DML/SELECT engine) + └── everything else ──→ ExecuteDMLInternal() ──→ SqlParser (shared DML/SELECT engine) Database.ExecuteSQL(sql) [directory mode] - └── SqlParser (full DDL + DML + SELECT, including CREATE VIEW/TRIGGER, COLUMNAR storage) + └── SqlParser (DDL + DML + SELECT from one parser) ``` -Both implementations delegate column mutations (`ADD COLUMN`, `DROP COLUMN`, `RENAME COLUMN`) -through the shared `ITable` interface so schema changes are handled consistently regardless of -storage backend. - --- ## See Also -- [`docs/storage/STORAGE_MODE_GUIDANCE.md`](STORAGE_MODE_GUIDANCE.md) — Columnar vs Page-Based storage within a database -- [`docs/manual/query.md`](../manual/query.md) — full SQL dialect reference +- [`docs/storage/STORAGE_MODE_GUIDANCE.md`](STORAGE_MODE_GUIDANCE.md) — columnar vs page-based storage within a database +- [`docs/manual/query.md`](../manual/query.md) — the SQL dialect reference - [`Examples/FluentMigrator/`](../../Examples/FluentMigrator/) — working FluentMigrator + SingleFileDatabase demo --- -*Last updated: v1.9.5* +*Last updated: 2.3.6 · 2026-12-06 — the matrices were re-measured by executing every row against both storage modes.* + +