Golem add postgres effect

From golemcloud/golem · View interactive version

Golem add postgres effect is an AI agent skill from the GitHub repository golemcloud/golem. Using PostgreSQL from an Effect-based Golem agent through @golemcloud/effect-golem/postgres. Use when connecting to PostgreSQL, running SQL, or adding PostgreSQL transactions to an Effect Golem application.

How to use this skill

Skill file

Using PostgreSQL from an Effect Golem Agent

Use the Effect SDK's PostgreSQL adapter. It implements Effect's SQL client over the

golem:rdbms/postgres@1.5.0 host interface, which works in Golem's WebAssembly runtime.

Do not install or import pg, @effect/sql-pg, or another native Node database driver. Generated

Effect projects already include compatible effect and @golemcloud/effect-golem dependencies.

Imports

Import PostgreSQL support from its package subpath:

import { Effect, Schema } from "effect";
import { SqlClient } from "effect/sql";
import { method } from "@golemcloud/effect-golem";
import { Pg, PgClient } from "@golemcloud/effect-golem/postgres";

Prefer the Canonical `SqlClient` Service

PgClient.layer provides both the PostgreSQL-specific adapter service and Effect's canonical

SqlClient.SqlClient tag. Keep portable repository code dependent on that generic tag and provide

the Golem adapter at the application boundary:

const PostgresLive = PgClient.layer({
  connectionAddress: "postgres://user:password@localhost:5432/app",
});

const findNote = (noteId: number) =>
  Effect.gen(function* () {
    const sql = yield* SqlClient.SqlClient;
    return yield* sql<{ id: number; body: string }>`
      SELECT id, body FROM notes WHERE id = ${noteId}
    `;
  });

const runnable = findNote(1).pipe(Effect.provide(PostgresLive));

Import SqlSchema, SqlResolver, or Migrator from effect/sql when a repository needs

schema decoding, request batching, or migrations. They consume the same canonical SqlClient

service; do not replace them with PostgreSQL-driver-specific wrappers. Keep Pg imports only for

PostgreSQL-specific rich parameter values or dialect-specific behavior.

Direct PgClient.make remains supported for a simple agent implementation that constructs one

client and closes over it. Use .layer when generic services or repository layers should receive

the client through Effect context.

Open and Reuse a Connection

Create the client once in the agent's init Effect and return it as state before methods

constructs the handlers, so the implemented agent instance reuses one host connection:

// In the existing .implement({ ... }) object:
init: ({ name }) => Effect.gen(function* () {
  const state = yield* Ref.make({ count: 0 });
  yield* Effect.logInfo("Counter constructed").pipe(Effect.annotateLogs({ name }));
  const sql = yield* PgClient.make({
    connectionAddress: "postgres://user:password@localhost:5432/app",
  });
  return { state, sql };
}),
methods: ({ state, sql }) => ({
  // Keep the existing handlers here, using state as before.
  checkPostgres: () => sql`SELECT 'postgres-ok'::text`.values.pipe(
    Effect.flatMap((rows) => typeof rows[0]?.[0] === "string"
      ? Effect.succeed(rows[0][0])
      : Effect.die("Expected a PostgreSQL string")),
    Effect.orDie,
  ),
}),

Import Ref from effect. Preserve all existing init work and state fields; return the client

alongside them. For the default counter template, remove .implement<Ref.Ref<{ count: number }>>

so the new { state, sql } type is inferred (or update the explicit type). Keep every existing

handler in methods: ({ state, sql }) => ({ ... }); do not return handlers from init.

PgClient.make opens the host-backed connection and can fail with Effect's SqlError. The Golem

agent runtime supplies its host and scope requirements. Do not look for connect, close,

query, or execute methods on PgClient; they are not this adapter's API.

Add a String Method to an Existing Agent

Add the method contract to the existing definition's methods map:

checkPostgres: method({
  input: {},
  success: Schema.String,
}),

Add a handler with the same TypeScript-cased property name to the object returned by methods.

Keep existing contracts and handlers unchanged unless the task requests otherwise.

The CLI agent type comes from the definition's name, not the exported TypeScript constant.

The default Effect template declares name: "CounterAgent", so invoke it as

CounterAgent("db-test"). If you rename an agent, keep the matching agent key in golem.yaml

aligned:

httpApi:
  deployments:
    local:
      - domain: test-app.localhost:9006
        agents:
          CounterAgent: {}

Changing only the exported constant name does not change the registered agent type.

For a positional query, use the statement's .values Effect and explicitly return the requested

cell:

checkPostgres: () =>
  Effect.gen(function* () {
    const rows = yield* sql`SELECT 'postgres-ok'::text`.values;
    const value = rows[0]?.[0];

    if (typeof value !== "string") {
      return yield* Effect.die(
        "Expected PostgreSQL row 0, column 0 to contain a string",
      );
    }

    return value;
  }).pipe(Effect.orDie),

The handler succeeds with a plain string; it does not expose a result wrapper in the agent

method contract. Make sure the handler explicitly returns value: .values yields all positional

rows, not the first cell. The success-only handler converts unexpected SQL failures to defects

with Effect.orDie. For recoverable failures, declare an error schema and map SQL errors to

that domain type. Defects fail the invocation; they do not guarantee retry.

Query Data

The client is an Effect SQL tagged-template function. Interpolate values rather than constructing

SQL strings; the client converts interpolations to PostgreSQL $1, $2, ... parameters.

interface NoteRow {
  readonly id: number;
  readonly body: string;
}

const rows = (yield* sql`
  SELECT id, body
  FROM notes
  WHERE id = ${1}
`) as ReadonlyArray<NoteRow>;

const note = rows[0];

Normal query results are arrays of objects keyed by column name. When column names are irrelevant,

use .values to read rows positionally:

const rows = yield* sql`SELECT 'postgres-ok'::text`.values;
const value = rows[0]?.[0];

if (typeof value !== "string") {
  return yield* Effect.die("Expected a PostgreSQL text value");
}

For an agent method whose contract says success: Schema.String, keep that public contract. The

handler still returns an Effect; do not change the success schema to a source-language-style

Result merely because database operations can fail. Apply Effect.orDie to the composed handler

for unexpected SQL failures, or declare an error schema and map failures to its domain type.

Create Tables and Write Data

Run DDL and writes through the same tagged-template API:

yield* sql`
  CREATE TABLE IF NOT EXISTS notes (
    id integer PRIMARY KEY,
    body text NOT NULL
  )
`;

yield* sql`
  INSERT INTO notes (id, body)
  VALUES (${1}, ${"hello"})
  ON CONFLICT (id) DO NOTHING
`;

yield* sql`
  UPDATE notes
  SET body = ${"updated"}
  WHERE id = ${1}
`;

Use RETURNING when the application needs written rows. Use a statement's .raw Effect when it

specifically needs the affected-row count:

const inserted = (yield* sql`
  INSERT INTO notes (id, body)
  VALUES (${2}, ${"second"})
  RETURNING id, body
`) as ReadonlyArray<NoteRow>;

const affected = (yield* sql`
  UPDATE notes SET body = ${"changed"} WHERE id = ${2}
`.raw) as bigint;

Plain strings, booleans, finite numbers, bigint, Date, Uint8Array, null, and undefined

are encoded automatically. Import Pg when PostgreSQL needs an explicit richer type:

import { Pg, PgClient } from "@golemcloud/effect-golem/postgres";

yield* sql`
  INSERT INTO documents (id, body)
  VALUES (${Pg.uuid(id)}, ${Pg.jsonb(body)})
`;

Transactions

Wrap one Effect in sql.withTransaction. Success commits; failure or interruption rolls back.

yield* sql.withTransaction(
  Effect.gen(function* () {
    yield* sql`
      UPDATE accounts SET balance = balance - ${amount} WHERE id = ${from}
    `;
    yield* sql`
      UPDATE accounts SET balance = balance + ${amount} WHERE id = ${to}
    `;
  }),
);

Do not manually call begin, commit, or rollback; those are not public methods on this client.

SQL Permissions and Migrations

Declare the agent's database grants in golem.yaml when it uses an explicit initialCard.

Ordinary reads need query; writes, table DDL, index creation, and table locks need mutate.

Resources use database.schema.table, with * allowed per component. An explicit card replaces

the default card, so it also needs env(?agent) @ ?agent : read : GOLEM_AGENT_ID and

env(?agent) @ ?agent : read : GOLEM_AGENT_TYPE: the SDK reads the agent type when it restores the

agent from a snapshot, and golem deploy warns about a card without both grants. When the agent

restores a snapshot with an explicit snapshot strategy, the SDK also reads the agent's ID through

self metadata, so the card then also needs agent(?agent) @ ?agent : view : *. For example:

env(?agent) @ ?agent : read : GOLEM_AGENT_ID
env(?agent) @ ?agent : read : GOLEM_AGENT_TYPE
rdbms(?env) @ ?agent : query : app.public.notes
rdbms(?env) @ ?agent : mutate : app.public.notes

The verb follows the SQL operation, not the client method. Golem analyzes SQL first and authorizes

every table target. A statement that reads one table and writes another needs both grants.

Starting a transaction currently requires both query and mutate on app.*.*; grants limited

to one table do not satisfy this requirement. Statements inside the transaction are still checked.

Use Migrator from effect/sql with PgClient.layer through the canonical SqlClient service.

Normal migrations should work with ordinary grants for their tracking table and application

tables. Supported SQL includes reads, writes, table creation and alteration, index creation,

table locks, and CTEs whose underlying reads and writes can be determined. Row-locking

SELECT ... FOR UPDATE or FOR SHARE needs mutate on the locked tables, including those selected

by an OF alias. Not every SQL form or dialect-specific clause is supported. Send one statement

per call. The adapter and Migrator do not automatically grant broad permissions.

If a required migration statement cannot be analyzed, such as CREATE SCHEMA or

CREATE EXTENSION, review its effects and database-role privileges before explicitly granting:

rdbms(?env) @ ?agent : unanalyzed : database(app)

Only the explicit unanalyzed verb with a database(...) resource grants this fallback.

The default agent card, wildcard table grants, and wildcard verbs do not include it;

prefer a concrete database name over the deliberately broad unanalyzed : database(*) form.

Never add it automatically for migrations or to fix an ordinary table-permission denial.

Golem always attempts analysis first. If analysis succeeds, insufficient table permission denies

the statement even when the agent holds an unanalyzed grant. Only unsupported analysis can use

the explicit fallback for the connection's database. Analysis and permission denials surface as

query-execution failures through the adapter's SqlError; inspect the error message before

changing grants. The database can still reject SQL that Golem permits.

The database role still enforces its privileges. database(app) selects the connection database;

it does not guarantee that arbitrary SQL affects only that database. Use a least-privilege role

and reserve unanalyzed SQL for trusted code, not model-generated statements.

Connection Configuration

Hardcode a connection URI only when a test explicitly requires it. For application code, declare a

redacted agent config field with defineConfig and resolve it before creating the client:

import { Effect, Redacted, Schema } from "effect";
import { defineConfig } from "@golemcloud/effect-golem";
import { PgClient } from "@golemcloud/effect-golem/postgres";

class DatabaseConfig extends defineConfig("Database.Config", {
  connectionAddress: Schema.Redacted(Schema.String),
}) {}

const config = yield* DatabaseConfig;
const connectionAddress = Redacted.value(yield* config.connectionAddress.get);
const sql = yield* PgClient.make({ connectionAddress });

Attach the config class to the agent definition with config: DatabaseConfig. Supply secret fields

through Golem secrets (or secretDefaults for local development), not plain agent config. The

adapter does not read DATABASE_URL or another environment variable automatically.

Key Constraints

layer when their schema, batching, or migration behavior is needed.

handling or mapping at the method boundary; Effect.orDie does not guarantee retry.

idempotent with patterns such as CREATE TABLE IF NOT EXISTS and ON CONFLICT.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.