Skip to content

Commit

Permalink
Merge pull request keystonejs#1404 from keystonejs/molomby/knex-reset…
Browse files Browse the repository at this point in the history
…-db-script

Adding a helper script to build/rebuild the KS test Postgres DB
  • Loading branch information
molomby authored Jul 17, 2019
2 parents a21c3ce + cf7103d commit 35f6741
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/adapter-knex/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ At present, the only fully tested backend is `Postgres`, however Knex gives the
## Setting Up Your Database

Before running Keystone, you must set up a database, a schema, and a user.
Assuming you're on MacOS and have Postgres installed the `build-test-db.sh` does this for you:

```sh
./packages/adapter-knex/build-test-db.sh
```

Otherwise, you can run the steps manually:

```shell
createdb -U postgres ks5_dev
Expand Down
49 changes: 49 additions & 0 deletions packages/adapter-knex/build-test-db.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#!/usr/bin/env bash

# Create or recreate and setup the Keystone test Postgres DB from scratch
# Will distroy any existing data, etc.
# When Keystone starts the knex adapter will recreate the structure

KS_DB_NAME="ks5_dev"
KS_SCHEMA_NAME="keystone"
KS_USER_NAME="keystone5"
KS_USER_PASS="k3yst0n3"

# On MacOS the super use is the current username, no password
SUPER_USER="${USER}"

# Our queries
DROP_CONNECTIONS_SQL="
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = '${KS_DB_NAME}'
AND pid <> pg_backend_pid();
"
DROP_DB_SQL="
DROP DATABASE IF EXISTS \"${KS_DB_NAME}\";
"
CREATE_DB_SQL="
CREATE DATABASE \"${KS_DB_NAME}\";
"
RECREATE_ROLE_SQL="
DROP USER IF EXISTS \"${KS_USER_NAME}\";
CREATE USER \"${KS_USER_NAME}\" PASSWORD '${KS_USER_PASS}';
"
SETUP_SCHEMA="
CREATE SCHEMA \"${KS_SCHEMA_NAME}\";
GRANT ALL ON SCHEMA \"${KS_SCHEMA_NAME}\" TO \"${KS_USER_NAME}\";
"
# Needed for `gen_random_uuid()` function, used by UUIDs
SETUP_UUIDS="
CREATE EXTENSION IF NOT EXISTS \"pgcrypto\";
"

# Run outside the KS DB (in template1)
psql template1 -U "${SUPER_USER}" -c "${DROP_CONNECTIONS_SQL}"
psql template1 -U "${SUPER_USER}" -c "${DROP_DB_SQL}"
psql template1 -U "${SUPER_USER}" -c "${CREATE_DB_SQL}"
psql template1 -U "${SUPER_USER}" -c "${RECREATE_ROLE_SQL}"

# Run in the new DB
psql "${KS_DB_NAME}" -U "${SUPER_USER}" -c "${SETUP_SCHEMA}"
psql "${KS_DB_NAME}" -U "${SUPER_USER}" -c "${SETUP_UUIDS}"

0 comments on commit 35f6741

Please sign in to comment.