uploadData() uses the Supabase client SDK to send each queued change to Supabase’s Data API, which is built on PostgREST. You don’t deploy a separate write endpoint: Supabase’s grants and row-level security (RLS) policies decide which writes each user can make. The Supabase guide and the Supabase demo apps use this route.
Add Grants and RLS Policies
Requests from a signed-in user run as Supabase’sauthenticated role, so your grants and RLS policies for that role must allow every write that your app uploads.
Grant the authenticated role access to every table that your app writes to, enable RLS on each one, and add a policy for each operation that your app uploads:
- A
PUTis an upsert, so it needsINSERTandUPDATEpolicies, and the existing row must be visible to the user. - A
PATCHneeds anUPDATEpolicy, and aDELETEneeds aDELETEpolicy.
WITH CHECK so that users can’t assign rows to someone else. For example:
grant select, insert, update, delete on public.lists to authenticated;
alter table public.lists enable row level security;
create policy "Owners manage their lists" on public.lists
for all to authenticated
using (owner_id = (select auth.uid()))
with check (owner_id = (select auth.uid()));
If
authenticated has grants on a table that has RLS disabled, any signed-in user can write any row in it. Check every table in the schemas that your app writes to, not only the tables that you sync.Transactions Are Not Atomic
The Supabase client SDK has no transaction support.uploadData() sends each change in a transaction as a separate request, and each request commits on its own. If one change in a transaction fails, the changes before it stay in the database.
For example, an app creates a list and its first item in one local transaction. If the insert of the item fails, the list is still created in Supabase.
If your app needs all changes in a transaction to be applied together or not at all, you have two options:
- Use the Edge Function route, which runs the reference write implementation as a Supabase Edge Function and applies each transaction atomically.
- Write a Postgres function that applies the whole transaction, and call it from
uploadData()with the Supabase client’srpc()method.
How the Connector Handles Errors
The example connectors are based on the Supabase demo apps, such as the React demo’sSupabaseConnector.ts. Their uploadData() checks the Postgres error code that Supabase returns:
| Error code | Meaning | What the connector does |
|---|---|---|
Class 22 | Data exception, such as a type mismatch | Logs the error and marks the transaction complete |
Class 23 | Constraint violation, such as NOT NULL, FOREIGN KEY, or UNIQUE | Logs the error and marks the transaction complete |
42501 | Insufficient privilege, usually a missing grant or an RLS policy that rejects the write | Logs the error and marks the transaction complete |
| Any other error | For example, a network error | Throws, so the SDK retries |
42501, see Uploads Fail With Error 42501.
The connector retries every other error, including errors that can never succeed, such as PGRST204 for a column that doesn’t exist in Supabase. Such a transaction becomes a blocked transaction and holds back every later write until you fix the cause. Check the app’s logs for repeated upload errors.
To reduce the number of requests, you can merge consecutive changes to the same table into one request. See Improve Supabase Connector.
Connector Examples
Copy the connector for your SDK into your app. Each one passes the Supabase Auth session token to PowerSync and uploads writes with the Supabase client SDK. There is no Supabase connector for Rust. The connectors read your Supabase project URL, your Supabase anon key, and your PowerSync instance URL from your app’s configuration, such as environment variables. Set those values in your app, then pass the connector toconnect() in place of your current connector.
- JavaScript
- TypeScript
- React Native
- Dart
- Kotlin
- Swift
- .NET
PowerSyncConnector.js
import { BaseObserver, UpdateType } from '@powersync/web';
import { createClient } from '@supabase/supabase-js';
/// Postgres Response codes that we cannot recover from by retrying.
const FATAL_RESPONSE_CODES = [
// Class 22 — Data Exception
// Examples include data type mismatch.
new RegExp('^22...$'),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
new RegExp('^23...$'),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
new RegExp('^42501$')
];
export class SupabaseConnector extends BaseObserver {
constructor() {
super();
this.config = {
supabaseUrl: import.meta.env.VITE_SUPABASE_URL,
powersyncUrl: import.meta.env.VITE_POWERSYNC_URL,
supabaseAnonKey: import.meta.env.VITE_SUPABASE_ANON_KEY
};
this.client = createClient(this.config.supabaseUrl, this.config.supabaseAnonKey, {
auth: {
persistSession: true
}
});
this.currentSession = null;
this.ready = false;
}
async init() {
if (this.ready) {
return;
}
const sessionResponse = await this.client.auth.getSession();
this.updateSession(sessionResponse.data.session);
this.ready = true;
this.iterateListeners((cb) => cb.initialized?.());
}
async login(username, password) {
const {
data: { session },
error
} = await this.client.auth.signInWithPassword({
email: username,
password: password
});
if (error) {
throw error;
}
this.updateSession(session);
}
async fetchCredentials() {
const {
data: { session },
error
} = await this.client.auth.getSession();
if (!session || error) {
throw new Error(`Could not fetch Supabase credentials: ${error}`);
}
console.debug('session expires at', session.expires_at);
return {
endpoint: this.config.powersyncUrl,
token: session.access_token ?? ''
};
}
async uploadData(database) {
const transaction = await database.getNextCrudTransaction();
if (!transaction) {
return;
}
let lastOp = null;
try {
// Note: If transactional consistency is important, use database functions
// or edge functions to process the entire transaction in a single call.
for (const op of transaction.crud) {
lastOp = op;
const table = this.client.from(op.table);
let result;
switch (op.op) {
case UpdateType.PUT: {
const record = { ...op.opData, id: op.id };
result = await table.upsert(record);
break;
}
case UpdateType.PATCH:
result = await table.update(op.opData).eq('id', op.id);
break;
case UpdateType.DELETE:
result = await table.delete().eq('id', op.id);
break;
}
if (result.error) {
console.error(result.error);
result.error.message = `Could not update Supabase. Received error: ${result.error.message}`;
throw result.error;
}
}
await transaction.complete();
} catch (ex) {
console.debug(ex);
if (typeof ex.code == 'string' && FATAL_RESPONSE_CODES.some((regex) => regex.test(ex.code))) {
/**
* Instead of blocking the queue with these errors,
* discard the (rest of the) transaction.
*
* Note that these errors typically indicate a bug in the application.
* If protecting against data loss is important, save the failing records
* elsewhere instead of discarding, and/or notify the user.
*/
console.error('Data upload error - discarding:', lastOp, ex);
await transaction.complete();
} else {
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
throw ex;
}
}
}
updateSession(session) {
this.currentSession = session;
if (!session) {
return;
}
this.iterateListeners((cb) => cb.sessionStarted?.(session));
}
}
PowerSyncConnector.ts
import {
BaseObserver,
UpdateType,
type CommonPowerSyncDatabase,
type CrudEntry,
type PowerSyncBackendConnector,
type PowerSyncCredentials
} from '@powersync/web';
import { Session, SupabaseClient, createClient } from '@supabase/supabase-js';
export type SupabaseConfig = {
supabaseUrl: string;
supabaseAnonKey: string;
powersyncUrl: string;
};
/// Postgres Response codes that we cannot recover from by retrying.
const FATAL_RESPONSE_CODES = [
// Class 22 — Data Exception
// Examples include data type mismatch.
new RegExp('^22...$'),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
new RegExp('^23...$'),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
new RegExp('^42501$')
];
export type SupabaseConnectorListener = {
initialized: () => void;
sessionStarted: (session: Session) => void;
};
export class SupabaseConnector extends BaseObserver<SupabaseConnectorListener> implements PowerSyncBackendConnector {
readonly client: SupabaseClient;
readonly config: SupabaseConfig;
ready: boolean;
currentSession: Session | null;
constructor() {
super();
this.config = {
supabaseUrl: import.meta.env.VITE_SUPABASE_URL,
powersyncUrl: import.meta.env.VITE_POWERSYNC_URL,
supabaseAnonKey: import.meta.env.VITE_SUPABASE_ANON_KEY
};
this.client = createClient(this.config.supabaseUrl, this.config.supabaseAnonKey, {
auth: {
persistSession: true
}
});
this.currentSession = null;
this.ready = false;
}
async init() {
if (this.ready) {
return;
}
const sessionResponse = await this.client.auth.getSession();
this.updateSession(sessionResponse.data.session);
this.ready = true;
this.iterateListeners((cb) => cb.initialized?.());
}
async login(username: string, password: string) {
const {
data: { session },
error
} = await this.client.auth.signInWithPassword({
email: username,
password: password
});
if (error) {
throw error;
}
this.updateSession(session);
}
async fetchCredentials() {
const {
data: { session },
error
} = await this.client.auth.getSession();
if (!session || error) {
throw new Error(`Could not fetch Supabase credentials: ${error}`);
}
console.debug('session expires at', session.expires_at);
return {
endpoint: this.config.powersyncUrl,
token: session.access_token ?? ''
} satisfies PowerSyncCredentials;
}
async uploadData(database: CommonPowerSyncDatabase): Promise<void> {
const transaction = await database.getNextCrudTransaction();
if (!transaction) {
return;
}
let lastOp: CrudEntry | null = null;
try {
// Note: If transactional consistency is important, use database functions
// or edge functions to process the entire transaction in a single call.
for (const op of transaction.crud) {
lastOp = op;
const table = this.client.from(op.table);
let result: any;
switch (op.op) {
case UpdateType.PUT:
const record = { ...op.opData, id: op.id };
result = await table.upsert(record);
break;
case UpdateType.PATCH:
result = await table.update(op.opData).eq('id', op.id);
break;
case UpdateType.DELETE:
result = await table.delete().eq('id', op.id);
break;
}
if (result.error) {
console.error(result.error);
result.error.message = `Could not update Supabase. Received error: ${result.error.message}`;
throw result.error;
}
}
await transaction.complete();
} catch (ex: any) {
console.debug(ex);
if (typeof ex.code == 'string' && FATAL_RESPONSE_CODES.some((regex) => regex.test(ex.code))) {
/**
* Instead of blocking the queue with these errors,
* discard the (rest of the) transaction.
*
* Note that these errors typically indicate a bug in the application.
* If protecting against data loss is important, save the failing records
* elsewhere instead of discarding, and/or notify the user.
*/
console.error('Data upload error - discarding:', lastOp, ex);
await transaction.complete();
} else {
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
throw ex;
}
}
}
updateSession(session: Session | null) {
this.currentSession = session;
if (!session) {
return;
}
this.iterateListeners((cb) => cb.sessionStarted?.(session));
}
}
PowerSyncConnector.ts
import { UpdateType, type CommonPowerSyncDatabase, type CrudEntry, type PowerSyncBackendConnector, type PowerSyncCredentials } from '@powersync/react-native';
import { SupabaseClient, createClient } from '@supabase/supabase-js';
import { AppConfig } from './AppConfig';
import { SupabaseStorageAdapter } from '../storage/SupabaseStorageAdapter';
import { System } from '../powersync/system';
/// Postgres Response codes that we cannot recover from by retrying.
const FATAL_RESPONSE_CODES = [
// Class 22 — Data Exception
// Examples include data type mismatch.
new RegExp('^22...$'),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
new RegExp('^23...$'),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
new RegExp('^42501$')
];
export class SupabaseConnector implements PowerSyncBackendConnector {
client: SupabaseClient;
storage: SupabaseStorageAdapter;
constructor(protected system: System) {
this.client = createClient(AppConfig.supabaseUrl, AppConfig.supabaseAnonKey, {
auth: {
persistSession: true,
storage: this.system.kvStorage
}
});
this.storage = new SupabaseStorageAdapter({ client: this.client });
}
async login(username: string, password: string) {
const { error } = await this.client.auth.signInWithPassword({
email: username,
password: password
});
if (error) {
throw error;
}
}
async userId() {
const {
data: { session },
} = await this.client.auth.getSession();
return session?.user.id;
}
async fetchCredentials() {
const {
data: { session },
error
} = await this.client.auth.getSession();
if (!session || error) {
throw new Error(`Could not fetch Supabase credentials: ${error}`);
}
console.debug('session expires at', session.expires_at);
return {
endpoint: AppConfig.powersyncUrl,
token: session.access_token ?? ''
} satisfies PowerSyncCredentials;
}
async uploadData(database: CommonPowerSyncDatabase): Promise<void> {
const transaction = await database.getNextCrudTransaction();
if (!transaction) {
return;
}
let lastOp: CrudEntry | null = null;
try {
// Note: If transactional consistency is important, use database functions
// or edge functions to process the entire transaction in a single call.
for (const op of transaction.crud) {
lastOp = op;
const table = this.client.from(op.table);
let result: any = null;
switch (op.op) {
case UpdateType.PUT:
// eslint-disable-next-line no-case-declarations
const record = { ...op.opData, id: op.id };
result = await table.upsert(record);
break;
case UpdateType.PATCH:
result = await table.update(op.opData).eq('id', op.id);
break;
case UpdateType.DELETE:
result = await table.delete().eq('id', op.id);
break;
}
if (result.error) {
console.error(result.error);
result.error.message = `Could not ${op.op} data to Supabase error: ${JSON.stringify(result)}`;
throw result.error;
}
}
await transaction.complete();
} catch (ex: any) {
console.debug(ex);
if (typeof ex.code == 'string' && FATAL_RESPONSE_CODES.some((regex) => regex.test(ex.code))) {
/**
* Instead of blocking the queue with these errors,
* discard the (rest of the) transaction.
*
* Note that these errors typically indicate a bug in the application.
* If protecting against data loss is important, save the failing records
* elsewhere instead of discarding, and/or notify the user.
*/
console.error('Data upload error - discarding:', lastOp, ex);
await transaction.complete();
} else {
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
throw ex;
}
}
}
}
lib/powersync.dart
// This file performs setup of the PowerSync database
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:powersync/powersync.dart';
import 'package:powersync_flutter_demo/migrations/fts_setup.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import './app_config.dart';
import './models/schema.dart';
import './supabase.dart';
final log = Logger('powersync-supabase');
/// Postgres Response codes that we cannot recover from by retrying.
final List<RegExp> fatalResponseCodes = [
// Class 22 — Data Exception
// Examples include data type mismatch.
RegExp(r'^22...$'),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
RegExp(r'^23...$'),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
RegExp(r'^42501$'),
];
/// Use Supabase for authentication and data upload.
class SupabaseConnector extends PowerSyncBackendConnector {
PowerSyncDatabase db;
Future<void>? _refreshFuture;
SupabaseConnector(this.db);
/// Get a Supabase token to authenticate against the PowerSync instance.
@override
Future<PowerSyncCredentials?> fetchCredentials() async {
// Wait for pending session refresh if any
await _refreshFuture;
// Use Supabase token for PowerSync
final session = Supabase.instance.client.auth.currentSession;
if (session == null) {
// Not logged in
return null;
}
// Use the access token to authenticate against PowerSync
final token = session.accessToken;
// userId and expiresAt are for debugging purposes only
final userId = session.user.id;
final expiresAt = session.expiresAt == null
? null
: DateTime.fromMillisecondsSinceEpoch(session.expiresAt! * 1000);
return PowerSyncCredentials(
endpoint: AppConfig.powersyncUrl,
token: token,
userId: userId,
expiresAt: expiresAt);
}
@override
void invalidateCredentials() {
// Trigger a session refresh if auth fails on PowerSync.
// Generally, sessions should be refreshed automatically by Supabase.
// However, in some cases it can be a while before the session refresh is
// retried. We attempt to trigger the refresh as soon as we get an auth
// failure on PowerSync.
//
// This could happen if the device was offline for a while and the session
// expired, and nothing else attempt to use the session it in the meantime.
//
// Timeout the refresh call to avoid waiting for long retries,
// and ignore any errors. Errors will surface as expired tokens.
_refreshFuture = Supabase.instance.client.auth
.refreshSession()
.timeout(const Duration(seconds: 5))
.then((response) => null, onError: (error) => null);
}
// Upload pending changes to Supabase.
@override
Future<void> uploadData(PowerSyncDatabase database) async {
// This function is called whenever there is data to upload, whether the
// device is online or offline.
// If this call throws an error, it is retried periodically.
final transaction = await database.getNextCrudTransaction();
if (transaction == null) {
return;
}
final rest = Supabase.instance.client.rest;
CrudEntry? lastOp;
try {
// Note: If transactional consistency is important, use database functions
// or edge functions to process the entire transaction in a single call.
for (var op in transaction.crud) {
lastOp = op;
final table = rest.from(op.table);
if (op.op == UpdateType.put) {
var data = Map<String, dynamic>.of(op.opData!);
data['id'] = op.id;
await table.upsert(data);
} else if (op.op == UpdateType.patch) {
await table.update(op.opData!).eq('id', op.id);
} else if (op.op == UpdateType.delete) {
await table.delete().eq('id', op.id);
}
}
// All operations successful.
await transaction.complete();
} on PostgrestException catch (e) {
if (e.code != null &&
fatalResponseCodes.any((re) => re.hasMatch(e.code!))) {
/// Instead of blocking the queue with these errors,
/// discard the (rest of the) transaction.
///
/// Note that these errors typically indicate a bug in the application.
/// If protecting against data loss is important, save the failing records
/// elsewhere instead of discarding, and/or notify the user.
log.severe('Data upload error - discarding $lastOp', e);
await transaction.complete();
} else {
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
rethrow;
}
}
}
}
/// Global reference to the database
late final PowerSyncDatabase db;
bool isLoggedIn() {
return Supabase.instance.client.auth.currentSession?.accessToken != null;
}
/// id of the user currently logged in
String? getUserId() {
return Supabase.instance.client.auth.currentSession?.user.id;
}
Future<String> getDatabasePath() async {
const dbFilename = 'powersync-demo.db';
// getApplicationSupportDirectory is not supported on Web
if (kIsWeb) {
return dbFilename;
}
final dir = await getApplicationSupportDirectory();
return join(dir.path, dbFilename);
}
Future<void> openDatabase() async {
// Open the local database
db = PowerSyncDatabase(
schema: schema, path: await getDatabasePath(), logger: attachedLogger);
await db.initialize();
await loadSupabase();
SupabaseConnector? currentConnector;
if (isLoggedIn()) {
// If the user is already logged in, connect immediately.
// Otherwise, connect once logged in.
currentConnector = SupabaseConnector(db);
db.connect(connector: currentConnector);
}
Supabase.instance.client.auth.onAuthStateChange.listen((data) async {
final AuthChangeEvent event = data.event;
if (event == AuthChangeEvent.signedIn) {
// Connect to PowerSync when the user is signed in
currentConnector = SupabaseConnector(db);
db.connect(connector: currentConnector!);
} else if (event == AuthChangeEvent.signedOut) {
// Implicit sign out - disconnect, but don't delete data
currentConnector = null;
await db.disconnect();
} else if (event == AuthChangeEvent.tokenRefreshed) {
// Supabase token refreshed - trigger token refresh for PowerSync.
currentConnector?.prefetchCredentials();
}
});
// Demo using SQLite Full-Text Search with PowerSync.
// See https://docs.powersync.com/usage-examples/full-text-search for more details
await configureFts(db);
}
/// Explicit sign out - clear database and log out.
Future<void> logout() async {
await Supabase.instance.client.auth.signOut();
await db.disconnectAndClear();
}
PowerSync.kt
package com.powersync.connector.supabase
import co.touchlab.kermit.Logger
import com.powersync.PowerSyncDatabase
import com.powersync.connectors.PowerSyncBackendConnector
import com.powersync.connectors.PowerSyncCredentials
import com.powersync.db.crud.CrudEntry
import com.powersync.db.crud.CrudTransaction
import com.powersync.db.crud.UpdateType
import com.powersync.db.runWrapped
import io.github.jan.supabase.SupabaseClient
import io.github.jan.supabase.annotations.SupabaseInternal
import io.github.jan.supabase.auth.Auth
import io.github.jan.supabase.auth.auth
import io.github.jan.supabase.auth.providers.builtin.Email
import io.github.jan.supabase.auth.status.SessionStatus
import io.github.jan.supabase.auth.user.UserSession
import io.github.jan.supabase.createSupabaseClient
import io.github.jan.supabase.postgrest.Postgrest
import io.github.jan.supabase.postgrest.from
import io.github.jan.supabase.storage.BucketApi
import io.github.jan.supabase.storage.Storage
import io.github.jan.supabase.storage.storage
import io.ktor.client.plugins.HttpSend
import io.ktor.client.plugins.plugin
import io.ktor.client.statement.bodyAsText
import io.ktor.utils.io.InternalAPI
import kotlinx.coroutines.flow.StateFlow
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonPrimitive
import kotlin.toString
/**
* Get a Supabase token to authenticate against the PowerSync instance.
*/
@OptIn(SupabaseInternal::class, InternalAPI::class)
public open class SupabaseConnector(
public val supabaseClient: SupabaseClient,
public val powerSyncEndpoint: String,
private val storageBucket: String? = null,
) : PowerSyncBackendConnector() {
private val json = Json { coerceInputValues = true }
private var errorCode: String? = null
public companion object PostgresFatalCodes {
// Using Regex patterns for Postgres error codes
private val FATAL_RESPONSE_CODES =
listOf(
// Class 22 — Data Exception
"^22...".toRegex(),
// Class 23 — Integrity Constraint Violation
"^23...".toRegex(),
// INSUFFICIENT PRIVILEGE
"^42501$".toRegex(),
)
public fun isFatalError(code: String): Boolean =
FATAL_RESPONSE_CODES.any { pattern ->
pattern.matches(code)
}
}
public fun storageBucket(): BucketApi {
if (storageBucket == null) {
throw Exception("No bucket has been specified")
}
return supabaseClient.storage[storageBucket]
}
public constructor(
supabaseUrl: String,
supabaseKey: String,
powerSyncEndpoint: String,
storageBucket: String? = null,
) : this(
supabaseClient =
createSupabaseClient(supabaseUrl, supabaseKey) {
install(Auth)
install(Postgrest)
if (storageBucket != null) {
install(Storage)
}
},
powerSyncEndpoint = powerSyncEndpoint,
storageBucket = storageBucket,
)
init {
require(supabaseClient.pluginManager.getPluginOrNull(Auth) != null) { "The Auth plugin must be installed on the Supabase client" }
require(
supabaseClient.pluginManager.getPluginOrNull(Postgrest) != null,
) { "The Postgrest plugin must be installed on the Supabase client" }
// This retrieves the error code from the response
// as this is not accessible in the Supabase client RestException
// to handle fatal Postgres errors
supabaseClient.httpClient.httpClient.plugin(HttpSend).intercept { request ->
val resp = execute(request)
val response = resp.response
if (response.status.value >= 400) {
val responseText = response.bodyAsText()
try {
val error =
json.decodeFromString<Map<String, String?>>(
responseText,
)
errorCode = error["code"]
} catch (e: Exception) {
Logger.e("Failed to parse error response: $e")
}
}
resp
}
}
public suspend fun login(
email: String,
password: String,
) {
runWrapped {
supabaseClient.auth.signInWith(Email) {
this.email = email
this.password = password
}
}
}
public suspend fun signUp(
email: String,
password: String,
) {
runWrapped {
supabaseClient.auth.signUpWith(Email) {
this.email = email
this.password = password
}
}
}
public suspend fun signOut() {
runWrapped {
supabaseClient.auth.signOut()
}
}
public fun session(): UserSession? = supabaseClient.auth.currentSessionOrNull()
public val sessionStatus: StateFlow<SessionStatus> = supabaseClient.auth.sessionStatus
public suspend fun loginAnonymously() {
runWrapped {
supabaseClient.auth.signInAnonymously()
}
}
/**
* Get credentials for PowerSync.
*/
override suspend fun fetchCredentials(): PowerSyncCredentials =
runWrapped {
check(supabaseClient.auth.sessionStatus.value is SessionStatus.Authenticated) { "Supabase client is not authenticated" }
// Use Supabase token for PowerSync
val session =
supabaseClient.auth.currentSessionOrNull()
?: error("Could not fetch Supabase credentials")
check(session.user != null) { "No user data" }
PowerSyncCredentials(
endpoint = powerSyncEndpoint,
token = session.accessToken, // Use the access token to authenticate against PowerSync
)
}
/**
* Uses the PostgREST APIs to upload a given [entry] to the backend database.
*
* This method should report errors during the upload as an exception that would be caught by [uploadData].
*/
public open suspend fun uploadCrudEntry(entry: CrudEntry) {
val table = supabaseClient.from(entry.table)
when (entry.op) {
UpdateType.PUT -> {
val data =
buildMap {
put("id", JsonPrimitive(entry.id))
entry.opData?.jsonValues?.let { putAll(it) }
}
table.upsert(data)
}
UpdateType.PATCH -> {
table.update(entry.opData!!.jsonValues) {
filter {
eq("id", entry.id)
}
}
}
UpdateType.DELETE -> {
table.delete {
filter {
eq("id", entry.id)
}
}
}
}
}
/**
* Handles an error during the upload. This method can be overridden to log errors or customize error handling.
*
* By default, it discards the rest of a transaction when the error code indicates that this is a fatal postgres
* error that can't be retried. Otherwise, it rethrows the exception so that the PowerSync SDK will retry.
*
* @param tx The full [CrudTransaction] we're in the process of uploading.
* @param entry The [CrudEntry] for which an upload has failed.
* @param exception The [Exception] thrown by the Supabase client.
* @param [errorCode] The postgres error code, if any.
* @throws Exception If the upload should be retried. If this method doesn't throw, it should mark [tx] as complete
* by invoking [CrudTransaction.complete]. In that case, the local write would be lost.
*/
public open suspend fun handleError(
tx: CrudTransaction,
entry: CrudEntry,
exception: Exception,
errorCode: String?,
) {
if (errorCode != null && isFatalError(errorCode)) {
/**
* Instead of blocking the queue with these errors,
* discard the (rest of the) transaction.
*
* Note that these errors typically indicate a bug in the application.
* If protecting against data loss is important, save the failing records
* elsewhere instead of discarding, and/or notify the user.
*/
Logger.e("Data upload error: ${exception.message}")
Logger.e("Discarding entry: $entry")
tx.complete(null)
return
}
Logger.e("Data upload error - retrying last entry: $entry, $exception")
throw exception
}
/**
* Upload local changes to the app backend (in this case Supabase).
*
* This function is called whenever there is data to upload, whether the device is online or offline.
* If this call throws an error, it is retried periodically.
*/
override suspend fun uploadData(database: PowerSyncDatabase) {
return runWrapped {
val transaction = database.getNextCrudTransaction() ?: return@runWrapped
var lastEntry: CrudEntry? = null
try {
for (entry in transaction.crud) {
lastEntry = entry
uploadCrudEntry(entry)
}
transaction.complete(null)
} catch (e: Exception) {
if (lastEntry != null) {
handleError(transaction, lastEntry, e, errorCode)
} else {
throw e
}
}
}
}
}
PowerSyncConnector.swift
import AnyCodable
import Auth
import PowerSync
import Supabase
import SwiftUI
private enum PostgresFatalCodes {
/// Postgres Response codes that we cannot recover from by retrying.
static let fatalResponseCodes: [String] = [
// Class 22 — Data Exception
// Examples include data type mismatch.
"22...",
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
"23...",
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
"42501",
]
static func isFatalError(_ code: String) -> Bool {
return fatalResponseCodes.contains { pattern in
code.range(of: pattern, options: [.regularExpression]) != nil
}
}
static func extractErrorCode(from error: any Error) -> String? {
// Look for code: Optional("XXXXX") pattern
let errorString = String(describing: error)
if let range = errorString.range(of: "code: Optional\\(\"([^\"]+)\"\\)", options: .regularExpression),
let codeRange = errorString[range].range(of: "\"([^\"]+)\"", options: .regularExpression)
{
// Extract just the code from within the quotes
let code = errorString[codeRange].dropFirst().dropLast()
return String(code)
}
return nil
}
}
@Observable
@MainActor // _session is mutable, limiting to the MainActor satisfies Sendable constraints
final class SupabaseConnector: PowerSyncBackendConnectorProtocol {
let powerSyncEndpoint: String = Secrets.powerSyncEndpoint
let client: SupabaseClient = .init(
supabaseURL: Secrets.supabaseURL,
supabaseKey: Secrets.supabaseAnonKey,
)
private(set) var session: Session?
private var errorCode: String?
@ObservationIgnored
private var observeAuthStateChangesTask: Task<Void, Error>?
init() {
session = client.auth.currentSession
observeAuthStateChangesTask = Task { [weak self] in
guard let self = self else { return }
for await (event, session) in self.client.auth.authStateChanges {
guard [.initialSession, .signedIn, .signedOut].contains(event) else { throw AuthError.sessionMissing }
self.session = session
}
}
}
var currentUserID: String {
guard let id = session?.user.id else {
preconditionFailure("Required session.")
}
return id.uuidString.lowercased()
}
func getStorageBucket() -> StorageFileApi? {
guard let bucket = Secrets.supabaseStorageBucket else {
return nil
}
return client.storage.from(bucket)
}
func fetchCredentials() async throws -> PowerSyncCredentials? {
session = try await client.auth.session
if session == nil {
throw AuthError.sessionMissing
}
let token = session!.accessToken
return PowerSyncCredentials(endpoint: powerSyncEndpoint, token: token)
}
func uploadData(database: PowerSyncDatabaseProtocol) async throws {
guard let transaction = try await database.getNextCrudTransaction() else { return }
var lastEntry: CrudEntry?
do {
for entry in transaction.crud {
lastEntry = entry
let tableName = entry.table
let table = client.from(tableName)
switch entry.op {
case .put:
var data = entry.opData ?? [:]
data["id"] = entry.id
try await table.upsert(data).execute()
case .patch:
guard let opData = entry.opData else { continue }
try await table.update(opData).eq("id", value: entry.id).execute()
case .delete:
try await table.delete().eq("id", value: entry.id).execute()
}
}
try await transaction.complete()
} catch {
if let errorCode = PostgresFatalCodes.extractErrorCode(from: error),
PostgresFatalCodes.isFatalError(errorCode)
{
/// Instead of blocking the queue with these errors,
/// discard the (rest of the) transaction.
///
/// Note that these errors typically indicate a bug in the application.
/// If protecting against data loss is important, save the failing records
/// elsewhere instead of discarding, and/or notify the user.
print("Data upload error: \(error)")
print("Discarding entry: \(lastEntry!)")
try await transaction.complete()
return
}
print("Data upload error - retrying last entry: \(lastEntry!), \(error)")
throw error
}
}
deinit {
observeAuthStateChangesTask?.cancel()
}
}
PowerSyncConnector.cs
namespace CommandLine;
using System.Text.RegularExpressions;
using CommandLine.Helpers;
using CommandLine.Models.Supabase;
using CommandLine.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PowerSync.Common.Client;
using PowerSync.Common.Client.Connection;
using PowerSync.Common.DB.Crud;
using Supabase;
using Supabase.Gotrue;
using Supabase.Postgrest.Exceptions;
using Supabase.Postgrest.Interfaces;
public class SupabaseConnector : IPowerSyncBackendConnector
{
/// <summary>
/// Postgres error codes that a retry can never fix, so the transaction is discarded
/// instead of being retried forever.
/// </summary>
private static readonly Regex[] FatalResponseCodes =
[
// Class 22 — Data Exception
// Examples include data type mismatch.
new Regex("^22...$"),
// Class 23 — Integrity Constraint Violation.
// Examples include NOT NULL, FOREIGN KEY and UNIQUE violations.
new Regex("^23...$"),
// INSUFFICIENT PRIVILEGE - typically a row-level security violation
new Regex("^42501$")
];
private readonly Supabase.Client _supabase;
private readonly Config _config;
private Session? _currentSession;
public Session? CurrentSession
{
get => _currentSession;
set
{
_currentSession = value;
if (_currentSession?.User?.Id != null)
{
UserId = _currentSession.User.Id;
}
}
}
public string UserId { get; private set; } = "";
public bool Ready { get; private set; }
public SupabaseConnector(Config config)
{
_config = config;
_supabase = new Supabase.Client(config.SupabaseUrl, config.SupabaseAnonKey, new SupabaseOptions
{
AutoConnectRealtime = true
});
_ = _supabase.InitializeAsync();
}
public async Task Login(string email, string password)
{
var response = await _supabase.Auth.SignInWithPassword(email, password);
if (response?.User == null || response.AccessToken == null)
{
throw new Exception("Login failed.");
}
CurrentSession = response;
}
public Task<PowerSyncCredentials?> FetchCredentials()
{
PowerSyncCredentials? credentials = null;
var sessionResponse = _supabase.Auth.CurrentSession;
if (sessionResponse?.AccessToken != null)
{
credentials = new PowerSyncCredentials(_config.PowerSyncUrl, sessionResponse.AccessToken);
}
return Task.FromResult(credentials);
}
public async Task UploadData(IPowerSyncDatabase database)
{
var transaction = await database.GetNextCrudTransaction();
if (transaction == null) return;
CrudEntry? lastOp = null;
try
{
foreach (var op in transaction.Crud)
{
lastOp = op;
switch (op.Op)
{
case UpdateType.PUT:
if (op.Table.ToLower().Trim() == "lists")
{
var model = JsonConvert.DeserializeObject<List>(JsonConvert.SerializeObject(op.OpData)) ?? throw new InvalidOperationException("Model is null.");
model.Id = op.Id;
await _supabase.From<List>().Upsert(model);
}
else if (op.Table.ToLower().Trim() == "todos")
{
var model = JsonConvert.DeserializeObject<Todo>(JsonConvert.SerializeObject(op.OpData)) ?? throw new InvalidOperationException("Model is null.");
model.Id = op.Id;
await _supabase.From<Todo>().Upsert(model);
}
break;
case UpdateType.PATCH:
if (op.OpData is null || op.OpData.Count == 0)
{
Console.WriteLine("PATCH skipped: No data to update.");
break;
}
if (op.Table.ToLower().Trim() == "lists")
{
// Create an update query for the 'List' table where the 'Id' matches 'op.Id'
IPostgrestTable<List> updateQuery = _supabase
.From<List>()
.Where(x => x.Id == op.Id);
// Loop through each key-value pair in the operation data (op.OpData) to apply updates dynamically
foreach (var kvp in op.OpData)
{
// Apply the "SET" operation for each key-value pair.
// The key represents the JSON property name and the value is the new value to be set
updateQuery = SupabasePatchHelper.ApplySet(updateQuery, kvp.Key, kvp.Value);
}
_ = await updateQuery.Update();
}
else if (op.Table.ToLower().Trim() == "todos")
{
// Create an update query for the 'Todo' table where the 'Id' matches 'op.Id'
IPostgrestTable<Todo> updateQuery = _supabase
.From<Todo>()
.Where(x => x.Id == op.Id);
// Loop through each key-value pair in the operation data (op.OpData) to apply updates dynamically
foreach (var kvp in op.OpData)
{
// Apply the "SET" operation for each key-value pair.
// The key represents the JSON property name and the value is the new value to be set
updateQuery = SupabasePatchHelper.ApplySet(updateQuery, kvp.Key, kvp.Value);
}
_ = await updateQuery.Update();
}
break;
case UpdateType.DELETE:
if (op.Table.ToLower().Trim() == "lists")
{
await _supabase
.From<List>()
.Where(x => x.Id == op.Id)
.Delete();
}
else if (op.Table.ToLower().Trim() == "todos")
{
await _supabase
.From<Todo>()
.Where(x => x.Id == op.Id)
.Delete();
}
break;
default:
throw new InvalidOperationException("Unknown operation type.");
}
}
await transaction.Complete();
}
catch (PostgrestException ex)
{
var errorCode = PostgresErrorCode(ex);
if (errorCode != null && FatalResponseCodes.Any(pattern => pattern.IsMatch(errorCode)))
{
// Instead of blocking the queue with these errors,
// discard the (rest of the) transaction.
//
// Note that these errors typically indicate a bug in the application.
// If protecting against data loss is important, save the failing records
// elsewhere instead of discarding, and/or notify the user.
Console.WriteLine($"Data upload error - discarding {lastOp}: {ex.Message}");
await transaction.Complete();
return;
}
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
Console.WriteLine($"Error during upload: {ex.Message}");
throw;
}
}
/// <summary>
/// Reads the Postgres error code from a PostgREST error response. PostgrestException does not
/// expose the code directly, so it is read from the response body.
/// </summary>
private static string? PostgresErrorCode(PostgrestException exception)
{
if (string.IsNullOrWhiteSpace(exception.Content))
{
return null;
}
try
{
return JObject.Parse(exception.Content!)["code"]?.ToString();
}
catch (JsonReaderException)
{
return null;
}
}
}
Related Pages
- Supabase guide: set up Supabase, PowerSync, and a demo app.
- Write Path Concepts: what happens when a write fails.
- Handling Update Conflicts: what happens when two clients change the same row.
- Custom Conflict Resolution: strategies for resolving conflicts.
- Client-Side Integration: the backend connector, and when the SDK calls
uploadData().