色々やるけど、database について。

基本的に、簡単な SQL 文は調べられていると便利だし、新しく始める場合は Postgres を使っておけば OK。

PostgreSQL

Basic

ECS とかやってると、簡単に table 追加することができるので、逆にその場で SQL いじることが多くなる気がする。

ユーザーを作るところまでやれば、アプリに hand over 出来るので、それをやるのに psql は以下,

# create a user
# that can make a database
# you might need to do -U postgres
createuser test_cli_user -d

# create database
createdb -U test_cli_user test_cli_db

psql -U test_cli_user test_cli_db
$ \du
$ \?
$ \d

# delete a database
dropdb -U test_cli_user test_cli_db

dropuser test_cli_user

Backup & Restore

pg_dump -U postgres -h localhost -F c -b -v -f mydb.backup mydb
pg_restore -U postgres -h localhost -d new_db -v mydb.backup

怖いので、

createdb -U postgres new_db

してすぐ上の pg_restore しちゃう。

でも普通に SQL 文を psql 中に保存したければ、

\COPY (SELECT id, name, email FROM users WHERE active = true) TO '/home/user/active_users.csv' WITH CSV HEADER;

でも、これなら、 *.sql を作っておけばいいような気もする。

そのほかめも

ALTER TABLE XXX DROP CONSTRAINT yyy

Golang

go get github.com/jmoiron/sqlx
go get github.com/lib/pq
package main

import (
    "fmt"

    "github.com/jmoiron/sqlx"
    _ "github.com/lib/pq"
)

func main() {
    _, err := sqlx.Connect("postgres", "user=test_cli_user dbname=test_cli_db sslmode=disable")

    if err != nil {
        fmt.Printf("%s", err)
    }
}

sqlc をすごく試してみたい

Rust

So far using the sqlx library seems to be a reasonable option. It is not a ORM, yet covers essential functionality to make your life easier. (like migration)

cli

  • ENV VARS
    DATABASE_URL=postgres://user:password@localhost:port/db_name
    

migration

sqlx migrate add add_meta

を ’0002addmeta.sql’ というファイルが保存されるので、

alter table todos add column meta JSONB;

Date: 2023-11-24 Fri 07:01