# Push to Postgres

> Write Sanda's numbers into a table in your own PostgreSQL database. Each run writes only the rows whose values changed, and never deletes one.

A push to Postgres writes Sanda's numbers into a table in a PostgreSQL database you run: revenue over the last twelve months for each customer, the overdue balance beside it, the date of their last order. The numbers come from your [semantic model](https://docs.sanda-os.com.au/semantic-model), so they mean what your team agreed they mean, and they land in an ordinary table your own application, queries and reports read like any other.

It works as every push does (see [Push](https://docs.sanda-os.com.au/streams/out)): each run reads the values, writes them the way Postgres stores them, compares them with what Postgres last accepted, and sends only the rows whose values changed. A run where nothing changed doesn't connect to the database at all.

:::note
Postgres is under **Choose a destination** on **Data · Streams · Push** once pushes to Postgres are switched on for your console. If it isn't listed, ask Sanda support. To read tables from a Postgres database into your warehouse instead, see [stream a Postgres database](https://docs.sanda-os.com.au/streams/postgres).
:::

## What it writes

A push writes to one table in the schema its connection names, and finds each row by a **key column**: a text or whole-number column that is different on every row, such as your customer code. A run updates the row with that key, and adds a row when the table has none. A push never deletes a row, and never clears a column because a row has left the push: that row keeps the values it has.

The key column doesn't need a unique index for this to work, but an index on it keeps each write quick on a large table. A table Sanda makes has one: its key column is the table's primary key.

You don't need to make the table first. A push can send a whole table from your semantic model, and Sanda makes a Postgres table for it if the schema hasn't one of that name (see [send a whole table](#send-a-whole-table)). A push can also write into a table you made yourself: the setup script's grants cover every table in the schema, including ones you make later.

If the table, or a column a push writes, goes missing later (someone dropped it, say), the next run makes it again and carries on, unless you turn that off (see [make the table if it isn't there](#make-the-table-if-it-isnt-there)).

## Connect Postgres

### Before you start

The database needs these, because Sanda reaches it over the internet:

- **PostgreSQL 12 or later, and its primary.** A read replica only takes reads, so Sanda refuses it when you connect.
- **An address on the internet.** A name such as `db.example.com`, or a public IPv4 address. Sanda refuses a private address (`10.x.x.x`, `192.168.x.x` and the like) and a name only your own network knows (`localhost`, a name ending `.local` or `.internal`, or a name with no dots). The database's firewall must let connections in from anywhere, protected by its password and TLS.
- **TLS, with a certificate from a public certificate authority.** Sanda connects with TLS and checks the certificate, so the password and every row are encrypted on the way and a server pretending to be yours is refused. A database whose certificate comes from a private authority can't be reached yet; most hosted databases use a public one.
- **Someone who can make a user.** Connecting makes a user and a schema for Sanda, which needs the database's owner, or a role that may create roles and grant on the schema.
- **Be an owner or admin in Sanda.** Only owners and admins connect a database and make a push, because a push writes into it on the whole workspace's behalf.

### Connect a database

:::steps
1. **Open Push.** In the console, go to **Data · Streams · Push**.
2. **Start connecting.** Press the **Postgres** card under **Choose a destination**. **Connect a Postgres database** opens under the cards. Once a database is connected, the card opens a new push instead: to connect another, press **Connected accounts** at the right of **Choose a destination**, then **Connect Postgres** in the window it opens.
3. **Say where it is.** Type its **Host** and the **Database** name. Leave **Port** empty for 5432, **Schema** empty for `sanda`, and **User** empty for `sanda_push`, or type the names you want.
4. **Run the setup script.** Under the fields, **Then run this in Postgres, as an administrator** shows a script with your names in it, filling in as you type. Copy it, put a long password of your own in place of `a long password of your own`, and run it in the database.
5. **Type the password.** Type the same password into **Password**.
6. **Check and connect.** Press **Check and connect**. Sanda signs in as the user over TLS, checks the database is the primary and runs version 12 or later, and checks the user can use the schema. Then it keeps the connection, with the password stored encrypted, never shown again in the console or to Sam. You land in a new push with the database chosen.
:::

Connect each database and schema once, however many pushes write to it.

### What the setup script does

The script makes two things, and grants nothing else:

| It makes | What it is for |
|---|---|
| A user, `sanda_push`, that signs in with your password | Reading, adding and updating rows in the schema's tables (including tables made later), and making tables in the schema. It can't delete a row, empty or drop a table, or write to any other schema. |
| A schema, `sanda`, if the database hasn't one by that name | Keeping what Sanda writes apart from the rest of the database. |

Sanda writes to a table you made in the schema yourself only while the user may insert into it and update it. The script's `GRANT … ON ALL TABLES` line covers the tables that are there when you run it, and its `ALTER DEFAULT PRIVILEGES` line the ones you make after. A table made by another role after the script ran needs its own grant.

### If Connect fails

Nothing is kept until the check passes, and the form says what to fix:

| The form says | What to do |
|---|---|
| Postgres didn't accept the password for the user | Run the setup script with your password in it, then type the same password and press **Check and connect** again. |
| The host has no database by that name | Check the **Database** name. Sanda folds a name to lower case, as Postgres does, so type one with capitals in double quotes, such as `"Sales"`. |
| Sanda couldn't reach the host on its port | Check the **Host** and **Port**, and that the database accepts connections from the internet. |
| Sanda couldn't make a verified TLS connection | The database must use TLS with a certificate from a public certificate authority. |
| The database only takes reads, so it is likely a replica | Connect the database's primary. |
| Sanda pushes to Postgres 12 or later | Upgrade the database, or push to another. |
| The database has no schema by that name | Run the script's `CREATE SCHEMA` line, or check the **Schema** name. |
| The user can't use the schema | Run the script's `GRANT` lines. |
| The database and schema are already connected | Each database and schema is connected once. Use the connection you have, or disconnect it first. |

### Disconnect

On Push, press **Connected accounts**, then **Disconnect** beside the database, and confirm. Sanda forgets the password. To end Sanda's access in Postgres too, run `ALTER ROLE sanda_push NOLOGIN`, or drop the role, as the database's owner. The pushes that write to the database stay, and run again once you connect it. Nothing in Postgres changes: the rows pushes already wrote stay in the table.

When Postgres stops accepting the password (you changed it, say), the database's row says **connect again**, and its pushes wait rather than failing. Press **Connect again** beside it, type the same host, database and schema with the new password, and press **Check and connect**: the same connection takes the new password, so every push on it carries on. To point a connection at another schema, connect that schema as a new database.

## Create a push to Postgres

Press **New push** on **Data · Streams · Push**, or the **Postgres** card once a database is connected. The editor asks the same four things as any push (see [create a push](https://docs.sanda-os.com.au/streams/create-a-stream-out)), in Postgres's words.

Under **What it sends**, a new push starts on **A whole table**: a table from your semantic model, one Postgres row for each of its rows, in a table Sanda makes if it isn't there (see [send a whole table](#send-a-whole-table)). **Values onto rows you have** writes chosen metrics and columns into a table you already have, column by column, as the rest of this section describes.

### Where it writes

- **Destination**, on a new push when more than one destination has an account connected: choose **Postgres**.
- **Postgres database**: the database and schema the push writes to.
- **Table**: the table whose rows get the values, from the tables in that schema the user may add rows to.

### How each record is found

- **Postgres column**: the key column, from the table's text and whole-number columns, each marked **key column**. A new push starts on **Choose a key column**.
- **Sanda value that holds it**: a column or a dimension, never a metric, because it says which one row a Sanda row is about.

Postgres compares text with its capitals, so `A1` and `a1` are two rows. A whole number is compared as its digits, so `42` and `42.0` are one row. Two Sanda rows with one key are both refused, because Postgres couldn't tell which to keep: group the push by the key so each has one row.

### What it writes

Under **What it writes**, pick a Postgres column on the left and the value for it on the right, or **A fixed value instead** for one that is the same on every row. Press **Add a column** for each one more. A push writes up to 200 columns.

- The line under each column says its Postgres type, such as `numeric(12,2)` or `timestamp with time zone`, and a column's comment in Postgres shows under it.
- Identity columns Postgres always numbers (`GENERATED ALWAYS AS IDENTITY`), generated columns, columns the user may not update, and types a push can't write (raw bytes and arrays) are listed under **columns Sanda can't write, and why**.
- A column that can't be empty and has no default is needed to add a row. The editor names any the push doesn't write, and saving warns of them again.

Saving checks the mapping against the table as Postgres has it now, and refuses in a sentence anything Postgres would not take, such as a column it no longer has.

## Send a whole table

A whole table sends every column you choose of a table on your semantic map, such as sales by store and day, one Postgres row for each of its rows. It is an ordinary push once it is saved: each run writes only the rows whose values changed.

:::steps
1. **Choose the table.** Under **The table**, pick the **Table** from your semantic map, and the column that is **Different on every row**, such as an order number. Each run finds a Postgres row by it, and adds a row when the table has none.
2. **Choose where it lands.** Under **Into**, **A new table** is chosen. Type the **Table name**, or keep the one Sanda suggests. Postgres keeps it lower case with underscores, such as `sales_by_store`, and the hint under it says the name it will have.
3. **Choose the columns.** Under **Columns**, every column is ticked to start. Each says the Postgres column it becomes and its type, such as `order_total · numeric(12,2)`. Untick any you don't want sent.
4. **Create the table.** Press **Create sales_by_store in Postgres** (it names your table). Sanda makes the table and its columns if the schema hasn't a table of that name, with a comment saying where its rows come from, and the editor moves to **A table Postgres already has**, with the table chosen and every column lined up.
5. **Finish and save.** Choose when it runs and name it, as for any push, and press **Save push**.
:::

If the schema already has a table of that name, the editor says so before you press **Create**, with **Send into it instead**. In **A table Postgres already has**, choose the **Postgres table** and the column it is **Found by**, and each of your columns lines up with the Postgres column whose name reads the same, ignoring case, spaces and underscores. A column with no match isn't sent until you press **Add the missing columns to** the table, which adds a column for each. Only the table's owner can add columns, so this works on tables Sanda made, and on tables you made only if Sanda's user owns them.

Each column keeps its type, or the nearest one Sanda makes:

| In your semantic model | In Postgres |
|---|---|
| Whole numbers | `bigint` |
| Numbers with decimal places, such as `numeric(12,2)` | `numeric` with the same places |
| Other numbers | `numeric`, `real` or `double precision`, as they were |
| Text | `text`, or `varchar` with its length where it has one |
| True or false | `boolean` |
| Dates, times, and dates with times | `date`, `time`, and `timestamp` (or `timestamptz` for a time with a zone) |
| JSON | `json` or `jsonb`, as it was |
| UUIDs | `uuid` |
| Lists and raw bytes | Not sent |

The key column becomes the table's primary key and can't be empty. A key that is neither text nor a whole number, such as a date or a UUID, is kept as text.

### Make the table if it isn't there

Under **How it sends**, **Make the table if it isn't there** is ticked on a new push. When a run finds the table, or a column the push writes, missing, it makes it (`CREATE TABLE IF NOT EXISTS`, then the missing columns) and carries on, once a run. A table made again starts empty, so Sanda forgets which rows it already sent and the next runs send every row again to fill it, and the run's detail says so. Untick it to have a run stop instead, with a sentence saying what is missing.

## How values are written

Every value is written the way its column stores it, before it is compared with what Postgres last accepted. Postgres reads each value with the column's own rules, so a column of a type Sanda has no rule for (an enum, an interval, a type of your own) takes the value as text and Postgres decides whether it fits.

- **Numbers** are rounded to the column's decimal places, so 100.004 and 100.0049 sent to a `numeric(18,2)` column are the same value.
- **Booleans** take yes or no, true or false, or one or zero.
- **Dates** take the value's day in your workspace's [reporting time zone](https://docs.sanda-os.com.au/workspace#reporting-time-zone). **Timestamps** take the instant, in UTC: a `timestamp` column holds the UTC clock reading, and a `timestamptz` column the instant itself.
- **`json` and `jsonb` columns** take JSON. Text that isn't JSON is written as a JSON string.
- **An empty value is written as NULL**, so a metric with nothing to measure doesn't leave last month's number standing.

A value that doesn't fit its column, such as text longer than a `varchar(40)` holds, is refused before anything is sent, and the run lists it.

## How a run sends

A run writes its changed rows in statements of up to 2,000 rows, each in a transaction of its own, and at most 50,000 rows a run. One statement updates the rows whose key the table has and adds the rest. A statement may run for up to 60 seconds before Postgres stops it, and waits at most 10 seconds for a row another session has locked. A run also stops sending after 7 minutes, and the next run carries on: what it leaves is counted as **left for a later run**. Each run's detail says how many Postgres statements it ran.

Writing the same rows twice leaves the table as writing them once, so a statement whose answer never came is simply written again by the next run.

**Send everything again**, on the push, writes every row it reads again over the next runs, including the ones Postgres already has, and releases held rows. Use it when the table was changed by hand. See [send everything again](https://docs.sanda-os.com.au/streams/runs#send-everything-again).

## When a run says why

### Rows Postgres refused

Postgres's own message comes first, because it names the column. Postgres refuses a statement whole without saying which row was at fault, so Sanda splits the statement until it finds the row, and only that row is refused. Sanda adds a hint for the common ones:

| Code | What it means |
|---|---|
| `POSTGRES_22P02` | The column takes a different kind of value, and this one isn't one Postgres reads. |
| `POSTGRES_22003` | The number is larger than the column holds. Widen the column, or round the value in Sanda. |
| `POSTGRES_22001` | The text is longer than the column holds. Widen the column in Postgres. |
| `POSTGRES_22007`, `POSTGRES_22008` | The column takes a date or a time, and the value isn't one Postgres reads, or is outside what it holds. |
| `POSTGRES_23502` | A column that can't be empty got no value. Map a value to it, or give it a default in Postgres. |
| `POSTGRES_23505` | Another row of the table already has this value in a column that must be different on every row. |
| `POSTGRES_23503`, `POSTGRES_23514` | The value points at a row another table hasn't got, or breaks a rule the table checks. |
| `BECCA_TOO_LARGE` | The row's values together are larger than one Postgres statement takes. |
| `BECCA_DUPLICATE` | More than one Sanda row has this key. |

A row Postgres refuses 3 runs in a row for the same value is held. See [held records](https://docs.sanda-os.com.au/streams/runs#held-records).

### A run that stops

A refusal about the push rather than one row stops the run in one sentence, and nothing is held for it:

| The run says | What to do |
|---|---|
| A column this push writes isn't in its table any more | The column was dropped or renamed, and **Make the table if it isn't there** is off, or adding it didn't help. Open the push, change or remove it, and save. |
| Postgres has no table that Sanda's user can reach any more | The table was dropped or renamed and **Make the table if it isn't there** is off, or the user's grant on it was taken away. Run the setup script's grants again, or open the push and choose another table. |
| Postgres didn't let Sanda's user make the table | The user can't make tables in the schema. Run the setup script's `GRANT USAGE, CREATE ON SCHEMA` line, or make the table yourself. |
| Postgres didn't let Sanda's user add columns | Only a table's owner can add a column. Add it in Postgres, or send into a table Sanda made. |
| Postgres no longer lets Sanda's user write to this table | Run the setup script's `GRANT` lines again. |
| Writing one batch took longer than 60 seconds | Add an index on the table's key column, then **Run now**. |
| The database only takes reads | The host now points at a replica. Connect the primary. |
| Postgres no longer accepts the password | The password was changed or the user dropped. The push waits until you press **Connect again** on Push with the new password. |

A database that was busy (a lock held by another session past the wait, a deadlock, a dropped connection) is nobody's failure: the run tries the step again.

:::links
- [Push](https://docs.sanda-os.com.au/streams/out): How every push works, and what counts as a change.
- [Create a push](https://docs.sanda-os.com.au/streams/create-a-stream-out): The editor, the preview and when a push runs.
- [Stream a Postgres database](https://docs.sanda-os.com.au/streams/postgres): Read tables from a Postgres database into your warehouse.
- [Runs](https://docs.sanda-os.com.au/streams/runs): What each run did, and why a row was refused or held.
:::
