PostgreSQL

suggest change

The Relational databases article shows the basics of package:postgres: opening a connection, Sql.named parameters, runTx and ServerException. This article goes further: connection settings and URLs, how parameters and types really work, how PostgreSQL types map to Dart values, RETURNING and upserts, prepared statements, streaming large results, transactions with savepoints and serializable retries, jsonb, LISTEN/NOTIFY, timeouts and error handling.

Connection pools have their own article: Database connection pooling covers Pool from package:postgres in depth (sizing, connectTimeout, session state leaks, broken connections), so this article only touches on it at the end.

package:postgres is a pure Dart, async driver that speaks the PostgreSQL wire protocol. It runs on the Dart VM (servers, CLI tools). A Flutter app should not connect to a database directly; put an HTTP API in between (see REST APIs).

Setup

dependencies:
  postgres: ^3.5.20

For a local server, Docker is the quickest option:

docker run -d --name pg -p 5432:5432 \
  -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=app \
  postgres:18

The examples were run with postgres 3.5.20 against PostgreSQL 18.6. They live in a Dart package named pgdemo, with shared code in lib/ and the programs in bin/.

Connecting

Connection.open takes an Endpoint (where to connect) and optional ConnectionSettings (how). Reading the endpoint from the standard PG* environment variables keeps passwords out of the code. Put this in lib/db.dart; the other examples import it:

import 'dart:io';

import 'package:postgres/postgres.dart';

Endpoint endpointFromEnv() {
  final env = Platform.environment;
  return Endpoint(
    host: env['PGHOST'] ?? 'localhost',
    port: int.parse(env['PGPORT'] ?? '5432'),
    database: env['PGDATABASE'] ?? 'app',
    username: env['PGUSER'] ?? 'postgres',
    password: env['PGPASSWORD'] ?? 'secret',
  );
}

Future<Connection> openConnection() => Connection.open(
      endpointFromEnv(),
      settings: ConnectionSettings(
        // Local server without TLS. Use SslMode.verifyFull in production.
        sslMode: SslMode.disable,
        applicationName: 'pgdemo',
        connectTimeout: Duration(seconds: 5),
        queryTimeout: Duration(seconds: 30),
      ),
    );
import 'package:pgdemo/db.dart';

Future<void> main() async {
  final conn = await openConnection();
  try {
    final p = conn.info.parameters;
    print('server ${p.serverVersion}, encoding ${p.serverEncoding}, '
        'time zone ${p.timeZone}');

    final res = await conn.execute(
      'SELECT current_database(), current_user, pg_backend_pid()',
    );
    final [db, user, pid] = res.first;
    print('database $db as $user, backend pid is an ${pid.runtimeType}');
    print('open: ${conn.isOpen}');
  } finally {
    await conn.close();
  }
  print('open after close: ${conn.isOpen}');
}

Output:

server 18.6, encoding UTF8, time zone UTC
database app as postgres, backend pid is an int
open: true
open after close: false

conn.info.parameters holds the values the server reports when you connect (and whenever they change): server_version, TimeZone, client_encoding and so on. isOpen turns false after close(), and also when the server or the network drops the connection.

The most useful ConnectionSettings:

Connection URLs

Hosting providers usually hand out a URL. Connection.openFromUrl parses it, including query options such as sslmode, application_name, connect_timeout and query_timeout:

import 'dart:io';

import 'package:postgres/postgres.dart';

Future<void> main() async {
  final url = Platform.environment['DATABASE_URL'] ??
      'postgresql://postgres:secret@localhost:5432/app?sslmode=disable';
  final conn = await Connection.openFromUrl(url);
  final res = await conn.execute('SHOW application_name');
  print('connected, application_name="${res.first[0]}"');
  await conn.close();

  try {
    await Connection.openFromUrl(
        url.replaceFirst(':secret@', ':wrong@'));
  } on ServerException catch (e) {
    print('${e.code}: ${e.message}');
  }
}

Output when run with DATABASE_URL=postgresql://postgres:secret@localhost:5432/app?sslmode=disable&application_name=reports:

connected, application_name="reports"
28P01: password authentication failed for user "postgres"

28P01 is the SQLSTATE code for invalid_password. Errors are covered in more detail at the end.

Parameters

Never build SQL with string interpolation. Pass values as parameters: they travel to the server separately from the SQL text, so a value can't change the meaning of the statement.

The driver supports two placeholder styles. A plain string uses PostgreSQL's own $1, $2 positional placeholders with a List. Sql.named lets you write @name placeholders with a Map and translates them to $n before sending:

import 'package:pgdemo/db.dart';
import 'package:postgres/postgres.dart';

Future<void> main() async {
  final conn = await openConnection();
  try {
    // Positional: $1, $2, ... with a List. Use a raw string (r'...').
    var res = await conn.execute(r'SELECT $1::int + $2', parameters: [40, 2]);
    print('positional: ${res.first.first}');

    // Named: @name with a Map. Sql.named does the translation to $n.
    res = await conn.execute(
      Sql.named('SELECT @greeting || \', \' || @who'),
      parameters: {'greeting': 'Hello', 'who': 'Postgres'},
    );
    print('named: ${res.first.first}');

    // Without context the server can't infer a type...
    try {
      await conn.execute(Sql.named('SELECT @a * @b'), parameters: {'a': 6, 'b': 7});
    } on ServerException catch (e) {
      print('untyped: ${e.code} ${e.message}');
    }
    // ...so give one: either a driver type annotation or an SQL cast.
    res = await conn.execute(
      Sql.named('SELECT @a:int4 * @b::int'),
      parameters: {'a': 6, 'b': 7},
    );
    print('typed: ${res.first.first}');

    // The same value can also carry its type explicitly.
    res = await conn.execute(
      r'SELECT $1 ->> $2',
      parameters: [TypedValue(Type.jsonb, {'lang': 'dart'}), 'lang'],
    );
    print('TypedValue: ${res.first.first}');

    // Arrays replace IN (...) lists.
    res = await conn.execute(
      Sql.named('SELECT count(*) FROM generate_series(1, 10) g WHERE g = ANY(@ids:_int4)'),
      parameters: {'ids': [2, 3, 11]},
    );
    print('ANY: ${res.first.first}');

    // :: casts, quoted strings and e-mail addresses are left alone.
    res = await conn.execute(
      Sql.named("SELECT '5'::int + @n, 'me@example.com'"),
      parameters: {'n': 1},
    );
    print('literals: ${res.first.toList()}');

    // Missing or extra parameters are caught before anything is sent.
    try {
      await conn.execute(Sql.named('SELECT @a::int'), parameters: {'a': 1, 'b': 2});
    } on ArgumentError catch (e) {
      print('extra: ${e.message}');
    }
  } finally {
    await conn.close();
  }
}

Output:

positional: 42
named: Hello, Postgres
untyped: 42725 operator is not unique: unknown * unknown
typed: 42
TypedValue: dart
ANY: 2
literals: [6, me@example.com]
extra: Contains superfluous variables: b

How it works:

Several statements in one call

By default execute uses the extended query protocol (parse, bind, execute), which allows only one statement per call. 'CREATE TABLE a (...); CREATE TABLE b (...)' fails with 42601 cannot insert multiple commands into a prepared statement. For schema scripts, pass queryMode: QueryMode.simple. The simple protocol accepts several statements but no parameters, so use it only for fixed SQL. The schema used by the rest of the article, in lib/schema.dart:

import 'package:postgres/postgres.dart';

Future<void> createSchema(Session db) async {
  await db.execute(
    '''
    DROP TABLE IF EXISTS order_items, orders, products;

    CREATE TABLE products (
      id         integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      sku        text NOT NULL UNIQUE,
      name       text NOT NULL,
      price      numeric(10,2) NOT NULL CHECK (price >= 0),
      stock      integer NOT NULL DEFAULT 0 CHECK (stock >= 0),
      tags       text[] NOT NULL DEFAULT '{}',
      updated_at timestamptz NOT NULL DEFAULT now()
    );

    CREATE TABLE orders (
      id         integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      customer   text NOT NULL,
      created_at timestamptz NOT NULL DEFAULT now()
    );

    CREATE TABLE order_items (
      order_id   integer NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
      product_id integer NOT NULL REFERENCES products(id),
      qty        integer NOT NULL CHECK (qty > 0),
      PRIMARY KEY (order_id, product_id)
    );
    ''',
    queryMode: QueryMode.simple,
  );
}

In version 3.5.20, running several SELECTs in one simple-mode call breaks the connection (Bad state: Future already completed), so keep simple mode for DDL and other statements that don't return rows.

How PostgreSQL types map to Dart

Values are decoded into Dart types based on the column type, so there's no string parsing for most columns. This program inserts one row with many column types and prints what comes back:

import 'dart:typed_data';

import 'package:pgdemo/db.dart';
import 'package:postgres/postgres.dart';

Future<void> main() async {
  final conn = await openConnection();
  try {
    await conn.execute('DROP TABLE IF EXISTS samples');
    await conn.execute('''
      CREATE TABLE samples (
        id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
        uid        uuid NOT NULL DEFAULT gen_random_uuid(),
        name       text NOT NULL,
        price      numeric(10,2) NOT NULL,
        ratio      double precision,
        active     boolean NOT NULL,
        tags       text[] NOT NULL,
        scores     integer[] NOT NULL,
        attrs      jsonb NOT NULL,
        born       date,
        created_at timestamptz NOT NULL DEFAULT now(),
        ttl        interval,
        data       bytea
      )
    ''');

    await conn.execute(
      Sql.named('''
        INSERT INTO samples
          (name, price, ratio, active, tags, scores, attrs, born, ttl, data)
        VALUES
          (@name, @price, @ratio, @active, @tags, @scores, @attrs, @born, @ttl:interval, @data)
      '''),
      parameters: {
        'name': 'Zażółć 🐘',
        'price': '19.99', // numeric: pass a String to keep it exact
        'ratio': 0.25,
        'active': true,
        'tags': ['new', 'sale'],
        'scores': [3, 1, 4],
        'attrs': {'color': 'red', 'size': 42},
        'born': DateTime.utc(1990, 5, 17),
        'ttl': Interval(days: 2, microseconds: Duration(hours: 3).inMicroseconds),
        'data': Uint8List.fromList([0xCA, 0xFE]),
      },
    );

    final res = await conn.execute('SELECT * FROM samples');
    final row = res.first;
    for (final (i, col) in res.schema.columns.indexed) {
      final v = row[i];
      final shown = col.columnName == 'uid' || col.columnName == 'created_at'
          ? '...'
          : '$v';
      print('${col.columnName!.padRight(10)} ${kind(v).padRight(20)} $shown');
    }
    final created = row[res.schema.columns.indexWhere((c) => c.columnName == 'created_at')] as DateTime;
    print('created_at isUtc: ${created.isUtc}');
  } finally {
    await conn.close();
  }
}

String kind(Object? v) => switch (v) {
      null => 'null',
      int() => 'int',
      double() => 'double',
      String() => 'String',
      bool() => 'bool',
      DateTime() => 'DateTime',
      Interval() => 'Interval',
      Uint8List() => 'Uint8List',
      List<String>() => 'List<String>',
      List<int>() => 'List<int>',
      Map<String, dynamic>() => 'Map<String, dynamic>',
      _ => v.runtimeType.toString(),
    };

Output (uid and created_at differ on every run):

id         int                  1
uid        String               ...
name       String               Zażółć 🐘
price      String               19.99
ratio      double               0.25
active     bool                 true
tags       List<String>         [new, sale]
scores     List<int>            [3, 1, 4]
attrs      Map<String, dynamic> {size: 42, color: red}
born       DateTime             1990-05-17 00:00:00.000Z
created_at DateTime             ...
ttl        Interval             2 days 10800000000 microseconds
data       Uint8List            [202, 254]
created_at isUtc: true
PostgreSQL Dart Notes
smallint, integer, bigint int
real, double precision double
numeric / decimal String exact; parse it yourself or use package:decimal
text, varchar, char String
uuid String
boolean bool
date, timestamp, timestamptz DateTime always UTC
interval Interval months, days and microseconds kept separately
json, jsonb Map, List, String, num... decoded with jsonDecode
bytea Uint8List
arrays (text[], integer[]...) List<T>
NULL null

A few types need care:

Inserting, updating and RETURNING

execute returns a Result, which is a List<ResultRow> plus affectedRows and schema. Each ResultRow is a List<Object?> of column values, so list patterns work for destructuring. RETURNING hands back generated values, such as identity ids and defaults, without a second query:

import 'package:pgdemo/db.dart';
import 'package:pgdemo/schema.dart';
import 'package:postgres/postgres.dart';

Future<void> main() async {
  final conn = await openConnection();
  try {
    await createSchema(conn);

    // INSERT ... RETURNING gives back generated values.
    final res = await conn.execute(
      Sql.named('''
        INSERT INTO products (sku, name, price, stock, tags)
        VALUES (@sku, @name, @price, @stock, @tags)
        RETURNING id, updated_at
      '''),
      parameters: {
        'sku': 'KB-01',
        'name': 'Keyboard',
        'price': '49.90',
        'stock': 12,
        'tags': ['input', 'usb'],
      },
    );
    final [id as int, updatedAt as DateTime] = res.first;
    print('inserted id=$id at ${updatedAt.year}, affected=${res.affectedRows}');

    // Several rows in one statement with unnest() over arrays.
    final many = await conn.execute(
      Sql.named('''
        INSERT INTO products (sku, name, price, stock)
        SELECT * FROM unnest(@skus::text[], @names::text[], @prices::numeric[], @stocks::int[])
        RETURNING id, sku
      '''),
      parameters: {
        'skus': ['MS-01', 'MN-27', 'CB-01'],
        'names': ['Mouse', 'Monitor 27"', 'USB-C cable'],
        'prices': ['19.99', '279.00', '9.50'],
        'stocks': [40, 0, 100],
      },
    );
    print('bulk: ${many.map((r) => '${r[1]}=${r[0]}').join(', ')}');

    final upd = await conn.execute(
      Sql.named('UPDATE products SET stock = stock + @n WHERE stock < @min'),
      parameters: {'n': 5, 'min': 10},
    );
    print('restocked ${upd.affectedRows}');

    final del = await conn.execute(
      Sql.named('DELETE FROM products WHERE sku = @sku'),
      parameters: {'sku': 'nope'},
    );
    print('deleted ${del.affectedRows}');

    final rows = await conn.execute(
      'SELECT id, sku, price, stock, tags FROM products ORDER BY id',
    );
    print('columns: ${rows.schema.columns.map((c) => c.columnName).toList()}');
    for (final row in rows) {
      print(row.toColumnMap());
    }
  } finally {
    await conn.close();
  }
}

Output:

inserted id=1 at 2026, affected=1
bulk: MS-01=2, MN-27=3, CB-01=4
restocked 1
deleted 0
columns: [id, sku, price, stock, tags]
{id: 1, sku: KB-01, price: 49.90, stock: 12, tags: [input, usb]}
{id: 2, sku: MS-01, price: 19.99, stock: 40, tags: []}
{id: 3, sku: MN-27, price: 279.00, stock: 5, tags: []}
{id: 4, sku: CB-01, price: 9.50, stock: 100, tags: []}

unnest() turns parallel arrays into rows, so one statement with four parameters inserts any number of rows. For large imports this is much faster than one INSERT per row because there's only one round trip.

affectedRows counts rows inserted, updated, deleted or returned by a SELECT. row.toColumnMap() builds a Map<String, dynamic> keyed by column name. An expression without an alias, such as SELECT 1 + 1, is named ?column? by the server, so give computed columns a name with AS.

Mapping rows to classes

A model class with a fromRow factory keeps column names and conversions in one place. The repository takes a Session, the interface shared by Connection, Pool and transactions, so the same code works in all three. lib/repo.dart:

import 'package:postgres/postgres.dart';

class Product {
  final int id;
  final String sku;
  final String name;
  final int priceCents;
  final int stock;
  final List<String> tags;

  Product(this.id, this.sku, this.name, this.priceCents, this.stock, this.tags);

  factory Product.fromRow(ResultRow row) {
    final m = row.toColumnMap();
    return Product(
      m['id'] as int,
      m['sku'] as String,
      m['name'] as String,
      _cents(m['price'] as String),
      m['stock'] as int,
      m['tags'] as List<String>,
    );
  }

  // numeric(10,2) arrives as a String with exactly 2 decimals, e.g. "49.90".
  static int _cents(String s) => int.parse(s.replaceFirst('.', ''));

  @override
  String toString() =>
      'Product($id, $sku, $name, ${priceCents ~/ 100}.${(priceCents % 100).toString().padLeft(2, '0')}, stock $stock, $tags)';
}

class ProductRepo {
  final Session db; // a Connection, a Pool or a transaction
  ProductRepo(this.db);

  static const _cols = 'id, sku, name, price, stock, tags';

  Future<Product?> bySku(String sku) async {
    final res = await db.execute(
      Sql.named('SELECT $_cols FROM products WHERE sku = @sku'),
      parameters: {'sku': sku},
    );
    return res.isEmpty ? null : Product.fromRow(res.first);
  }

  Future<List<Product>> search({String? tag, int limit = 10}) async {
    final res = await db.execute(
      Sql.named('''
        SELECT $_cols FROM products
        WHERE @tag:text IS NULL OR @tag = ANY(tags)
        ORDER BY price DESC
        LIMIT @limit
      '''),
      parameters: {'tag': tag, 'limit': limit},
    );
    return res.map(Product.fromRow).toList();
  }
}
import 'package:pgdemo/db.dart';
import 'package:pgdemo/repo.dart';

Future<void> main() async {
  final conn = await openConnection();
  try {
    final repo = ProductRepo(conn);
    print(await repo.bySku('KB-01'));
    print(await repo.bySku('XX-99'));
    print((await repo.search(limit: 2)).map((p) => p.sku).toList());
    print((await repo.search(tag: 'usb')).map((p) => p.sku).toList());
  } finally {
    await conn.close();
  }
}

Output:

Product(1, KB-01, Keyboard, 49.90, stock 12, [input, usb])
null
[MN-27, KB-01]
[KB-01]

_cols is a constant, so interpolating it into the SQL is safe; user values still go through @sku, @tag and @limit. The @tag:text IS NULL OR ... trick gives one query with an optional filter. The annotation is needed because @tag IS NULL alone gives the server no clue about the type.

Upserts

INSERT ... ON CONFLICT inserts a row or, if a unique constraint is violated, updates the existing one (DO UPDATE) or skips it (DO NOTHING). EXCLUDED refers to the row you tried to insert. To find out what happened, use the xmax system column: it's 0 for a freshly inserted row. A WHERE on the update skips rows that wouldn't change, and those return no row at all:

import 'package:pgdemo/db.dart';
import 'package:postgres/postgres.dart';

Future<void> upsertStock(Session db, String sku, String name, int stock) async {
  final res = await db.execute(
    Sql.named('''
      INSERT INTO products (sku, name, price, stock)
      VALUES (@sku, @name, 0, @stock)
      ON CONFLICT (sku) DO UPDATE
        SET stock = EXCLUDED.stock, updated_at = now()
        WHERE products.stock IS DISTINCT FROM EXCLUDED.stock
      RETURNING id, (xmax = 0) AS inserted
    '''),
    parameters: {'sku': sku, 'name': name, 'stock': stock},
  );
  if (res.isEmpty) {
    print('$sku: unchanged');
  } else {
    final [id, inserted as bool] = res.first;
    print('$sku: ${inserted ? 'inserted' : 'updated'} (id $id)');
  }
}

Future<void> main() async {
  final conn = await openConnection();
  try {
    await upsertStock(conn, 'MS-01', 'Mouse', 35);
    await upsertStock(conn, 'MS-01', 'Mouse', 35);
    await upsertStock(conn, 'PD-01', 'Mouse pad', 80);

    final res = await conn.execute(
      Sql.named('''
        INSERT INTO products (sku, name, price) VALUES (@sku, @name, 0)
        ON CONFLICT (sku) DO NOTHING
      '''),
      parameters: {'sku': 'KB-01', 'name': 'Another keyboard'},
    );
    print('DO NOTHING affected ${res.affectedRows} rows');
  } finally {
    await conn.close();
  }
}

Output:

MS-01: updated (id 2)
MS-01: unchanged
PD-01: inserted (id 7)
DO NOTHING affected 0 rows

Notice the ids: PD-01 got 7, not 5. An INSERT takes a value from the identity sequence before it detects the conflict, and sequence values are never handed back. Gaps in ids are normal in PostgreSQL; don't use ids to count rows.

Prepared statements

Every execute with parameters already uses a prepared statement under the hood, but it's thrown away after the call. conn.prepare() keeps it on the server, so the SQL is parsed and planned once and then run many times with run(). Free it with dispose() when done (it also goes away when the connection closes):

import 'package:pgdemo/db.dart';
import 'package:postgres/postgres.dart';

Future<void> main() async {
  final conn = await openConnection();
  try {
    final insert = await conn.prepare(Sql.named(
      'INSERT INTO products (sku, name, price, stock) '
      'VALUES (@sku, @name, @price:numeric, @stock) RETURNING id',
    ));
    try {
      final items = [
        ('HD-01', 'Headphones', '89.00', 7),
        ('WC-01', 'Webcam', '59.90', 15),
      ];
      for (final (sku, name, price, stock) in items) {
        final r = await insert.run(
          {'sku': sku, 'name': name, 'price': price, 'stock': stock},
        );
        print('inserted $sku -> id ${r.first.first}');
      }
    } finally {
      await insert.dispose();
    }

    final lowStock = await conn.prepare(
      r'SELECT sku, stock FROM products WHERE stock < $1 ORDER BY stock',
    );
    for (final limit in [10, 20]) {
      final r = await lowStock.run([limit]);
      print('stock < $limit: ${r.map((row) => '${row[0]}(${row[1]})').join(' ')}');
    }
    await lowStock.dispose();
  } finally {
    await conn.close();
  }
}

Output:

inserted HD-01 -> id 9
inserted WC-01 -> id 10
stock < 10: MN-27(5) HD-01(7)
stock < 20: MN-27(5) HD-01(7) KB-01(12) WC-01(15)

A prepared statement belongs to the connection that created it. With a pool, prepare and use it inside pool.withConnection(...), as shown in Database connection pooling.

Streaming large results

execute collects all rows into a list before it completes. For exports or batch jobs over millions of rows, stmt.bind(params) returns a ResultStream, and rows are handed to you as they arrive instead of being collected first:

import 'package:pgdemo/db.dart';

Future<void> main() async {
  final conn = await openConnection();
  try {
    final stmt = await conn.prepare(
      r'SELECT g, md5(g::text) FROM generate_series(1, $1) AS g',
    );
    var count = 0;
    var bytes = 0;
    await for (final row in stmt.bind([1000000])) {
      count++;
      bytes += (row[1] as String).length;
    }
    await stmt.dispose();
    print('streamed $count rows, $bytes hex chars');
  } finally {
    await conn.close();
  }
}

Output:

streamed 1000000 rows, 32000000 hex chars

The connection is busy until the stream is drained or cancelled, so don't run other queries on it inside the loop. If processing each row is slow and the job takes long, consider keyset pagination instead (WHERE id > @last ORDER BY id LIMIT 1000), which doesn't hold one long-running query open. To write the rows as CSV with proper quoting, see CSV.

Transactions

runTx sends BEGIN, runs your callback with a TxSession, and sends COMMIT when the callback completes. If the callback throws anything, it sends ROLLBACK and rethrows. It returns your callback's result. Use SELECT ... FOR UPDATE to lock rows you're about to change, so concurrent transactions wait instead of overselling:

import 'package:pgdemo/db.dart';
import 'package:postgres/postgres.dart';

class OutOfStock implements Exception {
  final String sku;
  OutOfStock(this.sku);
  @override
  String toString() => 'OutOfStock($sku)';
}

Future<int> placeOrder(Connection conn, String customer, Map<String, int> items) {
  return conn.runTx((tx) async {
    final order = await tx.execute(
      Sql.named('INSERT INTO orders (customer) VALUES (@c) RETURNING id'),
      parameters: {'c': customer},
    );
    final orderId = order.first.first as int;

    for (final MapEntry(key: sku, value: qty) in items.entries) {
      // Lock the product row until COMMIT so concurrent orders queue up.
      final res = await tx.execute(
        Sql.named('SELECT id, stock FROM products WHERE sku = @sku FOR UPDATE'),
        parameters: {'sku': sku},
      );
      if (res.isEmpty) throw ArgumentError('unknown sku $sku');
      final [productId as int, stock as int] = res.first;
      if (stock < qty) throw OutOfStock(sku);

      await tx.execute(
        Sql.named('UPDATE products SET stock = stock - @qty WHERE id = @id'),
        parameters: {'qty': qty, 'id': productId},
      );
      await tx.execute(
        Sql.named('INSERT INTO order_items VALUES (@o, @p, @qty)'),
        parameters: {'o': orderId, 'p': productId, 'qty': qty},
      );
    }
    return orderId;
  });
}

Future<void> main() async {
  final conn = await openConnection();
  try {
    final id = await placeOrder(conn, 'alice', {'KB-01': 2, 'MS-01': 1});
    print('order $id placed');

    try {
      await placeOrder(conn, 'bob', {'MS-01': 1, 'KB-01': 500});
    } on OutOfStock catch (e) {
      print('rolled back: $e');
    }

    final res = await conn.execute('''
      SELECT (SELECT count(*) FROM orders),
             (SELECT stock FROM products WHERE sku = 'KB-01'),
             (SELECT stock FROM products WHERE sku = 'MS-01')
    ''');
    final [orders, kb, ms] = res.first;
    print('orders: $orders, KB-01 stock: $kb, MS-01 stock: $ms');
  } finally {
    await conn.close();
  }
}

Output:

order 1 placed
rolled back: OutOfStock(KB-01)
orders: 1, KB-01 stock: 10, MS-01 stock: 34

The second order decremented MS-01 before it found out KB-01 was out of stock; the rollback undid that and removed the order row.

Errors inside a transaction, savepoints and read-only transactions

PostgreSQL aborts the whole transaction on the first error. Catching the exception in Dart doesn't help: every later statement fails until the transaction ends. If you want to tolerate one failing statement, wrap it in a savepoint:

import 'package:pgdemo/db.dart';
import 'package:postgres/postgres.dart';

Future<void> main() async {
  final conn = await openConnection();
  try {
    // 1. Catching a server error inside runTx does not save the transaction.
    try {
      await conn.runTx((tx) async {
        try {
          await tx.execute("INSERT INTO products (sku, name, price) VALUES ('KB-01', 'dup', 1)");
        } on UniqueViolationException {
          print('duplicate ignored?');
        }
        await tx.execute("INSERT INTO products (sku, name, price) VALUES ('NEW-1', 'new', 1)");
      });
    } on ServerException catch (e) {
      print('runTx failed: ${e.code} ${e.message}');
    }

    // 2. A savepoint limits the damage to one statement.
    await conn.runTx((tx) async {
      await tx.execute('SAVEPOINT before_insert');
      try {
        await tx.execute("INSERT INTO products (sku, name, price) VALUES ('KB-01', 'dup', 1)");
        await tx.execute('RELEASE SAVEPOINT before_insert');
      } on UniqueViolationException {
        await tx.execute('ROLLBACK TO SAVEPOINT before_insert');
        print('duplicate skipped');
      }
      await tx.execute("INSERT INTO products (sku, name, price) VALUES ('NEW-1', 'new', 1)");
    });
    final n = await conn.execute("SELECT count(*) FROM products WHERE sku = 'NEW-1'");
    print('NEW-1 rows: ${n.first.first}');

    // 3. Explicit rollback without throwing.
    final r = await conn.runTx((tx) async {
      await tx.execute("DELETE FROM products WHERE sku = 'NEW-1'");
      await tx.rollback();
      return 'dry run';
    });
    final n2 = await conn.execute("SELECT count(*) FROM products WHERE sku = 'NEW-1'");
    print('$r, NEW-1 rows: ${n2.first.first}');

    // 4. Using the outer connection inside runTx.
    try {
      await conn.runTx((tx) async {
        await conn.execute('SELECT 1');
      });
    } catch (e) {
      print('${e.runtimeType}: $e');
    }

    // 5. Read-only transaction
    try {
      await conn.runTx(
        (tx) => tx.execute("DELETE FROM products WHERE sku = 'NEW-1'"),
        settings: TransactionSettings(accessMode: AccessMode.readOnly),
      );
    } on ServerException catch (e) {
      print('${e.code}: ${e.message}');
    }
  } finally {
    await conn.close();
  }
}

Output:

duplicate ignored?
runTx failed: 25P02 current transaction is aborted, commands ignored until end of transaction block
duplicate skipped
NEW-1 rows: 1
dry run, NEW-1 rows: 1
PgException: Severity.error Attempting to execute query on connection while inside a `runTx` call.
25006: cannot execute DELETE in a read-only transaction

What the five parts show:

  1. After a failed statement, the next one fails with 25P02, and runTx rolls back and rethrows.
  2. ROLLBACK TO SAVEPOINT undoes only the failed statement and the transaction can continue.
  3. tx.rollback() ends the transaction without an exception; runTx still returns the callback's value. Handy for dry runs.
  4. While runTx is active, the outer connection refuses other work. Always use tx inside the callback.
  5. TransactionSettings sets the isolation level, access mode and deferrable mode for one transaction.

runTx can't be nested on the same connection; use savepoints for nested units of work.

Serializable transactions and retries

The default isolation level, READ COMMITTED, lets a transaction see rows committed by others while it runs. Check-then-insert logic ("allow at most 2 bookings per slot") is then racy unless you lock something. SERIALIZABLE makes PostgreSQL detect such races and abort one of the transactions with 40001 serialization_failure. The application has to retry it:

import 'dart:async';

import 'package:pgdemo/db.dart';
import 'package:postgres/postgres.dart';

const _retryable = {'40001', '40P01'}; // serialization_failure, deadlock_detected

Future<R> runTxWithRetry<R>(
  SessionExecutor db,
  Future<R> Function(TxSession tx) body, {
  int maxAttempts = 5,
}) async {
  for (var attempt = 1;; attempt++) {
    try {
      return await db.runTx(
        body,
        settings: TransactionSettings(isolationLevel: IsolationLevel.serializable),
      );
    } on ServerException catch (e) {
      if (!_retryable.contains(e.code) || attempt == maxAttempts) rethrow;
      print('attempt $attempt failed with ${e.code}, retrying');
      await Future<void>.delayed(Duration(milliseconds: 20 * attempt));
    }
  }
}

/// Books slot A for [who] if it has fewer than 2 bookings.
/// [afterRead] lets the demo pause between the check and the insert.
Future<String> book(Connection conn, String who, [Future<void> Function()? afterRead]) {
  return runTxWithRetry(conn, (tx) async {
    final res = await tx.execute("SELECT count(*) FROM bookings WHERE slot = 'A'");
    final taken = res.first.first as int;
    await afterRead?.call();
    if (taken >= 2) return '$who: slot full';
    await tx.execute(
      Sql.named("INSERT INTO bookings (slot, who) VALUES ('A', @who)"),
      parameters: {'who': who},
    );
    return '$who: booked';
  });
}

Future<void> main() async {
  final a = await openConnection();
  final b = await openConnection();
  try {
    await a.execute('DROP TABLE IF EXISTS bookings');
    await a.execute('CREATE TABLE bookings (slot text NOT NULL, who text NOT NULL)');
    await a.execute("INSERT INTO bookings VALUES ('A', 'zoe')");

    final aHasRead = Completer<void>();
    final bIsDone = Completer<void>();

    // Alice reads "1 booking", then waits until Bob has committed his booking.
    final alice = book(a, 'alice', () async {
      if (aHasRead.isCompleted) return; // only pause on the first attempt
      aHasRead.complete();
      await bIsDone.future;
    });

    await aHasRead.future;
    print(await book(b, 'bob'));
    bIsDone.complete();
    print(await alice);

    final all = await a.execute('SELECT who FROM bookings ORDER BY who');
    print('bookings: ${all.map((r) => r[0]).toList()}');
  } finally {
    await a.close();
    await b.close();
  }
}

Output:

bob: booked
attempt 1 failed with 40001, retrying
alice: slot full
bookings: [bob, zoe]

Both transactions saw one booking. Bob committed first. When Alice tried to commit an insert based on a count that was no longer true, PostgreSQL aborted her transaction. The retry saw two bookings and returned "slot full". Without SERIALIZABLE, both would have booked and the slot would have three bookings.

Keep the body of a retried transaction free of side effects such as sending email, since it may run more than once. Deadlocks (40P01) can happen at any isolation level, and the same retry handles them. See Cancellation and timeouts for backoff strategies.

jsonb

jsonb stores JSON in a parsed, indexable form. A Dart Map or List passed for a jsonb parameter is encoded with jsonEncode, and jsonb columns decode back to Map/List. The @> (contains) operator can use a GIN index:

import 'package:pgdemo/db.dart';
import 'package:postgres/postgres.dart';

Future<void> main() async {
  final conn = await openConnection();
  try {
    await conn.execute('DROP TABLE IF EXISTS events');
    await conn.execute('''
      CREATE TABLE events (
        id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
        payload jsonb NOT NULL
      )
    ''');
    await conn.execute('CREATE INDEX events_payload_idx ON events USING gin (payload)');

    final insert = await conn.prepare(
      Sql.named('INSERT INTO events (payload) VALUES (@p:jsonb)'),
    );
    for (final p in [
      {'type': 'signup', 'user': {'id': 1, 'plan': 'free'}},
      {'type': 'purchase', 'user': {'id': 1}, 'items': ['KB-01'], 'total': 49.9},
      {'type': 'purchase', 'user': {'id': 2}, 'items': ['MS-01', 'CB-01'], 'total': 29.49},
    ]) {
      await insert.run({'p': p});
    }
    await insert.dispose();

    // @> (contains) can use the GIN index; the Map is encoded as jsonb.
    final res = await conn.execute(
      Sql.named('''
        SELECT id, payload->'user'->>'id' AS user_id, payload->'items' AS items,
               (payload->>'total')::numeric AS total
        FROM events
        WHERE payload @> @filter:jsonb
        ORDER BY id
      '''),
      parameters: {'filter': {'type': 'purchase'}},
    );
    for (final row in res) {
      final m = row.toColumnMap();
      print('event ${m['id']}: user ${m['user_id']}, items ${m['items']}, '
          'total ${m['total']}');
    }

    final whole = await conn.execute('SELECT payload FROM events WHERE id = 1');
    final payload = whole.first.first as Map<String, dynamic>;
    print('plan: ${payload['user']['plan']}');
  } finally {
    await conn.close();
  }
}

Output:

event 2: user 1, items [KB-01], total 49.9
event 3: user 2, items [MS-01, CB-01], total 29.49
plan: free

-> returns jsonb (decoded to Dart objects), ->> returns text, which is why user_id comes back as a String and total needs a cast to numeric. For the conversion between JSON and Dart classes, see JSON.

LISTEN and NOTIFY

PostgreSQL has a built-in publish/subscribe mechanism. NOTIFY channel, 'payload' (or pg_notify()) sends a message to every connection that ran LISTEN channel. conn.channels['name'] is a stream of payloads; subscribing to it sends LISTEN, cancelling sends UNLISTEN. Combined with a trigger, it tells your app about changes no matter who made them:

import 'dart:async';
import 'dart:convert';

import 'package:pgdemo/db.dart';
import 'package:postgres/postgres.dart';

Future<void> main() async {
  final listener = await openConnection();
  final writer = await openConnection();
  try {
    // A trigger that publishes every stock change as JSON.
    await writer.execute(
      r'''
      CREATE OR REPLACE FUNCTION notify_stock() RETURNS trigger AS $$
      BEGIN
        PERFORM pg_notify('stock_changed',
          json_build_object('sku', NEW.sku, 'stock', NEW.stock)::text);
        RETURN NEW;
      END $$ LANGUAGE plpgsql;

      CREATE OR REPLACE TRIGGER products_stock_notify
        AFTER UPDATE OF stock ON products
        FOR EACH ROW EXECUTE FUNCTION notify_stock();
      ''',
      queryMode: QueryMode.simple,
    );

    final received = <String>[];
    final done = Completer<void>();
    // Subscribing sends LISTEN stock_changed on this connection.
    final sub = listener.channels['stock_changed'].listen((payload) {
      final m = jsonDecode(payload) as Map<String, dynamic>;
      received.add('${m['sku']}=${m['stock']}');
      if (received.length == 3 && !done.isCompleted) done.complete();
    });
    await Future<void>.delayed(Duration(milliseconds: 100)); // let LISTEN run

    await writer.execute(
      "UPDATE products SET stock = stock - 1 WHERE sku IN ('KB-01', 'MS-01')",
    );
    // Notifications sent inside a transaction are delivered only on COMMIT.
    await writer.runTx((tx) async {
      await tx.execute("UPDATE products SET stock = 0 WHERE sku = 'CB-01'");
      print('inside tx, received so far: ${received.length}');
    });
    await writer.channels.notify('other_channel', 'ignored by our listener');

    await done.future.timeout(Duration(seconds: 5));
    received.sort();
    print('received: $received');
    await sub.cancel(); // sends UNLISTEN
  } finally {
    await listener.close();
    await writer.close();
  }
}

Output:

inside tx, received so far: 2
received: [CB-01=0, KB-01=9, MS-01=33]

Things to know:

Handling errors

Errors reported by the server throw ServerException, a subclass of PgException. The code field holds the five-character SQLSTATE code, and fields like detail, hint, constraintName, tableName, columnName and position (1-based character offset in the SQL) give context. Unique and foreign key violations have their own subclasses:

import 'dart:async';

import 'package:pgdemo/db.dart';
import 'package:postgres/postgres.dart';

Future<void> run(Connection conn, String sql) async {
  try {
    await conn.execute(sql);
  } on UniqueViolationException catch (e) {
    print('unique violation on ${e.constraintName}: ${e.detail}');
  } on ForeignKeyViolationException catch (e) {
    print('foreign key ${e.constraintName}: ${e.detail}');
  } on ServerException catch (e) {
    print('${e.code} ${e.message}'
        '${e.constraintName != null ? ' [${e.constraintName}]' : ''}'
        '${e.position != null ? ' at position ${e.position}' : ''}');
  }
}

Future<void> main() async {
  final conn = await openConnection();
  try {
    await run(conn, "INSERT INTO products (sku, name, price) VALUES ('KB-01', 'x', 1)");
    await run(conn, 'INSERT INTO order_items VALUES (1, 999, 1)');
    await run(conn, "INSERT INTO products (sku, name, price) VALUES ('X-1', 'x', -5)");
    await run(conn, "INSERT INTO products (sku, price) VALUES ('X-2', 5)");
    await run(conn, 'SELECT nme FROM products');
    await run(conn, 'SELECT * FROM prodcts');
    await run(conn, 'SELEC 1');
    print('connection still open: ${conn.isOpen}');

    // Per-query timeout: the driver asks the server to cancel the query.
    try {
      await conn.execute('SELECT pg_sleep(5)', timeout: Duration(milliseconds: 500));
    } on TimeoutException catch (e) {
      print('timed out: $e');
    }
    final after = await conn.execute('SELECT 1');
    print('after timeout: ${after.first.first}, open: ${conn.isOpen}');
  } finally {
    await conn.close();
  }
}

Output:

unique violation on products_sku_key: Key (sku)=(KB-01) already exists.
foreign key order_items_product_id_fkey: Key (product_id)=(999) is not present in table "products".
23514 new row for relation "products" violates check constraint "products_price_check" [products_price_check]
23502 null value in column "name" of relation "products" violates not-null constraint
42703 column "nme" does not exist at position 8
42P01 relation "prodcts" does not exist at position 15
42601 syntax error at or near "SELEC" at position 1
connection still open: true
timed out: Severity.error 57014: canceling statement due to user request
after timeout: 1, open: true

After a server error the connection stays usable (unless you're in a transaction, see above). A query that runs past its timeout is cancelled on the server (57014) and the driver throws an exception that is both a ServerException and a TimeoutException; the connection stays open. Only if the server doesn't answer the cancel request in time does the driver close the connection.

Common SQLSTATE codes:

Code Name Typical cause
23505 unique_violation duplicate value in a UNIQUE / PRIMARY KEY column
23503 foreign_key_violation reference to a missing row, or deleting a referenced row
23502 not_null_violation NULL (or a missing value) in a NOT NULL column
23514 check_violation a CHECK constraint failed
40001 serialization_failure retry the transaction
40P01 deadlock_detected retry the transaction
25P02 in_failed_sql_transaction statement after an error in the same transaction
42P01 undefined_table table doesn't exist (or wrong search_path)
42703 undefined_column typo in a column name
57014 query_canceled timeout or cancel request
28P01 invalid_password wrong user or password
3D000 invalid_catalog_name database doesn't exist

Check code (or the exception type), not the message text: messages are translated when the server runs with a non-English lc_messages.

Connection pools

A server handling concurrent requests needs several connections, since each connection runs one query at a time. Pool implements the same Session and SessionExecutor interfaces as Connection, so execute, runTx and the ProductRepo above work unchanged:

import 'package:pgdemo/db.dart';
import 'package:pgdemo/repo.dart';
import 'package:postgres/postgres.dart';

final pool = Pool.withEndpoints(
  [endpointFromEnv()],
  settings: PoolSettings(maxConnectionCount: 4, sslMode: SslMode.disable),
);

Future<void> main() async {
  final repo = ProductRepo(pool); // a Pool is a Session too
  final found = await Future.wait([
    for (final sku in ['KB-01', 'MS-01', 'HD-01']) repo.bySku(sku),
  ]);
  print(found.map((p) => '${p!.sku}: ${p.stock}').join(', '));
  await pool.close();
}

Output:

KB-01: 9, MS-01: 33, HD-01: 7

The default maxConnectionCount is 1, which serializes all queries; that and the other pitfalls (waiting for a free connection, session settings leaking between borrowers, recycling connections) are covered in Database connection pooling.

Best practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents