document-dataply 0.0.8 → 0.0.9-alpha.1

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/readme.md CHANGED
@@ -50,14 +50,16 @@ type MyDocument = {
50
50
  }
51
51
 
52
52
  async function main() {
53
- const db = DocumentDataply.Define<MyDocument>().Options({
54
- wal: 'my-database.wal',
55
- indices: {
56
- name: true, // Index both existing and new data
57
- age: false, // Index only new data
58
- 'tags.0': true // Index the first element of the 'tags' array
59
- }
60
- }).Open('my-database.db');
53
+ const db = DocumentDataply.Define<MyDocument>()
54
+ .Options({ wal: 'my-database.wal' })
55
+ .Open('my-database.db');
56
+
57
+ // Register indices before init (Recommended)
58
+ await db.createIndex('name', { type: 'btree', fields: ['name'] });
59
+ await db.createIndex('tags_0', { type: 'btree', fields: ['tags.0'] });
60
+
61
+ // Composite Index support
62
+ await db.createIndex('idx_name_age', { type: 'btree', fields: ['name', 'age'] });
61
63
 
62
64
  // Initialize database
63
65
  await db.init();
@@ -93,15 +95,30 @@ main();
93
95
 
94
96
  ## Advanced Usage
95
97
 
96
- ### Indexing Policies
98
+ ### Dynamic Index Management
97
99
 
98
- When defining indices in the `options`, you can specify a boolean value.
100
+ `document-dataply` supports creating indices at any time—whether before or after the database is initialized.
99
101
 
100
- - `true`: The library indexes all existing documents for that field during `init()`, and also indexes all subsequent insertions.
101
- - `false`: The library only indexes documents inserted after this configuration.
102
+ - **Pre-Init**: Creating an index before `db.init()` ensures that the database is ready with all necessary structures from the start.
103
+ - **Post-Init**: You can call `db.createIndex()` even after the database is already running. The library will automatically create the index and perform **backfilling** (populating the index with existing data) in the background.
102
104
 
103
- > [!NOTE]
104
- > `db.init()` automatically performs a backfilling process for fields marked as `true`.
105
+ ```typescript
106
+ // Create a new index on an existing database
107
+ await db.createIndex('idx_new_field', { type: 'btree', fields: ['newField'] });
108
+ ```
109
+
110
+ ### Composite Indexing
111
+
112
+ You can create an index on multiple fields. This is useful for optimizing queries that filter or sort by multiple criteria.
113
+
114
+ ```typescript
115
+ await db.createIndex('idx_composite', {
116
+ type: 'btree',
117
+ fields: ['category', 'price', 'status']
118
+ });
119
+ ```
120
+
121
+ The sorting is performed element-by-element in the order defined in the `fields` array. If all values are equal, the system uses the internal `_id` as a fallback to ensure stable sorting.
105
122
 
106
123
  ### Batch Insertion
107
124
 
@@ -147,6 +164,19 @@ For detailed usage and error handling patterns, see the [Transaction Guide (TRAN
147
164
 
148
165
  For details on streaming mechanisms and bandwidth optimization tips, see the [Stream Guide (STREAM.md)](./docs/STREAM.md).
149
166
 
167
+ ### Schema Migration
168
+
169
+ As your document structure evolves, you can use the `migration()` method to safely update your database. This method uses a `schemeVersion` to track which migrations have been applied.
170
+
171
+ ```typescript
172
+ await db.migration(1, async (tx) => {
173
+ // Add a new index for an existing database
174
+ await db.createIndex('age', { type: 'btree', fields: ['age'] }, tx);
175
+ });
176
+ ```
177
+
178
+ For more details on handling database evolution, see the [Migration Guide (MIGRATION.md)](./docs/MIGRATION.md).
179
+
150
180
  ## Tips and Advanced Features
151
181
 
152
182
  For more information on performance optimization and advanced features, see [TIPS.md](./docs/TIPS.md).
@@ -155,16 +185,32 @@ For more information on performance optimization and advanced features, see [TIP
155
185
  - **Sorting and Pagination**: Detailed usage of `limit`, `orderBy`, and `sortOrder`.
156
186
  - **Memory Management**: When to use `stream` vs `drain()`.
157
187
  - **Performance**: Optimizing bulk data insertion using `insertBatch`.
158
- - **Indexing Policies**: Deep dive into index backfilling and configuration.
188
+ - **Indexing Policies**: Dynamic index creation and automatic backfilling.
189
+ - **Composite Indexes**: Indexing multiple fields for complex queries.
159
190
 
160
191
  ## API Reference
161
192
 
162
- ### `DocumentDataply.Define<T>().Options(options).Open(file)`
163
- Creates or opens a database instance. `T` defines the document structure.
164
- `options.indices` is an object where keys are field names and values are booleans indicating the [Indexing Policy](#indexing-policies).
193
+ ### `db.createIndex(name, options, tx?)`
194
+ Registers or creates a named index. Can be called at any time.
195
+ - `options`: `{ type: 'btree', fields: string[] }` or `{ type: 'fts', fields: string, tokenizer: ... }`.
196
+ - `tx`: Optional transaction.
197
+ - Returns `Promise<this>` for chaining.
198
+
199
+ ### `db.dropIndex(name, tx?)`
200
+ Removes a named index from the database.
201
+ - `name`: The name of the index to drop.
202
+ - `tx`: Optional transaction.
203
+ - Returns `Promise<this>` for chaining.
204
+ - Note: The internal `_id` index cannot be dropped.
165
205
 
166
206
  ### `db.init()`
167
- Initializes the database, sets up internal metadata, and prepares indices.
207
+ Initializes the database and sets up system-managed indices. It also triggers backfilling for indices registered before `init()`.
208
+
209
+ ### `db.migration(version, callback, tx?)`
210
+ Runs a migration callback if the current `schemeVersion` is lower than the target `version`.
211
+ - `version`: The target scheme version (number).
212
+ - `callback`: An async function `(tx: Transaction) => Promise<void>`.
213
+ - `tx`: Optional transaction.
168
214
 
169
215
  ### `db.insert(document, tx?)`
170
216
  Inserts a single document. Each document is automatically assigned a unique, immutable `_id` field. The method returns this `_id` (`number`).
@@ -188,7 +234,10 @@ Fully replaces documents matching the query while preserving their `_id`. Return
188
234
  Deletes documents matching the query. Returns the number of deleted documents.
189
235
 
190
236
  ### `db.getMetadata(tx?)`
191
- Returns physical storage information (number of pages, number of rows, etc.).
237
+ Returns physical storage information and index metadata.
238
+ - Returns `Promise<{ pageSize, pageCount, rowCount, indices, schemeVersion }>`
239
+ - `indices`: List of user-defined index names.
240
+ - `schemeVersion`: The current schema version of the database.
192
241
 
193
242
  ### `db.createTransaction()`
194
243
  Returns a new `Transaction` object.