plexivo_client 0.4.0
plexivo_client: ^0.4.0 copied to clipboard
Plexivo Postgres for Flutter and Dart — a Backend-as-a-Service and Firebase alternative on PostgreSQL. Auth, queries with joins, realtime, GraphQL and functions.
plexivo_client #
Plexivo Postgres for Flutter and Dart. A complete backend for your app on real PostgreSQL: sign-in, a Data API you query straight from Flutter, joins, aggregates, transactions, realtime, presence and GraphQL — with row-level security deciding what every user may read and write.
- Your database, directly from Flutter. Query with Supabase-style names (
select,eq,order) or GORM-style models (where,preload,joins,first,create). No API server to write. - Real joins. Belongs-to, has-many, many-to-many, nested three deep, inner and left joins, filters and order on related rows, subqueries.
- Sign-in built in. Email and password, guests, one-time codes, Google, GitHub and Microsoft with PKCE, sessions on every device, profile metadata.
- Live. Row changes as a
Stream, presence and broadcast for rooms, live GraphQL queries — and channels that reconnect and renew their tokens by themselves. - Every platform. Android, iOS, web, macOS, Windows, Linux and Dart servers. Pure Dart, null-safe.
dependencies:
plexivo_client: ^0.4.0
Contents: Quick start · Connect · Authentication · Reading and writing · Filters · Joins and related rows · Aggregates · Upsert and bulk writes · Transactions and functions · Raw SQL on a server · Realtime · GraphQL · Row-level security recipes · Types · Errors · Coming from Firebase · Coming from Supabase
Quick start (Flutter) #
A live todo list, synced across devices, in five minutes.
1. Create a Plexivo Postgres in the console and turn on its Data API. From the database's Connect tab, copy the Project URL and the publishable key.
2. Create a table. A table reaches your app when row-level security is on and a policy allows it. Run this once (in the console's SQL editor, or psql through plexivo db connect):
CREATE TABLE IF NOT EXISTS todos (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
owner_id uuid NOT NULL DEFAULT auth.uid(),
title text NOT NULL CHECK (length(title) BETWEEN 1 AND 200),
done boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE todos ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS own_todos ON todos;
CREATE POLICY own_todos ON todos FOR ALL TO authenticated
USING (owner_id = auth.uid()) WITH CHECK (owner_id = auth.uid());
GRANT SELECT, INSERT, UPDATE, DELETE ON todos TO authenticated;
-- Realtime for this table (the same as the console's Realtime switch).
CREATE OR REPLACE TRIGGER plexivo_realtime AFTER INSERT OR UPDATE OR DELETE ON todos
FOR EACH ROW EXECUTE FUNCTION auth.realtime_notify('id');
3. Add the package: flutter pub add plexivo_client
4. Write the app in lib/main.dart:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:plexivo_client/plexivo_client.dart';
/// One client for the whole app. The publishable key is safe to ship.
final db = PlexivoClient(
const String.fromEnvironment('PLEXIVO_URL'),
const String.fromEnvironment('PLEXIVO_PUBLISHABLE_KEY'),
);
void main() => runApp(const TodoApp());
/// Shows the sign-in page or the todos, following the auth state.
class TodoApp extends StatelessWidget {
/// Creates the app.
const TodoApp({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Todos',
home: StreamBuilder<PlexivoAuthState>(
stream: db.authStateChanges,
builder: (context, _) => db.session == null ? const SignInPage() : const TodoPage(),
),
);
}
/// Starts a guest session; link an email later and keep every row.
class SignInPage extends StatelessWidget {
/// Creates the page.
const SignInPage({super.key});
@override
Widget build(BuildContext context) => Scaffold(
body: Center(
child: FilledButton(
onPressed: () => db.signInAnonymously(),
child: const Text('Continue as guest'),
),
),
);
}
/// The signed-in user's todos, live.
class TodoPage extends StatefulWidget {
/// Creates the page.
const TodoPage({super.key});
@override
State<TodoPage> createState() => _TodoPageState();
}
class _TodoPageState extends State<TodoPage> {
final _input = TextEditingController();
final _todos = StreamController<List<Map<String, dynamic>>>();
final _live = db.channel('changes:todos')..subscribe();
late final StreamSubscription<PlexivoChange> _changes;
@override
void initState() {
super.initState();
// Listen first, then load once joined: no change is ever missed.
_changes = _live.changes.listen((_) => _load());
_live.ready().then((_) => _load(), onError: _todos.addError);
}
Future<void> _load() async => _todos.add(await db.from('todos').order('created_at'));
Future<void> _add(String title) async {
_input.clear();
await db.from('todos').insert({'title': title});
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Todos'),
actions: [IconButton(icon: const Icon(Icons.logout), onPressed: () => db.signOut())],
),
body: Column(children: [
Padding(
padding: const EdgeInsets.all(12),
child: TextField(
controller: _input,
decoration: const InputDecoration(hintText: 'What needs doing?'),
onSubmitted: _add,
),
),
Expanded(
child: StreamBuilder<List<Map<String, dynamic>>>(
stream: _todos.stream,
builder: (context, snapshot) {
if (snapshot.hasError) return Center(child: Text('${snapshot.error}'));
if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
return ListView(children: [
for (final todo in snapshot.data!)
CheckboxListTile(
title: Text(todo['title'] as String),
value: todo['done'] as bool,
onChanged: (done) async {
await db.from('todos').eq('id', todo['id']).update({'done': done});
},
),
]);
},
),
),
]),
);
@override
void dispose() {
_changes.cancel();
_live.unsubscribe();
_todos.close();
_input.dispose();
super.dispose();
}
}
5. Run it — on a phone, a desktop or the web:
flutter run --dart-define=PLEXIVO_URL=https://api.plexivo.io/client/v1/data-… --dart-define=PLEXIVO_PUBLISHABLE_KEY=plx_publishable_…
Open it on two devices: a todo added on one appears on the other. Each user sees only their own rows, because the policy says so. For Flutter web, add your site's origin to the Data API's allowed origins on the Connect tab. A fuller app — email sign-in, todos and a chat with a typing indicator — is in example/flutter_app.
Connect #
final db = PlexivoClient('https://api.plexivo.io/client/v1/data-a1b2c3d4e5f6', 'plx_publishable_…');
Keep one client for the life of your app. It holds the signed-in session, sends its access token with every request, refreshes it when it expires, and retries the request once.
- The publishable key belongs in your app. It can do only what your policies allow.
- The secret key belongs on a server. It bypasses row-level security and runs raw SQL. A web build refuses it outright (
secret_key_in_browser), and so does the Data API when a browser sends it. - Pass values with
--dart-definerather than in source, as in the quick start.
The examples below use a small blog — profiles, posts, comments, tags and post_tags, plus a shop's products — whose SQL is in example/blog.sql.
Authentication #
Your app's own users. Policies see the signed-in user as auth.uid().
// Sign up, with profile data kept on the user as user_metadata
await db.signUp(
email: 'ada@example.com',
password: 'correct horse battery',
data: {'name': 'Ada', 'avatar_url': 'https://example.com/ada.png'},
);
print(db.currentUser?['user_metadata']); // {name: Ada, avatar_url: …}
// Change the profile data: keys are merged, null removes one
await db.updateUser(data: {'name': 'Ada Lovelace', 'avatar_url': null});
// Sign out, and back in
await db.signOut();
await db.signInWithPassword(email: 'ada@example.com', password: 'correct horse battery');
print((await db.getUser())['email']);
Auth state as a stream. Every change is an event, ready for a StreamBuilder (as in the quick start) or your router:
final events = db.authStateChanges.listen((state) {
// SIGNED_UP, SIGNED_IN, TOKEN_REFRESHED, USER_UPDATED, PASSWORD_CHANGED, USER_DELETED, SIGNED_OUT
print('${state.event}: ${state.session?['user']?['email']}');
});
await db.refreshSession();
await events.cancel();
Stay signed in across launches. Save the session from each event in encrypted storage (for example flutter_secure_storage), and hand it back when the app starts:
final saved = db.session; // what you stored
final restored = PlexivoClient('https://api.plexivo.io/client/v1/data-a1b2c3d4e5f6', 'plx_publishable_…', initialSession: saved);
print(restored.currentUser?['email']);
Guests start at once and become full accounts later, keeping their id and every row:
final guest = PlexivoClient('https://api.plexivo.io/client/v1/data-a1b2c3d4e5f6', 'plx_publishable_…');
await guest.signInAnonymously();
await guest.from('todos').insert({'title': 'Saved before signing up'});
await guest.linkEmail(email: 'grace@example.com', password: 'correct horse battery');
print(guest.currentUser?['is_anonymous']); // false
Devices. Every sign-in is a session; list them and sign one out, or all:
final sessions = await db.listSessions(); // each with id, current, created_at …
for (final s in sessions.where((s) => s['current'] != true)) {
await db.revokeSession(s['id'] as String);
}
await db.signOut(allSessions: true); // every device
One-time codes and password reset arrive by email:
await db.signInWithOtp('ada@example.com'); // emails a sign-in code
await db.resetPasswordForEmail('ada@example.com'); // emails a reset code
await db.verifyOtp(email: 'ada@example.com', token: codeFromEmail);
await db.verifyPasswordRecovery(email: 'ada@example.com', code: codeFromEmail, newPassword: 'a new long password');
Google, GitHub and Microsoft (OAuth with PKCE): open the URL, then exchange the code your redirect receives.
final url = db.getOAuthSignInUrl(provider: 'github', redirectTo: 'myapp://auth-callback');
print(url.queryParameters['code_challenge_method']); // S256
// launchUrl(url) with url_launcher; keep db.oauthCodeVerifier if the app may restart meanwhile
await db.exchangeCodeForSession(codeFromRedirect, codeVerifier: savedVerifier);
Two-factor authentication (TOTP), organisations with roles and invitations, and account deletion are built in too: db.mfa.enroll(), db.orgs.create(name: …), db.orgs.invite(…), db.deleteUser(password: …).
Reading and writing #
Awaiting a query runs it. A read returns a PlexivoResult: a List<Map<String, dynamic>> that also carries count.
// Create: one row, or many — returned as stored, with defaults and keys
final post = await db.from('posts').create({'title': 'Hello, Postgres', 'status': 'published'});
await db.from('posts').insert([
{'title': 'Second post', 'tags': ['dart', 'flutter']},
{'title': 'Third post', 'meta': {'lang': 'en'}},
]);
// Read: columns, filters, order, pages
final latest = await db.from('posts')
.select('id, title, likes')
.eq('status', 'published')
.order('created_at', 'desc')
.limit(20);
print(latest.first['title']);
final one = await db.from('posts').first(post['id']); // or RecordNotFoundException
final maybe = await db.from('posts').firstOrNull(-1); // null
final page = await db.from('posts').paginate(page: 1, perPage: 10);
print('${page.total} posts, ${page.totalPages} pages, ${one['title']}, $maybe');
// Update and delete always say which rows
await db.from('posts').eq('id', post['id']).update({'body': 'Now with a body'});
await db.from('posts').where('id', post['id']).increment('likes');
await db.from('posts').eq('title', 'Third post').delete();
Both dialects work on the same builder, so mix them freely:
| Supabase-style | GORM-style |
|---|---|
.select('id, title', 'exact') |
.select(['id', 'title']) |
.eq('status', 'draft') |
.where('status', 'draft') |
.gt('likes', 10) |
.where('likes', '>', 10) |
.order('likes', 'desc') |
.order('likes desc'), .latest() |
.range(0, 9) |
.limit(10).offset(0), .page(1, 10) |
.single() / .maybeSingle() |
.first() / .firstOrNull() / .sole() |
.insert(row) |
.create(row), .createMany(rows), .save(row) |
More reads: find([ids]), last(), take(), pluck('title'), exists(), count(), findInBatches(500, …) and await for (final row in query.each()) for every row, a thousand at a time. An update or delete without a filter is refused (missing_where); allowGlobalUpdate() opts in.
Filters #
final posts = db.from('posts');
await posts.eq('status', 'published').neq('likes', 0).gte('likes', 5).lt('likes', 100);
await posts.like('title', 'Post%').ilike('body', '%postgres%');
await posts.inFilter('status', ['draft', 'archived']).isFilter('meta', null);
await posts.contains('tags', ['dart']).overlaps('tags', ['dart', 'go']);
await posts.contains('meta', {'lang': 'en'}); // jsonb @>
await posts.textSearch('search', 'postgres -mysql', type: 'websearch');
// OR, AND and NOT, as PostgREST strings …
await posts.or('likes.gte.10,and(status.eq.draft,title.ilike.*todo*)');
await posts.not('status', 'eq', 'archived');
// … or GORM-style: AND binds tighter than OR, closures make groups
await posts
.where('status', 'published')
.where((PlexivoConditions q) => q.where('likes', '>', 10).orWhere('tags', 'contains', ['featured']))
.whereNot('title', 'ilike', '%draft%')
.whereBetween('likes', 1, 1000)
.whereJson('meta', 'lang', 'en'); // a value inside jsonb
| Operator | Supabase-style | GORM-style where(column, op, value) |
|---|---|---|
| equals, not equals | eq, neq |
=, != (<>) |
| compare | gt, gte, lt, lte |
>, >=, <, <= |
| pattern | like, ilike |
like, ilike, not like, not ilike |
| regular expression | filter(col, 'match', re) |
~ (match), ~* (imatch) |
| list | inFilter |
in, not in, whereIn, whereNotIn |
| null, true, false | isFilter |
is, is not, whereNull, whereNotNull |
| arrays, ranges, jsonb | contains, containedBy, overlaps |
contains (@>), contained by (<@), overlaps (&&) |
| full-text | textSearch(col, q, type: 'plain' / 'phrase' / 'websearch') |
fts, plfts, phfts, wfts, whereSearch |
| negation, groups | not, or('a.eq.1,b.gt.2') |
whereNot, orWhere, closures |
Filter values are always sent as data, never as SQL. DateTime values are sent as UTC ISO 8601.
Order and pages: order('likes', 'desc'), order('published_at', 'desc', 'last') (nulls last), several order calls for tie-breakers, limit, offset, range(from, to), page(n, size) and paginate(page:, perPage:). Ask for the total with select('*', 'exact') and read result.count; select('*', 'exact', true) returns only the count.
Joins and related rows #
Plexivo Postgres follows your foreign keys, so related rows come back in the same request — as Supabase select strings, or as GORM models with named relations.
Supabase-style select strings:
// Many-to-one and one-to-many, renamed, nested three deep
final feed = await db.from('posts').select('''
id, title,
author:profiles(username, country),
comments(body, author:profiles(username)),
post_tags(tags(name))
''').eq('status', 'published');
print(feed.first['author']['username']);
// Inner join: only posts that have at least one comment
await db.from('posts').select('id, title, comments!inner(id)');
// Count related rows, and order an embed's rows
await db.from('posts').select('id, comments(count)');
await db.from('posts').select('id, comments(id, body)').orderReferenced('comments', 'created_at', 'desc');
When two foreign keys link the same tables, name the one to follow: profiles!posts_author_id_fkey(username).
GORM-style models name each relation once; every query then understands it:
db.model('posts', relations: {
'author': const PlexivoRelation.belongsTo('profiles', foreignKey: 'author_id'),
'comments': const PlexivoRelation.hasMany('comments', foreignKey: 'post_id'),
'tags': const PlexivoRelation.manyToMany('tags', through: 'post_tags', foreignKey: 'post_id', otherKey: 'tag_id'),
});
db.model('comments', relations: {
'author': const PlexivoRelation.belongsTo('profiles', foreignKey: 'author_id'),
});
final posts = await db.from('posts')
.preload('author', (PlexivoEmbed a) => a.select('username')) // LEFT JOIN, one map
.preload('comments', (PlexivoEmbed c) => c.where('approved', true).order('created_at', 'desc').limit(3))
.preload('comments.author') // a path: Preload("Comments.Author")
.preload('tags') // many-to-many, a list
.withCount('comments') // comments_count
.order('author.username') // order by a related column
.limit(20);
print(posts.first['tags']);
// Only posts with a matching related row: INNER JOIN, whereHas, whereDoesntHave
await db.from('posts').joins('comments', (PlexivoEmbed c) => c.where('approved', true));
await db.from('posts').whereHas('tags', (PlexivoEmbed t) => t.where('name', 'dart'));
await db.from('posts').whereDoesntHave('comments');
// A subquery: GORM's Where("author_id IN (?)", subquery)
final fromIndia = db.from('profiles').select('id').eq('country', 'IN');
await db.from('posts').whereIn('author_id', fromIndia);
await db.from('posts').whereNotIn('author_id', fromIndia);
Every related row is read as the signed-in user, so each table's policies apply at every level — a subquery, a join or an embed never shows a row the user may not read. Ordering by a related column (order('profiles.username'), or a model relation name) works for to-one relations; use orderReferenced or the embed's own order for to-many rows. Related rows nest up to four levels deep.
Any join you can write in SQL: put it in a view with security_invoker, and read the view like a table — the policies of every table in it still apply:
// CREATE VIEW post_feed WITH (security_invoker = true) AS SELECT p.id, p.title, pr.username AS author, … FROM posts p JOIN profiles pr …
final rows = await db.from('post_feed').select('id, title, author, comments').order('comments', 'desc').limit(10);
print(rows.length);
Aggregates #
final posts = db.from('posts').eq('status', 'published');
print(await posts.count());
print(await posts.sum('likes'));
print(await posts.avg('likes'));
print(await posts.max('created_at'));
// GROUP BY with HAVING and ORDER BY an aggregate
final perStatus = await db.from('posts')
.groupBy('status')
.having('count', '>', 0)
.order('count(*)', 'desc')
.aggregate({'count': true, 'sum': ['likes'], 'max': ['likes']});
print(perStatus);
// Aggregates of related rows, per row
await db.from('posts').withAggregate('comments', {'count': true, 'max': ['created_at']});
Upsert and bulk writes #
// Insert, or update the row with the same unique key — here a composite one
await db.from('products').upsert(
{'sku': 'KETTLE', 'region': 'IN', 'name': 'Kettle', 'price': 1499},
onConflict: 'owner_id,sku,region',
);
// Only overwrite chosen columns; or keep the existing row
await db.from('products').upsert(
{'sku': 'KETTLE', 'region': 'IN', 'name': 'Ignored', 'price': 1299},
onConflict: 'owner_id,sku,region',
update: ['price'],
);
await db.from('products').upsert(
{'sku': 'KETTLE', 'region': 'IN', 'name': 'Ignored', 'price': 1},
onConflict: 'owner_id,sku,region',
ignore: true,
);
// Thousands of rows: up to 1,000 per request, in batches
final rows = [for (var i = 0; i < 2500; i++) {'sku': 'SKU-$i', 'region': 'IN', 'name': 'Item $i'}];
await db.from('products').createInBatches(rows, 1000);
// Bulk update and delete by filter; returning('minimal') skips sending rows back
final changed = await db.from('products').like('sku', 'SKU-%').returning('minimal').update({'stock': 10});
print(changed.count); // 2500
await db.from('products').like('sku', 'SKU-%').delete();
Transactions and functions #
Transactions run several operations in one request: all commit, or none. Record them on tx without awaiting, and pass a result to a later step with .ref():
final results = await db.transaction((tx) {
final post = tx.from('posts').insert({'title': 'Launch day', 'status': 'published'});
tx.from('comments').insert({'post_id': post.ref('id'), 'body': 'First!'});
tx.from('posts').where('title', 'Launch day').lockForUpdate().find(); // SELECT … FOR UPDATE
});
print(results.length); // 3
try {
await db.transaction((tx) {
tx.from('posts').insert({'title': 'Never saved'});
tx.from('comments').insert({'post_id': -1, 'body': 'No such post'});
});
} on PlexivoException catch (e) {
print('rolled back at step ${e.operation}: ${e.code}');
}
Database functions (exposed with COMMENT ON FUNCTION … IS '@expose') run as the signed-in user. Await a call for its result, or — for a function that returns rows — chain filters, order, paging and related rows, as on a table:
final likes = await db.rpc('like_post', {'post': (await db.from('posts').eq('status', 'published').first())['id']});
print(likes); // a number
final hits = await db.rpc('search_posts', {'q': 'postgres'})
.select('id, title, author:profiles(username)', 'exact')
.gte('likes', 0)
.order('likes', 'desc')
.range(0, 9);
print('${hits.length} of ${hits.count}');
final top = await db.rpc('posts_per_author').order('likes', 'desc').limit(1).maybeSingle();
print(top.data?['author']);
Raw SQL on a server #
On a server, a script or in Plexivo Functions, the secret key runs SQL with $1, $2 … parameters. It bypasses row-level security, so it never goes in an app.
import 'dart:io';
final server = PlexivoClient(
'https://api.plexivo.io/client/v1/data-a1b2c3d4e5f6',
Platform.environment['PLEXIVO_SECRET_KEY']!,
);
// Rows, with parameters: values never go into the SQL text
final top = await server.raw(r'''
select pr.username, count(*) as posts, sum(p.likes) as likes
from posts p join profiles pr on pr.id = p.author_id
where p.created_at > $1
group by pr.username order by likes desc limit $2
''', [DateTime.now().subtract(const Duration(days: 30)), 10]);
print(top);
// A statement's row count
final archived = await server.exec(r"update posts set status = 'archived' where created_at < $1 and status = 'draft'", [DateTime.utc(2020)]);
print(archived.rowCount);
// Several statements in one transaction: all commit, or none
await server.sql.transaction([
'create table if not exists audit_log (id bigserial primary key, what text, at timestamptz default now())',
{'sql': r'insert into audit_log (what) values ($1)', 'params': ['nightly clean-up']},
]);
Raw SQL goes through the connection pooler, so write it pooler-safe: pass values as parameters, keep each call self-contained (no SET, PREPARE, temporary tables or advisory locks carried between calls), and put statements that belong together in one sql.transaction. The publishable key and signed-in users get secret_key_required; a web build refuses the secret key before sending anything. Migrations come built in: server.migrate([...]), server.rollback(...) and server.migrator.autoMigrate([models]).
Realtime #
Row changes arrive as a Stream, each one only for subscribers whose policies let them read the row. Switch a table on with the plexivo_realtime trigger (as in the quick start) or the console's Realtime tab.
final feed = db.channel('changes:posts', 'status=eq.published')..subscribe();
feed.changes.listen((PlexivoChange change) {
print('${change.type} ${change.record ?? change.old}'); // insert | update | delete
});
await feed.ready();
final next = feed.changes.first;
await db.from('posts').insert({'title': 'Live!', 'status': 'published'});
await next.timeout(const Duration(seconds: 10));
await feed.unsubscribe();
Rooms carry broadcast messages and presence — who is here — without touching a table:
final room = db.channel('room:lobby', null, {'name': 'Ada'})..subscribe();
room.presence.listen((p) => print('${p.event}: ${p.state.keys.length} online'));
room.on('cursor').listen((payload) => print('cursor at ${payload['x']}'));
await room.ready();
final friend = other.channel('room:lobby', null, {'name': 'Grace'})..subscribe();
await friend.ready();
final heard = room.on('cursor').first;
friend.sendBroadcast('cursor', {'x': 10, 'y': 20});
await heard.timeout(const Duration(seconds: 10));
await friend.unsubscribe();
await room.unsubscribe();
Always connected. A channel reconnects by itself after a dropped connection, renews the user's access token before it expires, and rejoins after the server ends it — then changes flow again. A join the server refuses (table_not_exposed, sign_in_required) is reported on errors and ready(), and not retried. Show the connection in your UI with status and statusChanges:
final channel = db.channel('changes:comments')..subscribe();
channel.statusChanges.listen((s) => print(s)); // connecting, joined, reconnecting, refused, closed
channel.errors.listen((reason) => print('realtime: $reason'));
await channel.ready();
channel.reconnect(); // e.g. when the device changes network
await channel.statusChanges.firstWhere((s) => s == PlexivoChannelStatus.joined);
await channel.unsubscribe();
In Flutter, turn changes into widget state with a StreamBuilder, as TodoPage does in the quick start: listen to changes first, then load the rows once ready() completes, and no change is ever missed. room:private:<name> rooms are for signed-in users only.
GraphQL #
A GraphQL API generated from your schema, exactly as wide as your policies — with live queries that answer again whenever a row they read changes.
final result = await db.graphql(
r'query Top($n: Int) { posts(where: {likes: {gte: 0}}, orderBy: [{likes: DESC}], limit: $n) { id title likes } }',
variables: {'n': 5},
);
print(result['data']);
final stop = await db.graphqlSubscribe(
'subscription { postsAggregate { count } }',
(answer) => print(answer['data']),
);
await stop();
persisted: true sends only the query's hash after the first call. Plexivo Functions, your server code beside your data, are one call away (db.functions.invoke('send-receipt', body: {...})), and so are files (db.storage.upload(...), download, createSignedDownloadUrl).
Row-level security recipes #
Policies are plain SQL, and they decide every read and write — through the Data API, joins, functions, realtime and GraphQL alike. A table reaches apps only with row-level security on and at least one policy. Inside a policy: auth.uid(), auth.role() (anon or authenticated), auth.jwt(), auth.email(), auth.is_anonymous(), and for organisations auth.is_org_member(org) and auth.has_org_role(org, 'admin').
Owner only — each user sees and changes their own rows:
DROP POLICY IF EXISTS own_todos ON todos;
CREATE POLICY own_todos ON todos FOR ALL TO authenticated
USING (owner_id = auth.uid()) WITH CHECK (owner_id = auth.uid());
Public read, owner write — published posts for everyone, drafts for their author:
DROP POLICY IF EXISTS posts_read ON posts;
CREATE POLICY posts_read ON posts FOR SELECT TO anon, authenticated
USING (status = 'published' OR author_id = auth.uid());
Teams — members of an organisation share its rows; admins delete them:
CREATE TABLE IF NOT EXISTS team_docs (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
org_id uuid NOT NULL,
title text NOT NULL
);
ALTER TABLE team_docs ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS team_read_write ON team_docs;
CREATE POLICY team_read_write ON team_docs FOR SELECT TO authenticated USING (auth.is_org_member(org_id));
DROP POLICY IF EXISTS team_insert ON team_docs;
CREATE POLICY team_insert ON team_docs FOR INSERT TO authenticated WITH CHECK (auth.is_org_member(org_id));
DROP POLICY IF EXISTS team_admin_delete ON team_docs;
CREATE POLICY team_admin_delete ON team_docs FOR DELETE TO authenticated USING (auth.has_org_role(org_id, 'admin'));
GRANT SELECT, INSERT, DELETE ON team_docs TO authenticated;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO authenticated;
final team = await db.orgs.create(name: 'Design team');
await db.from('team_docs').insert({'org_id': team['id'], 'title': 'Brand guide'});
print((await db.from('team_docs').select()).length); // 1
print((await outsider.from('team_docs').select()).length); // 0: not a member
Signed-in users only, guests read-only: USING (auth.role() = 'authenticated' AND NOT auth.is_anonymous()). A column a user may not change: keep it out of GRANT UPDATE (col1, col2) ON t TO authenticated.
Types #
| PostgreSQL | Dart, reading | Dart, writing |
|---|---|---|
text, varchar, uuid, enum |
String |
String |
integer, bigint |
int (64-bit, exact) |
int |
numeric |
num — select price::text for every digit |
num, or a String for exact digits |
real, double precision |
double |
double |
boolean |
bool |
bool |
json, jsonb |
Map / List |
Map / List |
text[], integer[] |
List |
List |
timestamptz, date |
ISO 8601 String — DateTime.parse it |
DateTime (sent as UTC) or String |
final row = await db.from('posts').create({
'title': 'Typed',
'tags': ['dart', 'postgres'],
'meta': {'lang': 'en', 'reading': {'minutes': 4}},
});
final back = await db.from('posts').select('id, likes::text, tags, meta, created_at').eq('id', row['id']).single();
final created = DateTime.parse(back.data!['created_at'] as String).toLocal();
print('${back.data!['tags']} ${back.data!['meta']['reading']['minutes']} min, $created');
Errors #
Every failure is a PlexivoException with statusCode, a stable code, a readable message, and — when the database had more to say — hint, sqlstate and details, plus a traceId to quote to support. RecordNotFoundException is the subtype for lookups that must find a row.
try {
await db.from('tags').insert({'name': 'dart'});
await db.from('tags').insert({'name': 'dart'});
} on PlexivoException catch (e) {
if (e.isUniqueViolation) print('That tag exists already.'); // code unique_violation, sqlstate 23505
print('${e.statusCode} ${e.code} ${e.sqlstate} ${e.traceId}');
}
try {
await db.from('posts').first(-1);
} on RecordNotFoundException {
print('No such post.');
}
| Code | Status | When |
|---|---|---|
invalid_request |
400 | A malformed query: unknown column, bad operator, too many filters or rows |
invalid_credentials, weak_password, metadata_too_large |
400–422 | Sign-in and sign-up |
invalid_api_key, invalid_access_token, token_expired |
401 | Keys and tokens (an expired token is refreshed for you) |
permission_denied |
403 | Row-level security or grants refused the write |
origin_denied, secret_key_in_browser, secret_key_required |
403 | A web origin not allowed; the secret key from a browser; raw SQL without it |
table_not_exposed, function_not_exposed |
404 | No row-level security, no policy, or no @expose |
record_not_found, multiple_rows |
404, 406 | first(), single() and friends |
unique_violation, foreign_key_violation |
409 | Constraints, with sqlstate |
check_violation, not_null_violation, invalid_value |
400 | Constraints and values, with sqlstate |
missing_where, transaction_already_sent |
400 | Refused by the SDK before sending |
too_large |
413 | A request body over the limit |
rate_limited |
429 | Slow down; wait for its retry_after |
sign_in_required |
403 | A realtime room or channel for signed-in users |
Coming from Firebase #
| Firebase (FlutterFire) | plexivo_client |
|---|---|
FirebaseAuth.instance.createUserWithEmailAndPassword |
db.signUp(email:, password:, data:) |
signInWithEmailAndPassword, signOut() |
db.signInWithPassword(…), db.signOut() |
authStateChanges(), currentUser |
db.authStateChanges, db.currentUser |
user.updateDisplayName(…) |
db.updateUser(data: {'name': …}) |
signInAnonymously(), linkWithCredential |
db.signInAnonymously(), db.linkEmail(…) |
GoogleAuthProvider, GithubAuthProvider |
db.getOAuthSignInUrl(provider:) + exchangeCodeForSession |
| Firestore collection, document | a table, a row |
collection('posts').add(data) |
db.from('posts').create(data) |
doc(id).set(data) / update(data) / delete() |
.upsert(data) / .eq('id', id).update(data) / .eq('id', id).delete() |
doc(id).get() |
db.from('posts').first(id) |
where('likes', isGreaterThan: 10).orderBy('likes').limit(20) |
.where('likes', '>', 10).order('likes').limit(20) |
startAfterDocument |
.paginate(page:, perPage:) or .range(from, to) |
count(), sum(), average() |
.count(), .sum(), .avg(), .aggregate() with groupBy |
| subcollections, denormalised copies | foreign keys and joins: .preload('comments'), select('*, comments(*)') |
snapshots() with a StreamBuilder |
db.channel('changes:posts').changes with a StreamBuilder |
runTransaction, WriteBatch |
db.transaction((tx) { … }) |
| Security Rules | row-level security policies in SQL |
Cloud Functions, httpsCallable |
database functions (db.rpc) and Plexivo Functions (db.functions.invoke) |
| Cloud Storage | db.storage.upload, download, createSignedDownloadUrl |
// Firestore: posts.where('status', isEqualTo: 'published').orderBy('likes', descending: true).limit(10).snapshots()
final channel = db.channel('changes:posts', 'status=eq.published')..subscribe();
Stream<List<Map<String, dynamic>>> topPosts() {
final query = db.from('posts').eq('status', 'published').order('likes', 'desc').limit(10);
final out = StreamController<List<Map<String, dynamic>>>();
final changes = channel.changes.listen((_) async => out.add(await query));
channel.ready().then((_) async => out.add(await query));
out.onCancel = changes.cancel;
return out.stream;
}
print((await topPosts().first).length);
await channel.unsubscribe();
Along the way you gain SQL joins, constraints and transactions, aggregates on the server, GraphQL, and your data in standard PostgreSQL.
Coming from Supabase #
The query builder speaks Supabase's names, so most code moves over by changing the client:
| supabase_flutter | plexivo_client |
|---|---|
Supabase.initialize(url:, anonKey:), Supabase.instance.client |
PlexivoClient(url, publishableKey) |
auth.signUp(email:, password:, data:) |
signUp(email:, password:, data:) |
auth.signInWithPassword, signInAnonymously, signInWithOtp, verifyOTP |
signInWithPassword, signInAnonymously, signInWithOtp, verifyOtp |
auth.signInWithOAuth(OAuthProvider.github) |
getOAuthSignInUrl(provider: 'github', …) + exchangeCodeForSession |
auth.updateUser(UserAttributes(data: …)) |
updateUser(data: …) |
auth.onAuthStateChange, auth.currentUser, auth.currentSession |
authStateChanges, currentUser, session |
from('t').select('*, author:profiles(*)') |
the same |
.eq .neq .gt .gte .lt .lte .like .ilike .contains .containedBy .overlaps .textSearch .match .not .or .filter |
the same |
.inFilter, .isFilter |
the same |
.order('c', ascending: false) |
.order('c', 'desc') (or false) |
.order('c', referencedTable: 'comments') |
.orderReferenced('comments', 'c') |
.limit(n, referencedTable: …) |
.preload('comments', (PlexivoEmbed c) => c.limit(n)) |
.range, .single, .maybeSingle, count: CountOption.exact |
.range, .single, .maybeSingle, select(cols, 'exact') |
.insert / .update / .upsert(onConflict:, ignoreDuplicates:) / .delete |
the same, upsert(…, onConflict:, ignore:) |
rpc('fn', params: {...}).eq(...).order(...) |
rpc('fn', {...}).eq(...).order(...) |
channel('x').onPostgresChanges(...) |
channel('changes:table', 'col=eq.value').changes |
channel('room').onBroadcast / onPresenceSync / track |
channel('room:name', null, presence) with on(event), presence, sendBroadcast |
functions.invoke, storage.from(bucket) |
functions.invoke, storage |
And beyond it: GORM-style models with preload paths, joins, whereHas, withCount, scopes, hooks and soft deletes; subqueries; ordering by related columns; multi-step transactions with references; grouped aggregates; and live GraphQL queries.
Examples #
example/flutter_app— a Flutter app: email sign-in, todos kept in sync across devices, and a realtime chat with a typing indicator.example/main.dart— auth, todos, realtime and a live GraphQL query from the command line:PLEXIVO_URL=… PLEXIVO_PUBLISHABLE_KEY=… dart run example/main.dart.example/schema.sql(the todos and chat tables, applied withexample/setup.dart) andexample/blog.sql(the blog these docs use).
Every code block in this README runs against a live Plexivo Postgres before each release (dart run tool/docs.dart), the quick start included, as a Flutter widget test and a web build.
License #
Apache-2.0. See LICENSE.