From 06b0db1209af6f3de9dbfc775c9523ec981c8403 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 3 Nov 2022 19:57:02 -0500 Subject: [PATCH] Add Check If User Role Exists For Database as a Postgres TIL --- README.md | 3 +- .../check-if-user-role-exists-for-database.md | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 postgres/check-if-user-role-exists-for-database.md diff --git a/README.md b/README.md index 8334347..8c53022 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1262 TILs and counting..._ +_1263 TILs and counting..._ --- @@ -588,6 +588,7 @@ _1262 TILs and counting..._ - [Capitalize All The Words](postgres/capitalize-all-the-words.md) - [Change The Current Directory For psql](postgres/change-the-current-directory-for-psql.md) - [Check If The Local Server Is Running](postgres/check-if-the-local-server-is-running.md) +- [Check If User Role Exists For Database](postgres/check-if-user-role-exists-for-database.md) - [Check Table For Any Oprhaned Records](postgres/check-table-for-any-orphaned-records.md) - [Checking Inequality](postgres/checking-inequality.md) - [Checking The Type Of A Value](postgres/checking-the-type-of-a-value.md) diff --git a/postgres/check-if-user-role-exists-for-database.md b/postgres/check-if-user-role-exists-for-database.md new file mode 100644 index 0000000..2ff3679 --- /dev/null +++ b/postgres/check-if-user-role-exists-for-database.md @@ -0,0 +1,33 @@ +# Check If User Role Exists For Database + +User roles define who can access a database cluster and broadly what level of +control they have over that cluster. + +The most straightforward way to check if a user role exists is to connect to +one of the databases in the cluster and run a query against the `pg_roles` +table. + +```sql +select * from pg_roles where rolename='dev'; + + rolname +------------ + dev +(1 row) +``` + +This same concept can be used in a script when automating some database setup. +To do that, we'll use `-c` (and some other flags) to dispatch a query to `psql` +from a shell context. + +```bash +psql postgres -tXAc "SELECT 1 FROM pg_roles WHERE rolname='dev'" \ + | grep -q 1 \ + || createuser --interactive dev +``` + +This queries for the value `1` if the user role named `dev` exists. The output +of that is piped to `grep` (in quiet mode, `-q`) to check if `1` is in the +output. If user roles doesn't exist and grep doesn't match on `1`, then the +right side of the _or_ (`||`) gets called. That command could be whatever. I've +chosen to call PostgreSQL's `createuser` to create the `dev` user role.