### NanoSQL Setup and Usage with NativeScript SQLite Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/nanosql-adapter.md This example demonstrates the complete setup process for NanoSQL using the NativeScript SQLite adapter. It includes creating a database, defining tables, registering the adapter, and performing basic insert and select operations. Ensure you have the necessary packages installed. ```typescript import { nSQL } from '@nano-sql/core'; import { NativeSQLite } from '@nativescript-community/sqlite/nanosql'; // Create and configure adapter const adapter = new NativeSQLite('myapp.db', { threading: false }); // Initialize NanoSQL nSQL() .createDatabase({ id: 'myapp', mode: 'PERM', tables: [ { name: 'users', columns: { id: { type: 'int', primaryKey: true, autoIncrement: true }, name: { type: 'string' }, email: { type: 'string', notNull: true }, age: { type: 'int', default: 0 } } }, { name: 'posts', columns: { id: { type: 'int', primaryKey: true, autoIncrement: true }, userId: { type: 'int' }, title: { type: 'string', notNull: true }, content: { type: 'string' } } } ], version: 1.0, onVersionUpdate: (newVersion) => { console.log('Database version updated to', newVersion); } }) .then(() => { // Register the SQLite adapter nSQL('users').setAdapter(adapter); nSQL('posts').setAdapter(adapter); return nSQL('users').init(); }) .then(() => { // Insert return nSQL('users').query('upsert', { name: 'Alice', email: 'alice@example.com', age: 30 }).exec(); }) .then(() => { // Query return nSQL('users') .query('select') .where(['age', '>', 25]) .exec(); }) .then((results) => { console.log('Users over 25:', results); }) .catch((err) => { console.error('Error:', err); }); ``` -------------------------------- ### TypeORM Setup with NativeScript SQLite Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/typeorm-integration.md Complete example demonstrating the setup of TypeORM with NativeScript SQLite. Includes entity definition, data source configuration, and basic CRUD operations. ```typescript // entities/user.ts import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column({ nullable: true }) email?: string; @Column('integer') age: number; } ``` ```typescript // database.ts import { DataSource } from 'typeorm'; import { installMixins, NativescriptConnectionOptions } from '@nativescript-community/sqlite/typeorm'; import { User } from './entities/user'; installMixins(); export const dataSource = new DataSource({ type: 'nativescript', database: 'myapp.db', entities: [User], synchronize: true, logging: ['error'] } as NativescriptConnectionOptions); ``` ```typescript // app.ts import { dataSource } from './database'; async function main() { await dataSource.initialize(); const userRepository = dataSource.getRepository(User); // Create const user = userRepository.create({ name: 'Alice', age: 30 }); await userRepository.save(user); // Read const found = await userRepository.findOne({ where: { id: user.id } }); // Update found.age = 31; await userRepository.save(found); // Delete await userRepository.remove(found); await dataSource.destroy(); } main().catch(console.error); ``` -------------------------------- ### TypeORM Integration Setup Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Shows how to install the necessary mixins and configure the TypeORM driver for use with Nativescript SQLite. ```typescript import { installMixins } from "@nativescript-community/sqlite/typeorm"; installMixins(); // Then proceed with TypeORM setup using NativescriptDriver ``` -------------------------------- ### Install NativeScript SQLite Plugin Source: https://github.com/nativescript-community/sqlite/blob/master/README.md Run this command from your project's root to install the plugin. ```bash ns plugin add @nativescript-community/sqlite ``` -------------------------------- ### Run Demo Application Source: https://github.com/nativescript-community/sqlite/blob/master/README.md Example command to run a specific demo application for Svelte on iOS. Replace placeholders for different frameworks and platforms. ```bash npm run demo.svelte.ios # Example ``` -------------------------------- ### SqliteRow Example Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/types.md Demonstrates how to create and access properties of a SqliteRow object, including handling nullable columns. ```typescript const row: SqliteRow = { id: 1, name: 'Alice', email: 'alice@example.com', age: 30, photo: null // nullable column }; // Access properties console.log(row.id); console.log(row['name']); ``` -------------------------------- ### Initialize and Use SQLite Database Source: https://github.com/nativescript-community/sqlite/blob/master/README.md Example demonstrating how to open or create a SQLite database, create a table, and insert data within a transaction. Ensure to handle potential exceptions. ```typescript import { openOrCreate, deleteDatabase } from "@nativescript-community/sqlite"; const sqlite = openOrCreate("path/to/db"); sqlite.execute("CREATE TABLE names (id INT, name TEXT)"); sqlite.transaction(cancelTransaction => { // Calling cancelTransaction will rollback all changes made to db names.forEach((name, id) => sqlite.execute( "INSERT INTO names (id, name) VALUES (?, ?)", [id, name] ) ); }); ``` -------------------------------- ### NanoSQL Setup with Native SQLite Adapter Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Integrates NanoSQL with the NativeScript SQLite adapter for database creation and initialization. Shows how to define tables and set the adapter. ```typescript import { nSQL } from '@nano-sql/core'; import { NativeSQLite } from '@nativescript-community/sqlite/nanosql'; const adapter = new NativeSQLite('app.db'); nSQL() .createDatabase({ id: 'myapp', tables: [{ name: 'users', columns: { id: { type: 'int', primaryKey: true }, name: { type: 'string' } } }] }) .then(() => { nSQL('users').setAdapter(adapter); return nSQL('users').init(); }); ``` -------------------------------- ### TypeORM Setup and Usage Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Configures and initializes TypeORM with the NativeScript SQLite driver. Demonstrates setting up the data source, defining entities, and fetching data using repositories. ```typescript import { DataSource } from 'typeorm'; import { installMixins } from '@nativescript-community/sqlite/typeorm'; installMixins(); const dataSource = new DataSource({ type: 'nativescript', database: 'app.db', entities: [User, Post], synchronize: true }); await dataSource.initialize(); const users = await dataSource.getRepository(User).find(); ``` -------------------------------- ### Basic Query with Read and Write Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Demonstrates opening a database, performing a read operation using `get`, and a write operation using `execute`. Includes basic error handling and database closing. ```typescript const db = openOrCreate('app.db'); try { // Read const user = await db.get('SELECT * FROM users WHERE id = ?', [123]); if (user) { console.log(user.name); } // Write await db.execute( 'INSERT INTO users (name, email) VALUES (?, ?)', ['Alice', 'alice@example.com'] ); } catch (error) { console.error('Error:', error); } finally { db.close(); } ``` -------------------------------- ### Install Dependencies with pnpm or yarn Source: https://github.com/nativescript-community/sqlite/blob/master/README.md The project requires either pnpm or yarn for dependency installation. npm is not supported. ```bash pnpm i ``` ```bash yarn ``` -------------------------------- ### TypeORM NativeScript SQLite Data Source Example Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/types.md Example of how to configure and initialize a TypeORM DataSource for NativeScript SQLite. Make sure to import and install necessary mixins before creating the DataSource. ```typescript import { DataSource } from 'typeorm'; import { installMixins, NativescriptConnectionOptions } from '@nativescript-community/sqlite/typeorm'; installMixins(); const dataSource = new DataSource({ type: 'nativescript', database: 'myapp.db', entities: [User, Post], synchronize: true, logging: true } as NativescriptConnectionOptions); ``` -------------------------------- ### Core SQLiteDatabase Methods Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Examples of common querying and execution methods for the SQLiteDatabase interface. ```typescript const result: Array = await db.selectArray({ from: "users", where: { age: { "<=": 30 } } }); const user: any = await db.get({ from: "users", where: { id: 1 } }); await db.execute({ sql: "CREATE TABLE IF NOT EXISTS logs (message TEXT);", args: [] }); await db.transaction({ operations: [ { "exec": "INSERT INTO logs (message) VALUES (?);", "values": ["First log entry"] }, { "exec": "INSERT INTO logs (message) VALUES (?);", "values": ["Second log entry"] } ] }); db.each({ from: "logs", where: { message: "First log entry" } }, (row: any) => { console.log(row); }, (err: any) => { console.error(err); }); await db.close(); const version: number = await db.getVersion(); await db.setVersion(version + 1); ``` -------------------------------- ### NativescriptDriver Constructor Example Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/typeorm-integration.md Demonstrates the typical instantiation of a TypeORM DataSource with the 'nativescript' type. TypeORM internally creates the NativescriptDriver instance. ```typescript const dataSource = new DataSource({ type: 'nativescript', database: 'myapp.db', entities: [User, Post] } as NativescriptConnectionOptions); // TypeORM internally creates: new NativescriptDriver(dataSource) await dataSource.initialize(); ``` -------------------------------- ### Core Methods - Version Management Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Get and set the database version. Useful for managing schema migrations. ```APIDOC ## Core Methods - Version ### Get version ```typescript const version = db.getVersion(); ``` ### Set version ```typescript db.setVersion(2); ``` ``` -------------------------------- ### SqliteRequestOptions Examples Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/types.md Shows how to use SqliteRequestOptions to control BLOB transformation and set a custom cursor window size for large queries on Android. ```typescript // Transform BLOBs to Uint8Array const row = await db.select( 'SELECT id, image FROM photos', [], { transformBlobs: true } ); // Custom cursor window size for Android const largeResult = await db.select( 'SELECT * FROM huge_table', [], { cursorWindowSize: 5 * 1024 * 1024 } // 5 MB ); ``` -------------------------------- ### Android SQLite Flags Example Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/configuration.md Demonstrates how to combine Android-specific SQLite flags for database creation and collation rules. These flags are passed via the 'flags' option when opening a database. ```typescript import { SQLiteDatabase } from 'android.database.sqlite'; const flags = SQLiteDatabase.CREATE_IF_NECESSARY | // Create database if it doesn't exist (usually desired) SQLiteDatabase.NO_LOCALIZED_COLLATORS; // Skip localization collation rules (standard default) const db = openOrCreate('app.db', { flags }); ``` -------------------------------- ### get Method Source: https://github.com/nativescript-community/sqlite/blob/master/docs/classes/SQLiteDatabase.html Retrieves a single row from the database based on the provided SQL query. ```APIDOC ## get ### Description Retrieves a single row from the database. ### Parameters * **query** (string) - The SQL query to execute. * **params** (any) - Parameters to bind to the query. ### Returns * **Promise** - A promise that resolves with the first row of the result set, or null if no rows are found. ``` -------------------------------- ### Handle Driver Module Not Found Error Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/errors.md This example demonstrates catching the `DriverPackageNotInstalledError` when the specified driver module cannot be found or loaded. ```typescript try { const dataSource = new DataSource({ type: 'nativescript', database: 'app.db', driver: require('nonexistent-module') // Missing module } as any); } catch (error) { console.error('Module not found:', error.message); } ``` -------------------------------- ### TypeORM DataSource Initialization with NativeScript SQLite Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/typeorm-integration.md Example demonstrating how to initialize a TypeORM DataSource for NativeScript SQLite. It includes setting the database path, entities, synchronization, logging, and custom 'extra' options for the driver. ```typescript import { DataSource } from 'typeorm'; import { installMixins, NativescriptConnectionOptions } from '@nativescript-community/sqlite/typeorm'; import { User, Post } from './entities'; installMixins(); const dataSource = new DataSource({ type: 'nativescript', database: 'myapp.db', entities: [User, Post], synchronize: process.env.NODE_ENV === 'development', logging: ['error', 'warn'], maxQueryExecutionTime: 1000, extra: { threading: true, // Android: use worker thread transformBlobs: true, // Convert BLOBs to Uint8Array cursorWindowSize: 2 * 1024 * 1024 // 2 MB cursor window } } as NativescriptConnectionOptions); await dataSource.initialize(); // Now use TypeORM repositories const userRepository = dataSource.getRepository(User); const users = await userRepository.find({ where: { age: MoreThan(18) } }); ``` -------------------------------- ### NanoSQL Integration Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/README.md Demonstrates integrating NativeScript SQLite with NanoSQL using the provided adapter. This setup allows using NanoSQL's API with SQLite as the backend. ```typescript import { nSQL } from '@nano-sql/core'; import { NativeSQLite } from '@nativescript-community/sqlite/nanosql'; const adapter = new NativeSQLite('myapp.db'); nSQL() .createDatabase({ id: 'myapp' }) .then(() => { nSQL('users').setAdapter(adapter); return nSQL('users').query('select').exec(); }); ``` -------------------------------- ### TypeORM Integration Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/README.md Shows how to integrate NativeScript SQLite with TypeORM for data management. Ensure TypeORM is installed and entities are defined correctly. ```typescript import { DataSource } from 'typeorm'; import { installMixins, NativescriptConnectionOptions } from '@nativescript-community/sqlite/typeorm'; import { User } from './entities/user'; installMixins(); const dataSource = new DataSource({ type: 'nativescript', database: 'myapp.db', entities: [User], synchronize: true } as NativescriptConnectionOptions); await dataSource.initialize(); const users = await dataSource.getRepository(User).find(); ``` -------------------------------- ### get(query, params?, options?) Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/core-sqlite-database.md Executes a SELECT query and returns the first matching row as an object. Useful for retrieving a single record based on specific criteria. ```APIDOC ## get(query, params?, options?) ### Description Executes a SELECT query and returns the first matching row as an object. Useful for retrieving a single record based on specific criteria. ### Method ```typescript get(query: string, params?: SqliteParams, options?: SqliteRequestOptions): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **query** (string) - Required - SQL SELECT query with optional `?` placeholders - **params** (SqliteParams) - Optional - Parameter value(s) to bind to placeholders - **options** (SqliteRequestOptions) - Optional - Configuration for this specific query ### Returns `Promise` — Promise resolving to first row object, or null if no rows match ### Throws Rejects if the SQL query is invalid or execution fails ### Example ```typescript const db = openOrCreate('mydb.sqlite'); const user = await db.get( 'SELECT id, name, email FROM users WHERE id = ?', [123] ); if (user) { console.log(user.email); } else { console.log('User not found'); } ``` ``` -------------------------------- ### select Source: https://github.com/nativescript-community/sqlite/blob/master/docs/classes/SQLiteDatabase.html Selects data from the database using a provided query. This method is similar to `get` but might have different underlying implementations or return types. ```APIDOC ## select ### Description Selects data from the database using a provided query. This method is similar to `get` but might have different underlying implementations or return types. ### Method Not specified (likely a method call in an SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **query**: string - The SQL query to execute. * **params** (any) - Optional. Parameters to bind to the query. * **options** (SqliteRequestOptions) - Optional. Additional options for the request. ### Returns Promise - A promise that resolves with the selected data. ``` -------------------------------- ### Execute SQL Queries Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Use these methods for various SELECT, INSERT, UPDATE, and DELETE operations. 'select' and 'get' return rows as objects, while 'selectArray' and 'getArray' return rows as arrays. 'execute' is for non-query statements. 'each' iterates over rows. ```typescript const rows: SqliteRow[] = await db.select(sql, params?, options?); ``` ```typescript const rows: SqliteParam[][] = await db.selectArray(sql, params?, options?); ``` ```typescript const row: SqliteRow = await db.get(sql, params?, options?); ``` ```typescript const row: SqliteParam[] = await db.getArray(sql, params?, options?); ``` ```typescript await db.execute(sql, params?); ``` ```typescript const count = await db.each(sql, params, callback, complete, options?); ``` -------------------------------- ### Run Demo Applications Source: https://github.com/nativescript-community/sqlite/blob/master/docs/index.html Build and run demo applications for different frameworks (Angular, React, Svelte, Vue) on iOS or Android. ```bash npm run demo.[ng|react|svelte|vue].[ios|android] ``` ```bash npm run demo.svelte.ios # Example ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/nativescript-community/sqlite/blob/master/README.md If you did not clone the repository with the --recursive flag, run this command to initialize submodules. ```bash git submodule update --init ``` -------------------------------- ### get Source: https://github.com/nativescript-community/sqlite/blob/master/docs/classes/SQLiteDatabase.html Retrieves a single row from the database based on the provided query. It can optionally accept parameters and options for the request. ```APIDOC ## get ### Description Retrieves a single row from the database based on the provided query. It can optionally accept parameters and options for the request. ### Method Not specified (likely a method call in an SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **query**: string - The SQL query to execute. * **params** (any) - Optional. Parameters to bind to the query. * **options** (SqliteRequestOptions) - Optional. Additional options for the request. ### Returns Promise - A promise that resolves with the retrieved row data. ``` -------------------------------- ### Build All Project Components Source: https://github.com/nativescript-community/sqlite/blob/master/README.md Command to build all project components. Note that `yarn build.all` may not always work due to path issues. ```bash npm run build.all ``` -------------------------------- ### Update Documentation Source: https://github.com/nativescript-community/sqlite/blob/master/README.md Run this command to update or regenerate the project's documentation files. ```bash npm run doc ``` -------------------------------- ### Opening or Creating a Database Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates how to open an existing SQLite database or create a new one if it doesn't exist. Platform-specific details are handled by the function. ```typescript import { openOrCreate } from "@nativescript-community/sqlite"; const db = await openOrCreate({ filename: "my.db", iosDatabaseLocation: "Documents", androidDatabaseLocation: "data/databases" }); ``` -------------------------------- ### Get SQLite Database Version Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/core-sqlite-database.md Retrieves the current user version of the database. Use this when you need to check the database schema version. ```typescript const db = openOrCreate('mydb.sqlite'); const version = db.getVersion(); console.log('Database version:', version); ``` -------------------------------- ### Publish Project Source: https://github.com/nativescript-community/sqlite/blob/master/README.md Use this command to publish the project, which is handled by Lerna. You can optionally force a major release by adding '-- --bump major'. ```shell npm run publish ``` -------------------------------- ### SQLite Row Types Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Defines 'SqliteRow' for object-based rows returned by 'select' and 'get', and 'RowArray' for array-based rows from 'selectArray' and 'getArray'. ```typescript // Object (select, get) interface SqliteRow { [columnName: string]: SqliteParam; } // Array (selectArray, getArray) type RowArray = SqliteParam[]; ``` -------------------------------- ### Initialize NativeSQLite Adapter Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/nanosql-adapter.md Instantiate the NativeSQLite adapter with a database file path. This adapter is then used during NanoSQL initialization to set the database backend. ```typescript import { NativeSQLite } from '@nativescript-community/sqlite/nanosql'; // Create adapter const adapter = new NativeSQLite('myapp.db'); // Later, during NanoSQL initialization nSQL('my_table').setAdapter(adapter).init({ tables: [{ name: 'users', columns: { id: { type: 'int', primaryKey: true }, name: { type: 'string' }, email: { type: 'string' } } }] }); ``` -------------------------------- ### Basic Database Operations Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/README.md Demonstrates opening, creating tables, inserting data, querying, and closing a SQLite database. Ensure the database file is managed appropriately. ```typescript import { openOrCreate, deleteDatabase } from '@nativescript-community/sqlite'; // Open or create a database const db = openOrCreate('myapp.db'); // Create table await db.execute(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT ) `); // Insert data await db.execute( 'INSERT INTO users (name, email) VALUES (?, ?)', ['Alice', 'alice@example.com'] ); // Query data const users = await db.select('SELECT * FROM users WHERE id > ?', [0]); console.log(users); // Close connection db.close(); // Delete database deleteDatabase('myapp.db'); ``` -------------------------------- ### Passing Parameters to SQL Queries Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/types.md Demonstrates how to pass single or multiple parameters to SQL queries using the db.get and db.select methods. Also shows how to execute queries with no parameters. ```typescript // Single parameter await db.get('SELECT * FROM users WHERE id = ?', 123); // Multiple parameters await db.select('SELECT * FROM users WHERE age > ? AND status = ?', [18, 'active']); // No parameters await db.select('SELECT * FROM users'); ``` -------------------------------- ### NativeSQLite Constructor Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/nanosql-adapter.md Initializes the NativeSQLite adapter. It sets up the path to the SQLite database file and optional connection settings. This adapter is then used to initialize NanoSQL. ```APIDOC ## NativeSQLite Constructor ### Description Initializes the NativeSQLite adapter, setting up the path to the SQLite database file and optional connection settings. This adapter is then used to initialize NanoSQL. ### Signature ```typescript constructor( filePath: string, options?: { flags?: number; threading?: boolean } ) ``` ### Parameters #### Path Parameters - **filePath** (string) - Required - Path to the SQLite database file, or database ID if used as in-memory database #### Query Parameters - **options** (object) - Optional - Connection options forwarded to `openOrCreate()` - **flags** (number) - Optional - Android SQLiteDatabase flags - **threading** (boolean) - Optional - Android: execute queries on background worker thread (Default: `false`) ### Example ```typescript import { NativeSQLite } from '@nativescript-community/sqlite/nanosql'; // Create adapter const adapter = new NativeSQLite('myapp.db'); // Later, during NanoSQL initialization nSQL('my_table').setAdapter(adapter).init({ tables: [{ name: 'users', columns: { id: { type: 'int', primaryKey: true }, name: { type: 'string' }, email: { type: 'string' } } }] }); ``` ``` -------------------------------- ### TypeORM Integration with NativeScript SQLite Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/00-START-HERE.md Shows how to integrate TypeORM with the NativeScript SQLite plugin. This involves installing mixins, configuring a DataSource, and initializing it to manage entities. ```typescript import { DataSource } from 'typeorm'; import { installMixins } from '@nativescript-community/sqlite/typeorm'; installMixins(); const dataSource = new DataSource({ type: 'nativescript', database: 'myapp.db', entities: [User], synchronize: true }); await dataSource.initialize(); const users = await dataSource.getRepository(User).find(); ``` -------------------------------- ### Raw SQL with Parameterized Queries Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Illustrates executing raw SQL statements with parameters using `db.execute` and `db.select`. Covers single, multiple, and array parameters for safe query construction. ```typescript // Single parameter await db.execute('INSERT INTO logs (message) VALUES (?)', 'Error occurred'); // Multiple parameters await db.execute( 'INSERT INTO users (name, email, age) VALUES (?, ?, ?)', ['Alice', 'alice@example.com', 30] ); // Arrays const results = await db.select( 'SELECT * FROM users WHERE age > ? AND status = ?', [18, 'active'] ); ``` -------------------------------- ### Import Core Functionality Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/README.md Import the main functions for opening/creating and deleting databases. ```typescript import { openOrCreate, deleteDatabase } from '@nativescript-community/sqlite'; ``` -------------------------------- ### Get Table Row Count Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/nanosql-adapter.md Retrieves the number of rows in a specified table. Returns 0 if the table is empty. This operation is efficient as it uses SQL COUNT(*). ```typescript getTableIndexLength( table: string, complete: (length: number) => void, error: (err: any) => void ): void ``` -------------------------------- ### Handle Missing Database Configuration Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/errors.md This snippet shows how to catch the `DriverOptionNotSetError` when the `database` option is not provided during DataSource initialization. ```typescript try { const dataSource = new DataSource({ type: 'nativescript', // database: 'app.db' -- MISSING entities: [User, Post] } as any); await dataSource.initialize(); } catch (error) { console.error('Driver error:', error.message); // "database option is not set" } ``` -------------------------------- ### Basic Database Operations with SQLite Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/00-START-HERE.md Demonstrates basic database operations: opening a database, performing a select query with a parameter, inserting data, and closing the connection. Ensure the database file exists or will be created. ```typescript import { openOrCreate } from '@nativescript-community/sqlite'; const db = openOrCreate('myapp.db'); // Query const users = await db.select('SELECT * FROM users WHERE age > ?', [18]); // Insert await db.execute('INSERT INTO users (name) VALUES (?)', ['Alice']); // Close db.close(); ``` -------------------------------- ### open Source: https://github.com/nativescript-community/sqlite/blob/master/docs/classes/SQLiteDatabase.html Opens the SQLite database connection. ```APIDOC ## open ### Description Opens the SQLite database connection. ### Method Not specified (likely a method call in an SDK) ### Parameters None ### Returns boolean - True if the database was opened successfully, false otherwise. ``` -------------------------------- ### Error Handling for Database Operations Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Provides an example of using a try-catch block to handle potential errors during database operations, such as constraint violations. Logs the error message for debugging. ```typescript try { const db = openOrCreate('app.db'); await db.execute('INSERT INTO users (id, name) VALUES (?, ?)', [1, 'Alice']); await db.execute('INSERT INTO users (id, name) VALUES (?, ?)', [1, 'Bob']); // Duplicate key } catch (error) { console.error('Insert failed:', error.message); // Error: UNIQUE constraint failed... } ``` -------------------------------- ### Execute SQL Queries with TypeORM and NativeScript SQLite Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/typeorm-integration.md Demonstrates how to initialize a TypeORM DataSource for NativeScript SQLite, create a query runner, and execute SELECT and INSERT queries. Shows how to use structured results and release the runner. ```typescript const dataSource = new DataSource({ type: 'nativescript', database: 'myapp.db', entities: [User], logging: true, maxQueryExecutionTime: 1000 // Log queries slower than 1 second } as NativescriptConnectionOptions); await dataSource.initialize(); const runner = dataSource.createQueryRunner(); // SELECT query const users = await runner.query('SELECT id, name FROM users WHERE age > ?', [18]); // INSERT query await runner.query('INSERT INTO users (name, age) VALUES (?, ?)', ['Alice', 30]); // With structured result const result = await runner.query( 'SELECT * FROM users', [], true // useStructuredResult ); console.log(result.records); // Array of users console.log(result.raw); // Same array await runner.release(); ``` -------------------------------- ### Normalizing TypeORM Column Types to SQLite Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/typeorm-integration.md Provides examples of how TypeORM column types are mapped to SQLite-compatible type strings by the `normalizeType` method. This is typically called internally during entity synchronization. ```typescript // Typically called internally during entity synchronization // Column type: Buffer → SQLite type: 'blob' // Column type: String → SQLite type: 'text' // Column type: Number → SQLite type: 'integer' ``` -------------------------------- ### Version Migration for Schema Changes Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Illustrates how to manage database schema versioning and apply migrations. Checks the current version, executes SQL to alter tables, and updates the version number. ```typescript const db = openOrCreate('app.db'); const currentVersion = db.getVersion() || 0; if (currentVersion < 2) { await db.execute('ALTER TABLE users ADD COLUMN email TEXT'); db.setVersion(2); } db.close(); ``` -------------------------------- ### Import Core SQLite Functionality Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Import the main functions for opening, creating, and deleting databases. ```typescript // Core import { openOrCreate, deleteDatabase } from '@nativescript-community/sqlite'; ``` -------------------------------- ### Override BLOB Transformation Per Query Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Set a default BLOB transformation behavior for the database and override it for specific queries. This example shows disabling transformation for a particular select statement. ```typescript const db = openOrCreate('app.db', { transformBlobs: true }); // Use database default (transform to Uint8Array) const rows1 = await db.select('SELECT photo FROM photos'); // Override for this query (don't transform) const rows2 = await db.select( 'SELECT photo FROM large_photos', [], { transformBlobs: false } ); ``` -------------------------------- ### NanoSQL Adapter Implementation Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates the basic structure of the NativeSQLite class used as an adapter for NanoSQL. This involves implementing core database operations. ```typescript import { NativeSQLite } from "@nativescript-community/sqlite/nanosql"; // Example of initializing the adapter (actual usage within NanoSQL setup) const adapter = new NativeSQLite({ filename: "my.db", iosDatabaseLocation: "Documents", androidDatabaseLocation: "data/databases" }); // NanoSQL would then use this adapter to perform operations like: // adapter.connect(); // adapter.createTable(...); // adapter.write(...); // adapter.read(...); // adapter.delete(...); // adapter.readMulti(...); ``` -------------------------------- ### Handle No Results in SQLite Queries Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/errors.md When a query returns no matching rows, `get()` returns `null` and `select()` returns an empty array without throwing an error. This behavior is consistent across platforms. ```typescript const db = openOrCreate('app.db'); const user = await db.get('SELECT * FROM users WHERE id = ?', [999]); console.log(user); // null (not an error) const users = await db.select('SELECT * FROM users WHERE id > ?', [999]); console.log(users); // [] (not an error) ``` -------------------------------- ### Get Table Primary Key Index Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/nanosql-adapter.md Retrieves the primary key index of all rows in a specified table. Returns an empty array if the table is empty. Useful for cache invalidation and index building. ```typescript getTableIndex( table: string, complete: (index: any[]) => void, error: (err: any) => void ): void ``` -------------------------------- ### Import NanoSQL Adapter Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/README.md Import the NanoSQL adapter for use with the NanoSQL library. ```typescript import { NativeSQLite } from '@nativescript-community/sqlite/nanosql'; ``` -------------------------------- ### connect(id, complete, error) Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/nanosql-adapter.md Opens or creates the SQLite database connection. This method is called by NanoSQL during its initialization process. ```APIDOC ## connect(id, complete, error) ### Description Opens or creates the SQLite database connection. Called by NanoSQL during initialization. ### Signature ```typescript connect( id: string, complete: () => void, error: (err: any) => void ): void ``` ### Parameters #### Path Parameters - **id** (string) - Required - NanoSQL instance ID; used as database name if `filePath` is empty #### Query Parameters - **complete** (() => void) - Required - Callback invoked on successful connection - **error** ((err: any) => void) - Required - Callback invoked if connection fails ### Remarks - If `filePath` is empty or falsy, `id` is used as the database path. - Initializes auto-increment support via NanoSQL's abstract SQLite functions. - Called automatically by NanoSQL during `.init()`. ### Example ```typescript const adapter = new NativeSQLite('myapp.db'); adapter.connect( 'my_instance', () => console.log('Connected'), (err) => console.error('Connection failed:', err) ); ``` ``` -------------------------------- ### Core Methods - Connection Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Manage the database connection. Includes opening or creating a database file, closing the connection, and deleting the database file. ```APIDOC ## Core Methods - Connection ### Open or create database ```typescript const db = openOrCreate('path/to/db.sqlite'); ``` ### Close connection ```typescript db.close(); ``` ### Delete database ```typescript deleteDatabase('path/to/db.sqlite'); ``` ``` -------------------------------- ### Open Database with Default Options Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/types.md Opens a SQLite database using default configuration, suitable for most use cases. ```typescript // Default options (suitable for most use cases) const db = openOrCreate('app.db'); ``` -------------------------------- ### Handle Transaction Rollback on Error Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/errors.md When an action function within a `transaction()` call throws an error, changes are automatically rolled back and the error is propagated. This example demonstrates simulating an error to trigger a rollback. ```typescript const db = openOrCreate('app.db'); try { await db.transaction(async () => { await db.execute('INSERT INTO users (name) VALUES (?)', ['Alice']); // Simulate an error throw new Error('Validation failed'); // This never executes, and the INSERT is rolled back await db.execute('INSERT INTO users (name) VALUES (?)', ['Bob']); }); } catch (error) { console.error('Transaction failed:', error.message); // "Validation failed" // The INSERT was rolled back; no users were added } ``` -------------------------------- ### Get Single Row as Object from SQLite Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/core-sqlite-database.md Use this method to fetch the first row matching a SELECT query. It returns the row as an object, or null if no match is found. Ensure the database is opened before use. ```typescript const db = openOrCreate('mydb.sqlite'); const user = await db.get( 'SELECT id, name, email FROM users WHERE id = ?', [123] ); if (user) { console.log(user.email); } else { console.log('User not found'); } ``` -------------------------------- ### Get Single Row as Array from SQLite Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/core-sqlite-database.md Use this method to fetch the first row matching a SELECT query as an array of values. Returns null if no rows match. Useful when column order is known but names are not critical. ```typescript const db = openOrCreate('mydb.sqlite'); const row = await db.getArray( 'SELECT id, name, email FROM users WHERE id = ?', [123] ); if (row) { console.log('Email:', row[2]); // Third column } ``` -------------------------------- ### select(query, params?, options?) Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/core-sqlite-database.md Executes a SQL SELECT query and returns all rows that match the criteria as an array of objects. Supports parameterized queries and query options. ```APIDOC ## select(query, params?, options?) ### Description Executes a SELECT query and returns all matching rows as objects. ### Method `select(query: string, params?: SqliteParams, options?: SqliteRequestOptions): Promise` ### Parameters #### Path Parameters - **query** (string) - Required - SQL SELECT query with optional `?` placeholders for parameterized queries - **params** (SqliteParams) - Optional - Parameter value(s) to bind to placeholders: single value, array of values, or null - **options** (SqliteRequestOptions) - Optional - Configuration for this specific query (blob transformation, cursor settings) ### Returns `Promise` — Promise resolving to array of row objects with column names as keys ### Throws Rejects if the SQL query is invalid or execution fails ### Example ```typescript const db = openOrCreate('mydb.sqlite'); const rows = await db.select( 'SELECT id, name FROM users WHERE age > ?', [18] ); rows.forEach(row => { console.log(row.id, row.name); }); ``` ``` -------------------------------- ### Update Readme Source: https://github.com/nativescript-community/sqlite/blob/master/README.md Execute this command to regenerate or update the README file for the project. ```bash npm run readme ``` -------------------------------- ### Install TypeORM Mixins for NativeScript SQLite Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/typeorm-integration.md Registers the NativeScript SQLite driver with TypeORM's driver factory. Must be called once before creating a `DataSource`. This function is idempotent and modifies TypeORM's internal driver factory to recognize the 'nativescript' type. ```typescript import { installMixins, NativescriptConnectionOptions } from '@nativescript-community/sqlite/typeorm'; import { DataSource } from 'typeorm'; import { User, Post } from './entities'; // Call once at application startup installMixins(); const dataSource = new DataSource({ type: 'nativescript', database: 'myapp.db', entities: [User, Post], synchronize: true, logging: true } as NativescriptConnectionOptions>); await dataSource.initialize(); ``` -------------------------------- ### Import Helper Functions Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Import utility functions for parameter conversion and byte array handling. ```typescript // Helpers import { paramsToStringArray, byteArrayToBuffer } from '@nativescript-community/sqlite'; ``` -------------------------------- ### Handle Transaction Cancellation via cancel() Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/errors.md Changes are rolled back when the `cancel()` callback is invoked within a transaction. The promise still resolves normally, so check the return value to distinguish cancellation from success. This example shows how to conditionally cancel a transaction. ```typescript const db = openOrCreate('app.db'); const result = await db.transaction(async (cancel) => { await db.execute('INSERT INTO users (name) VALUES (?)', ['Alice']); // Check for a condition const count = await db.get('SELECT COUNT(*) as cnt FROM users WHERE name = ?', ['Alice']); if (count.cnt > 5) { cancel(); // Trigger rollback return null; // Return gracefully } return 'Success'; }); console.log(result); // null (cancelled) or 'Success' // No user was added due to cancellation or success ``` -------------------------------- ### Handle Nested Transaction Errors and Rollback Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/errors.md Errors or cancellations in a nested (inner) transaction participate in the outer transaction. If the outer transaction is rolled back, the inner transaction is also rolled back. This example demonstrates an inner transaction error leading to an outer transaction cancellation. ```typescript const db = openOrCreate('app.db'); try { await db.transaction(async (outerCancel) => { await db.execute('INSERT INTO users (name) VALUES (?)', ['Outer']); try { await db.transaction(async (innerCancel) => { await db.execute('INSERT INTO users (name) VALUES (?)', ['Inner']); throw new Error('Inner error'); }); } catch (innerError) { console.error('Inner transaction failed:', innerError); outerCancel(); // Cancel outer transaction } }); } catch (outerError) { console.error('Outer transaction failed:', outerError); } // Both inserts were rolled back; no users added ``` -------------------------------- ### BLOB Handling for Binary Data Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Demonstrates storing and retrieving binary large objects (BLOBs) using `Uint8Array`. Shows how to configure the database for blob transformation and handle data. ```typescript const db = openOrCreate('app.db', { transformBlobs: true }); // Store BLOB const buffer = new Uint8Array([1, 2, 3, 4]); await db.execute('INSERT INTO files (data) VALUES (?)', [buffer]); // Retrieve BLOB const row = await db.get('SELECT data FROM files WHERE id = 1'); const data: Uint8Array = row.data; ``` -------------------------------- ### Database and Query Level Option Precedence Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/configuration.md Illustrates how database-level configuration options can be overridden by query-specific options. Database options set during openOrCreate serve as defaults for subsequent queries. ```typescript // Database-level: transform BLOBs, cursor window 2MB const db = openOrCreate('app.db', { transformBlobs: true, cursorWindowSize: 2 * 1024 * 1024 }); // Query-level: override to NOT transform BLOBs for this query only const rows = await db.select( 'SELECT image FROM photos', [], { transformBlobs: false } ); // Subsequent queries use database defaults again const moreRows = await db.select('SELECT image FROM more_photos'); // transformBlobs is true, cursorWindowSize is 2MB ``` -------------------------------- ### DatabaseOptions Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/types.md Configuration options when opening or creating a database connection. These options are set once when opening the database and can be overridden by individual query options. ```APIDOC ## DatabaseOptions Configuration options when opening or creating a database connection. ```typescript type DatabaseOptions = { threading?: boolean; readOnly?: boolean; flags?: number; } & SqliteRequestOptions ``` Extends `SqliteRequestOptions` with database-level connection options. | Property | Type | Required | Default | Description | |----------|------|----------|---------|-------------| | `threading` | `boolean` | No | `false` | (Android only) If true, execute queries on a separate worker thread to avoid blocking the UI thread | | `readOnly` | `boolean` | No | `false` | (iOS only) If true, open the database in read-only mode | | `flags` | `number` | No | — | (Android only) Flags passed to `SQLiteDatabase.openDatabase()` or `Activity.openOrCreateDatabase()`. Default: `CREATE_IF_NECESSARY | NO_LOCALIZED_COLLATORS` | | `transformBlobs` | `boolean` | No | `true` | If true, BLOB columns are converted to Uint8Array; inherited by all queries unless overridden | | `cursorWindowSize` | `number` | No | — | (Android only) Default cursor window size in bytes; inherited by all queries unless overridden | | `cursorWindowName` | `string` | No | `'window'` | (Android only) Default cursor window name; inherited by all queries unless overridden | **Remarks:** - These options are set once when opening the database with `openOrCreate()` or `wrapDb()` - Individual query options from `SqliteRequestOptions` override these defaults - `threading` significantly changes query execution model; use with careful testing **Example:** ```typescript // Default options (suitable for most use cases) const db = openOrCreate('app.db'); // Android: Enable worker thread, disable blob transformation const db = openOrCreate('app.db', { threading: true, transformBlobs: false, cursorWindowSize: 1024 * 1024 // 1 MB }); // iOS: Read-only database const db = openOrCreate('/path/to/backup.db', { readOnly: true }); ``` **Methods accepting DatabaseOptions:** - `openOrCreate()` - `wrapDb()` **Source:** `src/sqlite/sqlite.common.ts:11` ``` -------------------------------- ### Import NanoSQL Integration Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Import the NativeSQLite adapter for use with NanoSQL. ```typescript // NanoSQL import { NativeSQLite } from '@nativescript-community/sqlite/nanosql'; ``` -------------------------------- ### Open, Close, and Delete Database Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Use 'openOrCreate' to establish a connection to a SQLite database file, 'close' to terminate the connection, and 'deleteDatabase' to remove the database file. ```typescript const db = openOrCreate('path/to/db.sqlite'); ``` ```typescript db.close(); ``` ```typescript deleteDatabase('path/to/db.sqlite'); ``` -------------------------------- ### Manage Database Version Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/quick-reference.md Retrieve the current database version using 'getVersion' and set a new version using 'setVersion'. ```typescript const version = db.getVersion(); ``` ```typescript db.setVersion(2); ``` -------------------------------- ### installMixins() Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/INDEX.md Registers the NativeScript SQLite driver with TypeORM. This function is essential for enabling TypeORM to use the SQLite database. ```APIDOC ## installMixins() ### Description Register NativeScript SQLite driver with TypeORM. ### Returns `void` ``` -------------------------------- ### SQLiteDatabase Constructor Source: https://github.com/nativescript-community/sqlite/blob/master/docs/classes/SQLiteDatabase.html Initializes a new instance of the SQLiteDatabase class. It can accept either a file path or an existing database object, along with optional configuration options. ```APIDOC ## constructor ### Description Initializes a new instance of the SQLiteDatabase class. ### Parameters * **filePathOrDb** (any) - The file path to the SQLite database or an existing database object. * **options** (DatabaseOptions) - Optional configuration options for the database. ### Returns * **SQLiteDatabase** - A new instance of the SQLiteDatabase class. ``` -------------------------------- ### Open or Create SQLite Database Source: https://github.com/nativescript-community/sqlite/blob/master/_autodocs/api-reference/openorcreate-deletedatabase.md Use this function to open an existing SQLite database file or create a new one if it does not exist. Platform-specific behaviors apply to file paths. The returned database connection is immediately open and ready for queries. ```typescript import { openOrCreate } from '@nativescript-community/sqlite'; // Android: Relative path (stored in app's private directory) const db = openOrCreate('myapp.db'); // Absolute path (both platforms) const db = openOrCreate('/path/to/database/myapp.db'); // In-memory database const memDb = openOrCreate(':memory:'); ``` ```typescript const db = openOrCreate('myapp.db', { threading: false, readOnly: false, transformBlobs: true, cursorWindowSize: 2048 }); ``` -------------------------------- ### Update Submodules Source: https://github.com/nativescript-community/sqlite/blob/master/README.md Run this command to update the submodules in the repository. This is the first step in updating the repo files. ```bash npm run update ```