import { Capacitor } from '@capacitor/core' import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite' import { defineCustomElements as defineJeep } from 'jeep-sqlite/loader' const DB_NAME = 'echo_local' const DB_VERSION = 1 const TRANSACTION_TABLE_SQL = ` CREATE TABLE IF NOT EXISTS transactions ( id TEXT PRIMARY KEY NOT NULL, amount REAL NOT NULL, merchant TEXT NOT NULL, category TEXT DEFAULT 'Uncategorized', date TEXT NOT NULL, note TEXT, sync_status INTEGER DEFAULT 0 ); ` let sqliteConnection let db let initialized = false const ensureJeepElement = async () => { if (!customElements.get('jeep-sqlite')) { defineJeep(window) } if (!document.querySelector('jeep-sqlite')) { const jeepEl = document.createElement('jeep-sqlite') document.body.appendChild(jeepEl) } await CapacitorSQLite.initWebStore() } const prepareConnection = async () => { if (!sqliteConnection) { sqliteConnection = new SQLiteConnection(CapacitorSQLite) } if (Capacitor.getPlatform() === 'web') { await ensureJeepElement() } const consistency = await sqliteConnection.checkConnectionsConsistency() if (!consistency.result) { await sqliteConnection.closeAllConnections() } const isConn = (await sqliteConnection.isConnection(DB_NAME, false)).result if (isConn) { db = await sqliteConnection.retrieveConnection(DB_NAME, false) } else { db = await sqliteConnection.createConnection(DB_NAME, false, 'no-encryption', DB_VERSION, false) } await db.open() await db.execute(TRANSACTION_TABLE_SQL) initialized = true } export const initSQLite = async () => { if (!initialized) { await prepareConnection() } return db } export const getDb = async () => { if (!initialized) { await initSQLite() } return db } export const closeSQLite = async () => { if (db) { await db.close() db = null } initialized = false } export const databaseName = DB_NAME