flatsql 0.2.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 (65) hide show
  1. package/LICENSE +190 -0
  2. package/README.md +489 -0
  3. package/dist/btree/btree.d.ts +34 -0
  4. package/dist/btree/btree.d.ts.map +1 -0
  5. package/dist/btree/btree.js +235 -0
  6. package/dist/btree/btree.js.map +1 -0
  7. package/dist/btree/index.d.ts +3 -0
  8. package/dist/btree/index.d.ts.map +1 -0
  9. package/dist/btree/index.js +3 -0
  10. package/dist/btree/index.js.map +1 -0
  11. package/dist/btree/types.d.ts +36 -0
  12. package/dist/btree/types.d.ts.map +1 -0
  13. package/dist/btree/types.js +55 -0
  14. package/dist/btree/types.js.map +1 -0
  15. package/dist/core/database.d.ts +45 -0
  16. package/dist/core/database.d.ts.map +1 -0
  17. package/dist/core/database.js +248 -0
  18. package/dist/core/database.js.map +1 -0
  19. package/dist/core/index.d.ts +3 -0
  20. package/dist/core/index.d.ts.map +1 -0
  21. package/dist/core/index.js +3 -0
  22. package/dist/core/index.js.map +1 -0
  23. package/dist/core/table-store.d.ts +28 -0
  24. package/dist/core/table-store.d.ts.map +1 -0
  25. package/dist/core/table-store.js +153 -0
  26. package/dist/core/table-store.js.map +1 -0
  27. package/dist/flatbuffer-accessor.d.ts +35 -0
  28. package/dist/flatbuffer-accessor.d.ts.map +1 -0
  29. package/dist/flatbuffer-accessor.js +114 -0
  30. package/dist/flatbuffer-accessor.js.map +1 -0
  31. package/dist/index.d.ts +12 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +15 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/schema/index.d.ts +3 -0
  36. package/dist/schema/index.d.ts.map +1 -0
  37. package/dist/schema/index.js +3 -0
  38. package/dist/schema/index.js.map +1 -0
  39. package/dist/schema/parser.d.ts +25 -0
  40. package/dist/schema/parser.d.ts.map +1 -0
  41. package/dist/schema/parser.js +394 -0
  42. package/dist/schema/parser.js.map +1 -0
  43. package/dist/schema/types.d.ts +33 -0
  44. package/dist/schema/types.d.ts.map +1 -0
  45. package/dist/schema/types.js +29 -0
  46. package/dist/schema/types.js.map +1 -0
  47. package/dist/storage/index.d.ts +3 -0
  48. package/dist/storage/index.d.ts.map +1 -0
  49. package/dist/storage/index.js +3 -0
  50. package/dist/storage/index.js.map +1 -0
  51. package/dist/storage/stacked-flatbuffers.d.ts +38 -0
  52. package/dist/storage/stacked-flatbuffers.d.ts.map +1 -0
  53. package/dist/storage/stacked-flatbuffers.js +253 -0
  54. package/dist/storage/stacked-flatbuffers.js.map +1 -0
  55. package/dist/storage/types.d.ts +23 -0
  56. package/dist/storage/types.d.ts.map +1 -0
  57. package/dist/storage/types.js +27 -0
  58. package/dist/storage/types.js.map +1 -0
  59. package/package.json +79 -0
  60. package/wasm/flatsql-client.js +280 -0
  61. package/wasm/flatsql.js +2 -0
  62. package/wasm/flatsql.wasm +0 -0
  63. package/wasm/flatsql.worker.js +209 -0
  64. package/wasm/index.d.ts +234 -0
  65. package/wasm/index.js +463 -0
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Digital Arsenal, Inc.
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,489 @@
1
+ # FlatSQL
2
+
3
+ [![CI](https://github.com/DigitalArsenal/flatsql/actions/workflows/ci.yml/badge.svg)](https://github.com/DigitalArsenal/flatsql/actions/workflows/ci.yml)
4
+ [![npm version](https://img.shields.io/npm/v/flatsql.svg)](https://www.npmjs.com/package/flatsql)
5
+ [![License](https://img.shields.io/badge/License-Apache%202.0-green.svg)](https://opensource.org/licenses/Apache-2.0)
6
+
7
+ **SQL queries over raw FlatBuffer storage** — A streaming query engine that keeps data in native FlatBuffer format while providing SQL access via SQLite virtual tables.
8
+
9
+ ## Live Demo
10
+
11
+ Try FlatSQL in your browser: **[https://digitalarsenal.github.io/flatsql/](https://digitalarsenal.github.io/flatsql/)**
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install flatsql
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ```javascript
22
+ import { initFlatSQL } from 'flatsql/wasm';
23
+
24
+ // Initialize
25
+ const flatsql = await initFlatSQL();
26
+
27
+ // Create database with schema
28
+ const db = flatsql.createDatabase(`
29
+ table User {
30
+ id: int (id);
31
+ name: string;
32
+ email: string (key);
33
+ age: int;
34
+ }
35
+ `, 'myapp');
36
+
37
+ // Register file identifier for routing
38
+ db.registerFileId('USER', 'User');
39
+
40
+ // Ingest FlatBuffer data (streaming)
41
+ db.ingest(flatbufferStream);
42
+
43
+ // Query with SQL
44
+ const result = db.query('SELECT * FROM User WHERE age > 25');
45
+ console.log(result.columns, result.rows);
46
+ ```
47
+
48
+ ## What is FlatSQL?
49
+
50
+ FlatSQL bridges two technologies:
51
+
52
+ - **[FlatBuffers](https://github.com/digitalarsenal/flatbuffers)** — Google's efficient cross-platform serialization library. Data is stored in binary format with zero-copy access (no parsing/unpacking needed).
53
+ - **SQLite** — The most widely deployed SQL database engine, used here only for SQL parsing and query execution.
54
+
55
+ The key insight: instead of converting FlatBuffers to SQLite rows (expensive), FlatSQL uses [SQLite virtual tables](https://sqlite.org/vtab.html) to query FlatBuffer data directly. Your data stays in portable FlatBuffer format, readable by any FlatBuffer tooling, while you get SQL query capabilities.
56
+
57
+ ## Why FlatSQL?
58
+
59
+ Traditional approach:
60
+ ```
61
+ FlatBuffer → Deserialize → SQLite rows → Query → Serialize → FlatBuffer
62
+ ```
63
+
64
+ FlatSQL approach:
65
+ ```
66
+ FlatBuffer → Query (via virtual table) → FlatBuffer
67
+ ```
68
+
69
+ **Benefits:**
70
+ - **Zero conversion overhead** — Data stays in FlatBuffer format
71
+ - **Streaming ingestion** — Indexes built during data arrival, not after
72
+ - **Portable output** — Exported data is standard FlatBuffers, readable by any tooling
73
+ - **Multi-source federation** — Query across multiple FlatBuffer sources with automatic source tagging
74
+
75
+ ## Source Code
76
+
77
+ | Repository | Description |
78
+ |------------|-------------|
79
+ | [digitalarsenal/flatsql](https://github.com/digitalarsenal/flatsql) | This project — FlatSQL query engine |
80
+ | [digitalarsenal/flatbuffers](https://github.com/digitalarsenal/flatbuffers) | Fork of Google FlatBuffers with WASM support |
81
+ | [flatc-wasm](https://digitalarsenal.github.io/flatbuffers/) | FlatBuffer compiler running in WebAssembly |
82
+
83
+ ## Usage
84
+
85
+ ### WASM (Browser/Node.js)
86
+
87
+ The C++ engine compiles to WebAssembly for cross-platform deployment:
88
+
89
+ ```javascript
90
+ import { initFlatSQL } from 'flatsql/wasm';
91
+
92
+ const flatsql = await initFlatSQL();
93
+
94
+ // Create database with schema
95
+ const db = flatsql.createDatabase(`
96
+ table User {
97
+ id: int (id);
98
+ name: string;
99
+ email: string (key);
100
+ age: int;
101
+ }
102
+ `, 'myapp');
103
+
104
+ // Register file identifier routing
105
+ db.registerFileId('USER', 'User');
106
+
107
+ // Enable demo field extractors (for testing)
108
+ db.enableDemoExtractors();
109
+
110
+ // Ingest FlatBuffer stream
111
+ // Format: [4-byte size LE][FlatBuffer][4-byte size LE][FlatBuffer]...
112
+ db.ingest(streamData);
113
+
114
+ // Query with SQL
115
+ const result = db.query('SELECT id, name, email FROM User WHERE age > 25');
116
+ console.log(result.columns); // ['id', 'name', 'email']
117
+ console.log(result.rows); // [[1, 'Alice', 'alice@example.com'], ...]
118
+
119
+ // Export database
120
+ const exported = db.exportData();
121
+
122
+ // Cleanup
123
+ db.destroy();
124
+ ```
125
+
126
+ ### TypeScript (Pure JavaScript)
127
+
128
+ A TypeScript implementation for environments where WASM isn't available:
129
+
130
+ ```typescript
131
+ import { FlatSQLDatabase, FlatcAccessor } from 'flatsql';
132
+ import { FlatcRunner } from 'flatc-wasm';
133
+
134
+ const flatc = await FlatcRunner.init();
135
+
136
+ const schema = `
137
+ namespace App;
138
+
139
+ table User {
140
+ id: int (key);
141
+ name: string (required);
142
+ email: string;
143
+ age: int;
144
+ }
145
+ `;
146
+
147
+ const accessor = new FlatcAccessor(flatc, schema);
148
+ const db = FlatSQLDatabase.fromSchema(schema, accessor, 'myapp');
149
+
150
+ // Insert records
151
+ db.insert('User', { id: 1, name: 'Alice', email: 'alice@example.com', age: 30 });
152
+ db.insert('User', { id: 2, name: 'Bob', email: 'bob@example.com', age: 25 });
153
+
154
+ // Query
155
+ const result = db.query('SELECT name, email FROM User WHERE age > 20');
156
+ console.log(result.rows);
157
+
158
+ // Export as standard FlatBuffers
159
+ const exported = db.exportData();
160
+ ```
161
+
162
+ ### Native C++ (Embedded)
163
+
164
+ For performance-critical applications, link the C++ library directly:
165
+
166
+ ```cpp
167
+ #include <flatsql/database.h>
168
+
169
+ auto db = flatsql::FlatSQLDatabase::fromSchema(schema, "mydb");
170
+
171
+ // Register file ID routing
172
+ db.registerFileId("USER", "User");
173
+
174
+ // Set field extractor
175
+ db.setFieldExtractor("User", extractUserField);
176
+
177
+ // Ingest streaming data
178
+ size_t recordsIngested = 0;
179
+ db.ingest(data, length, &recordsIngested);
180
+
181
+ // Query
182
+ auto result = db.query("SELECT * FROM User WHERE id = 5");
183
+ for (size_t i = 0; i < result.rowCount(); i++) {
184
+ std::cout << result.getString(i, "name") << std::endl;
185
+ }
186
+ ```
187
+
188
+ ## Architecture
189
+
190
+ ```
191
+ ┌─────────────────────────────────────────────────────────────┐
192
+ │ FlatSQLDatabase │
193
+ ├─────────────────────────────────────────────────────────────┤
194
+ │ SchemaParser │ SQLiteEngine │
195
+ │ (FlatBuffers IDL) │ (Virtual Tables) │
196
+ ├─────────────────────────────────────────────────────────────┤
197
+ │ TableStore (per table) │
198
+ │ ┌────────────────────────────────────────────────────────┐ │
199
+ │ │ SQLite Indexes Field Extractors │ │
200
+ │ │ (id, email, timestamp) (getField callbacks) │ │
201
+ │ └────────────────────────────────────────────────────────┘ │
202
+ ├─────────────────────────────────────────────────────────────┤
203
+ │ StackedFlatBufferStore (append-only) │
204
+ │ ┌──────────────────────────────────────────────────────┐ │
205
+ │ │ [Header][FB₁][FB₂][FB₃]... │ │
206
+ │ └──────────────────────────────────────────────────────┘ │
207
+ └─────────────────────────────────────────────────────────────┘
208
+ ```
209
+
210
+ ### Stream Format
211
+
212
+ FlatSQL ingests size-prefixed FlatBuffer streams:
213
+
214
+ ```
215
+ [4-byte size LE][FlatBuffer with file_id][4-byte size LE][FlatBuffer]...
216
+ ```
217
+
218
+ The 4-byte file identifier in each FlatBuffer determines which table receives the record.
219
+
220
+ ## SQL Support
221
+
222
+ ### Supported
223
+
224
+ - `SELECT` with column selection
225
+ - `WHERE` with `=`, `<`, `>`, `<=`, `>=`, `BETWEEN`, `LIKE`, `AND`, `OR`
226
+ - `ORDER BY` (ASC/DESC)
227
+ - `LIMIT` and `OFFSET`
228
+ - `COUNT(*)` aggregate
229
+ - Index-accelerated queries on `(id)` and `(key)` columns
230
+
231
+ ### Not Supported
232
+
233
+ - `JOIN` (query one table at a time)
234
+ - `GROUP BY`, `HAVING`, most aggregates
235
+ - `INSERT`, `UPDATE`, `DELETE` (use API methods instead)
236
+ - Subqueries, CTEs, window functions
237
+
238
+ ## Performance
239
+
240
+ FlatSQL outperforms traditional SQLite on query operations:
241
+
242
+ | Operation | FlatSQL | SQLite | Speedup |
243
+ |-----------|---------|--------|---------|
244
+ | Point query (by id) | 3.50 ms | 3.93 ms | 1.1x |
245
+ | Point query (by key) | 5.23 ms | 6.94 ms | 1.3x |
246
+ | Direct index lookup | 1.56 ms | 3.93 ms | 2.5x |
247
+ | Full scan | 0.84 ms | 1.25 ms | 1.5x |
248
+ | Direct iteration | 0.05 ms | 1.25 ms | 25x |
249
+
250
+ *Benchmarks: 10,000 records, 10,000 query iterations, Apple M3 Ultra*
251
+
252
+ ## Performance Trade-offs
253
+
254
+ FlatSQL uses SQLite's virtual table (VTable) API to expose FlatBuffer data as queryable tables. This architecture enables SQL queries over raw binary data, but comes with fundamental trade-offs that affect performance characteristics.
255
+
256
+ ### Access Paths
257
+
258
+ FlatSQL provides three access paths with different performance profiles:
259
+
260
+ | Access Path | Latency | Throughput | Use Case |
261
+ |-------------|---------|------------|----------|
262
+ | **Zero-Copy API** | 1.7 µs | 580K ops/sec | Direct index lookup, returns raw FlatBuffer pointer |
263
+ | **VTable SQL** | 12.9 µs | 78K ops/sec | Full SQL queries via SQLite |
264
+ | **Pure SQLite** | 2.5 µs | 400K ops/sec | Baseline comparison |
265
+
266
+ ### Why VTable Queries Are Slower Than Pure SQLite
267
+
268
+ SQLite's VTable API has fundamental limitations that prevent FlatSQL from matching pure SQLite query performance:
269
+
270
+ 1. **Per-Column Extraction** — The `xColumn()` callback is invoked once per column per row. There is no batch API to extract multiple fields at once, meaning each field access has function call overhead.
271
+
272
+ 2. **Mandatory Value Conversion** — All values must be converted to SQLite's internal format via `sqlite3_result_*()` functions. Even though FlatBuffers already store data in an efficient binary format, we must convert strings to SQLite strings, integers to SQLite integers, etc.
273
+
274
+ 3. **Row-by-Row Processing** — The `xNext()` callback advances one row at a time with no vectorized or batch iteration. This prevents SIMD optimizations or processing multiple records per call.
275
+
276
+ 4. **No Direct Memory Access** — SQLite cannot read FlatBuffer memory directly; all data must flow through the VTable callback interface, adding overhead for every field access.
277
+
278
+ ### When to Use Each Access Path
279
+
280
+ **Use the Zero-Copy API when:**
281
+ - You need maximum throughput for point lookups
282
+ - You're building hot paths that query by indexed keys
283
+ - You can work directly with FlatBuffer data structures
284
+
285
+ ```cpp
286
+ // Zero-copy: returns pointer to raw FlatBuffer (1.7 µs)
287
+ const uint8_t* data = db.findRawByIndex("User", "email", email, &len);
288
+ auto user = GetUser(data); // Direct FlatBuffer access
289
+ ```
290
+
291
+ **Use VTable SQL when:**
292
+ - You need complex queries (filtering, sorting, aggregation)
293
+ - Query flexibility is more important than raw speed
294
+ - You're doing ad-hoc exploration of the data
295
+
296
+ ```cpp
297
+ // VTable SQL: full query capability (12.9 µs)
298
+ auto result = db.query("SELECT * FROM User WHERE age > 25 ORDER BY name");
299
+ ```
300
+
301
+ ### Architecture: SQLite-Backed Indexes
302
+
303
+ FlatSQL uses SQLite's highly optimized B-tree for indexing (not a custom implementation). This provides:
304
+
305
+ - **Battle-tested performance** — SQLite's B-tree is used by billions of devices
306
+ - **Consistent behavior** — Same indexing code path as pure SQLite
307
+ - **Fast path optimization** — Type-specific lookups bypass `std::variant` overhead
308
+
309
+ The index stores `(key, sequence) → (offset, length)` mappings, allowing O(log n) lookups that return pointers directly into the FlatBuffer storage.
310
+
311
+ ### Trade-off Summary
312
+
313
+ | Aspect | FlatSQL | Pure SQLite |
314
+ |--------|---------|-------------|
315
+ | Point lookup (indexed) | **1.4x faster** (zero-copy API) | Baseline |
316
+ | SQL queries | 5-7x slower (VTable overhead) | Baseline |
317
+ | Storage format | FlatBuffers (portable, zero-copy) | SQLite pages |
318
+ | Data conversion | None (zero-copy) or on-demand | Always required |
319
+ | Streaming ingest | Append-only, real-time indexing | Row-by-row inserts |
320
+
321
+ **Bottom line:** FlatSQL excels when you need streaming ingestion of FlatBuffer data with SQL query capability. Use the zero-copy API for performance-critical lookups; use SQL for complex queries where flexibility matters more than speed.
322
+
323
+ ## Building from Source
324
+
325
+ ### Prerequisites
326
+
327
+ - Node.js 18+
328
+ - CMake 3.20+ (for WASM builds)
329
+ - Emscripten (for WASM builds)
330
+
331
+ ### TypeScript Build
332
+
333
+ ```bash
334
+ npm install
335
+ npm run build
336
+ npm test
337
+ ```
338
+
339
+ ### WASM Build
340
+
341
+ ```bash
342
+ # Clone DA-FlatBuffers (required dependency)
343
+ git clone https://github.com/DigitalArsenal/flatbuffers.git ../flatbuffers
344
+
345
+ # Build WASM
346
+ cd cpp
347
+ emcmake cmake -B build-wasm -DCMAKE_BUILD_TYPE=Release
348
+ cmake --build build-wasm
349
+ ```
350
+
351
+ Output: `wasm/flatsql.js` and `wasm/flatsql.wasm`
352
+
353
+ ### Run Demo Locally
354
+
355
+ ```bash
356
+ npm run serve
357
+ # Open http://localhost:8081
358
+ ```
359
+
360
+ ## API Reference
361
+
362
+ ### initFlatSQL()
363
+
364
+ ```typescript
365
+ import { initFlatSQL } from 'flatsql/wasm';
366
+
367
+ const flatsql = await initFlatSQL();
368
+ ```
369
+
370
+ ### createDatabase(schema, name)
371
+
372
+ ```typescript
373
+ const db = flatsql.createDatabase(schemaString, 'dbname');
374
+ ```
375
+
376
+ ### db.registerFileId(fileId, tableName)
377
+
378
+ ```typescript
379
+ db.registerFileId('USER', 'User'); // Route "USER" FlatBuffers to User table
380
+ ```
381
+
382
+ ### db.ingest(data, source?)
383
+
384
+ ```typescript
385
+ const bytesConsumed = db.ingest(uint8ArrayStream);
386
+ // Or with source tagging (requires registerSource first):
387
+ const bytesConsumed = db.ingest(uint8ArrayStream, 'satellite-1');
388
+ ```
389
+
390
+ ### db.query(sql)
391
+
392
+ ```typescript
393
+ const result = db.query('SELECT * FROM User WHERE age > 25');
394
+ // result.columns: string[]
395
+ // result.rows: any[][]
396
+ ```
397
+
398
+ ### db.exportData()
399
+
400
+ ```typescript
401
+ const data = db.exportData(); // Returns Uint8Array
402
+ ```
403
+
404
+ ### db.registerSource(sourceName)
405
+
406
+ ```typescript
407
+ db.registerSource('satellite-1'); // Creates User@satellite-1, Post@satellite-1, etc.
408
+ ```
409
+
410
+ ### db.createUnifiedViews()
411
+
412
+ ```typescript
413
+ db.createUnifiedViews(); // Creates unified views with _source column
414
+ ```
415
+
416
+ ### db.listSources()
417
+
418
+ ```typescript
419
+ const sources = db.listSources(); // ['satellite-1', 'satellite-2', ...]
420
+ ```
421
+
422
+ ## Multi-Source Queries
423
+
424
+ FlatSQL supports federating multiple data sources with the same schema. Each source gets its own set of tables, and you can query them individually or across all sources.
425
+
426
+ ### Use Case
427
+
428
+ Imagine you have multiple satellites streaming telemetry data with the same schema:
429
+
430
+ ```javascript
431
+ // Register sources
432
+ db.registerSource('satellite-1');
433
+ db.registerSource('satellite-2');
434
+ db.registerSource('ground-station');
435
+
436
+ // Register file IDs and extractors (must be done after registerSource)
437
+ db.registerFileId('TELE', 'Telemetry');
438
+ db.enableDemoExtractors();
439
+
440
+ // Create unified views (call once after all sources registered)
441
+ db.createUnifiedViews();
442
+
443
+ // Ingest from different sources
444
+ db.ingest(satellite1Stream, 'satellite-1');
445
+ db.ingest(satellite2Stream, 'satellite-2');
446
+ db.ingest(groundStream, 'ground-station');
447
+
448
+ // Query a specific source
449
+ db.query('SELECT * FROM "Telemetry@satellite-1" WHERE signal > 50');
450
+
451
+ // Query across all sources (unified view)
452
+ db.query('SELECT * FROM Telemetry WHERE timestamp > 1000');
453
+ ```
454
+
455
+ ### Table Naming Convention
456
+
457
+ - **Source-specific tables**: `TableName@sourceName` (e.g., `User@siteA`, `Telemetry@satellite-1`)
458
+ - **Unified views**: `TableName` (e.g., `User`, `Telemetry`) - combines all source tables with a `_source` column
459
+
460
+ ### The _source Column
461
+
462
+ Unified views include a `_source` column that identifies which source each row came from:
463
+
464
+ ```sql
465
+ -- See source for each record
466
+ SELECT _source, id, name FROM User LIMIT 10;
467
+
468
+ -- Count records by source
469
+ SELECT _source, COUNT(*) as count FROM User GROUP BY _source;
470
+
471
+ -- Filter by source in unified view
472
+ SELECT * FROM User WHERE _source = 'satellite-1';
473
+ ```
474
+
475
+ ## License
476
+
477
+ Apache 2.0
478
+
479
+ ## Contributing
480
+
481
+ Contributions welcome. Please open an issue first to discuss significant changes.
482
+
483
+ ## Contact
484
+
485
+ For questions, licensing inquiries, or commercial support: [tj@digitalarsenal.io](mailto:tj@digitalarsenal.io)
486
+
487
+ ---
488
+
489
+ Built on [DA-FlatBuffers](https://digitalarsenal.github.io/flatbuffers/) and [SQLite](https://sqlite.org/).