Fork of github.com/did-method-plc/did-method-plc
1# pg
2
3Helpers for working with postgres
4
5## Usage
6
7### `with-test-db.sh`
8
9This script allows you to run any command with a fresh, ephemeral/single-use postgres database available. When the script starts a Dockerized postgres container starts-up, and when the script completes that container is removed.
10
11The environment variable `DATABASE_URL` will be set with a connection string that can be used to connect to the database. The [`PG*` environment variables](https://www.postgresql.org/docs/current/libpq-envars.html) that are recognized by libpq (i.e. used by the `psql` client) are also set.
12
13**Example**
14
15```
16$ ./with-test-db.sh psql -c 'select 1;'
17[+] Running 1/1
18 ⠿ Container pg-db_test-1 Healthy 1.8s
19
20 ?column?
21----------
22 1
23(1 row)
24
25
26[+] Running 1/1
27 ⠿ Container pg-db_test-1 Stopped 0.1s
28Going to remove pg-db_test-1
29[+] Running 1/0
30 ⠿ Container pg-db_test-1 Removed
31```
32
33### `docker-compose.yaml`
34
35The Docker compose file can be used to run containerized versions of postgres either for single use (as is used by `with-test-db.sh`), or for longer-term use. These are setup as separate services named `test_db` and `db` respectively. In both cases the database is available on the host machine's `localhost` and credentials are:
36
37- Username: pg
38- Password: password
39
40However, each service uses a different port, documented below, to avoid conflicts.
41
42#### `test_db` service for single use
43
44The single-use `test_db` service does not have any persistent storage. When the container is removed, data in the database disappears with it.
45
46This service runs on port `5433`.
47
48```
49$ docker compose up test_db # start container
50$ docker compose stop test_db # stop container
51$ docker compose rm test_db # remove container
52```
53
54#### `db` service for persistent use
55
56The `db` service has persistent storage on the host machine managed by Docker under a volume named `pg_plc_db`. When the container is removed, data in the database will remain on the host machine. In order to start fresh, you would need to remove the volume.
57
58This service runs on port `5432`.
59
60```
61$ docker compose up db -d # start container
62$ docker compose stop db # stop container
63$ docker compose rm db # remove container
64$ docker volume rm pg_plc_db # remove volume
65```