Zero2Prod: Day 3 – Setup database and sqlx

Database clients

Threads are for working in parallel, async is for waiting in parallel.

CrateQuery interfaceCompile-time safetyAsync
tokio-postgresSQLNoYes
sqlxSQLYesYes
dieselDSLYesNo

Docker

Setup run scripts

#!/bin/bash
set -eo pipefail

run-start-docker() {
    docker compose up -d
}

# -------- this is the magic ------- #
source "$PROJECT_ROOT/scripts/_cli.sh"

docker-compose.yml

services:
  postgres:
    image: postgres
    container_name: newsletter-db
    environment:
      POSTGRES_USER: "${DB_USER:?}"
      POSTGRES_PASSWORD: "${DB_PASSWORD:?}"
      POSTGRES_DB: "${DB_NAME:?}"
    ports:
      - "${DB_PORT}:5432"
    volumes:
      - newsletter-db-data:/var/lib/postgresql/data
    command: ["postgres", "-N", "1000"]
    # ^ Increased maximum number of connections for testing purposes

volumes:
  newsletter-db-data:

.env

DB_USER=postgres
DB_PASSWORD=magic
DB_NAME=newsletter
DB_PORT=5432

.envrc

export  PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
export RELATIVE_PATH=$(git rev-parse --show-prefix   2>/dev/null)

source .env
export DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@localhost:${DB_PORT}/${DB_NAME}

PATH_add "$PWD"

sqlx

Install sqlx crate

add sqlx --features=runtime-tokio-rustls,macros,postgres,uuid,chrono,migrate
  • runtime-tokio-rustls tells sqlx to use the tokio runtime for its futures and rustls as TLS backend
  • macros gives us access to sqlx::query! and sqlx::query_as!, which we will be using exten- sively
  • postgres unlocks Postgres-specific functionality (e.g. non-standard SQL types)
  • uuid adds support for mapping SQL UUIDs to the Uuid type from the uuid crate. We need it to work with our id column
  • chrono adds support for mapping SQL timestamptz to the DateTime<T> type from the chrono crate. We need it to work with our subscribed_at column
  • migrate gives us access to the same functions used under the hood by sqlx-cli to manage migrations. It will turn out to be useful for our test suite

Using the cli

sqlx database create
sqlx migrate add create_subscription_table

config crate

It supports multiple file formats and it supports combining different sources hierarchically (e.g. environment variables, con-figuration files, etc.)

Author

I'm Oliver Nguyen. A software maker working mostly in Go and JavaScript. I enjoy learning and seeing a better version of myself each day. Occasionally spin off new open source projects. Share knowledge and thoughts during my journey. Connect with me on , , , and .

Back Back