# SQL workflows, versioning, and multi-tenancy

> Go beyond standard S3 with PostgreSQL-native workflows: commit objects in the same transaction as relational rows, restore historical versions, fork whole buckets without copying bytes, and isolate tenants with RLS.

---

LLMS index: [llms.txt](/llms.txt)

---

HTTP clients see `pgs3` as an S3 endpoint, but inside PostgreSQL the exact same buckets and objects are accessible through SQL functions. That unlocks capabilities a standalone object store cannot offer: atomic cross-table transactions, zero-byte bucket forks, one-call version promotion, and PostgreSQL Row-Level Security (RLS).

## How storage and deduplication work {#storage}

<a id="request"></a>
<a id="concurrency"></a>

Understanding three storage details explains why `pgs3` operations behave the way they do:

- **Content-addressed blobs (`pgs3.blob`)**: Every non-delete object version references a physical blob keyed by its SHA-256 digest. Uploading the same bytes twice—or copying, restoring, or forking objects—increments a reference count instead of duplicating payload bytes.
- **Inline vs. chunked layout**: Blobs up to `pgs3.inline_threshold` (default 64 KiB) store one inline copy in `pgs3.blob`. Larger blobs are split into 4 MiB chunks (`pgs3.chunk_size`) across hash-partitioned `pgs3.chunk` tables; completed multipart uploads stitch ordered `pgs3.blob_extent` references together without rewriting the uploaded parts.
- **Short-transaction concurrency**: Same-key writes acquire a key-level lock so precondition checks (`If-None-Match`, `If-Match`) and version publication are serialized atomically. Streaming uploads commit each chunk in its own short transaction and stay invisible until the final commit publishes the object version.

For full schema diagrams and design rationale, see [design.md](https://github.com/pgsty/pgs3/blob/v0.1.2/docs/design.md), [schema.md](https://github.com/pgsty/pgs3/blob/v0.1.2/docs/schema.md), and [decisions.md](https://github.com/pgsty/pgs3/blob/v0.1.2/docs/decisions.md).

## 1. Commit business rows and objects atomically {#transactional}

A classic failure mode with external object stores is writing a file to S3 and then failing to insert the matching database row (or rolling back the database row while leaving an orphan object behind). With `pgs3`, both live inside one PostgreSQL transaction.

Assume `tenant_app` is an unprivileged tenant role created as shown in [Manage tenants and credentials](#tenants):

```sql
CREATE TABLE app_reports (
    report_id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title       text NOT NULL,
    bucket_name text NOT NULL,
    object_key  text NOT NULL,
    version_id  bigint NOT NULL,
    created_at  timestamptz NOT NULL DEFAULT now()
);
GRANT INSERT, SELECT ON app_reports TO tenant_app;

BEGIN;
SET LOCAL ROLE tenant_app;

SELECT pgs3.create_bucket('reports');

WITH uploaded AS (
    SELECT *
    FROM pgs3.put(
        'reports',
        '2026/q4-summary.json',
        convert_to('{"revenue":1280000,"currency":"USD"}', 'UTF8'),
        'application/json',
        '{"author":"billing"}'::jsonb
    )
)
INSERT INTO app_reports (title, bucket_name, object_key, version_id)
SELECT 'Q4 Summary', 'reports', u.key, u.version_id
FROM uploaded AS u
RETURNING report_id, bucket_name, object_key, version_id;

COMMIT;
```

```text
 report_id | bucket_name |      object_key      | version_id
-----------+-------------+----------------------+------------
         1 | reports     | 2026/q4-summary.json |          1
```

If anything in the transaction fails before `COMMIT`, both the `app_reports` row and the `pgs3` object disappear together. Once committed, any S3 client authenticated as `tenant_app` can immediately download `reports/2026/q4-summary.json`.

## 2. Version history and instant rollback {#versioning}

<a id="example"></a>

Every overwrite in `pgs3` creates a new monotonically ordered `version_id`, and every ordinary delete inserts a delete marker. Calling `pgs3.restore()` promotes a chosen historical version back to the latest state by appending a new version row that points to the original SHA-256 blob—history is never rewritten.

```sql
BEGIN;
SET LOCAL ROLE tenant_app;

-- Write v1 and capture its version_id in psql
SELECT (pgs3.put('reports', 'prompts/system.txt', convert_to('v1: strict mode', 'UTF8'))).version_id
    AS v1_id \gset

-- Overwrite with a buggy v2
SELECT (pgs3.put('reports', 'prompts/system.txt', convert_to('v2: broken prompt', 'UTF8'))).version_id;

-- Promote v1 back to latest (creates v3 pointing to v1's blob)
SELECT version_id, size, etag
FROM pgs3.restore('reports', 'prompts/system.txt', :v1_id);

-- Verify the latest content is back to v1
SELECT convert_from((pgs3.get('reports', 'prompts/system.txt')).body, 'UTF8') AS current_body;

COMMIT;
```

```text
 current_body
-----------------
 v1: strict mode
```

You can also pass `p_if_match => '<current-etag>'` to `pgs3.restore()` to abort the rollback if another writer updated the key in the meantime. Over HTTP, `pgs3` exposes the same operation via its extension route `POST /{bucket}/{key}?restore&versionId={id}`.

## 3. Fork a bucket without copying payload bytes {#fork}

`pgs3.fork_bucket()` creates a brand-new bucket populated with the latest object versions (and delete markers) of a source bucket. Underlying SHA-256 blobs are shared via reference counting; only metadata rows and reference counts are written. Subsequent writes to either bucket are completely independent.

This is especially useful for **AI agent experiment branches**, **pre-release staging checkpoints**, or **reproducible evaluation snapshots**:

```sql
BEGIN;
SET LOCAL ROLE tenant_app;

-- Fork the latest state of 'reports' into a new experiment bucket
SELECT pgs3.fork_bucket('reports', 'reports-exp-42') AS copied_entries;

-- Mutate the forked bucket freely
SELECT pgs3.put('reports-exp-42', 'prompts/system.txt', convert_to('experiment prompt', 'UTF8'));

-- Confirm the source bucket is untouched
SELECT 'source' AS side, convert_from((pgs3.get('reports', 'prompts/system.txt')).body, 'UTF8') AS body
UNION ALL
SELECT 'fork',   convert_from((pgs3.get('reports-exp-42', 'prompts/system.txt')).body, 'UTF8');

COMMIT;
```

```text
  side  |       body
--------+-------------------
 source | v1: strict mode
 fork   | experiment prompt
```

Keep two constraints in mind:
- The destination bucket must not already exist.
- Forking shares physical bytes, so disk growth for large blobs is minimal, but it still inserts metadata rows, updates indexes, and generates WAL proportional to the number of latest entries in the source bucket.

## 4. Multi-tenancy and credential lifecycle {#tenants}

<a id="roles"></a>
<a id="keys"></a>
<a id="audit"></a>

### How tenant isolation works

`pgs3` separates the **runtime service identity** from **tenant identities**:

1. **Service role (`pgs3.server_role`, default `pgs3_server`)**: Created automatically when the extension is installed. HTTP workers connect as this restricted `NOLOGIN NOINHERIT` role only to look up credentials and switch roles.
2. **Tenant roles**: Ordinary, unprivileged `NOLOGIN NOINHERIT` roles that you create (one per customer, team, or agent workspace). When you bind a credential with `pgs3.create_credential()`, `pgs3` grants `pgs3_server` `SET`-only membership in that tenant role.
3. **Per-request RLS**: After verifying a request's SigV4 signature, the HTTP worker executes `SET LOCAL ROLE <tenant>` inside the request transaction. Row-Level Security policies ensure each tenant only sees and modifies buckets owned by roles it has `USAGE` membership in.

> [!CAUTION]
> Never bind a `SUPERUSER`, `BYPASSRLS`, `CREATEROLE`, `CREATEDB`, or `REPLICATION` role to an S3 credential—`pgs3.create_credential()` rejects elevated roles by design.

### Provision two isolated tenants

Run credential administration as a database operator (credential functions are revoked from `PUBLIC`):

```sql
-- Create two isolated, unprivileged tenant roles
CREATE ROLE tenant_alice NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;
CREATE ROLE tenant_bob   NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;

-- Bind distinct access keys (generate secrets externally with openssl rand -hex 32)
SELECT pgs3.create_credential('AKIAALICE0000001', '<alice-secret>', 'tenant_alice');
SELECT pgs3.create_credential('AKIABOB000000001', '<bob-secret>',   'tenant_bob');
```

Verify isolation in SQL—`tenant_bob` cannot see or read `tenant_alice`'s bucket:

```sql
BEGIN;
SET LOCAL ROLE tenant_alice;
SELECT pgs3.create_bucket('alice-private');
SELECT pgs3.put('alice-private', 'secret.txt', convert_to('for alice only', 'UTF8'));
COMMIT;

BEGIN;
SET LOCAL ROLE tenant_bob;
SELECT * FROM pgs3.list_buckets();  -- returns 0 rows
COMMIT;
```

### Rotate, suspend, and audit credentials

Issue separate access keys per client or service so you can rotate or revoke one without disrupting others:

```sql
-- Rotate the signing secret in place (run over a protected TLS/local session)
SELECT pgs3.rotate_credential('AKIAALICE0000001', '<new-alice-secret>');

-- Temporarily suspend a compromised key (immediately blocks new S3 requests)
SELECT pgs3.set_credential_enabled('AKIAALICE0000001', false);

-- Reassign a key to another unprivileged tenant role
SELECT pgs3.set_credential_role('AKIAALICE0000001', 'tenant_alice_v2');

-- Permanently remove an unused key
SELECT pgs3.delete_credential('AKIAALICE0000001');

-- Audit non-secret credential columns
SELECT access_key, role_name, enabled, created_at
FROM pgs3.credential
ORDER BY access_key;
```

Tenant SQL functions default to `EXECUTE` for `PUBLIC`, which allows any database role with `CONNECT` to create its own buckets while keeping other tenants' buckets hidden via RLS. If bucket creation must be allowlisted, revoke `EXECUTE` on `pgs3.create_bucket(text, jsonb)` from `PUBLIC` and grant it only to approved roles. Never grant tenants `SELECT` on `pgs3.credential`.

For the full list of SQL signatures, see the [SQL reference](/docs/pgs3/reference/#sql).

---

Backlinks:

- [Getting started](/docs/pgs3/getting-started/)
