nodblite 0.0.0-stage → 0.6.7

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.
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 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 2026 Titor-Z
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 CHANGED
@@ -1,3 +1,185 @@
1
- # Temporary Holding Version
1
+ # nodblite
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **像 SQLite 一样小巧的单文件 NoSQL 文档数据库** —— MongoDB 风格查询,零配置,无需服务进程。
4
+
5
+ ```bash
6
+ npm install nodblite
7
+ ```
8
+
9
+ ```js
10
+ import { Database } from 'nodblite';
11
+
12
+ const db = new Database('app.nodb');
13
+
14
+ const id = db.insert('users', { name: '张三', age: 30 });
15
+ const adults = db.find('users', { age: { $gte: 18 } }, { sort: { age: -1 } });
16
+
17
+ db.close();
18
+ ```
19
+
20
+ 整个数据库就是一个 `.nodb` 文件 —— 复制即迁移,备份即拷贝。
21
+
22
+ 📖 **[完整文档](https://titor-z.github.io/nosqlite/)** · [与 MongoDB 的差异](https://titor-z.github.io/nosqlite/reference/compatibility/)
23
+
24
+ ---
25
+
26
+ ## 为什么用它
27
+
28
+ | | |
29
+ |---|---|
30
+ | **零配置** | 没有服务进程,没有端口,没有配置文件 |
31
+ | **单文件** | 一个 `.nodb` 文件,`cp` 就是备份 |
32
+ | **MongoDB 语义** | 查询/更新/索引语法与 MongoDB 一致,迁移成本低 |
33
+ | **同步 API** | 没有 `await` 地狱,手感像 `better-sqlite3` |
34
+ | **TypeScript** | 完整类型定义,`find<T>()` 泛型推断 |
35
+
36
+ ## 安装
37
+
38
+ ```bash
39
+ npm install nodblite
40
+ ```
41
+
42
+ 需要 Node.js 18+。底层通过 [koffi](https://www.npmjs.com/package/koffi) 调用预编译动态库,**不需要 node-gyp、不需要 Python、不需要 C++ 编译器**。
43
+
44
+ 支持平台:macOS(arm64/x64)、Linux(x64)、Windows(x64)。
45
+
46
+ ## 快速上手
47
+
48
+ ```js
49
+ import { Database } from 'nodblite';
50
+
51
+ const db = new Database('app.nodb'); // 不存在则自动创建
52
+
53
+ // 插入
54
+ const id = db.insert('users', { name: '张三', age: 30 });
55
+ db.insertMany('users', [
56
+ { name: '李四', age: 25 },
57
+ { name: '王五', age: 42 },
58
+ ]);
59
+
60
+ // 查询
61
+ const adults = db.find('users', { age: { $gte: 18 } }, { sort: { age: -1 } });
62
+ const one = db.get('users', id);
63
+
64
+ // 分页:一次拿到总数与当页,不用查两次
65
+ const { total, items } = db.findPage('users', {}, { skip: 0, limit: 20 });
66
+
67
+ // 更新
68
+ db.update('users', { name: '张三' }, { $inc: { age: 1 } });
69
+ db.upsert('users', { email: 'a@b.c' }, { $set: { name: '新人' } });
70
+
71
+ // 删除
72
+ db.delete('users', { age: { $lt: 18 } });
73
+
74
+ db.close();
75
+ ```
76
+
77
+ ## 索引
78
+
79
+ ```js
80
+ // 单字段
81
+ db.createIndex('users', 'age_1', 'age');
82
+
83
+ // 唯一
84
+ db.createIndex('users', 'email_1', 'email', { unique: true });
85
+
86
+ // 复合(遵循 MongoDB 前缀原则)
87
+ db.createIndex('users', 'status_age', 'status', { fields: ['status', 'age'] });
88
+
89
+ // 降序
90
+ db.createIndex('users', 'age_-1', 'age', { fields: ['age'], directions: [-1] });
91
+
92
+ // 看看查询会不会走索引
93
+ const plan = db.explain('users', { age: { $gte: 18 } });
94
+ console.log(plan.stage); // 'IXSCAN' 或 'COLLSCAN'
95
+ console.log(plan.indexName); // 'age_1'
96
+ ```
97
+
98
+ ## TypeScript
99
+
100
+ ```ts
101
+ import { Database } from 'nodblite';
102
+
103
+ interface User {
104
+ _id?: string;
105
+ name: string;
106
+ age: number;
107
+ tags?: string[];
108
+ }
109
+
110
+ const db = new Database('app.nodb');
111
+
112
+ const adults: User[] = db.find<User>('users', { age: { $gte: 18 } });
113
+ const page = db.findPage<User>('users', { tags: { $all: ['admin'] } });
114
+ ```
115
+
116
+ 类型会拦截常见错误:
117
+
118
+ ```ts
119
+ db.find<User>('users', { age: { $gte: '字符串' } }); // ❌ 类型错误
120
+ db.update<User>('users', {}, { $inc: { age: 'x' } }); // ❌ 类型错误
121
+ ```
122
+
123
+ ## 支持的查询操作符
124
+
125
+ `$eq` `$ne` `$gt` `$gte` `$lt` `$lte` `$in` `$nin` `$regex`
126
+ `$exists` `$type` `$all` `$size` `$elemMatch`
127
+ `$and` `$or` `$nor` `$not`
128
+
129
+ ## 支持的更新操作符
130
+
131
+ `$set` `$unset` `$inc` `$mul` `$min` `$max` `$rename`
132
+ `$push` `$addToSet` `$pull` `$pop` `$currentDate`
133
+
134
+ ## 资源管理
135
+
136
+ ```js
137
+ // 手动关闭
138
+ const db = new Database('app.nodb');
139
+ db.close();
140
+
141
+ // 或用 using 自动关闭(TypeScript 5.2+ / Node 22+)
142
+ using db = new Database('app.nodb');
143
+ ```
144
+
145
+ ## 错误处理
146
+
147
+ 所有错误都是 `NodbliteError` 的子类,带稳定的 `code`:
148
+
149
+ ```js
150
+ import { Errors } from 'nodblite';
151
+
152
+ try {
153
+ db.insert('users', { email: 'a@b.c' });
154
+ } catch (e) {
155
+ if (e instanceof Errors.DuplicateKeyError) {
156
+ console.log('邮箱已存在');
157
+ }
158
+ }
159
+ ```
160
+
161
+ | 错误类 | code | 场景 |
162
+ |---|---|---|
163
+ | `DuplicateKeyError` | 1 | 主键或唯一索引冲突 |
164
+ | `InvalidPathError` | 2 | 后缀不是 `.nodb` |
165
+ | `InvalidFilterError` | 6 | 过滤条件语法错误 |
166
+ | `InvalidUpdateError` | 7 | 更新操作符错误 |
167
+ | `InvalidDocumentError` | 10 | 文档不是合法 JSON 对象 |
168
+
169
+ ## 常见问题
170
+
171
+ **能多进程同时写吗?**
172
+ 不能。`.nodb` 由进程独占(SQLite 同款约束)。需要多服务共享,请用 `nodblite-server` + MongoDB 驱动。
173
+
174
+ **和 MongoDB driver 有什么区别?**
175
+ 这个包是**进程内直连**,没有网络开销,没有服务进程 —— 适合桌面应用、CLI、单机服务。需要跨进程/跨语言共享时用 wire 协议。
176
+
177
+ **Deno / Bun 能用吗?**
178
+ 这个包依赖 koffi(Node 原生模块),目前只在 Node.js 上验证过。Deno/Bun 推荐用 wire 协议。
179
+
180
+ **性能如何?**
181
+ 查询走索引时是高选择率快 300–4000 倍(10 万文档实测)。批量写入用 `insertMany`,比逐条快两个数量级。详见[性能文档](https://titor-z.github.io/nosqlite/reference/performance/)。
182
+
183
+ ## License
184
+
185
+ Apache-2.0
@@ -0,0 +1,40 @@
1
+ /**
2
+ * 定位动态库。
3
+ *
4
+ * 查找顺序:
5
+ * 1. 环境变量 `NODBLITE_LIB`(显式指定,最高优先级)
6
+ * 2. 包内 `prebuilds/<platform>-<arch>/`
7
+ * 3. 包内 `prebuilds/`
8
+ * 4. 开发场景:`../target/release/` 与 `../target/debug/`
9
+ */
10
+ export function resolveLibPath(): any;
11
+ /** 加载 koffi 并声明所有用到的 C 函数与结构。 */
12
+ export function loadBindings(libPath?: any): {
13
+ koffi: any;
14
+ Slice: any;
15
+ Result: any;
16
+ open: any;
17
+ close: any;
18
+ insert: any;
19
+ insertMany: any;
20
+ get: any;
21
+ update: any;
22
+ delete: any;
23
+ upsert: any;
24
+ count: any;
25
+ find: any;
26
+ findPage: any;
27
+ listCollections: any;
28
+ createIndex: any;
29
+ createIndexComposite: any;
30
+ listIndexes: any;
31
+ dropIndex: any;
32
+ explain: any;
33
+ cursorNext: any;
34
+ cursorClose: any;
35
+ resultFree: any;
36
+ lastError: any;
37
+ lastErrorCode: any;
38
+ };
39
+ /** 把 C 的 `NodbliteSlice` 解成 JS 字符串。 */
40
+ export function sliceToString(koffi: any, s: any): any;
@@ -0,0 +1,124 @@
1
+ // nodblite 的 koffi 绑定层。
2
+ //
3
+ // 本文件只做「C ABI ↔ JS」的机械映射,不含业务逻辑。
4
+ // 所有函数签名必须与 include/nodblite.h 严格一致 —— 改头文件后要同步这里。
5
+ import { createRequire } from 'node:module';
6
+ import { existsSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ const require = createRequire(import.meta.url);
10
+ const __dirname = dirname(fileURLToPath(import.meta.url));
11
+ /** 各平台动态库文件名。 */
12
+ const LIB_NAMES = {
13
+ darwin: 'libnodblite.dylib',
14
+ linux: 'libnodblite.so',
15
+ win32: 'nodblite.dll',
16
+ };
17
+ /**
18
+ * 定位动态库。
19
+ *
20
+ * 查找顺序:
21
+ * 1. 环境变量 `NODBLITE_LIB`(显式指定,最高优先级)
22
+ * 2. 包内 `prebuilds/<platform>-<arch>/`
23
+ * 3. 包内 `prebuilds/`
24
+ * 4. 开发场景:`../target/release/` 与 `../target/debug/`
25
+ */
26
+ export function resolveLibPath() {
27
+ if (process.env.NODBLITE_LIB) {
28
+ if (!existsSync(process.env.NODBLITE_LIB)) {
29
+ throw new Error(`NODBLITE_LIB 指向的文件不存在: ${process.env.NODBLITE_LIB}`);
30
+ }
31
+ return process.env.NODBLITE_LIB;
32
+ }
33
+ const name = LIB_NAMES[process.platform];
34
+ if (!name) {
35
+ throw new Error(`不支持的平台: ${process.platform}(支持 darwin / linux / win32)`);
36
+ }
37
+ const candidates = [
38
+ join(__dirname, '..', 'prebuilds', `${process.platform}-${process.arch}`, name),
39
+ join(__dirname, '..', 'prebuilds', name),
40
+ // 源码仓库内直接使用时
41
+ join(__dirname, '..', '..', 'target', 'release', name),
42
+ join(__dirname, '..', '..', 'target', 'debug', name),
43
+ ];
44
+ for (const p of candidates) {
45
+ if (existsSync(p))
46
+ return p;
47
+ }
48
+ throw new Error(`找不到 nodblite 动态库(${name})。\n` +
49
+ `已尝试:\n${candidates.map((c) => ` - ${c}`).join('\n')}\n\n` +
50
+ `解决办法:\n` +
51
+ ` 1. 在源码仓库执行 cargo build --release,或\n` +
52
+ ` 2. 设置环境变量 NODBLITE_LIB=/path/to/${name}\n` +
53
+ ` 3. 从 https://github.com/Titor-Z/nosqlite/releases 下载 FFI 包`);
54
+ }
55
+ // koffi 的结构类型注册表是**全局**的:`koffi.struct()` 同名只能调一次,
56
+ // 否则抛 "Duplicate type name"。所以这里缓存起来,进程内只声明一次。
57
+ let cachedKoffi = null;
58
+ let cachedTypes = null;
59
+ /** 拿到 koffi 与只声明一次的结构类型。 */
60
+ function getKoffiAndTypes() {
61
+ if (cachedKoffi)
62
+ return { koffi: cachedKoffi, ...cachedTypes };
63
+ const koffi = require('koffi');
64
+ const Slice = koffi.struct('NodbliteSlice', {
65
+ ptr: 'uint8_t *',
66
+ len: 'size_t',
67
+ });
68
+ const Result = koffi.struct('NodbliteResult', {
69
+ code: 'int32',
70
+ count: 'uint64',
71
+ affected: 'uint64',
72
+ docs: koffi.pointer(Slice),
73
+ value: Slice,
74
+ });
75
+ cachedKoffi = koffi;
76
+ cachedTypes = { Slice, Result };
77
+ return { koffi, Slice, Result };
78
+ }
79
+ /** 加载 koffi 并声明所有用到的 C 函数与结构。 */
80
+ export function loadBindings(libPath = resolveLibPath()) {
81
+ const { koffi, Slice, Result } = getKoffiAndTypes();
82
+ const lib = koffi.load(libPath);
83
+ // ---------- 函数 ----------
84
+ const fn = (sig) => lib.func(sig);
85
+ return {
86
+ koffi,
87
+ Slice,
88
+ Result,
89
+ open: fn('void *nodblite_open(const char *path, uint8_t create_if_missing)'),
90
+ close: fn('void nodblite_close(void *db)'),
91
+ insert: fn('void *nodblite_insert(void *db, const char *coll, const char *doc)'),
92
+ insertMany: fn('void *nodblite_insert_many(void *db, const char *coll, const char *docs)'),
93
+ get: fn('void *nodblite_get(void *db, const char *coll, const char *id)'),
94
+ update: fn('void *nodblite_update(void *db, const char *coll, const char *filter, const char *upd)'),
95
+ delete: fn('void *nodblite_delete(void *db, const char *coll, const char *filter)'),
96
+ upsert: fn('void *nodblite_upsert(void *db, const char *coll, const char *filter, const char *upd)'),
97
+ count: fn('void *nodblite_count(void *db, const char *coll, const char *filter)'),
98
+ find: fn('void *nodblite_find(void *db, const char *coll, const char *filter, ' +
99
+ 'const char *sort, const char *fields, uint64_t skip, uint64_t limit)'),
100
+ findPage: fn('void *nodblite_find_page(void *db, const char *coll, const char *filter, ' +
101
+ 'const char *sort, const char *fields, uint64_t skip, uint64_t limit, ' +
102
+ 'uint8_t limit_is_null)'),
103
+ listCollections: fn('void *nodblite_list_collections(void *db)'),
104
+ createIndex: fn('void *nodblite_create_index(void *db, const char *coll, const char *name, ' +
105
+ 'const char *field, uint8_t unique, uint8_t sparse)'),
106
+ createIndexComposite: fn('void *nodblite_create_index_composite(void *db, const char *coll, const char *name, ' +
107
+ 'const char *fields, const char *dirs, uint8_t unique, uint8_t sparse)'),
108
+ listIndexes: fn('void *nodblite_list_indexes(void *db, const char *coll)'),
109
+ dropIndex: fn('void *nodblite_drop_index(void *db, const char *coll, const char *name)'),
110
+ explain: fn('void *nodblite_explain(void *db, const char *coll, const char *filter, ' +
111
+ 'const char *sort)'),
112
+ cursorNext: fn('void *nodblite_cursor_next(void *cur)'),
113
+ cursorClose: fn('void nodblite_cursor_close(void *cur)'),
114
+ resultFree: fn('void nodblite_result_free(void *r)'),
115
+ lastError: fn('const char *nodblite_last_error()'),
116
+ lastErrorCode: fn('int32 nodblite_last_error_code()'),
117
+ };
118
+ }
119
+ /** 把 C 的 `NodbliteSlice` 解成 JS 字符串。 */
120
+ export function sliceToString(koffi, s) {
121
+ if (!s || s.len === 0)
122
+ return '';
123
+ return Buffer.from(koffi.decode(s.ptr, 'uint8_t', s.len)).toString('utf8');
124
+ }
@@ -0,0 +1,114 @@
1
+ /** 所有 nodblite 错误的基类。 */
2
+ export class NodbliteError extends Error {
3
+ constructor(code: any, message: any, op: any);
4
+ name: any;
5
+ code: any;
6
+ /** 出错的操作名,如 "insert" / "find"。 */
7
+ op: any;
8
+ }
9
+ /** 动态创建具体错误类,便于 `instanceof` 判断。 */
10
+ export const Errors: {
11
+ [k: string]: any;
12
+ };
13
+ /**
14
+ * 一个 nodblite 数据库。
15
+ *
16
+ * 用法与 better-sqlite3 类似:
17
+ * ```js
18
+ * import { Database } from 'nodblite';
19
+ * const db = new Database('app.nodb');
20
+ * db.collection('users').insert({ name: '张三' });
21
+ * db.close();
22
+ * ```
23
+ */
24
+ export class Database {
25
+ /**
26
+ * @param {string} path 数据库文件路径(必须以 `.nodb` 结尾)
27
+ * @param {{create?: boolean, libPath?: string}} [opts]
28
+ */
29
+ constructor(path: string, opts?: {
30
+ create?: boolean;
31
+ libPath?: string;
32
+ });
33
+ path: string;
34
+ /**
35
+ * 查询文档。
36
+ * @template T
37
+ * @param {string} collection
38
+ * @param {object} [filter] MongoDB 风格过滤条件
39
+ * @param {{sort?: object, fields?: object, skip?: number, limit?: number}} [opts]
40
+ * @returns {T[]}
41
+ */
42
+ find<T>(collection: string, filter?: object, opts?: {
43
+ sort?: object;
44
+ fields?: object;
45
+ skip?: number;
46
+ limit?: number;
47
+ }): T[];
48
+ /**
49
+ * 分页查询:一次拿到「匹配总数 + 当页文档」,省掉单独 count。
50
+ * @template T
51
+ * @returns {{total: number, items: T[]}}
52
+ */
53
+ findPage<T>(collection: any, filter?: {}, opts?: {}): {
54
+ total: number;
55
+ items: T[];
56
+ };
57
+ /**
58
+ * 按 `_id` 读单条,不存在返回 `null`。
59
+ * @template T
60
+ * @returns {T | null}
61
+ */
62
+ get<T>(collection: any, id: any): T | null;
63
+ /** 计数。 */
64
+ count(collection: any, filter?: {}): number;
65
+ /** 列出全部集合名。 */
66
+ collections(): any;
67
+ /** 插入一条,返回 `_id`。 */
68
+ insert(collection: any, doc: any): any;
69
+ /** 批量插入(单事务),返回 `_id` 数组。 */
70
+ insertMany(collection: any, docs: any): any;
71
+ /** 更新,返回实际修改条数。 */
72
+ update(collection: any, filter: any, update: any): number;
73
+ /** 删除,返回删除条数。 */
74
+ delete(collection: any, filter: any): number;
75
+ /**
76
+ * 更新或插入。
77
+ * @returns {{updated: number} | {inserted: string}}
78
+ */
79
+ upsert(collection: any, filter: any, update: any): {
80
+ updated: number;
81
+ } | {
82
+ inserted: string;
83
+ };
84
+ /**
85
+ * 创建索引。
86
+ * @param {{unique?: boolean, sparse?: boolean, fields?: string[], directions?: number[]}} [opts]
87
+ * 传 `fields` 则为复合索引;否则用 `field`。
88
+ */
89
+ createIndex(collection: any, name: any, field: any, opts?: {
90
+ unique?: boolean;
91
+ sparse?: boolean;
92
+ fields?: string[];
93
+ directions?: number[];
94
+ }): any;
95
+ /** 列出索引定义。 */
96
+ listIndexes(collection: any): any;
97
+ /** 删除索引。 */
98
+ dropIndex(collection: any, name: any): boolean;
99
+ /**
100
+ * 查看查询计划。
101
+ * @returns {{stage: 'IXSCAN' | 'COLLSCAN', [k: string]: unknown}}
102
+ */
103
+ explain(collection: any, filter?: {}, sort?: null): {
104
+ stage: "IXSCAN" | "COLLSCAN";
105
+ [k: string]: unknown;
106
+ };
107
+ /** 关闭数据库。可重复调用。 */
108
+ close(): void;
109
+ /** 支持 `using db = new Database(...)` 自动关闭。 */
110
+ [Symbol.dispose](): void;
111
+ #private;
112
+ }
113
+ export { resolveLibPath };
114
+ import { resolveLibPath } from './bindings.js';
package/dist/index.js ADDED
@@ -0,0 +1,233 @@
1
+ // nodblite 的核心 API —— 同步风格,API 手感对齐 better-sqlite3。
2
+ //
3
+ // 为什么是同步的:C ABI 本身是同步的,套一层 Promise 只是把同步调用包进
4
+ // 微任务,不会带来任何并发收益,反而让调用方多写 await。这与 better-sqlite3
5
+ // 的判断一致。
6
+ import { loadBindings, sliceToString, resolveLibPath } from './bindings.js';
7
+ /** nodblite 错误码 → 错误类名。 */
8
+ const ERROR_NAMES = {
9
+ 1: 'DuplicateKeyError',
10
+ 2: 'InvalidPathError',
11
+ 3: 'InvalidFormatError',
12
+ 4: 'VersionMismatchError',
13
+ 5: 'InvalidCollectionError',
14
+ 6: 'InvalidFilterError',
15
+ 7: 'InvalidUpdateError',
16
+ 8: 'InvalidSortError',
17
+ 9: 'InvalidProjectionError',
18
+ 10: 'InvalidDocumentError',
19
+ 11: 'IoError',
20
+ 99: 'InternalError',
21
+ };
22
+ /** 所有 nodblite 错误的基类。 */
23
+ export class NodbliteError extends Error {
24
+ constructor(code, message, op) {
25
+ super(message || `nodblite 错误 ${code}`);
26
+ this.name = ERROR_NAMES[code] || 'NodbliteError';
27
+ this.code = code;
28
+ /** 出错的操作名,如 "insert" / "find"。 */
29
+ this.op = op || '';
30
+ }
31
+ }
32
+ /** 动态创建具体错误类,便于 `instanceof` 判断。 */
33
+ export const Errors = Object.fromEntries(Object.values(ERROR_NAMES).map((name) => [
34
+ name,
35
+ class extends NodbliteError {
36
+ constructor(code, message, op) {
37
+ super(code, message, op);
38
+ this.name = name;
39
+ }
40
+ },
41
+ ]));
42
+ function makeError(code, message, op) {
43
+ const Cls = Errors[ERROR_NAMES[code]] || NodbliteError;
44
+ return new Cls(code, message, op);
45
+ }
46
+ /**
47
+ * 一个 nodblite 数据库。
48
+ *
49
+ * 用法与 better-sqlite3 类似:
50
+ * ```js
51
+ * import { Database } from 'nodblite';
52
+ * const db = new Database('app.nodb');
53
+ * db.collection('users').insert({ name: '张三' });
54
+ * db.close();
55
+ * ```
56
+ */
57
+ export class Database {
58
+ #f;
59
+ #db;
60
+ #closed = false;
61
+ /**
62
+ * @param {string} path 数据库文件路径(必须以 `.nodb` 结尾)
63
+ * @param {{create?: boolean, libPath?: string}} [opts]
64
+ */
65
+ constructor(path, opts = {}) {
66
+ if (!path || typeof path !== 'string') {
67
+ throw new TypeError('Database 需要一个文件路径');
68
+ }
69
+ if (!path.toLowerCase().endsWith('.nodb')) {
70
+ throw new Error(`文件后缀必须是 .nodb,收到: ${path}`);
71
+ }
72
+ this.#f = loadBindings(opts.libPath ?? resolveLibPath());
73
+ this.path = path;
74
+ this.#db = this.#f.open(path, opts.create === false ? 0 : 1);
75
+ if (!this.#db) {
76
+ throw makeError(this.#f.lastErrorCode(), this.#lastError(), 'open');
77
+ }
78
+ }
79
+ #lastError() {
80
+ const p = this.#f.lastError();
81
+ if (!p)
82
+ return '';
83
+ // lastError 返回 C 字符串指针;koffi 对 const char* 返回值已自动转成 string,
84
+ // 但也可能是裸指针,两种都兼容。
85
+ return typeof p === 'string' ? p : this.#f.koffi.decode(p, 'char');
86
+ }
87
+ #assertOpen() {
88
+ if (this.#closed)
89
+ throw new Error('数据库已关闭');
90
+ }
91
+ /**
92
+ * 执行一次 C 调用并把结果拷成普通 JS 值。
93
+ *
94
+ * **关键**:`value` / `docs` 指向 arena 内部内存,必须在 `resultFree` 之前
95
+ * 全部拷出来,否则会读到已释放内存(表现为乱码或崩溃)。
96
+ */
97
+ #call(raw) {
98
+ this.#assertOpen();
99
+ if (!raw)
100
+ throw makeError(this.#f.lastErrorCode(), this.#lastError(), '');
101
+ try {
102
+ const r = this.#f.koffi.decode(raw, this.#f.Result);
103
+ if (r.code !== 0) {
104
+ throw makeError(r.code, this.#lastError(), '');
105
+ }
106
+ const { Slice, koffi } = this.#f;
107
+ return {
108
+ count: Number(r.count),
109
+ affected: Number(r.affected),
110
+ value: sliceToString(koffi, r.value),
111
+ docs: r.count === 0
112
+ ? []
113
+ : koffi.decode(r.docs, Slice, r.count).map((s) => sliceToString(koffi, s)),
114
+ };
115
+ }
116
+ finally {
117
+ this.#f.resultFree(raw);
118
+ }
119
+ }
120
+ // ==================== 读 ====================
121
+ /**
122
+ * 查询文档。
123
+ * @template T
124
+ * @param {string} collection
125
+ * @param {object} [filter] MongoDB 风格过滤条件
126
+ * @param {{sort?: object, fields?: object, skip?: number, limit?: number}} [opts]
127
+ * @returns {T[]}
128
+ */
129
+ find(collection, filter = {}, opts = {}) {
130
+ const r = this.#call(this.#f.find(this.#db, collection, JSON.stringify(filter), opts.sort ? JSON.stringify(opts.sort) : null, opts.fields ? JSON.stringify(opts.fields) : null, BigInt(opts.skip ?? 0), BigInt(opts.limit ?? 0)));
131
+ return r.docs.map((s) => JSON.parse(s));
132
+ }
133
+ /**
134
+ * 分页查询:一次拿到「匹配总数 + 当页文档」,省掉单独 count。
135
+ * @template T
136
+ * @returns {{total: number, items: T[]}}
137
+ */
138
+ findPage(collection, filter = {}, opts = {}) {
139
+ const r = this.#call(this.#f.findPage(this.#db, collection, JSON.stringify(filter), opts.sort ? JSON.stringify(opts.sort) : null, opts.fields ? JSON.stringify(opts.fields) : null, BigInt(opts.skip ?? 0), BigInt(opts.limit ?? 0), opts.limit == null ? 1 : 0));
140
+ return { total: r.affected, items: r.docs.map((s) => JSON.parse(s)) };
141
+ }
142
+ /**
143
+ * 按 `_id` 读单条,不存在返回 `null`。
144
+ * @template T
145
+ * @returns {T | null}
146
+ */
147
+ get(collection, id) {
148
+ const r = this.#call(this.#f.get(this.#db, collection, String(id)));
149
+ return r.value === '' ? null : JSON.parse(r.value);
150
+ }
151
+ /** 计数。 */
152
+ count(collection, filter = {}) {
153
+ return this.#call(this.#f.count(this.#db, collection, JSON.stringify(filter))).affected;
154
+ }
155
+ /** 列出全部集合名。 */
156
+ collections() {
157
+ return this.#call(this.#f.listCollections(this.#db)).docs.map((s) => JSON.parse(s));
158
+ }
159
+ // ==================== 写 ====================
160
+ /** 插入一条,返回 `_id`。 */
161
+ insert(collection, doc) {
162
+ return this.#call(this.#f.insert(this.#db, collection, JSON.stringify(doc))).value;
163
+ }
164
+ /** 批量插入(单事务),返回 `_id` 数组。 */
165
+ insertMany(collection, docs) {
166
+ if (!Array.isArray(docs))
167
+ throw new TypeError('insertMany 需要数组');
168
+ const r = this.#call(this.#f.insertMany(this.#db, collection, JSON.stringify(docs)));
169
+ return JSON.parse(r.value);
170
+ }
171
+ /** 更新,返回实际修改条数。 */
172
+ update(collection, filter, update) {
173
+ return this.#call(this.#f.update(this.#db, collection, JSON.stringify(filter), JSON.stringify(update))).affected;
174
+ }
175
+ /** 删除,返回删除条数。 */
176
+ delete(collection, filter) {
177
+ return this.#call(this.#f.delete(this.#db, collection, JSON.stringify(filter))).affected;
178
+ }
179
+ /**
180
+ * 更新或插入。
181
+ * @returns {{updated: number} | {inserted: string}}
182
+ */
183
+ upsert(collection, filter, update) {
184
+ const r = this.#call(this.#f.upsert(this.#db, collection, JSON.stringify(filter), JSON.stringify(update)));
185
+ return JSON.parse(r.value);
186
+ }
187
+ // ==================== 索引 ====================
188
+ /**
189
+ * 创建索引。
190
+ * @param {{unique?: boolean, sparse?: boolean, fields?: string[], directions?: number[]}} [opts]
191
+ * 传 `fields` 则为复合索引;否则用 `field`。
192
+ */
193
+ createIndex(collection, name, field, opts = {}) {
194
+ const unique = opts.unique ? 1 : 0;
195
+ const sparse = opts.sparse ? 1 : 0;
196
+ if (opts.fields && opts.fields.length > 0) {
197
+ const r = this.#call(this.#f.createIndexComposite(this.#db, collection, name, JSON.stringify(opts.fields), opts.directions ? JSON.stringify(opts.directions) : null, unique, sparse));
198
+ return r.value;
199
+ }
200
+ const r = this.#call(this.#f.createIndex(this.#db, collection, name, field, unique, sparse));
201
+ return r.value;
202
+ }
203
+ /** 列出索引定义。 */
204
+ listIndexes(collection) {
205
+ return JSON.parse(this.#call(this.#f.listIndexes(this.#db, collection)).value);
206
+ }
207
+ /** 删除索引。 */
208
+ dropIndex(collection, name) {
209
+ return this.#call(this.#f.dropIndex(this.#db, collection, name)).value === 'true';
210
+ }
211
+ /**
212
+ * 查看查询计划。
213
+ * @returns {{stage: 'IXSCAN' | 'COLLSCAN', [k: string]: unknown}}
214
+ */
215
+ explain(collection, filter = {}, sort = null) {
216
+ const r = this.#call(this.#f.explain(this.#db, collection, JSON.stringify(filter), sort ? JSON.stringify(sort) : null));
217
+ return JSON.parse(r.value);
218
+ }
219
+ // ==================== 生命周期 ====================
220
+ /** 关闭数据库。可重复调用。 */
221
+ close() {
222
+ if (this.#closed)
223
+ return;
224
+ this.#f.close(this.#db);
225
+ this.#db = null;
226
+ this.#closed = true;
227
+ }
228
+ /** 支持 `using db = new Database(...)` 自动关闭。 */
229
+ [Symbol.dispose]() {
230
+ this.close();
231
+ }
232
+ }
233
+ export { resolveLibPath };
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "nodblite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.7",
4
+ "description": "单文件 NoSQL 文档数据库 —— MongoDB 风格查询,零配置,无需服务进程",
5
+ "keywords": ["database", "nosql", "embedded", "document", "mongodb", "sqlite"],
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/Titor-Z/nosqlite"
10
+ },
11
+ "homepage": "https://titor-z.github.io/nosqlite/",
12
+ "type": "module",
13
+ "main": "./dist/index.cjs",
14
+ "module": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "require": "./dist/index.cjs"
21
+ }
22
+ },
23
+ "files": ["dist", "prebuilds", "README.md", "LICENSE"],
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc",
29
+ "test": "node --test test/*.test.js"
30
+ },
31
+ "dependencies": {
32
+ "koffi": "^2.9.0"
33
+ },
34
+ "devDependencies": {
35
+ "typescript": "^5.6.0"
36
+ }
37
+ }
Binary file