• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**************************************************************************************************
2 * EJDB2
3 *
4 * MIT License
5 *
6 * Copyright (c) 2012-2021 Softmotions Ltd <info@softmotions.com>
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 *  copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in all
16 * copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 * SOFTWARE.
25 *************************************************************************************************/
26
27declare namespace ejdb2_react_native {
28  export type Placeholder = string | number;
29
30  export type JQLExecuteCallback = (doc: JBDOC, jql?: JQL) => any;
31
32  interface JQLUseQueryCallback<T> {
33    (jql: JQL): Promise<T>;
34  }
35
36  /**
37   * EJDB2 Error helpers.
38   */
39  export class JBE {
40    /**
41     * Returns `true` if given error [err] is `IWKV_ERROR_NOTFOUND`
42     * @param err
43     */
44    static isNotFound(err: any): boolean;
45
46    /**
47     * Returns `true` if given errror [err] is `JQL_ERROR_QUERY_PARSE`
48     * @param {Error} err
49     * @return {boolean}
50     */
51    static isInvalidQuery(err: any): boolean;
52  }
53
54  /**
55   * Database open options.
56   */
57  interface OpenOptions {
58    /**
59     * Open databas in read-only mode.
60     */
61    readonly?: boolean;
62
63    /**
64     * Truncate database file on open.
65     */
66    truncate?: boolean;
67
68    /**
69     * Enable WAL. Default: true.
70     */
71    wal_enabled?: boolean;
72
73    /**
74     * Check CRC32 sum for every WAL checkpoint.
75     * Default: false.
76     */
77    wal_check_crc_on_checkpoint?: boolean;
78
79    /**
80     * Size of checkpoint buffer in bytes.
81     * Default: 1Gb. Android: 64Mb
82     */
83    wal_checkpoint_buffer_sz?: number;
84
85    /**
86     * WAL buffer size in bytes.
87     * Default: 8Mb. Android: 2Mb.
88     */
89    wal_wal_buffer_sz?: number;
90
91    /**
92     * Checkpoint timeout in seconds.
93     * Default: 300. Android: 60.
94     */
95    wal_checkpoint_timeout_sec?: number;
96
97    /**
98     * Savepoint timeout in secods.
99     * Default: 10.
100     */
101    wal_savepoint_timeout_sec?: number;
102
103    /**
104     * Initial size of buffer in bytes used to process/store document on queries.
105     * Preferable average size of document.
106     * Default: 65536. Minimal: 16384.
107     */
108    document_buffer_sz?: number;
109
110    /**
111     * Max sorting buffer size in bytes.
112     * If exceeded, an overflow temp file for data will be created.
113     * Default: 16777216. Minimal: 1048576
114     */
115    sort_buffer_sz?: number;
116  }
117
118  /**
119   * Query execution options.
120   */
121  interface QueryOptions {
122    /**
123     * Overrides `limit` encoded in query
124     */
125    limit?: number | string;
126
127    /**
128     *  Overrides `skip` encoded in query
129     */
130    skip?: number | string;
131  }
132
133  /**
134   * Collection index descriptor.
135   */
136  interface IndexDescriptor {
137    /**
138     * rfc6901 JSON pointer to indexed field.
139     */
140    ptr: string;
141
142    /**
143     * Index mode as bit mask:
144     *
145     * - 0x01 EJDB_IDX_UNIQUE 	Index is unique
146     * - 0x04 EJDB_IDX_STR 	Index for JSON string field value type
147     * - 0x08 EJDB_IDX_I64 	Index for 8 bytes width signed integer field values
148     * - 0x10 EJDB_IDX_F64 	Index for 8 bytes width signed floating point field values.
149     */
150    mode: number;
151
152    /**
153     * Index flags. See iwkv.h#iwdb_flags_t
154     */
155    idbf: number;
156
157    /**
158     * Internal index database identifier.
159     */
160    dbid: number;
161
162    /**
163     * Number of indexed records.
164     */
165    rnum: number;
166  }
167
168  /**
169   * Collection descriptor.
170   */
171  interface CollectionDescriptor {
172    /**
173     * Name of collection.
174     */
175    name: string;
176
177    /**
178     * Internal database identifier.
179     */
180    dbid: number;
181
182    /**
183     * Number of documents stored in collection.
184     */
185    rnum: number;
186
187    /**
188     * List of collection indexes.
189     */
190    indexes: Array<IndexDescriptor>;
191  }
192
193  interface EJDB2Info {
194    /**
195     * Database engine version string.
196     * Eg. "2.0.29"
197     */
198    version: string;
199
200    /**
201     * Database file path.
202     */
203    file: string;
204
205    /**
206     * Database file size in bytes.
207     */
208    size: number;
209
210    /**
211     * List of database collections.
212     */
213    collections: Array<CollectionDescriptor>;
214  }
215
216  /**
217   * EJDB2 document.
218   */
219  interface JBDOC {
220    /*
221     * Document identifier
222     */
223    id: number;
224
225    /**
226     * Document JSON object
227     */
228    json: any;
229
230    /**
231     * String represen
232     */
233    toString(): string;
234  }
235
236  /**
237   * Database wrapper.
238   */
239  export class EJDB2 {
240    /**
241     * Open database identified by relative `filename` in context of
242     * React Native database directory used for sqlite db.
243     *
244     * @param filename `filename` in context of RN sqlite database directory
245     * @param opts Database mode options
246     */
247    static open(name: string, opts?: OpenOptions): EJDB2;
248
249    /**
250     * Closes database instance.
251     */
252    close(): Promise<void>;
253
254    /**
255     * Get json body with database metadata object.
256     */
257    info(): Promise<EJDB2Info>;
258
259    /**
260     * Create instance of [query] specified for [collection].
261     * If [collection] is not specified a [query] spec must contain collection name,
262     * eg: `@mycollection/[foo=bar]`
263     *
264     * @note WARNING In order to avoid memory leaks, dispose created query object by {@link JQL#close}
265     *       or use {@link JQL#use}
266     *
267     * @param query Query text
268     * @param collection Optional collection used in query
269     * @returns {JQL}
270     */
271    createQuery(query: string, collection?: string): JQL;
272
273    /**
274     * Saves [json] document under specified [id] or create a document
275     * with new generated `id`. Returns promise holding actual document `id`.
276     */
277    put(collection: String, json: object | string, id?: number): Promise<number>;
278
279    /**
280     * Apply rfc6902/rfc7386 JSON [patch] to the document identified by [id].
281     */
282    patch(collection: string, json: object | string, id: number): Promise<void>;
283
284    /**
285     * Apply JSON merge patch (rfc7396) to the document identified by `id` or
286     * insert new document under specified `id`.
287     */
288    patchOrPut(collection: string, json: object | string, id: number): Promise<void>;
289
290    /**
291     * Get json body of document identified by [id] and stored in [collection].
292     *
293     * If document with given `id` is not found then `Error` will be thrown.
294     * Not found error can be detected by {@link JBE.isNotFound}
295     */
296    get(collection: string, id: number): Promise<object>;
297
298    /**
299     * Get json body of document identified by [id] and stored in [collection].
300     *
301     * If document with given `id` is not found then `null` will be resoved.
302     */
303    getOrNull(collection: string, id: number): Promise<object|null>;
304
305    /**
306     * Removes document idenfied by [id] from [collection].
307     *
308     * If document with given `id` is not found then `Error` will be thrown.
309     * Not found error can be detected by {@link JBE.isNotFound}
310     */
311    del(collection: string, id: number): Promise<void>;
312
313    /**
314     * Renames collection
315     */
316    renameCollection(oldCollectionName: string, newCollectionName: string): Promise<void>;
317
318    /**
319     * Ensures json document database index specified by [path] json pointer to string data type.
320     */
321    ensureStringIndex(collection: string, path: string, unique?: boolean): Promise<void>;
322
323    /**
324     * Removes specified database index.
325     */
326    removeStringIndex(collection: string, path: string, unique?: boolean): Promise<void>;
327
328    /**
329     * Ensures json document database index specified by [path] json pointer to integer data type.
330     */
331    ensureIntIndex(collection: string, path: string, unique?: boolean): Promise<void>;
332
333    /**
334     * Removes specified database index.
335     */
336    removeIntIndex(collection: string, path: string, unique?: boolean): Promise<void>;
337
338    /**
339     * Ensures json document database index specified by [path] json pointer to floating point data type.
340     */
341    ensureFloatIndex(collection: string, path: string, unique?: boolean): Promise<void>;
342
343    /**
344     * Removes specified database index.
345     */
346    removeFloatIndex(collection: string, path: string, unique?: boolean): Promise<void>;
347
348    /**
349     * Removes database [collection].
350     */
351    removeCollection(collection: string): Promise<void>;
352
353    /**
354     * Creates an online database backup image and copies it into the specified [fileName].
355     * During online backup phase read/write database operations are allowed and not
356     * blocked for significant amount of time. Returns promise with backup
357     * finish time as number of milliseconds since epoch.
358     */
359    onlineBackup(fileName: string): Promise<number>;
360  }
361
362  /**
363   * EJDB Query.
364   */
365  interface JQL {
366    /**
367     * Database instance associated with this query.
368     */
369    readonly db: EJDB2;
370
371    /**
372     * Query text.
373     */
374    readonly query: string;
375
376    /**
377     * Retrieve query execution plan.
378     */
379    readonly explainLog: string | null;
380
381    /**
382     * Number of documents to skip.
383     */
384    readonly skip: number;
385
386    /**
387     * Maximum number of documents to fetch.
388     */
389    readonly limit: number;
390
391    /**
392     * Collection name used in query
393     */
394    readonly collection: string;
395
396    /**
397     * Set number of documents to skip.
398     * Specified value overrides `skip` option encoded in query.
399     * @param {number} skip
400     */
401    withSkip(skip: number): JQL;
402
403    /**
404     * Set maximum number of documents to fetch.
405     * Specified value overrides `limit` option encoded in query.
406     * @param {number} limit Limit
407     */
408    withLimit(limit: number): JQL;
409
410    /**
411     * Set collection to use with query.
412     * Value overrides collection encoded in query.
413     */
414    withCollection(coll: string): JQL;
415
416    /**
417     * Turn on explain query mode
418     */
419    withExplain(): JQL;
420
421    /**
422     * Set string [val] at the specified [placeholder].
423     */
424    setString(placeholder: Placeholder, val: string): JQL;
425
426    /**
427     * Set [json] at the specified [placeholder].
428     */
429    setJSON(placeholder: Placeholder, val: string | object): JQL;
430
431    /**
432     * Set [regexp] string at the specified [placeholder].
433     * @note `RegExp` options are ignored.
434     */
435    setRegexp(placeholder: Placeholder, val: string | RegExp): JQL;
436
437    /**
438     * Set number [val] at the specified [placeholder].
439     */
440    setNumber(placeholder: Placeholder, val: number): JQL;
441
442    /**
443     * Set boolean [val] at the specified [placeholder].
444     */
445    setBoolean(placeholder: Placeholder, val: boolean): JQL;
446
447    /**
448     * Set `null` at the specified [placeholder].
449     */
450    setNull(placeholder: Placeholder): JQL;
451
452    /**
453     * Execute this query.
454     */
455    execute(dispose: boolean, callback: JQLExecuteCallback): Promise<void>;
456
457    /**
458     * Execute this query then dispose it.
459     */
460    useExecute(callback: JQLExecuteCallback): Promise<void>;
461
462    /**
463     * Uses query in `callback` then closes it.
464     * @param callback Function accepts `JQL` query object.
465     * @return `usefn` promise value.
466     */
467    use<T>(callback: JQLUseQueryCallback<T>): Promise<T>;
468
469    /**
470     * List matched document.
471     * @note Use it with care to avoid wasting of memory.
472     *       See {@link JQL#use} for result-set callback API.
473     * @param opts
474     */
475    list(opts: QueryOptions): Promise<JBDOC[]>;
476
477    /**
478     * Collects up to [n] documents from result set into array.
479     * @param n Default: 1
480     */
481    firstN(n?: number): Promise<JBDOC[]>;
482
483    /**
484     * Returns a first record in result set.
485     * If no reconds found `null` resolved promise will be returned.
486     */
487    first(): Promise<JBDOC | null>;
488
489    /**
490     * Returns a scalar integer value as result of query execution.
491     * Eg.: A count query: `/... | count`
492     */
493    scalarInt(): Promise<number>;
494
495    /**
496     * Reset query parameters.
497     */
498    reset(): Promise<void>;
499
500    /**
501     * Disposes JQL instance and releases all underlying resources.
502     */
503    close(): void;
504  }
505}
506
507export = ejdb2_react_native;
508