w3resource

Integrating SQLite with Supabase for Efficient Data Management


SQLite with Supabase: Combining Local and Cloud Databases

SQLite and Supabase are two distinct tools serving different purposes. SQLite is a lightweight, serverless database primarily used for local data storage, whereas Supabase is an open-source backend-as-a-service solution that provides cloud database management and API functionality. Combining the two can be advantageous for scenarios where local data processing needs to sync with cloud storage. This guide explains how SQLite and Supabase can work together, with code examples and best practices.


Overview of SQLite and Supabase Integration

  • SQLite: A local database suitable for lightweight, offline-first applications.
  • Supabase: A cloud-based solution offering PostgreSQL with additional features like authentication and real-time subscriptions.

Why Combine SQLite and Supabase?

  • Offline Sync: Store data locally with SQLite and sync it with Supabase when online.
  • Performance: SQLite handles local queries, reducing latency and improving user experience.
  • Scalability: Supabase offers scalable cloud storage for centralized data management.

Setting Up Supabase

    1. Install the Supabase Client
    Add the Supabase client to your project using NPM or Yarn:

    npm install @supabase/supabase-js
    

    2. Initialize the Supabase Client
    Replace the placeholders with your Supabase project URL and API key.

    import { createClient } from '@supabase/supabase-js';
    
    const supabaseUrl = 'https://your-project.supabase.co';
    const supabaseKey = 'your-api-key';
    const supabase = createClient(supabaseUrl, supabaseKey);
    

SQLite Integration

    1. Install SQLite Library
    Install SQLite for local storage:

    npm install sqlite3
    

    2. Set Up SQLite
    Create a new database and initialize a table:

    const sqlite3 = require('sqlite3').verbose();
    
    // Open or create a local SQLite database
    const db = new sqlite3.Database('local_data.db');
    
    // Create a table
    db.run(
      'CREATE TABLE IF NOT EXISTS local_data (id INTEGER PRIMARY KEY, name TEXT, synced BOOLEAN)',
      err => {
        if (err) {
          console.error('Error creating table', err);
        } else {
          console.log('Table created successfully');
        }
      }
    );
    

Example: Syncing SQLite with Supabase

1. Insert Data into SQLite

Code:

// Insert a record into the local database
db.run(
  'INSERT INTO local_data (name, synced) VALUES (?, ?)',
  ['Example Data', false], // Parameters for the query
  err => {
    if (err) {
      console.error('Error inserting data', err);
    } else {
      console.log('Data inserted successfully');
    }
  }
);

2. Sync Data with Supabase

Code:

// Fetch unsynced data from SQLite
db.all('SELECT * FROM local_data WHERE synced = ?', [false], async (err, rows) => {
  if (err) {
    console.error('Error fetching data', err);
    return;
  }

  for (const row of rows) {
    try {
      // Insert data into Supabase
      const { error } = await supabase.from('remote_data').insert([{ id: row.id, name: row.name }]);
      if (!error) {
        // Mark record as synced
        db.run('UPDATE local_data SET synced = ? WHERE id = ?', [true, row.id], err => {
          if (err) {
            console.error('Error updating sync status', err);
          } else {
            console.log(`Record ${row.id} synced successfully`);
          }
        });
      } else {
        console.error('Error syncing data with Supabase', error);
      }
    } catch (error) {
      console.error('Sync process failed', error);
    }
  }
});

Explanation:

    1. SQLite Initialization
    The SQLite database is initialized and a table named local_data is created to store local records.

    2. Data Insertion
    New records are added to SQLite with a synced flag indicating whether the record has been synced with Supabase.

    3. Data Sync Process
    Unsynced records are fetched from SQLite, and each record is inserted into the Supabase cloud database. Upon successful insertion, the synced flag is updated locally to avoid redundant uploads.

    4. Error Handling
    The code handles errors at every step to ensure the application remains robust even if syncing fails temporarily.


Advantages of SQLite and Supabase Integration

    1. Reliability: Local SQLite database ensures the app works offline.

    2. Scalability: Supabase handles large-scale cloud storage seamlessly.

    3. Flexibility: Combines the speed of local processing with the power of cloud computing.

    4. Cost-Effective: Both SQLite and Supabase are free to use, making them ideal for small-to-medium projects.

Practical Guides to SQLite Snippets and Examples.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/sqlite/snippets/combining-sqlite-with-supabase.php