All files / src/lib/powersync runes.svelte.ts

57.14% Statements 4/7
100% Branches 1/1
25% Functions 1/4
57.14% Lines 4/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85                                                                1x 1x 1x                                                                           1x                        
// Reactive query helper using Svelte 5 runes.
// The .svelte.ts extension enables $state and $effect outside .svelte files.
//
// Usage inside a Svelte component or another .svelte.ts file:
//   const q = useQuery<WorkoutRow>('SELECT * FROM workouts WHERE athlete_id = ?', [userId]);
//   // q.data, q.isLoading, q.error are reactive
 
import { getDB } from './db';
 
export interface QueryResult<T> {
  data: T[];
  isLoading: boolean;
  error: Error | null;
}
 
/**
 * Reactive PowerSync query using Svelte 5 $state and $effect.
 *
 * Subscribes to live query updates via db.watch(). The subscription is
 * automatically cleaned up when the effect re-runs (sql/params change)
 * or when the component is destroyed.
 *
 * Must be called inside a component initialisation context or another
 * reactive context (i.e. not in an async function at the top level).
 *
 * @param sql    - SQL query string with ? placeholders
 * @param params - Optional array of parameter values
 */
export function useQuery<T = Record<string, unknown>>(
  sql: string,
  params: unknown[] = [],
): QueryResult<T> {
  let data = $state<T[]>([]);
  let isLoading = $state(true);
  let error = $state<Error | null>(null);
 
  $effect(() => {
    const db = getDB();
    if (!db) {
      isLoading = false;
      return;
    }
 
    const controller = new AbortController();
 
    // Reset to loading state when sql/params change
    isLoading = true;
    error = null;
 
    (async () => {
      try {
        for await (const result of db.watch(sql, params, {
          signal: controller.signal,
        })) {
          data = (result.rows?._array ?? []) as T[];
          isLoading = false;
        }
      } catch (err) {
        if ((err as Error)?.name === 'AbortError') {
          // Normal cleanup — ignore
          return;
        }
        error = err instanceof Error ? err : new Error(String(err));
        isLoading = false;
      }
    })();
 
    return () => {
      controller.abort();
    };
  });
 
  return {
    get data() {
      return data;
    },
    get isLoading() {
      return isLoading;
    },
    get error() {
      return error;
    },
  };
}