DartAdvanced 2 min read

Dart PostgreSQL tutorial: parameterized queries and transactions

Replace ephemeral storage with a deliberate schema, parameterized access and transaction boundaries.

On this page

An in-memory repository is useful for a first API, but its data disappears on restart and is not shared between service replicas. A durable backend needs a schema, migrations, connection ownership and a concurrency policy.

Create a small schema

CREATE TABLE tasks (
  id BIGSERIAL PRIMARY KEY,
  owner_id TEXT NOT NULL,
  title TEXT NOT NULL CHECK (char_length(title) BETWEEN 1 AND 120),
  done BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE INDEX tasks_owner_id_id ON tasks(owner_id, id);

This example uses PostgreSQL character length, which differs from the teaching Dart String.length rule for some Unicode input. Align the application’s final text-length policy before adopting both constraints. Version schema changes as migrations; do not recreate tables each time the server starts.

Parameterize values

Add the postgres package to a local server project. After establishing a configured connection using the driver’s current setup, a repository method can use this fragment:

final rows = await connection.execute(
  Sql.named('SELECT id, title, done FROM tasks '
      'WHERE owner_id=@owner ORDER BY id LIMIT @limit'),
  parameters: {'owner': verifiedOwnerId, 'limit': 20},
);
final items = rows.map((row) => row.toColumnMap()).toList();

The connection, imported postgres types and verified owner are supplied by the server. Never interpolate a user value into the SQL string. Parameters protect values; dynamic table or column identifiers still require an allowlist and a deliberate query design.

Choose the transaction boundary

For a multi-step operation, use the driver’s transaction API so the relevant reads/writes succeed or fail together. Choose constraints and isolation for the actual invariant. A transaction does not automatically prevent every lost update or make a network request outside the database atomic.

Production connection pooling needs bounded concurrency, timeout configuration and shutdown cleanup. Keep credentials in server-side environment/secret configuration and require the transport/security settings appropriate to your database host.

Adapt the application contract

The sample TaskStore is synchronous. A database-backed repository needs asynchronous methods, and handlers must await them. Refactor the interface and tests rather than replacing a synchronous map expression with an unawaited database future.

The postgres package documentation is the source for the installed driver’s API. These queries require a configured PostgreSQL service; the downloadable in-memory project’s tests do not claim to test a database deployment.

Exercise

Implement a repository behind an asynchronous interface and write an integration test against a disposable database. Test duplicate/invalid data, owner isolation and rollback. Verify the API’s HTTP contract remains unchanged after replacing storage.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.