@isdk/kvsqlite
Version:
SQlite(>=3.45.0) key/value Document store
1,002 lines (959 loc) • 45 kB
text/typescript
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;
}
}
/**
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;
/**
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;
};
/**
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 = {requireExactProps: false}> = {
[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,
> = {
// 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): IKVObjItem[];
/**
* Builds a SQL WHERE clause from the provided filter conditions.
*
* This function converts a record of filter conditions into a SQL WHERE clause string.
*
* @param filter - A record of key-value pairs representing the filter conditions.
* @param options - Optional settings including field information mappings.
* @returns A string representing the SQL WHERE clause.
*/
buildWhereClause(filter: Record<string, any>, options?: IKVSetOptions): string;
/**
* Retrieves information about the table structure.
*
* This function queries the database to get detailed information about the specified table,
* including field names, types, constraints, and default values.
*
* @param options - Optional settings including the collection name and whether to map field names.
* @returns An object containing detailed information about the table fields.
*/
tableInfo(options?: IKVSetOptions): Required<IKVFieldOptions> | undefined;
enableFts(options?: IKVCreateFtsOptions): void;
/**
* Searches the full-text search (FTS) index for records matching the provided query.
*
* This function constructs and executes a SQL query to search the FTS index of the specified collection.
* It supports different query styles and options for field selection and deserialization.
* Additionally, it allows filtering with regular SQL conditions via the `options.query` parameter.
*
* @param query - A string, object, or array of objects representing the search query.
* @param options - Optional settings including collection name, field names, FTS query style, and deserialization options.
* @param options.query - An optional SQL filter condition or an object that will be converted into a WHERE clause using [buildWhereClause].
* @param options.retrieveFull - An optional boolean indicating whether to retrieve the full document or just the ID.
* @returns An array of objects representing the search results.
*
* ### Query Style Options
*
* The ftsQueryStyle option determines how the FTS query is interpreted:
*
* - **`false` or `undefined`**: Simple mode. The query string is wrapped in single quotes.
* - **`true`**: Advanced mode. The query string is used as-is without any wrapping.
* - **`string`**: Wraps the query content with the specified SQLite function, e.g., `'simple_query'`.
*
* @example
*
* searchFts("hello", { ftsQueryStyle: false });
* `Gnerate SQL Condition: MATCH 'hello'`
*
* searchFts("'apple OR banana'", { ftsQueryStyle: true });
* `Gnerate SQL Condition: MATCH 'apple OR banana'`
*
* searchFts({ $or: ["apple", "banana"] }, { ftsQueryStyle: false });
* `Gnerate SQL Condition: MATCH 'apple OR banana'`
*
* searchFts("senior | backend", { ftsQueryStyle: "replace(?, '|', 'OR')" });
* `Gnerate SQL Condition: MATCH replace('senior | backend', '|', 'OR')`
*
* // Using `options.query` with an object to generate WHERE clause
* searchFts("developer", {
* query: {_id: {$like: 'fts2_%'}},
* });
* `Generated SQL Condition: MATCH 'developer' AND _id like 'fts2_%'`
*/
searchFts(query: string | Record<string, any> | Record<string, any>[], options?: IKVSetOptions & IKVCreateFtsOptions & {
retrieveFull?: boolean;
}): {
_id: string;
[KV_VALUE_SYMBOL]: any;
}[];
/**
* Drops the current table from the database.
*
* This function removes the table associated with the current instance from the database.
*/
drop(): void;
}
declare class KVSqliteAttachments {
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;
preCalcSize: Statement;
constructor(name: string, db: KVSqlite);
/**
* Get file content
* @param docId
* @param filename
* @returns
*/
get(docId: IKVDocumentId, filename: string): {
filename: string;
content: Buffer;
};
list(docId: IKVDocumentId, filename?: string): unknown[];
add(docId: IKVDocumentId, filename: string, content: Buffer, options?: {
isText?: boolean;
mime?: string;
}): KVSqliteRunResult;
update(docId: IKVDocumentId, filename: string, content: Buffer, options?: {
isText?: boolean;
mime?: string;
}): KVSqliteRunResult;
del(docId: IKVDocumentId, filename?: string | string[]): KVSqliteRunResult | KVSqliteRunResult[];
}
declare const KVFileCurrentVer = 5;
declare const KV_FILE_VER_NAME = "ver";
declare const DefaultKVCollection = "kv";
declare const SYS_KV_COLLECTION = "_sys_kv";
declare const KV_VALUE_SYMBOL = "\u503C";
declare const KV_TYPE_SYMBOL = "\u578B";
declare const KV_VALUE_FIELD_NAME = "value";
declare const KV_TYPE_FIELD_NAME = "type";
declare const KV_CREATEDAT_FIELD_NAME = "createdAt";
declare const KV_UPDATEDAT_FIELD_NAME = "updatedAt";
declare const KV_FIELD_SYMBOL_MAP: Record<string, string>;
declare const KV_FIELD_SYMBOL_MAP_REVERSE: Record<string, string>;
declare const KV_NAME_SYMBOL = "\u540D";
declare const KV_NAME_FIELD_NAME = "name";
/**
@example
// 如果要map:
updateKVFieldSymbol(KV_TYPE_SYMBOL, KV_TYPE_FIELD_NAME)
const table = db.create(mainTableName, {
fields: {[sourceFieldName]: {name: sourceFieldName, type: 'TEXT',}, [KV_TYPE_SYMBOL]: {}},
fts: {
unIndexed: [sourceFieldName, KV_TYPE_SYMBOL, '_id'],
},
indexes: [
{name: KV_TYPE_FIELD_NAME, fields: [KV_TYPE_FIELD_NAME], unique: false},
],
}) as KVSqliteCollection
*/
type IKVDocumentId = string | number;
interface KVSqliteRunResult extends Database.RunResult {
}
interface IKVObjItem {
_id: IKVDocumentId;
[name: string]: any;
}
interface IKVSerdeOptions {
serialize?: (val: any) => string;
deserialize?: (val: string) => any;
}
interface IKVSetOptions extends Database.Options, IKVSerdeOptions {
id?: string;
location?: string;
collection?: string;
collections?: (string | IKVCreateOptions | IKVCreateExOptions)[];
overwrite?: boolean;
singleValue?: boolean;
ignoreExists?: boolean;
ftsQueryStyle?: string | boolean;
dictPath?: string;
usingJsonb?: boolean;
fieldNames?: string[];
sort?: string | string[];
order?: 'ASC' | 'DESC';
size?: number;
page?: number;
query?: string | any;
mapped?: boolean;
fieldInfos?: Required<IKVFieldOptions>;
[name: string]: any;
}
interface IKVCreateFtsPluginOptions {
/**
* The path to the plugin specific to this language.
*/
path: string;
load?: (db: KVSqlite, options: IKVCreateFtsPluginOptions) => void;
/**
* An object holding additional configurations for the plugin related to this language.
*/
[name: string]: any;
}
/**
* Contains options tailored to a specific language's FTS setup, including plugin paths and configurations.
*/
interface IKVCreateFtsLanguageOptions {
/**
* The language identifier, such as 'zh' for Chinese or 'en' for English.
*/
name: string;
plugin?: IKVCreateFtsPluginOptions;
/**
* Defines the tokenization method or plugin identifier to be used.
*/
tokenize?: string;
/**
* Additional tokenize options for the language.
*/
options?: string;
}
/**
* Represents options for creating an FTS (Full-Text Search) table in SQLite with additional support for multiple languages and plugins.
*/
interface IKVCreateFtsOptions {
/**
* Specifies fields that should not be indexed in the FTS table.
*/
unIndexed?: string[];
/**
* Lists fields to be excluded from full-text search.
*/
exclude?: string[];
/**
* Specifies fields that should be indexed in the FTS table.
*/
include?: string[];
/**
* Configures prefix matching behavior.
*/
prefix?: string;
fields?: string[];
/**
* Configures the language for full-text search.
*/
language?: string | IKVCreateFtsLanguageOptions;
/**
* Control Inclusion of Indexed Fields in FTS Indexing
*
* * When skipIndexed is set to true, fields that are already indexed will be automatically excluded from the FTS (Full-Text Search) indexing process by adding them to the unindexed list.
* * When set to false, this behavior is disabled, and all specified fields will be included in the FTS indexing process regardless of whether they are already indexed.
*
* defaults to `true`
*/
skipIndexed?: boolean;
}
interface IKVFieldOption {
name?: string;
type?: string;
notNull?: boolean;
primary?: boolean;
default?: any;
unique?: boolean;
constraint?: string;
foreignKey?: {
reference: string;
referenceField?: string;
isJson?: boolean;
onUpdate?: 'CASCADE' | 'SET NULL' | 'SET DEFAULT' | 'NO ACTION';
onDelete?: 'CASCADE' | 'SET NULL' | 'SET DEFAULT' | 'NO ACTION';
};
index?: {
name: string;
unique?: boolean;
partial?: boolean;
};
}
interface IKVFieldOptions {
[name: string]: IKVFieldOption;
}
type IKVFieldOptionEx = string | IKVFieldOption;
interface IKVIndexOptions {
name: string;
fields: string[];
unique?: boolean;
partial?: string;
}
interface IKVTriggerOptions {
name: string;
event: 'UPDATE' | 'INSERT' | 'DELETE';
triggerTiming: 'BEFORE' | 'AFTER';
condition?: string;
action: string;
}
interface IKVCreateBaseOptions extends IKVSerdeOptions {
name?: string;
usingJsonb?: boolean;
fts?: true | IKVCreateFtsOptions;
indexes?: IKVIndexOptions | IKVIndexOptions[];
triggers?: IKVTriggerOptions[];
[k: string]: any;
}
interface IKVCreateOptions extends IKVCreateBaseOptions {
fields?: IKVFieldOptions;
}
interface IKVCreateExOptions extends IKVCreateBaseOptions {
fields?: IKVFieldOptionEx[];
}
interface ISqliteIndexListItem {
seq: number;
name: string;
unique: boolean;
partial: number;
origin: 'c' | 'u' | 'pk';
fields: string[];
}
interface ISqliteSqlMasterBaseFields {
name?: string;
type?: 'table' | 'index' | 'trigger' | 'view' | 'virtual_table';
}
interface ISqliteSqlSchemaOptions extends ISqliteSqlMasterBaseFields {
excludeUnmanaged?: boolean;
}
interface ISqliteSqlMasterFields extends Required<ISqliteSqlMasterBaseFields> {
tbl_name: string;
sql: string;
rootpage: number;
}
export { DefaultKVCollection, type IKVCollections, type IKVCreateBaseOptions, type IKVCreateExOptions, type IKVCreateFtsLanguageOptions, type IKVCreateFtsOptions, type IKVCreateFtsPluginOptions, type IKVCreateOptions, type IKVDocumentId, type IKVFieldOption, type IKVFieldOptionEx, type IKVFieldOptions, type IKVIndexOptions, type IKVObjItem, type IKVSerdeOptions, type IKVSetOptions, type IKVTriggerOptions, type ISqliteIndexListItem, type ISqliteSqlMasterBaseFields, type ISqliteSqlMasterFields, type ISqliteSqlSchemaOptions, KVFileCurrentVer, KVSqlite, KVSqliteAttachments, KVSqliteCollection, type KVSqliteRunResult, KV_CREATEDAT_FIELD_NAME, KV_FIELD_SYMBOL_MAP, KV_FIELD_SYMBOL_MAP_REVERSE, KV_FILE_VER_NAME, KV_NAME_FIELD_NAME, KV_NAME_SYMBOL, KV_TYPE_FIELD_NAME, KV_TYPE_SYMBOL, KV_UPDATEDAT_FIELD_NAME, KV_VALUE_FIELD_NAME, KV_VALUE_SYMBOL, SYS_KV_COLLECTION, updateKVFieldSymbol };