UNPKG

@isdk/kvsqlite

Version:

[![npm version](https://img.shields.io/npm/v/@isdk/kvsqlite.svg)](https://www.npmjs.com/package/@isdk/kvsqlite) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

1,244 lines (1,085 loc) 61.7 kB
import Database, { Statement } from 'better-sqlite3'; declare global { // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- It has to be an `interface` so that it can be merged. interface SymbolConstructor { readonly observable: symbol; } } /** Extract all optional keys from the given type. This is useful when you want to create a new type that contains different type values for the optional keys only. @example ``` import type {OptionalKeysOf, Except} from 'type-fest'; interface User { name: string; surname: string; luckyNumber?: number; } const REMOVE_FIELD = Symbol('remove field symbol'); type UpdateOperation<Entity extends object> = Except<Partial<Entity>, OptionalKeysOf<Entity>> & { [Key in OptionalKeysOf<Entity>]?: Entity[Key] | typeof REMOVE_FIELD; }; const update1: UpdateOperation<User> = { name: 'Alice' }; const update2: UpdateOperation<User> = { name: 'Bob', luckyNumber: REMOVE_FIELD }; ``` @category Utilities */ type OptionalKeysOf<BaseType extends object> = BaseType extends unknown // For distributing `BaseType` ? (keyof { [Key in keyof BaseType as BaseType extends Record<Key, BaseType[Key]> ? never : Key]: never }) & (keyof BaseType) // Intersect with `keyof BaseType` to ensure result of `OptionalKeysOf<BaseType>` is always assignable to `keyof BaseType` : never; // Should never happen /** Extract all required keys from the given type. This is useful when you want to create a new type that contains different type values for the required keys only or use the list of keys for validation purposes, etc... @example ``` import type {RequiredKeysOf} from 'type-fest'; declare function createValidation<Entity extends object, Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>>(field: Key, validator: (value: Entity[Key]) => boolean): ValidatorFn; interface User { name: string; surname: string; luckyNumber?: number; } const validator1 = createValidation<User>('name', value => value.length < 25); const validator2 = createValidation<User>('surname', value => value.length < 25); ``` @category Utilities */ type RequiredKeysOf<BaseType extends object> = BaseType extends unknown // For distributing `BaseType` ? Exclude<keyof BaseType, OptionalKeysOf<BaseType>> : never; // Should never happen /** Returns a boolean for whether the given type is `never`. @link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919 @link https://stackoverflow.com/a/53984913/10292952 @link https://www.zhenghao.io/posts/ts-never Useful in type utilities, such as checking if something does not occur. @example ``` import type {IsNever, And} from 'type-fest'; // https://github.com/andnp/SimplyTyped/blob/master/src/types/strings.ts type AreStringsEqual<A extends string, B extends string> = And< IsNever<Exclude<A, B>> extends true ? true : false, IsNever<Exclude<B, A>> extends true ? true : false >; type EndIfEqual<I extends string, O extends string> = AreStringsEqual<I, O> extends true ? never : void; function endIfEqual<I extends string, O extends string>(input: I, output: O): EndIfEqual<I, O> { if (input === output) { process.exit(0); } } endIfEqual('abc', 'abc'); //=> never endIfEqual('abc', '123'); //=> void ``` @category Type Guard @category Utilities */ type IsNever<T> = [T] extends [never] ? true : false; /** An if-else-like type that resolves depending on whether the given type is `never`. @see {@link IsNever} @example ``` import type {IfNever} from 'type-fest'; type ShouldBeTrue = IfNever<never>; //=> true type ShouldBeBar = IfNever<'not never', 'foo', 'bar'>; //=> 'bar' ``` @category Type Guard @category Utilities */ type IfNever<T, TypeIfNever = true, TypeIfNotNever = false> = ( IsNever<T> extends true ? TypeIfNever : TypeIfNotNever ); // Can eventually be replaced with the built-in once this library supports // TS5.4+ only. Tracked in https://github.com/sindresorhus/type-fest/issues/848 type NoInfer<T> = T extends infer U ? U : never; /** Returns a boolean for whether the given type is `any`. @link https://stackoverflow.com/a/49928360/1490091 Useful in type utilities, such as disallowing `any`s to be passed to a function. @example ``` import type {IsAny} from 'type-fest'; const typedObject = {a: 1, b: 2} as const; const anyObject: any = {a: 1, b: 2}; function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(obj: O, key: K) { return obj[key]; } const typedA = get(typedObject, 'a'); //=> 1 const anyA = get(anyObject, 'a'); //=> any ``` @category Type Guard @category Utilities */ type IsAny<T> = 0 extends 1 & NoInfer<T> ? true : false; /** Returns a boolean for whether the two given types are equal. @link https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650 @link https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796 Use-cases: - If you want to make a conditional branch based on the result of a comparison of two types. @example ``` import type {IsEqual} from 'type-fest'; // This type returns a boolean for whether the given array includes the given item. // `IsEqual` is used to compare the given array at position 0 and the given item and then return true if they are equal. type Includes<Value extends readonly any[], Item> = Value extends readonly [Value[0], ...infer rest] ? IsEqual<Value[0], Item> extends true ? true : Includes<rest, Item> : false; ``` @category Type Guard @category Utilities */ type IsEqual<A, B> = (<G>() => G extends A & G | G ? 1 : 2) extends (<G>() => G extends B & G | G ? 1 : 2) ? true : false; /** Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability. @example ``` import type {Simplify} from 'type-fest'; type PositionProps = { top: number; left: number; }; type SizeProps = { width: number; height: number; }; // In your editor, hovering over `Props` will show a flattened object with all the properties. type Props = Simplify<PositionProps & SizeProps>; ``` Sometimes it is desired to pass a value as a function argument that has a different type. At first inspection it may seem assignable, and then you discover it is not because the `value`'s type definition was defined as an interface. In the following example, `fn` requires an argument of type `Record<string, unknown>`. If the value is defined as a literal, then it is assignable. And if the `value` is defined as type using the `Simplify` utility the value is assignable. But if the `value` is defined as an interface, it is not assignable because the interface is not sealed and elsewhere a non-string property could be added to the interface. If the type definition must be an interface (perhaps it was defined in a third-party npm package), then the `value` can be defined as `const value: Simplify<SomeInterface> = ...`. Then `value` will be assignable to the `fn` argument. Or the `value` can be cast as `Simplify<SomeInterface>` if you can't re-declare the `value`. @example ``` import type {Simplify} from 'type-fest'; interface SomeInterface { foo: number; bar?: string; baz: number | undefined; } type SomeType = { foo: number; bar?: string; baz: number | undefined; }; const literal = {foo: 123, bar: 'hello', baz: 456}; const someType: SomeType = literal; const someInterface: SomeInterface = literal; function fn(object: Record<string, unknown>): void {} fn(literal); // Good: literal object type is sealed fn(someType); // Good: type is sealed fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type` ``` @link https://github.com/microsoft/TypeScript/issues/15300 @see SimplifyDeep @category Object */ type Simplify<T> = {[KeyType in keyof T]: T[KeyType]} & {}; /** Omit any index signatures from the given object type, leaving only explicitly defined properties. This is the counterpart of `PickIndexSignature`. Use-cases: - Remove overly permissive signatures from third-party types. This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747). It relies on the fact that an empty object (`{}`) is assignable to an object with just an index signature, like `Record<string, unknown>`, but not to an object with explicitly defined keys, like `Record<'foo' | 'bar', unknown>`. (The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.) ``` const indexed: Record<string, unknown> = {}; // Allowed const keyed: Record<'foo', unknown> = {}; // Error // => TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar ``` Instead of causing a type error like the above, you can also use a [conditional type](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html) to test whether a type is assignable to another: ``` type Indexed = {} extends Record<string, unknown> ? '✅ `{}` is assignable to `Record<string, unknown>`' : '❌ `{}` is NOT assignable to `Record<string, unknown>`'; // => '✅ `{}` is assignable to `Record<string, unknown>`' type Keyed = {} extends Record<'foo' | 'bar', unknown> ? "✅ `{}` is assignable to `Record<'foo' | 'bar', unknown>`" : "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`"; // => "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`" ``` Using a [mapped type](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#further-exploration), you can then check for each `KeyType` of `ObjectType`... ``` import type {OmitIndexSignature} from 'type-fest'; type OmitIndexSignature<ObjectType> = { [KeyType in keyof ObjectType // Map each key of `ObjectType`... ]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature<Foo> == Foo`. }; ``` ...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)... ``` import type {OmitIndexSignature} from 'type-fest'; type OmitIndexSignature<ObjectType> = { [KeyType in keyof ObjectType // Is `{}` assignable to `Record<KeyType, unknown>`? as {} extends Record<KeyType, unknown> ? ... // ✅ `{}` is assignable to `Record<KeyType, unknown>` : ... // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>` ]: ObjectType[KeyType]; }; ``` If `{}` is assignable, it means that `KeyType` is an index signature and we want to remove it. If it is not assignable, `KeyType` is a "real" key and we want to keep it. @example ``` import type {OmitIndexSignature} from 'type-fest'; interface Example { // These index signatures will be removed. [x: string]: any [x: number]: any [x: symbol]: any [x: `head-${string}`]: string [x: `${string}-tail`]: string [x: `head-${string}-tail`]: string [x: `${bigint}`]: string [x: `embedded-${number}`]: string // These explicitly defined keys will remain. foo: 'bar'; qux?: 'baz'; } type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>; // => { foo: 'bar'; qux?: 'baz' | undefined; } ``` @see PickIndexSignature @category Object */ type OmitIndexSignature<ObjectType> = { [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown> ? never : KeyType]: ObjectType[KeyType]; }; /** Pick only index signatures from the given object type, leaving out all explicitly defined properties. This is the counterpart of `OmitIndexSignature`. @example ``` import type {PickIndexSignature} from 'type-fest'; declare const symbolKey: unique symbol; type Example = { // These index signatures will remain. [x: string]: unknown; [x: number]: unknown; [x: symbol]: unknown; [x: `head-${string}`]: string; [x: `${string}-tail`]: string; [x: `head-${string}-tail`]: string; [x: `${bigint}`]: string; [x: `embedded-${number}`]: string; // These explicitly defined keys will be removed. ['kebab-case-key']: string; [symbolKey]: string; foo: 'bar'; qux?: 'baz'; }; type ExampleIndexSignature = PickIndexSignature<Example>; // { // [x: string]: unknown; // [x: number]: unknown; // [x: symbol]: unknown; // [x: `head-${string}`]: string; // [x: `${string}-tail`]: string; // [x: `head-${string}-tail`]: string; // [x: `${bigint}`]: string; // [x: `embedded-${number}`]: string; // } ``` @see OmitIndexSignature @category Object */ type PickIndexSignature<ObjectType> = { [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown> ? KeyType : never]: ObjectType[KeyType]; }; // Merges two objects without worrying about index signatures. type SimpleMerge<Destination, Source> = { [Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key]; } & Source; /** Merge two types into a new type. Keys of the second type overrides keys of the first type. @example ``` import type {Merge} from 'type-fest'; interface Foo { [x: string]: unknown; [x: number]: unknown; foo: string; bar: symbol; } type Bar = { [x: number]: number; [x: symbol]: unknown; bar: Date; baz: boolean; }; export type FooBar = Merge<Foo, Bar>; // => { // [x: string]: unknown; // [x: number]: number; // [x: symbol]: unknown; // foo: string; // bar: Date; // baz: boolean; // } ``` @category Object */ type Merge<Destination, Source> = Simplify< SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>> & SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>> >; /** An if-else-like type that resolves depending on whether the given type is `any`. @see {@link IsAny} @example ``` import type {IfAny} from 'type-fest'; type ShouldBeTrue = IfAny<any>; //=> true type ShouldBeBar = IfAny<'not any', 'foo', 'bar'>; //=> 'bar' ``` @category Type Guard @category Utilities */ type IfAny<T, TypeIfAny = true, TypeIfNotAny = false> = ( IsAny<T> extends true ? TypeIfAny : TypeIfNotAny ); // Should never happen /** An if-else-like type that resolves depending on whether the given type is `any` or `never`. @example ``` // When `T` is a NOT `any` or `never` (like `string`) => Returns `IfNotAnyOrNever` branch type A = IfNotAnyOrNever<string, 'VALID', 'IS_ANY', 'IS_NEVER'>; //=> 'VALID' // When `T` is `any` => Returns `IfAny` branch type B = IfNotAnyOrNever<any, 'VALID', 'IS_ANY', 'IS_NEVER'>; //=> 'IS_ANY' // When `T` is `never` => Returns `IfNever` branch type C = IfNotAnyOrNever<never, 'VALID', 'IS_ANY', 'IS_NEVER'>; //=> 'IS_NEVER' ``` */ type IfNotAnyOrNever<T, IfNotAnyOrNever, IfAny = any, IfNever = never> = IsAny<T> extends true ? IfAny : IsNever<T> extends true ? IfNever : IfNotAnyOrNever; /** Merges user specified options with default options. @example ``` type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false}; type SpecifiedOptions = {leavesOnly: true}; type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>; //=> {maxRecursionDepth: 10; leavesOnly: true} ``` @example ``` // Complains if default values are not provided for optional options type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10}; type SpecifiedOptions = {}; type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>; // ~~~~~~~~~~~~~~~~~~~ // Property 'leavesOnly' is missing in type 'DefaultPathsOptions' but required in type '{ maxRecursionDepth: number; leavesOnly: boolean; }'. ``` @example ``` // Complains if an option's default type does not conform to the expected type type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: 'no'}; type SpecifiedOptions = {}; type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>; // ~~~~~~~~~~~~~~~~~~~ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'. ``` @example ``` // Complains if an option's specified type does not conform to the expected type type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean}; type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false}; type SpecifiedOptions = {leavesOnly: 'yes'}; type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>; // ~~~~~~~~~~~~~~~~ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'. ``` */ type ApplyDefaultOptions< Options extends object, Defaults extends Simplify<Omit<Required<Options>, RequiredKeysOf<Options>> & Partial<Record<RequiredKeysOf<Options>, never>>>, SpecifiedOptions extends Options, > = IfAny<SpecifiedOptions, Defaults, IfNever<SpecifiedOptions, Defaults, Simplify<Merge<Defaults, { [Key in keyof SpecifiedOptions as Key extends OptionalKeysOf<Options> ? Extract<SpecifiedOptions[Key], undefined> extends never ? Key : never : Key ]: SpecifiedOptions[Key] }> & Required<Options>> // `& Required<Options>` ensures that `ApplyDefaultOptions<SomeOption, ...>` is always assignable to `Required<SomeOption>` >>; /** Filter out keys from an object. Returns `never` if `Exclude` is strictly equal to `Key`. Returns `never` if `Key` extends `Exclude`. Returns `Key` otherwise. @example ``` type Filtered = Filter<'foo', 'foo'>; //=> never ``` @example ``` type Filtered = Filter<'bar', string>; //=> never ``` @example ``` type Filtered = Filter<'bar', 'foo'>; //=> 'bar' ``` @see {Except} */ type Filter<KeyType, ExcludeType> = IsEqual<KeyType, ExcludeType> extends true ? never : (KeyType extends ExcludeType ? never : KeyType); type ExceptOptions = { /** Disallow assigning non-specified properties. Note that any omitted properties in the resulting type will be present in autocomplete as `undefined`. @default false */ requireExactProps?: boolean; }; type DefaultExceptOptions = { requireExactProps: false; }; /** Create a type from an object type without certain keys. We recommend setting the `requireExactProps` option to `true`. This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically. This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types ([microsoft/TypeScript#30825](https://github.com/microsoft/TypeScript/issues/30825#issuecomment-523668235)). @example ``` import type {Except} from 'type-fest'; type Foo = { a: number; b: string; }; type FooWithoutA = Except<Foo, 'a'>; //=> {b: string} const fooWithoutA: FooWithoutA = {a: 1, b: '2'}; //=> errors: 'a' does not exist in type '{ b: string; }' type FooWithoutB = Except<Foo, 'b', {requireExactProps: true}>; //=> {a: number} & Partial<Record<"b", never>> const fooWithoutB: FooWithoutB = {a: 1, b: '2'}; //=> errors at 'b': Type 'string' is not assignable to type 'undefined'. // The `Omit` utility type doesn't work when omitting specific keys from objects containing index signatures. // Consider the following example: type UserData = { [metadata: string]: string; email: string; name: string; role: 'admin' | 'user'; }; // `Omit` clearly doesn't behave as expected in this case: type PostPayload = Omit<UserData, 'email'>; //=> type PostPayload = { [x: string]: string; [x: number]: string; } // In situations like this, `Except` works better. // It simply removes the `email` key while preserving all the other keys. type PostPayload = Except<UserData, 'email'>; //=> type PostPayload = { [x: string]: string; name: string; role: 'admin' | 'user'; } ``` @category Object */ type Except<ObjectType, KeysType extends keyof ObjectType, Options extends ExceptOptions = {}> = _Except<ObjectType, KeysType, ApplyDefaultOptions<ExceptOptions, DefaultExceptOptions, Options>>; type _Except<ObjectType, KeysType extends keyof ObjectType, Options extends Required<ExceptOptions>> = { [KeyType in keyof ObjectType as Filter<KeyType, KeysType>]: ObjectType[KeyType]; } & (Options['requireExactProps'] extends true ? Partial<Record<KeysType, never>> : {}); /** Create a type that requires at least one of the given keys. The remaining keys are kept as is. @example ``` import type {RequireAtLeastOne} from 'type-fest'; type Responder = { text?: () => string; json?: () => string; secure?: boolean; }; const responder: RequireAtLeastOne<Responder, 'text' | 'json'> = { json: () => '{"message": "ok"}', secure: true }; ``` @category Object */ type RequireAtLeastOne< ObjectType, KeysType extends keyof ObjectType = keyof ObjectType, > = IfNotAnyOrNever<ObjectType, IfNever<KeysType, never, _RequireAtLeastOne<ObjectType, IfAny<KeysType, keyof ObjectType, KeysType>> >>; type _RequireAtLeastOne< ObjectType, KeysType extends keyof ObjectType, > = { // For each `Key` in `KeysType` make a mapped type: [Key in KeysType]-?: Required<Pick<ObjectType, Key>> & // 1. Make `Key`'s type required // 2. Make all other keys in `KeysType` optional Partial<Pick<ObjectType, Exclude<KeysType, Key>>>; }[KeysType] & // 3. Add the remaining keys not in `KeysType` Except<ObjectType, KeysType>; declare function updateKVFieldSymbol(k: string, v: string): void; interface IKVCollections { [name: string]: KVSqliteCollection; } /** * Represents a SQLite database with extended functionality for managing collections and documents. * * This class extends the `Database` class and provides additional methods for creating, managing, and querying collections. * It supports operations such as creating collections, inserting and retrieving documents, and handling full-text search. */ declare class KVSqlite extends Database { /** * The unique id of the database. */ id: string | undefined; preIsExists: Statement; ftsLoaded: { [lang: string]: boolean; }; collections: IKVCollections; serdeOptions: IKVSerdeOptions; /** * Generates a SQL dump string for a given SQLite database. * * @param db The path to the SQLite database file or a SQLite database instance. * @returns The SQL dump string. */ static dump(db: string | Database.Database): string; /** * Constructs a new instance of KVSqlite. * * This constructor initializes a new KVSqlite instance with the specified filename and options. * It handles the creation of directories, prepares SQL statements, sets serialization and deserialization options, * and initializes collections as specified in the options. * * @param filename - The filename or buffer for the SQLite database file. * @param options - Optional settings including serialization, deserialization, ID, and collection configurations. */ constructor(filename?: string | Buffer, options?: IKVSetOptions & IKVCreateOptions & IKVCreateExOptions); /** * Creates multiple collections in the database. * * This function creates multiple collections (tables) based on the provided array of collection names or configuration objects. * Each element in the array can be either a string representing the collection name or an object containing collection options. * If a collection already exists, it does nothing for that collection. * * @param collections - An array of collection names or configuration objects. * @param options - Optional default settings for the collections, used if individual collection options are not provided. */ createCollections(collections: (string | IKVCreateOptions | IKVCreateExOptions)[], options?: IKVCreateOptions | IKVCreateExOptions): void; tryUpgradeVer(ver?: number): void; usingJsonb(collection?: string): boolean | undefined; getSysConfig(key: string, collection?: string): any; setSysConfig(key: string, value: any, collection?: string): KVSqliteRunResult | undefined; getSerdeOptions(options?: any): IKVSerdeOptions; /** * Creates a new collection in the database. * * This function creates a new collection (table) with the specified name and options. * If the collection already exists, it does nothing and returns the existing collection instance. * * @param name - The name of the collection to create. * @param options - Optional settings for the collection, including fields, FTS configuration, and JSONB usage. * @returns The newly created collection instance. */ create(name: string, options?: IKVCreateOptions | IKVCreateExOptions): KVSqliteCollection | undefined; /** * Retrieves a collection by name. * * This function returns the collection instance for the specified name. If the collection does not exist in memory, * it checks if the collection exists in the database and initializes it if necessary. * * @param name - The name of the collection to retrieve. * @returns The collection instance if it exists, otherwise `undefined`. */ getCollection(name: string): KVSqliteCollection; /** * Drops a specified collection from the database. * * This function removes a collection (table) from the database. It throws an error if the collection is a system collection * (e.g., `SYS_KV_COLLECTION` or `DefaultKVCollection`). It also cleans up related entries in the system collection. * * @param name - The name of the collection to drop. * @throws An error if the collection is a system collection. */ drop(name: string): void; /** * Sets or updates a document in a specified collection. * * This function inserts or updates a document in the specified collection using the provided document ID and object. * It supports different parameter configurations and defaults to the `DefaultKVCollection` if no collection is specified. * * @param docId - The ID of the document or an object representing the document. * @param obj - An optional object representing the document or options. * @param options - Optional settings including the collection name and other options. * @returns The result of the set operation. */ set(docId: IKVDocumentId | IKVObjItem, obj?: IKVObjItem | IKVSetOptions, options?: IKVSetOptions): KVSqliteRunResult; /** * Sets an extended property for a document in a specified collection. * * This function updates or inserts a specific property for a document using the provided document ID, key, and value. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param docId - The ID of the document. * @param key - The key of the property to set. * @param value - The value of the property to set. * @param options - Optional settings including the collection name and other options. * @returns The result of the set operation. */ setExtend(docId: IKVDocumentId, key: string, value: any, options?: IKVSetOptions): KVSqliteRunResult; /** * Sets multiple extended properties for a document in a specified collection. * * This function updates or inserts multiple properties for a document using the provided document ID and an object of properties. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param docId - The ID of the document. * @param aDoc - An object containing the properties to set. * @param options - Optional settings including the collection name and other options. * @returns An array of results from the set operations. */ setExtends(docId: IKVDocumentId, aDoc: any, options?: IKVSetOptions): KVSqliteRunResult[]; /** * Inserts or updates multiple documents in a specified collection. * * This function performs a bulk operation to insert or update multiple documents in the specified collection. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param objs - An array of objects representing the documents to insert or update. * @param options - Optional settings including the collection name and other options. * @returns An array of results from the insert or update operations. */ bulkDocs(objs: IKVObjItem[], options?: IKVSetOptions): KVSqliteRunResult[]; /** * Retrieves the value of an extended property for a document in a specified collection based on the specified property name. * * This function fetches the value of a specific property for a document using the provided document ID and property name. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param docId - The ID of the document. * @param aPropName - An optional string representing the property name to retrieve. * @param options - Optional settings including the collection name. * @returns The value of the specified property. */ get(_id: IKVDocumentId, options?: IKVSetOptions): IKVObjItem; getExtend(docId: IKVDocumentId, aPropName?: string, options?: IKVSetOptions): any; /** * Retrieves extended properties for a document in a specified collection based on the specified property names or patterns. * * This function fetches properties for a document using the provided document ID and property names or patterns. * It supports retrieving single or multiple properties and can return either a single value or an object containing all properties. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param docId - The ID of the document. * @param aPropName - An optional string or array of strings representing the property names or patterns. * @param options - Optional settings including the collection name and whether to return a single value. * @returns The retrieved properties as an object or a single value if `singleValue` is true. */ getExtends(docId: IKVDocumentId, aPropName?: string | string[], options?: IKVSetOptions): IKVObjItem; /** * Deletes records from a specified collection based on the provided ID, array of IDs, or filter conditions. * * This function deletes records from the specified collection using the provided ID, array of IDs, or filter conditions. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param _id - An optional ID, array of IDs, or filter object representing the records to delete. * @param options - Optional settings including the collection name. * @returns The result of the delete operation(s). */ del(_id?: IKVDocumentId | IKVDocumentId[] | Record<string, any>, options?: IKVSetOptions): KVSqliteRunResult | KVSqliteRunResult[]; /** * Checks if a record with the specified ID exists in a specified collection. * * This function determines whether a record with the given ID exists in the specified collection. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param _id - The ID of the record to check. * @param options - Optional settings including the collection name. * @returns A boolean indicating whether the record exists. */ isExists(_id: IKVDocumentId, options?: IKVSetOptions): boolean; /** * Counts the number of records in a specified collection based on the provided query. * * This function returns the count of records that match the specified query in the specified collection. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param query - An optional string or object representing the query conditions. * @param options - Optional settings including the collection name. * @returns The number of records matching the query. */ count(query?: string | Record<string, any>, options?: IKVSetOptions): number; /** * Lists records from a specified collection based on the provided query and options. * * This function retrieves records from the specified collection, applying optional filters, sorting, pagination, * and field selection. If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param query - A string or object representing the query conditions. * @param options - Optional settings including the collection name, size, page, sort order, and field names. * @returns An array of objects representing the listed records. */ list(query?: string | IKVSetOptions, options?: IKVSetOptions): IKVObjItem[]; createJsonIndex(indexName: string, fields: string | string[], options?: IKVSetOptions): KVSqliteRunResult; createIndex(indexName: string, fields: string | string[], options?: IKVSetOptions): KVSqliteRunResult; /** * Executes an advanced search query on a specified collection. * * This function performs an advanced search operation on the specified collection using the provided query string or object and options. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param query - A string or record of key-value pairs representing the search query. * @param options - Optional settings including the collection name and other search options. * @returns An array of objects representing the search results. */ searchEx(query: string | Record<string, string>, options?: IKVSetOptions): IKVObjItem[]; /** * Searches for records in a specified collection based on the provided filter conditions. * * This function performs a search operation on the specified collection using the given filter conditions and options. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param filter - A record of key-value pairs representing the filter conditions. * @param options - Optional settings including the collection name and other search options. * @returns An array of objects representing the search results. */ search(filter: Record<string, any>, options?: IKVSetOptions): IKVObjItem[]; /** * Builds a SQL WHERE clause from the provided filter conditions for a specified collection. * * This function constructs a SQL WHERE clause based on the given filter conditions and options. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param filter - A record of key-value pairs representing the filter conditions. * @param options - Optional settings including the collection name and other options. * @returns A string representing the SQL WHERE clause. */ buildWhereClause(filter: Record<string, any>, options?: IKVSetOptions): string; /** * Checks if a database object of a specified type and name exists. * * This function determines whether a specified database object (e.g., table, index) exists in the database. * * @param type - The type of the database object (e.g., 'table', 'index'). * @param name - The name of the database object to check. * @returns A boolean indicating whether the database object exists. */ isTypeExists(type: string, name: string): boolean; /** * Checks if a collection (table) exists in the database. * * This function determines whether a specified collection (table) exists in the database. * * @param collection - The name of the collection to check. * @returns A boolean indicating whether the collection exists. */ isCollectionExists(collection: string): boolean; loadFtsLanguage(options?: IKVCreateFtsOptions): void; /** * Retrieves information about the table structure for a specified collection. * * This function fetches detailed information about the table structure, including field names, types, constraints, and default values. * If no collection is specified, it defaults to the `DefaultKVCollection`. * * @param collection - The name of the collection or an object containing options. * @param options - Optional settings including the collection name and other options. * @returns An object containing detailed information about the table fields. */ tableInfo(collection?: string | IKVSetOptions, options?: IKVSetOptions): Required<IKVFieldOptions> | undefined; _tableInfo(options?: IKVSetOptions): Required<IKVFieldOptions> | undefined; sqlSchema(options?: ISqliteSqlSchemaOptions): ISqliteSqlMasterFields[]; sqlSchema(name: string, options?: ISqliteSqlSchemaOptions): ISqliteSqlMasterFields; /** * Generates a SQL dump string for the database. * @returns The SQL dump string */ dump(): string; isManagedTable(name: string): false | IKVFieldOption | undefined; enableFts(collection?: string, options?: IKVCreateFtsOptions): void; /** * Searches the full-text search (FTS) index for records matching the provided query. * * This function delegates the search operation to the specified collection's `searchFts` method. * If no collection is specified in the options, it defaults to the `DefaultKVCollection`. * * @param query - A record or array of records representing the search query. * @param options - Optional settings including the collection name and other search options. * @returns An array of objects representing the search results. */ searchFts(query: Record<string, any> | Record<string, any>[], options?: IKVSetOptions): { _id: string; 值: any; }[]; } declare class KVSqliteCollection { name: string; protected db: KVSqlite; preAdd: Statement; preUpdate: Statement; preExists: Statement; preGet: Statement; preDel: Statement; preDelAll: Statement; preCount: Statement; preCountW: Statement; preSearchKey: Statement; preSearchKeyAll: Statement; preAll: Statement; preAllLimit: Statement; jsonb: string; createIndexAndTriggerForAutoTimestamp(fields: { [name: string]: RequireAtLeastOne<IKVFieldOption, 'type'>; }): void; /** * Constructs a new instance of KVSqliteCollection. * * This constructor initializes a new collection in the database with the specified name and options. * It handles the creation of the table if it does not already exist, sets up fields, and prepares SQL statements for various operations. * * @param name - The name of the collection. * @param db - The KVSqlite database instance. * @param options - Optional settings for the collection, including fields, FTS configuration, and JSONB usage. */ constructor(name: string, db: KVSqlite, options?: IKVCreateOptions); _set(obj: IKVObjItem, options?: IKVSetOptions): KVSqliteRunResult; /** * Sets or updates a document in the table. * * This function inserts or updates a document in the table using the provided document ID and object. * It supports different parameter configurations and executes the operation within a transaction to ensure atomicity. * * @param docId - The ID of the document or an object representing the document. * @param obj - An optional object representing the document or options. * @param options - Optional settings for the operation. * @returns The result of the set operation. */ set(docId: IKVDocumentId | IKVObjItem, obj?: IKVObjItem | IKVSetOptions, options?: IKVSetOptions): KVSqliteRunResult; _setExtend(docId: IKVDocumentId, key: string, value: any, options?: IKVSetOptions): KVSqliteRunResult; /** * Sets an extended property for a document in a transaction. * * This function updates or inserts a specific property for a document using the provided document ID, key, and value. * It executes the operation within a transaction to ensure atomicity. * * @param docId - The ID of the document. * @param key - The key of the property to set. * @param value - The value of the property to set. * @param options - Optional settings for the operation. * @returns The result of the set operation. */ setExtend(docId: IKVDocumentId, key: string, value: any, options?: IKVSetOptions): KVSqliteRunResult; /** * Sets multiple extended properties for a document in a transaction. * * This function updates or inserts multiple properties for a document using the provided document ID and an object of properties. * It executes the operations within a transaction to ensure atomicity. * * @param docId - The ID of the document. * @param aDoc - An object containing the properties to set. * @param options - Optional settings for the operation. * @returns An array of results from the set operations. */ setExtends(docId: IKVDocumentId, aDoc: any, options?: IKVSetOptions): KVSqliteRunResult[]; /** * Inserts or updates multiple documents in a transaction. * * This function performs a bulk operation to insert or update multiple documents in the table. * It executes the operations within a transaction to ensure atomicity. * * @param objs - An array of objects representing the documents to insert or update. * @param options - Optional settings for the operation. * @returns An array of results from the insert or update operations. */ bulkDocs(objs: IKVObjItem[], options?: IKVSetOptions): KVSqliteRunResult[]; /** * Retrieves a document by its ID and ensures it includes the document ID. * * This function fetches a document from the table using the provided document ID. * It ensures that the returned object includes the document ID as a property. * * @param _id - The ID of the document to retrieve. * @returns The retrieved document as an object with the document ID included. */ get(_id: IKVDocumentId): IKVObjItem; /** * Retrieves a document by its ID and processes the result. * * This function fetches a document from the table using the provided document ID. * It processes the result by parsing SQL fields, handling JSON values, and mapping fields as necessary. * * @param _id - The ID of the document to retrieve. * @returns The retrieved document as an object, string, boolean, or number. */ getEx(_id: IKVDocumentId): IKVObjItem | string | boolean | number; /** * Retrieves the value of an extended property for a document based on the specified property name. * * This function fetches the value of a specific property for a document using the provided document ID and property name. * If no property name is provided, it retrieves the entire document. * * @param docId - The ID of the document. * @param aPropName - An optional string representing the property name to retrieve. * @returns The value of the specified property or the entire document if no property name is provided. */ getExtend(docId: IKVDocumentId, aPropName?: string): any; /** * Checks if an extended property exists for a document based on the specified property name. * * This function checks if a specific property exists for a document using the provided document ID and property name. * If no property name is provided, it checks for the existence of the entire document. * * @param docId - The ID of the document. * @param aPropName - An optional string representing the property name to check. * @returns A boolean indicating whether the property exists. */ isExistsExtend(docId: IKVDocumentId, aPropName?: string): boolean; /** * Deletes an extended property for a document based on the specified property name. * * This function deletes a specific property for a document using the provided document ID and property name. * If no property name is provided, it deletes the entire document. * * @param docId - The ID of the document. * @param aPropName - An optional string representing the property name to delete. * @returns The result of the delete operation. */ delExtend(docId: IKVDocumentId, aPropName?: string): KVSqliteRunResult | KVSqliteRunResult[]; /** * Retrieves extended properties for a document based on the specified property names or patterns. * * This function fetches properties for a document using the provided document ID and property names or patterns. * It supports retrieving single or multiple properties and can return either a single value or an object containing all properties. * * @param docId - The ID of the document. * @param aPropName - An optional string or array of strings representing the property names or patterns. * @param options - Optional settings including whether to return a single value. * @param options.singleValue whether return value if only one property. * @returns The retrieved extends properties as an object or a single value if `singleValue` is true. */ getExtends(docId: IKVDocumentId, aPropName?: string | string[], options?: IKVSetOptions): IKVObjItem; /** * Deletes records from the collection based on the provided ID, array of IDs, or filter conditions. * * This function deletes records from the collection using the provided ID, array of IDs, or filter conditions. * It supports deleting multiple records within a transaction if an array of IDs is provided. * If a filter object is provided, it constructs a SQL WHERE clause from the filter and deletes matching records. * If no ID or filter is provided, it deletes all records in the collection. * * @param _id - An optional ID, array of IDs, or filter object representing the records to delete. * @returns The result of the delete operation(s). */ del(_id?: IKVDocumentId | IKVDocumentId[] | Record<string, any>): KVSqliteRunResult | KVSqliteRunResult[]; /** * Checks if a record with the specified ID exists in the table. * * This function returns a boolean indicating whether a record with the given ID exists. * * @param _id - The ID of the record to check. * @returns A boolean indicating whether the record exists. */ isExists(_id: IKVDocumentId): boolean; /** * Counts the number of records in the collection based on the provided query. * * This function returns the count of records that match the specified query. * If the query is an object, it constructs a SQL WHERE clause from the query object. * * @param query - An optional string or object representing the query conditions. * @returns The number of records matching the query. */ count(query?: string | Record<string, any>): number; /** * Lists records from the table based on the provided query and options. * * This function retrieves records from the table, applying optional filters, sorting, pagination, * and field selection. It supports both string queries and object-based query options. * * @param query - A string or object representing the query conditions. * @param options - Optional settings including size, page, sort order, and field names. * @returns An array of objects representing the listed records. */ list(query?: string | IKVSetOptions, options?: IKVSetOptions): IKVObjItem[]; getSchema(): any; createSchema(options: IKVCreateOptions): void; createTable(name: string, options: IKVCreateOptions): void; createJsonIndex(indexName: string, fields: string | string[]): KVSqliteRunResult; createTableIndex(indexName: string, fields: string | string[]): KVSqliteRunResult; createIndex(index: IKVIndexOptions, options?: IKVCreateOptions): KVSqliteRunResult; createIndexes(options: IKVCreateOptions): KVSqliteRunResult[]; createTrigger(trigger: IKVTriggerOptions, options?: IKVCreateOptions): Database.RunResult; renameField(oldName: string, newName: string | IKVFieldOption, options?: IKVSetOptions): Database.RunResult | undefined; /** * Executes an advanced search query on the database. * * This function constructs and executes a SQL query based on the provided query string or object, * options for sorting, pagination, and field selection. * * @param query - A string or record of key-value pairs representing the search query. * @param options - Optional settings including field information mappings, sorting, pagination, and field names. * @returns An array of objects representing the search results. */ searchEx(query: string | Record<string, string>, options?: IKVSetOptions): IKVObjItem[]; /** * Searches for records based on the provided filter conditions. * * This function constructs a SQL WHERE clause using the provided filter and options, * and then performs the search using the constructed WHERE clause. * * @param filter - A record of key-value pairs representing the filter conditions. * @param options - Optional settings including field information mappings. * @returns The result of the search operation. */ search(filter: Record<string, any>, options?: IKVSetOptions