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)

168 lines (120 loc) 5.44 kB
**@isdk/kvsqlite** *** # KVSqlite [![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) A powerful, document-oriented SQLite Key-Value store with full-text search, built on `better-sqlite3`. KVSqlite is a high-performance, persistent Key-Value store that directly extends `better-sqlite3`. It provides a flexible, MongoDB-like document API on top of SQLite's robust feature set, designed for Node.js applications that need a simple yet powerful local database with advanced features like full-text search and flexible indexing. ## ✨ Key Features - **Flexible Document-Style API**: Seamlessly store and query complex JSON objects. Fixed fields and JSON data are automatically merged. - **Automatic Timestamps**: `createdAt` and `updatedAt` fields are automatically managed by database triggers. - **Powerful Full-Text Search (FTS5)**: Integrated support for boolean queries, result ranking, and advanced tokenizers, including pre-packaged Chinese word segmentation. - **Advanced Indexing**: Create unique, partial, and JSON indexes for optimized query performance. - **Transactional Integrity**: ACID-compliant transactions for reliable data manipulation. - **Extensible**: Load custom SQLite extensions and plugins. ## 📦 Installation This library requires `better-sqlite3` as a peer dependency. ```bash # Using npm npm install @isdk/kvsqlite better-sqlite3 # Using yarn yarn add @isdk/kvsqlite better-sqlite3 ``` ## 🚀 Quick Start The `KVSqlite` constructor is identical to `better-sqlite3`'s `Database` constructor. You can pass KVSqlite-specific options in the second argument. ```typescript import { KVSqlite } from '@isdk/kvsqlite'; // 1. Initialize the KVSqlite database. // The constructor is the same as for better-sqlite3's Database. // Use ':memory:' for an in-memory DB, or a file path for persistence. const db = new KVSqlite(':memory:'); // By default, a collection named `kv` is created. // You can operate on it directly from the db instance. await db.set('some_key', { info: 'default collection data' }); const defaultData = await db.get('some_key'); console.log('Data in default collection:', defaultData); // 2. Create and use a named collection for structured data (Recommended). interface User { _id: string; name: string; age: number; } // Use the .create() method on the db instance to get a collection. const users = db.create('users'); // 3. Now, perform operations on the 'users' collection. const alice: User = { _id: 'u001', name: 'Alice', age: 30, }; await users.set(alice); const foundUser = await users.get('u001'); console.log('Found in users collection:', foundUser); // 4. (Optional) Create collections on initialization. const dbWithCollections = new KVSqlite(':memory:', { collections: ['products', 'orders'] }); const products = dbWithCollections.getCollection('products'); await products.set({ _id: 'p1', name: 'Laptop' }); console.log('Found in products collection:', await products.get('p1')); ``` ## Advanced Usage ### Full-Text Search (FTS5) Enable FTS5 when creating a collection to perform advanced text searches. ```typescript import { KVSqlite } from '@isdk/kvsqlite'; const db = new KVSqlite(':memory:'); const posts = db.create('posts', { // Enable FTS on creation fts: true, }); await posts.bulkDocs([ { _id: 'p01', content: 'SQLite is a powerful and fast database engine.' }, { _id: 'p02', content: 'KVSqlite provides a simple API for SQLite.' }, ]); // Search for one or more terms const results = await posts.searchFts('powerful OR simple'); console.log(results); ``` ### Chinese Full-Text Search KVSqlite comes with a pre-built plugin for Chinese word segmentation. ```typescript import { KVSqlite } from '@isdk/kvsqlite'; const db = new KVSqlite(':memory:'); const articles = db.create('articles', { fts: { language: 'zh', // Enable the Chinese tokenizer }, }); await articles.set({ _id: 'a01', content: '数据库是一个非常有用的工具' }); // The search query will be tokenized automatically const results = await articles.searchFts('数据库 工具'); console.log(results); ``` ### Using Custom Fields and Indexes You can define a fixed schema with typed fields and create indexes for faster queries. ```typescript import { KVSqlite } from '@isdk/kvsqlite'; const db = new KVSqlite(':memory:'); const products = db.create('products', { // Define fixed fields alongside the default '_id' and 'val' fields: { category: { type: 'TEXT' }, price: { type: 'REAL' }, }, indexes: [ // Create an index on the 'category' field { name: 'category_idx', fields: ['category'] }, // Create a partial index for expensive products { name: 'expensive_idx', fields: ['price'], partial: 'price > 1000' }, ], }); await products.set({ _id: 'prod01', category: 'electronics', price: 1200, val: { name: 'Laptop' } }); // This query will be fast due to the index const electronics = await products.searchEx({ category: 'electronics' }); console.log(electronics); ``` ## 📚 API Documentation For a detailed API reference, please see the [generated TypeDoc documentation](./docs/README.md). ## 📜 License This project is licensed under the MIT License. See the [LICENSE-MIT](_media/LICENSE-MIT) file for details.