Skip to content

Getting Started

  1. Install the package

    Terminal window
    npm i @capgo/capacitor-data-storage-sqlite
  2. Sync with native projects

    Terminal window
    npx cap sync
  3. Configure the plugin

    No additional setup required for iOS.

  4. Basic operations

    import { CapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
    // Set a value
    await CapacitorDataStorageSqlite.set({
    key: 'username',
    value: 'john_doe'
    });
    // Get a value
    const { value } = await CapacitorDataStorageSqlite.get({
    key: 'username'
    });
    console.log('Username:', value); // "john_doe"
    // Remove a value
    await CapacitorDataStorageSqlite.remove({
    key: 'username'
    });
    // Clear all data
    await CapacitorDataStorageSqlite.clear();
    // Check if key exists
    const { result } = await CapacitorDataStorageSqlite.iskey({
    key: 'username'
    });
    console.log('Key exists:', result); // true or false
    // Get all keys
    const { keys } = await CapacitorDataStorageSqlite.keys();
    console.log('All keys:', keys);
    // Get all values
    const { values } = await CapacitorDataStorageSqlite.values();
    console.log('All values:', values);
  5. Advanced usage

    import { CapacitorDataStorageSqlite } from '@capgo/capacitor-data-storage-sqlite';
    export class StorageService {
    private dbName = 'app_storage';
    private isEncrypted = false;
    async initialize(encrypted = false) {
    this.isEncrypted = encrypted;
    // Open storage with options
    await CapacitorDataStorageSqlite.openStore({
    database: this.dbName,
    encrypted: encrypted,
    mode: encrypted ? 'encryption' : 'no-encryption',
    version: 1
    });
    }
    // Generic storage methods
    async setObject<T>(key: string, data: T): Promise<void> {
    const value = JSON.stringify(data);
    await CapacitorDataStorageSqlite.set({ key, value });
    }
    async getObject<T>(key: string): Promise<T | null> {
    try {
    const { value } = await CapacitorDataStorageSqlite.get({ key });
    return value ? JSON.parse(value) : null;
    } catch (error) {
    console.error('Error getting object:', error);
    return null;
    }
    }
    // Batch operations
    async setMultiple(items: Record<string, any>): Promise<void> {
    for (const [key, value] of Object.entries(items)) {
    await CapacitorDataStorageSqlite.set({
    key,
    value: typeof value === 'string' ? value : JSON.stringify(value)
    });
    }
    }
    async getMultiple(keys: string[]): Promise<Record<string, any>> {
    const results: Record<string, any> = {};
    for (const key of keys) {
    try {
    const { value } = await CapacitorDataStorageSqlite.get({ key });
    results[key] = value;
    } catch (error) {
    results[key] = null;
    }
    }
    return results;
    }
    // Table management
    async getTables(): Promise<string[]> {
    const { tables } = await CapacitorDataStorageSqlite.tables();
    return tables;
    }
    async deleteTable(table: string): Promise<void> {
    await CapacitorDataStorageSqlite.deleteTable({ table });
    }
    // Import/Export functionality
    async exportToJson(): Promise<any[]> {
    const { keys } = await CapacitorDataStorageSqlite.keys();
    const { values } = await CapacitorDataStorageSqlite.values();
    return keys.map((key, index) => ({
    key,
    value: values[index]
    }));
    }
    async importFromJson(data: Array<{ key: string; value: string }>): Promise<void> {
    // Clear existing data
    await CapacitorDataStorageSqlite.clear();
    // Import new data
    for (const item of data) {
    await CapacitorDataStorageSqlite.set({
    key: item.key,
    value: item.value
    });
    }
    }
    // Filtering and searching
    async keysStartingWith(prefix: string): Promise<string[]> {
    const { keys } = await CapacitorDataStorageSqlite.keys();
    return keys.filter(key => key.startsWith(prefix));
    }
    async filterByPrefix(prefix: string): Promise<Array<{ key: string; value: string }>> {
    const { keys } = await CapacitorDataStorageSqlite.keys();
    const { values } = await CapacitorDataStorageSqlite.values();
    const filtered: Array<{ key: string; value: string }> = [];
    keys.forEach((key, index) => {
    if (key.startsWith(prefix)) {
    filtered.push({ key, value: values[index] });
    }
    });
    return filtered;
    }
    // Close database when done
    async close(): Promise<void> {
    await CapacitorDataStorageSqlite.closeStore({
    database: this.dbName
    });
    }
    }
    // Usage example
    const storage = new StorageService();
    await storage.initialize(true); // Use encryption
    // Store user data
    await storage.setObject('user_profile', {
    id: 123,
    name: 'John Doe',
    email: 'john@example.com'
    });
    // Retrieve user data
    const profile = await storage.getObject<any>('user_profile');
    console.log('User profile:', profile);

API Reference

Methods

openStore(options: OpenStoreOptions)

Open a storage database.

Parameters:

  • options.database: string - Database name
  • options.encrypted: boolean - Enable encryption
  • options.mode: string - ‘encryption’ or ‘no-encryption’
  • options.version: number - Database version

closeStore(options: CloseStoreOptions)

Close the storage database.

set(options: SetOptions)

Store a key-value pair.

Parameters:

  • options.key: string - Storage key
  • options.value: string - Value to store

get(options: GetOptions)

Retrieve a value by key.

Returns: Promise<{ value: string }>

remove(options: RemoveOptions)

Remove a key-value pair.

clear()

Clear all data from storage.

iskey(options: IskeyOptions)

Check if a key exists.

Returns: Promise<{ result: boolean }>

keys()

Get all storage keys.

Returns: Promise<{ keys: string[] }>

values()

Get all storage values.

Returns: Promise<{ values: string[] }>

tables()

Get all table names.

Returns: Promise<{ tables: string[] }>

deleteTable(options: DeleteTableOptions)

Delete a specific table.

Interfaces

interface OpenStoreOptions {
database: string;
encrypted?: boolean;
mode?: string;
version?: number;
}
interface SetOptions {
key: string;
value: string;
}
interface GetOptions {
key: string;
}
interface RemoveOptions {
key: string;
}

Platform Notes

iOS

  • Uses SQLite3 with optional SQLCipher for encryption
  • Data persists across app updates
  • Supports iOS 11.0+

Android

  • Uses SQLite with optional SQLCipher
  • Data persists across app updates
  • Supports Android 5.0 (API 21)+

Common Use Cases

  1. User Preferences: Store app settings and preferences
  2. Cache Management: Cache API responses and data
  3. Offline Storage: Store data for offline access
  4. Session Management: Manage user sessions securely
  5. Token Storage: Securely store authentication tokens

Best Practices

  1. Use Encryption for Sensitive Data

    // For sensitive data like tokens
    await openStore({
    database: 'secure_db',
    encrypted: true,
    mode: 'encryption'
    });
  2. Organize Keys with Prefixes

    // Use prefixes for organization
    await set({ key: 'user:123:profile', value: userData });
    await set({ key: 'cache:api:users', value: apiData });
  3. Handle Large Data Carefully

    // For large objects, consider compression
    const compressed = compress(largeData);
    await set({ key: 'large_data', value: compressed });
  4. Regular Cleanup

    // Remove expired cache entries
    const keys = await keys();
    for (const key of keys.keys) {
    if (key.startsWith('cache:') && isExpired(key)) {
    await remove({ key });
    }
    }

Troubleshooting

Database not opening:

  • Check database name is valid (alphanumeric, underscores)
  • Ensure no special characters in database name
  • Verify encryption mode matches existing database

Data not persisting:

  • Ensure openStore is called before operations
  • Check for any errors in console
  • Verify key names are strings

Performance issues:

  • Avoid storing very large values
  • Use batch operations when possible
  • Consider using multiple databases for different data types