Using Database SDK

Use the JavaScript relational SDK to write and query data, join related rows, calculate aggregates, and call stored functions.

Supported Features

Install the JavaScript relational SDK:

npm install @fusabase/fusabase-relational

Import createClient, and create a relational client.

import {
  createClient,
  RelationalDatabaseError,
} from "@fusabase/fusabase-relational";

const client = createClient("https://example.com/ords/USER1/", {
  schema: "user1",
  app_name: "TodoApp",
  app_type: "WEB",
  app_id: "app-id",
  project_id: "project-id",
  objs_type: "base",
  backend_type: "RELATIONAL",
  storage_bucket: "bucket-name",
  auth_type: "base",
  auth_id: "auth-id"
});

The config object requires schema, app_type, app_id, project_id, objs_type, storage_bucket, auth_type, and auth_id. The app_name field is optional. A supplied backend_type for this client is "RELATIONAL".

Replace the example URL and configuration values with those copied from the Console. Preserve the generated authentication and storage settings.

The SDK supports:

Normal database HTTP responses return data, error, count, status, and statusText. A RelationalDatabaseError can provide message, status, code, details, and hint.

Writing Data Examples

Start a write operation with client.from("relation"). Chain select() when you need the operation to return rows.

Insert, Update, Delete, and Upsert Examples

Insert a row:

const { data, error } = await client
  .from("todos")
  .insert({
    title: "Write documentation",
    completed: false,
    priority: 2,
  })
  .select("id,title,completed,priority");

Update matching rows:

const { data, error } = await client
  .from("todos")
  .update({ completed: true })
  .eq("id", 42);

Read the rows with a separate select() to retrieve stored Boolean values. UPDATE returning responses can contain string values for Boolean columns.

Delete rows that match a filter:

const { data, error } = await client
  .from("todos")
  .delete()
  .eq("id", 42)
  .select("id,title");

Use upsert() to insert rows or update existing rows when a conflict occurs. The onConflict option identifies the unique or primary-key column:

const { data, error } = await client
  .from("todos")
  .upsert(
    {
      id: 42,
      title: "Update release documentation",
      completed: true,
    },
    { onConflict: "id" },
  )
  .select("id,title,completed");

Bulk Insert Example

Pass an array of rows to insert() for a bulk insert:

const { data, error } = await client
  .from("todos")
  .insert([
    { title: "Plan release", completed: false },
    { title: "Publish release notes", completed: false },
  ])
  .select("id,title");

Reading Data

Use select() to retrieve rows. Filters are chainable, and multiple filters use logical AND unless you group them with or() or and().

Selecting Columns

Use * to select all columns, or provide a comma-separated projection. Use alias:column to rename a selected column:

const { data, error } = await client
  .from("todos")
  .select("todo_id:id,todo_title:title,completed")
  .eq("completed", false);

Unaliased properties use the database column names. For an unquoted Oracle table, these include ID, TITLE, and COMPLETED. Explicit aliases use the names supplied in the projection.

Use single() to convert exactly one returned row from an array to an object. It returns null when the query returns zero or multiple rows.

const { data, error } = await client
  .from("todos")
  .select("id,title")
  .eq("id", 42)
  .single();

Like single(), maybeSingle() returns an object for exactly one row and null for zero or multiple rows in this SDK.

const { data, error } = await client
  .from("todos")
  .select("id,title")
  .eq("id", 999999)
  .maybeSingle();

Filtering, Ordering, and Pagination Examples

The SDK supports the following filters. Multiple filters use logical AND unless you group them with or() or and().

eq(column, value) tests equality:

.eq("completed", false)

neq(column, value) tests inequality:

.neq("status", "archived")

gt(column, value) tests whether a value is greater than another value:

.gt("priority", 3)

gte(column, value) tests whether a value is greater than or equal to another value:

.gte("priority", 2)

lt(column, value) tests whether a value is less than another value:

.lt("priority", 5)

lte(column, value) tests whether a value is less than or equal to another value:

.lte("priority", 5)

like(column, pattern) performs a case-sensitive pattern match. Use % as a wildcard:

.like("title", "%release%")

ilike(column, pattern) performs a pattern match that is not case-sensitive:

.ilike("title", "%documentation%")

ilikeAllOf(column, patterns) matches every pattern without case sensitivity:

.ilikeAllOf("title", ["%sdk%", "%guide%"])

ilikeAnyOf(column, patterns) matches at least one pattern without case sensitivity:

.ilikeAnyOf("title", ["%bug%", "%feature%"])

is(column, value) tests null, true, or false:

.is("completed_at", null)

in(column, values) matches one of the supplied values:

.in("status", ["open", "pending"])

textSearch(column, query) performs a text-style search:

.textSearch("title", "documentation")

match(query) adds equality filters from an object:

.match({ status: "open", priority: 2 })

not(column, operator, value) negates a filter condition:

.not("status", "eq", "archived")

filter(column, operator, value) applies a named back-end filter operator:

.filter("priority", "between", [2, 5])

or(filters) groups PostgREST-style filters with OR:

.or("status.eq.open,status.eq.pending")

and(filters) groups PostgREST-style filters with AND:

.and("priority.gte.2,status.eq.open")

Combine filters by chaining them:

const { data, error } = await client
  .from("todos")
  .select("id,title,priority,status")
  .eq("status", "open")
  .gte("priority", 2)
  .ilike("title", "%sdk%")
  .order("priority", { ascending: false });

The SDK provides equality, comparison, pattern, text-search, matching, negation, and grouped filters. Use the -> operator in a column path to filter JSON fields:

const { data, error } = await client
  .from("events")
  .select("*")
  .eq("metadata->status->code", "ACTIVE")
  .gt("metadata->metrics->score", 10);

Use order() to sort results. Its options include ascending, nullsFirst, path, datatype, maxLength, and sortByMinMax:

const { data, error } = await client
  .from("todos")
  .select("*")
  .order("created_at", {
    ascending: false,
    nullsFirst: false,
  });

Sort a JSON value as follows:

const { data, error } = await client
  .from("events")
  .select("*")
  .order("metadata->priority", {
    ascending: false,
    datatype: "number",
  });

limit(count) restricts the maximum number of returned rows:

const { data, error } = await client
  .from("todos")
  .select("*")
  .limit(20);

range(from, to) returns an inclusive result range:

const { data, error } = await client
  .from("todos")
  .select("*")
  .order("id")
  .range(20, 39);

Querying Views

from(relation) starts an operation on a table, view, or other relational object in the active schema. Query a view by passing its name to from():

const { data, error } = await client
  .from("active_todos_view")
  .select("id,title,owner_id");

Advanced Features

Use projections to retrieve related data and aggregates. Use rpc() to execute a stored database function or procedure.

Relationship and Join Query Examples

Select related rows in the select() projection. Related tables use a left join by default:

const { data, error } = await client
  .from("users")
  .select("id,name,orders(id,total,status)");

Use !inner to return only parent rows that have matching related rows:

const { data, error } = await client
  .from("users")
  .select("id,name,orders!inner(id,total,status)");

Use alias:relation to assign a relation alias. Select relation(count) to include a related-row count:

const { data, error } = await client
  .from("users")
  .select("id,name,purchases:orders(id,total)");
const { data, error } = await client
  .from("users")
  .select("id,name,orders(count)");

Aggregate Query Examples

Use aggregate expressions in select(). The SDK supports count, sum, avg, min, and max:

count() returns the number of rows:

row_count:count()

column.sum() returns the sum of a numeric column:

total:amount.sum()

column.avg() returns the average of a numeric column:

average:amount.avg()

column.min() returns the minimum column value:

minimum:amount.min()

column.max() returns the maximum column value:

maximum:amount.max()
const { data, error } = await client
  .from("orders")
  .select(`
    row_count:count(),
    total:amount.sum(),
    average:amount.avg(),
    minimum:amount.min(),
    maximum:amount.max()
  `)
  .single();

An example result is:

{
  row_count: 2,
  total: 167.5,
  average: 83.75,
  minimum: 42,
  maximum: 125.5
}

RPC Examples

Use rpc(fn, args?, options?) to execute a stored database function or procedure. Pass named function parameters in args.

The routine must exist in the active schema. Authorize execution through a database role assigned to the application’s DDS Data Role.

For example, have a database administrator grant execution of TESTUSER.CALCULATE_ORDER_TOTAL to the project’s unauthenticated Data Role:

CREATE ROLE app_rpc_executor;
GRANT EXECUTE ON TESTUSER.CALCULATE_ORDER_TOTAL TO app_rpc_executor;
GRANT app_rpc_executor TO "TESTUSER$NOAUTH_ROLE";

Use your project’s schema, routine, and intended Data Role. app_rpc_executor is the database role created for this privilege.

Call the function with its named parameter. This example assumes that CALCULATE_ORDER_TOTAL accepts P_ORDER_ID:

const { data, error } = await client.rpc(
  "calculate_order_total",
  { p_order_id: 42 }
);

if (error) {
  throw error;
}

Request Controls

Use request controls to cancel a request, configure retries for a select() request, or add a request-specific HTTP header.

Associate an AbortSignal with a request. Canceling the signal cancels that request:

const controller = new AbortController();

const request = client
  .from("todos")
  .select("*")
  .abortSignal(controller.signal);

controller.abort();

try {
  await request;
} catch (error) {
  if (error.name !== "AbortError") {
    throw error;
  }
}

Configure retries with retry(options?):

const { data, error } = await client
  .from("todos")
  .select("*")
  .retry({
    maxRetries: 3,
    initialDelayMs: 500,
    maxDelayMs: 5000,
  });

Disable retries as follows:

const { data, error } = await client
  .from("todos")
  .select("*")
  .retry(false);

Add a request-specific HTTP header with setHeader(name, value):

const { data, error } = await client
  .from("todos")
  .select("*")
  .setHeader("x-request-id", "request-123");

TypeScript Response Helpers

Use returns<T>() to set the expected response type without changing the request:

These unaliased projections use an unquoted Oracle table. Its returned column names are uppercase, so the TypeScript properties below match those names.

type Todo = {
  ID: number;
  TITLE: string;
  COMPLETED: boolean;
};

const result = await client
  .from("todos")
  .select("id,title,completed")
  .returns<Todo[]>();

Use overrideTypes<T>() to override or merge the inferred response type without changing the request:

type TodoSummary = {
  ID: number;
  TITLE: string;
};

const result = await client
  .from("todos")
  .select("id,title")
  .overrideTypes<TodoSummary[]>();

Responses and Errors

Normal database HTTP responses produce the following envelope. Validation, transport, cancellation, and response-parsing failures can throw; handle those exceptions as well as the error field:

type RelationalResponse<T> = {
  data: T | null;
  error: RelationalDatabaseError | null;
  count: number | null;
  status: number;
  statusText: string;
  offline?: {
    fromCache: boolean;
    hasPendingWrites: boolean;
  };
};

Check error before using data. Use an application-level error handler for thrown request failures:

try {
  const { data, error } = await client
    .from("todos")
    .insert({ title: "Write documentation" });

  if (error) {
    console.error("Message:", error.message);
    console.error("HTTP status:", error.status);
    console.error("Code:", error.code);
    console.error("Details:", error.details);
    console.error("Hint:", error.hint);
  } else {
    console.log(data);
  }
} catch (error) {
  console.error("Request failed:", error);
}

Use throwOnError() to change server-side failures from an error response into a thrown RelationalDatabaseError:

try {
  const { data } = await client
    .from("missing_table")
    .select("*")
    .throwOnError();

  console.log(data);
} catch (error) {
  if (error instanceof RelationalDatabaseError) {
    console.error("Request failed:", error.message);
    console.error("Status:", error.status);
  } else {
    throw error;
  }
}

RelationalDatabaseError can provide message, status, code, details, and hint.