Alexander Yurchenko

PostgreSQL, models, and migrations in Laravel Rust

Created
Updated
Author
Alexander Yurchenko

At the end of the lesson on shared state, the GET and POST routes share one TicketStore. The preview route formats a title without writing a record. Restarting the process brings the list back to its two initial tickets. Keep the same project and move storage into PostgreSQL.

Set up a dedicated database

You need Bash, curl, jq, and local PostgreSQL 18 server tools. From the root of your lesson 08 project, create scripts/ and save this file as scripts/ticket-db.sh. Run the commands as an unprivileged user. The example uses Linux. Set PG_BIN to the actual PostgreSQL 18 binary directory if your installation uses a different path.

The script has three phases. init starts the cluster, provision and migrate prepare the database, and inspect, serve, and stop work with the cluster you selected.

The cluster only accepts connections through a Unix socket in a directory with mode 0700. PostgreSQL's peer method checks the operating system user against a local role map. This example needs no passwords. Your OS user can choose a role in this cluster, so the role split limits the application's privileges and gives no separation between people.

BASH
#!/usr/bin/env bash
set -euo pipefail

[[ $(id -u) != 0 && $(id -un) =~ ^[a-zA-Z_][a-zA-Z_0-9-]*$ ]]
: "${PG_BIN:?Set PG_BIN to the PostgreSQL 18 bin directory}"
: "${TICKET_LAB:?Set TICKET_LAB to the private cluster directory}"

# Check the path and owner so the script cannot operate on another cluster.
lab=$TICKET_LAB
[[ $lab =~ ^/tmp/ticket-lab\.[a-zA-Z0-9]{8}$ && $lab == "$(realpath -e -- "$lab")" ]]
[[ -O $lab && $(stat -c %a -- "$lab") == 700 ]]
socket=$lab/socket
port=55439
binary=${CARGO_TARGET_DIR:-target}/debug/laravel-rust-skeleton

pg() {
  local tool=$1
  shift
  env -i HOME="$lab" PATH=/usr/bin:/bin LC_ALL=C "$PG_BIN/$tool" "$@"
}

# A clean environment and explicit Unix socket prevent PG* variables from redirecting the connection.
sql() {
  local role=$1 database=$2
  shift 2
  env -i HOME="$lab" PATH=/usr/bin:/bin LC_ALL=C PGCONNECT_TIMEOUT=3 \
    PGOPTIONS='-c search_path=ticket_data -c statement_timeout=3000 -c lock_timeout=2000' \
    "$PG_BIN/psql" -X -w -v ON_ERROR_STOP=1 -At \
    -h "$socket" -p "$port" -U "$role" -d "$database" "$@"
}

verify() {
  local role=$1 database=$2 schema=$3 actual
  [[ -O $socket && $(stat -c %a -- "$socket") == 700 && -S $socket/.s.PGSQL.$port && -O $socket/.s.PGSQL.$port ]]
  # For setup and shutdown, verify the server’s own data directory.
  if [[ $role == ya_cluster_admin ]]; then
    actual=$(sql "$role" "$database" -c "
      SELECT current_database(), current_user, session_user, current_setting('port'),
             current_setting('unix_socket_directories'), inet_server_addr() IS NULL,
             current_setting('data_directory'), current_setting('listen_addresses'),
             (SELECT rolsuper FROM pg_roles WHERE rolname = current_user)")
    [[ $actual == "$database|$role|$role|$port|$socket|t|$lab/data||t" ]]
    return
  fi
  actual=$(sql "$role" "$database" -c "
    SELECT current_database(), current_user, session_user, current_setting('port'),
           inet_server_addr() IS NULL,
           (SELECT pg_get_userbyid(datdba) FROM pg_database WHERE datname=current_database()),
           COALESCE(current_schema()::text, ''),
           (SELECT NOT (rolsuper OR rolcreatedb OR rolcreaterole OR rolbypassrls)
            FROM pg_roles WHERE rolname=current_user)")
  [[ $actual == "$database|$role|$role|$port|t|ticket_owner|$schema|t" ]]
  # The schema owner can run migrations, while the API role gets only the privileges it needs.
  if [[ $schema == ticket_data ]]; then
    actual=$(sql "$role" "$database" -c "
      SELECT pg_get_userbyid(nspowner),
             has_schema_privilege(current_user, oid, 'USAGE'),
             has_schema_privilege(current_user, oid, 'CREATE')
      FROM pg_namespace WHERE nspname='ticket_data'")
    if [[ $role == ticket_owner ]]; then
      [[ $actual == 'ticket_owner|t|t' ]]
    else
      [[ $actual == 'ticket_owner|t|f' ]]
      actual=$(sql "$role" "$database" -c "
        SELECT pg_get_userbyid(relowner),
               has_table_privilege(current_user, oid, 'SELECT'),
               has_table_privilege(current_user, oid, 'DELETE'),
               has_column_privilege(current_user, oid, 'title', 'INSERT'),
               has_column_privilege(current_user, oid, 'title', 'UPDATE'),
               has_column_privilege(current_user, oid, 'slot', 'INSERT'),
               has_column_privilege(current_user, oid, 'status', 'UPDATE'),
               NOT has_column_privilege(current_user, oid, 'id', 'INSERT,UPDATE'),
               NOT has_column_privilege(current_user, oid, 'slot', 'UPDATE'),
               NOT has_column_privilege(current_user, oid, 'status', 'INSERT'),
               NOT has_database_privilege(current_user, current_database(), 'TEMP')
        FROM pg_class WHERE oid='ticket_data.tickets'::regclass")
      [[ $actual == 'ticket_owner|t|t|t|t|t|t|t|t|t|t' ]]
    fi
  fi
}

run_app() {
  local role=$1 database=$2
  shift 2
  exec env -i HOME="$lab" PATH=/usr/bin:/bin APP_ENV=local APP_DEBUG=false \
    TICKET_SOCKET="$socket" TICKET_DATABASE="$database" TICKET_ROLE="$role" \
    "$(realpath -e -- "$binary")" "$@"
}

if [[ ${BASH_SOURCE[0]} != "$0" ]]; then
  return
fi

case "${1:-}" in
  init)
    [[ ! -e $lab/data && ! -e $socket ]]
    umask 077
    mkdir "$socket"
    pg initdb -D "$lab/data" -U ya_cluster_admin --auth-local=peer \
      --auth-host=reject --encoding=UTF8 --no-instructions
    cat > "$lab/data/pg_hba.conf" <<'HBA'
local postgres ya_cluster_admin peer map=tickets
local ticket_demo,ticket_test ticket_owner,ticket_api peer map=tickets
HBA
    os_user=$(id -un)
    printf 'tickets %s %s\n' "$os_user" ya_cluster_admin \
      "$os_user" ticket_owner "$os_user" ticket_api > "$lab/data/pg_ident.conf"
    pg pg_ctl -D "$lab/data" -l "$lab/postgres.log" -w -t 10 \
      -o "-h '' -k $socket -p $port -c unix_socket_permissions=0700" start
    verify ya_cluster_admin postgres ''
    sql ya_cluster_admin postgres -c 'CREATE ROLE ticket_owner LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE'
    sql ya_cluster_admin postgres -c 'CREATE ROLE ticket_api LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE'
    ;;
  provision|migrate|inspect|serve)
    database=${2:-ticket_demo}
    [[ $database == ticket_demo || $database == ticket_test ]]
    case "$1" in
      provision)
        verify ya_cluster_admin postgres ''
        sql ya_cluster_admin postgres -c "CREATE DATABASE $database OWNER ticket_owner"
        verify ticket_owner "$database" ''
        sql ticket_owner "$database" -c "REVOKE ALL ON DATABASE $database FROM PUBLIC"
        sql ticket_owner "$database" -c "GRANT CONNECT ON DATABASE $database TO ticket_api"
        sql ticket_owner "$database" -c 'CREATE SCHEMA ticket_data AUTHORIZATION ticket_owner'
        verify ticket_owner "$database" ticket_data
        sql ticket_owner "$database" -c 'GRANT USAGE ON SCHEMA ticket_data TO ticket_api'
        ;;
      migrate)
        verify ticket_owner "$database" ticket_data
        run_app ticket_owner "$database" migrate
        ;;
      inspect)
        verify ticket_api "$database" ticket_data
        sql ticket_api "$database" -c "
          SELECT conname, pg_get_constraintdef(oid) FROM pg_constraint
          WHERE conrelid='ticket_data.tickets'::regclass ORDER BY conname"
        sql ticket_api "$database" -c 'SELECT id, title, status FROM tickets ORDER BY id'
        ;;
      serve)
        # The server does not start if database identity or privileges differ.
        verify ticket_api "$database" ticket_data
        http_port=${3:-18080}
        [[ $http_port == 0 || ( $http_port =~ ^[0-9]{1,5}$ && 10#$http_port -ge 1024 && 10#$http_port -le 65535 ) ]]
        run_app ticket_api "$database" serve --host=127.0.0.1 --port="$http_port"
        ;;
    esac
    ;;
  stop)
    verify ya_cluster_admin postgres ''
    pg pg_ctl -D "$lab/data" -m fast -w -t 10 stop
    ;;
  *)
    exit 2
    ;;
esac

Before a write, the script connects through the specified private socket and checks the port, database, current role, and session role. For migrations it checks schema ownership and the right to create objects. Before starting the server it also checks privileges on the ticket table and verifies the role cannot create objects in the schema. ya_cluster_admin provisions the new cluster and databases. ticket_owner runs migrations, and the HTTP server uses ticket_api.

Configure PostgreSQL in the application

Save the Cargo.lock for the data lessons as Cargo.lock in the demo project root. It uses the same resolved dependencies as lesson 08. The Cargo.toml manifest already pins laravel-rust = "=0.1.4" with the database-postgres feature enabled. Keep the manifest as it is. Commands with --locked use the versions in the file. If you have not fetched the dependencies yet, run cargo fetch --locked before building offline.

Replace src/config/database.rs. This section defines the connection for Laravel Rust's database manager. The manager reuses the pool, and each handler receives it through Inject<DatabaseManager>. The script supplies the connection settings in a clean environment. Keep the existing local key and application settings in your .env. This connection ignores DATABASE_URL. If the required settings are missing, the section registers no fallback connection.

RUST
use std::env;

use laravel::config::database::{ConnectionConfig, Database};
use laravel::config::{self, Env};
use laravel::db::sqlx::postgres::{PgConnectOptions, PgSslMode};
use laravel::time::ToSpan;

#[config::section]
fn database(_: &Env) -> Database {
    let mut database = Database::default();
    // Incomplete configuration must not select a fallback connection.
    let (Ok(socket), Ok(name), Ok(role)) = (
        env::var("TICKET_SOCKET"),
        env::var("TICKET_DATABASE"),
        env::var("TICKET_ROLE"),
    ) else {
        return database;
    };

    if !socket.starts_with('/')
        || !matches!(name.as_str(), "ticket_demo" | "ticket_test")
        || !matches!(role.as_str(), "ticket_owner" | "ticket_api")
        || env::vars_os().any(|(key, _)| key.to_string_lossy().starts_with("PG"))
    {
        return database;
    }

    // The Unix socket needs no network address. Timeouts bound statement and lock waits.
    let options = PgConnectOptions::new_without_pgpass()
        .socket(socket)
        .port(55439)
        .database(&name)
        .username(&role)
        .ssl_mode(PgSslMode::Disable)
        .options([
            ("search_path", "ticket_data"),
            ("statement_timeout", "3000"),
            ("lock_timeout", "2000"),
            ("default_transaction_isolation", "read committed"),
        ]);

    // A small pool caps connection use, and acquiring a connection also has a timeout.
    database.add_connection(
        "postgres",
        ConnectionConfig::postgres(options)
            .max_connections(4)
            .acquire_timeout(3.seconds()),
    );
    database
}

Replace src/app.rs. Keep route and migration registration in configure. The database configuration selects the connection, so there is no longer an in-memory store to register.

RUST
use laravel::foundation::ApplicationBuilder;
use laravel::{Application, inertia, model};

use crate::http::middleware::{HandleInertiaRequests, example_middleware};
use crate::models::User;
use crate::routes;

pub fn configure() -> ApplicationBuilder {
    Application::configure()
        .with_migrations(laravel::db::migrations!("database/migrations"))
        .with_schema(laravel::db::schema!("database/schema"))
        .with_auth(|auth, _| {
            auth.session::<model::Users<User>>();
        })
        .with_routing(|routing, _| {
            routing
                .web(routes::web::routes)
                .api(routes::api::routes)
                .channels(routes::channels::routes)
                .health("/up");
        })
        .with_middleware(|middleware, _| {
            middleware.web(|web| {
                web.append(inertia::middleware(HandleInertiaRequests))
                    .append(example_middleware);
            });
        })
}

pub fn create() -> Application {
    configure().create()
}

The skeleton allows any CORS origin on api/*. Replace src/config/cors.rs with an empty list of CORS paths. You'll call the tutorial API from a local terminal.

RUST
use laravel::config;
use laravel::config::cors::Cors;

#[config::section]
fn cors() -> Cors {
    // Local terminal requests need no browser CORS permissions.
    Cors {
        paths: Vec::new(),
        ..Cors::default()
    }
}

Define the schema and the ticket model

Add database/migrations/0001_01_01_000003_create_tickets_table.rs. Laravel Rust embeds the migration files at build time, so rebuild after adding the file. A migration function that takes &mut AnyTransaction runs on PostgreSQL in the same transaction as its migration record. Here that groups the table, the two synthetic records, and the grants. The &AnyConnection signature opts out of that transaction.

RUST
use laravel::db::{self, AnyTransaction};

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    // The explicit Unicode White_Space list matches how Rust trim() treats the ends of a string.
    db::query!(
        tx,
        r"CREATE TABLE tickets (
            id bigint GENERATED ALWAYS AS IDENTITY (MAXVALUE 4294967295) PRIMARY KEY,
            title text NOT NULL,
            status text NOT NULL DEFAULT 'open',
            slot integer NOT NULL UNIQUE,
            CONSTRAINT tickets_positive_id CHECK (id BETWEEN 1 AND 4294967295),
            CONSTRAINT tickets_slot_range CHECK (slot BETWEEN 1 AND 32),
            CONSTRAINT tickets_status CHECK (status IN ('open', 'closed')),
            CONSTRAINT tickets_title CHECK (
                char_length(title) BETWEEN 1 AND 120 AND
                title = btrim(title, U&'\0009\000a\000b\000c\000d\0020\0085\00a0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200a\2028\2029\202f\205f\3000')
            )
        )"
    )
    .statement()
    .await?;

    // Seed and grant in the same transaction so the migration takes effect as a whole.
    db::query!(
        tx,
        "INSERT INTO tickets (slot, title, status) VALUES
         (1, 'Reset password', 'open'), (2, 'Update invoice', 'closed')"
    )
    .insert()
    .await?;

    db::query!(
        tx,
        "GRANT SELECT, INSERT (title, slot), UPDATE (title, status), DELETE ON tickets TO ticket_api"
    )
    .statement()
    .await?;

    Ok(())
}

The positive id fits the route's u32 range. PostgreSQL stores it as bigint, which Rust can read as i64 without loss. The title column accepts 1–120 Unicode scalar values and checks for the same surrounding whitespace that Rust's trim removes. PostgreSQL text cannot hold NUL, so the application checks for it before writing. The preview retains its earlier validation because it never touches the database.

The PostgreSQL literal U&'…' uses hexadecimal escapes for the 25 Unicode White_Space characters. Plain btrim(title) removes only the ordinary space, so it would leave a nonbreaking space at the edge, for example. The explicit list matches Rust’s trim(). In these examples, Rust \0 and JSON \u0000 represent NUL, while Rust \u{00a0} represents a nonbreaking space.

Replace src/routes/api/store.rs. The migration defines the schema and constraints, and Ticket describes one query result row. The native db::FromRow derive maps columns to fields by name. This mapping does not use the ORM’s #[model] attribute. Serialize keeps the response at three fields. Parameterized db::query! lets us specify the lock, choose a slot within capacity, and return the stored row with RETURNING. In the next lesson, the same mechanism performs a partial update in one atomic statement.

RUST
use laravel::db::{self, AnyConnection};
use laravel::{Result, abort};
use serde::Serialize;

#[derive(db::FromRow, Serialize)]
pub(super) struct Ticket {
    id: i64,
    title: String,
    status: String,
}

impl Ticket {
    // Bound parameters travel separately from the SQL, so user input cannot become query syntax.
    pub(super) async fn list(db: &AnyConnection, status: Option<&str>) -> Result<Vec<Self>> {
        db::query!(
            db,
            "SELECT id, title, status FROM tickets
             WHERE ({status}::text IS NULL OR status = {status})
             ORDER BY id LIMIT 32"
        )
        .select_as()
        .await
    }

    pub(super) async fn get(db: &AnyConnection, id: i64) -> Result<Option<Self>> {
        db::query!(db, "SELECT id, title, status FROM tickets WHERE id = {id}")
            .select_one_as()
            .await
    }

    pub(super) async fn insert(db: &AnyConnection, title: &str) -> Result<Option<Self>> {
        // The lock serializes slot allocation and is released when the transaction ends.
        db.transaction(async |tx| {
            db::query!(tx, "SELECT pg_advisory_xact_lock(128991, 1)")
                .statement()
                .await?;
            // At READ COMMITTED this statement sees the insert committed before the lock was acquired.
            // Slots can be reused, while a separate sequence assigns each ID.
            db::query!(
                tx,
                "INSERT INTO tickets (slot, title)
                 SELECT n, {title} FROM generate_series(1, 32) AS slots(n)
                 WHERE NOT EXISTS (SELECT 1 FROM tickets WHERE slot = n)
                 ORDER BY n LIMIT 1
                 RETURNING id, title, status"
            )
            .insert_returning_as()
            .await
        })
        .await
    }
}

pub(super) fn database_error(_: laravel::Error) -> laravel::Error {
    // Keep database error details out of the client response.
    abort(500)
}

There are 32 internal slots, including the two starting tickets. Each slot is unique and must fall between 1 and 32, which rules out a 33rd row. A transaction-level advisory lock lets concurrent creates choose a free slot in turn. At READ COMMITTED, the statement after acquiring the lock sees the previously committed insert. A deleted ticket frees its slot. IDs come from a separate sequence, and gaps are normal.

Replace src/routes/api.rs. The paths and filter stay the same. Creation passes only the title. The database supplies the initial status and ID. A full table returns 409 and a database failure returns a safe 500. A zero ID still returns 400, while a well-formed ID for a missing ticket returns 404.

RUST
mod store;

use store::{Ticket, database_error};

use laravel::container::Inject;
use laravel::db::DatabaseManager;
use laravel::http::middleware::LimitBody;
use laravel::http::{Created, Json, Query};
use laravel::routing::{Params, Router};
use laravel::validation::{InvalidInput, Validate};
use laravel::{Result, abort_with};
use serde::{Deserialize, Serialize};
use serde_json::json;

pub fn routes(route: &mut Router) {
    route.get("/version", async || Json(json!({ "laravel": laravel::VERSION })));
    route.get("/tickets", index);
    route.get("/tickets/{id}", show);
    route
        .post("/tickets", create)
        .middleware(LimitBody::bytes(TICKET_BODY_LIMIT));
    route
        .post("/tickets/preview", preview)
        .middleware(LimitBody::bytes(TICKET_BODY_LIMIT));
}

#[laravel::query]
struct TicketQuery {
    // Keep an unknown nonempty value available for an explicit 400.
    status: Option<String>,
}

impl TicketQuery {
    fn filter(&self) -> Result<Option<&str>> {
        match self.status.as_deref() {
            None => Ok(None),
            Some(status @ ("open" | "closed")) => Ok(Some(status)),
            Some(_) => Err(abort_with(400, "Status must be open or closed.")),
        }
    }
}

async fn index(db: Inject<DatabaseManager>, Query(query): Query<TicketQuery>) -> Result<Json<Vec<Ticket>>> {
    let status = query.filter()?;
    let db = db.default_connection().map_err(database_error)?;
    Ok(Json(Ticket::list(&db, status).await.map_err(database_error)?))
}

async fn show(db: Inject<DatabaseManager>, Params(id): Params<u32>) -> Result<Json<Ticket>> {
    positive_id(id)?;
    let db = db.default_connection().map_err(database_error)?;
    // Handle the query error before checking for a missing row, so a database failure cannot become a 404.
    let ticket = Ticket::get(&db, i64::from(id))
        .await
        .map_err(database_error)?
        .ok_or_else(|| abort_with(404, "Ticket not found."))?;
    Ok(Json(ticket))
}

async fn create(db: Inject<DatabaseManager>, Json(input): Json<CreateTicket>) -> Result<Created<Ticket>> {
    let title = input.validated_title()?;
    // PostgreSQL text cannot store NUL. The preview does not use the database.
    if title.contains('\0') {
        return Err(InvalidInput::new()
            .with("title", "The title must not contain NUL.")
            .into());
    }
    let db = db.default_connection().map_err(database_error)?;
    // Only a successful query that returns no row means the store is full.
    let ticket = Ticket::insert(&db, &title)
        .await
        .map_err(database_error)?
        .ok_or_else(|| abort_with(409, "Ticket store is full."))?;
    Ok(Created(ticket))
}

fn positive_id(id: u32) -> Result<()> {
    if id == 0 {
        return Err(abort_with(400, "Ticket ID must be positive."));
    }
    Ok(())
}

const TICKET_BODY_LIMIT: usize = 4096;
const MAX_TITLE_LENGTH: usize = 120;

#[derive(Deserialize, Validate)]
struct CreateTicket {
    title: String,
}

#[derive(Serialize)]
struct TicketPreview {
    title: String,
}

async fn preview(Json(input): Json<CreateTicket>) -> Result<Json<TicketPreview>> {
    Ok(Json(TicketPreview {
        title: input.validated_title()?,
    }))
}

impl CreateTicket {
    fn validated_title(&self) -> Result<String> {
        let title = self.title.trim();
        let problem = if title.is_empty() {
            "Enter a ticket title."
        } else if title.chars().count() > MAX_TITLE_LENGTH {
            "The title must have at most 120 Unicode scalar values."
        } else {
            return Ok(title.to_owned());
        };
        Err(InvalidInput::new().with("title", problem).into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ticket_zero_fails_the_domain_check() {
        assert!(positive_id(1).is_ok());
        assert_eq!(positive_id(0).expect_err("zero").status(), 400);
    }

    #[test]
    fn title_validation_counts_trimmed_unicode_scalars() {
        let title = "🦀".repeat(120);
        let valid = CreateTicket {
            title: format!("  {title}  "),
        };
        assert_eq!(valid.validated_title().expect("120 scalars"), title);
        let invalid = CreateTicket {
            title: format!("{title}🦀"),
        };
        assert_eq!(invalid.validated_title().expect_err("121 scalars").status(), 422);
        let blank = CreateTicket {
            title: "\u{00a0}\t".into(),
        };
        assert_eq!(blank.validated_title().expect_err("blank").status(), 422);
    }
}

Apply the migrations and restart the server

Build from the project root. The inspection shows the constraints and two initial tickets. Keep TICKET_LAB in this terminal so the next command runs against the same cluster.

BASH
export CARGO_TARGET_DIR="$PWD/target"
export CARGO_BUILD_BUILD_DIR="$CARGO_TARGET_DIR/build"
export CARGO_INCREMENTAL=0
cargo build --locked --offline

BASH
export PG_BIN=/usr/lib/postgresql/18/bin
TICKET_LAB=$(mktemp -d /tmp/ticket-lab.XXXXXXXX)
export TICKET_LAB
bash scripts/ticket-db.sh init &&
  bash scripts/ticket-db.sh provision ticket_demo &&
  bash scripts/ticket-db.sh migrate ticket_demo &&
  bash scripts/ticket-db.sh inspect ticket_demo

Start the application in the first terminal. PostgreSQL in this cluster has a local Unix socket only, and HTTP binds to 127.0.0.1:18080. If the port is in use, choose a free unprivileged port and change it here and in the HTTP commands.

BASH
bash scripts/ticket-db.sh serve ticket_demo 18080

In a second terminal, check the existing filter and create a ticket. Use jq to save the ID from the response for the next request.

In ticket and the standalone request below, -q comes first so curl skips the default configuration file, such as .curlrc.

BASH
base=http://127.0.0.1:18080/api/tickets
ticket() {
  curl -q -fsS --noproxy '*' --max-time 8 -H 'Accept: application/json' "$@"
}
ticket "$base?status=open" | jq -e 'length == 1 and .[0].status == "open"'
created=$(ticket -H 'Content-Type: application/json' \
  --data '{"title":"  Paper jam  "}' "$base")
printf '%s\n' "$created" | jq -e '.title == "Paper jam" and .status == "open"'
id=$(jq -er '.id' <<< "$created")

Press Ctrl+C in the first terminal and run the same serve command again. In the second terminal, read the ticket by its saved ID. The database stays running during the application restart.

BASH
ticket "$base/$id" | jq -e --argjson id "$id" \
  '. == {id: $id, title: "Paper jam", status: "open"}'

Try a rejected request in the second terminal. The response is 422 with errors.title. Then press Ctrl+C in the first terminal, where PG_BIN and TICKET_LAB are still set. Run bash scripts/ticket-db.sh inspect ticket_demo there and confirm that there are still three tickets. Leave the cluster running. In the next lesson you will run serve against the same database.

BASH
curl -q -isS --noproxy '*' --max-time 8 -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  --data '{"title":"a\u0000b"}' "$base"

HTTP
HTTP/1.1 422 Unprocessable Entity
content-type: application/json

{"message":"The title must not contain NUL.","errors":{"title":["The title must not contain NUL."]}}

Summary

The same routes now keep records across restarts. The migration defines valid table state, and the model describes the rows the application reads. In the lesson on ticket CRUD, you'll add updates and deletes.

References