# Postgres

A store for Postgres is one table and one function, in
[tests/postgres/store.ts](../tests/postgres/store.ts). Copy it; it is not part
of the package, because the package has no database driver in it.

```sql
CREATE TABLE burying_beetle (
	scope text NOT NULL,
	id text NOT NULL,
	version numeric[] NOT NULL,
	deleted boolean NOT NULL,
	deleted_at bigint,
	PRIMARY KEY (scope, id)
);
```

`version` is `numeric[]` so that tuples and integers beyond 64 bits compare
exactly. `deleted_at` is milliseconds from the guard's clock.

`advance` takes `pg_advisory_xact_lock(hashtext(scope), hashtext(id))`, reads
the row, runs `decide`, and upserts the row on `apply`. The lock lasts until
the transaction ends, which serialises events for one entity, including the
first one, when there is no row yet for `SELECT ... FOR UPDATE` to lock. Two
entities whose hashes collide wait for each other and nothing worse.

Build the store on the transaction that makes your own write:

```ts
await sql.begin(async (tx) => {
	const guard = new Guard({ store: postgresStore(tx) });
	if ((await guard.advance({ scope: "github:octo/repo", id: issue.node_id, version: [Date.parse(issue.updated_at), 0], kind: "write" })) === "apply") {
		await tx`UPDATE issues SET title = ${issue.title} WHERE id = ${issue.node_id}`;
	}
});
```

If your write fails, the transaction rolls back the record too, and the
sender's retry applies.

`scripts/test-postgres.sh` starts Postgres 17 in a container and runs
`checkStore` against this store, plus the rollback case above.
