Skip to content

SQL queries within docker-entrypoint.sh with custom psqlrc config #901

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
bartelemi opened this issue Oct 23, 2021 · 0 comments · Fixed by #902
Closed

SQL queries within docker-entrypoint.sh with custom psqlrc config #901

bartelemi opened this issue Oct 23, 2021 · 0 comments · Fixed by #902

Comments

@bartelemi
Copy link
Contributor

bartelemi commented Oct 23, 2021

Bug Info

When mounting a custom .psqlrc configuration file with timing enabled, some SQL queries within the docker-entrypoint.sh do not return the expected values, as they are superseded by the timing strings. For instance, it breaks the script that creates the initial database from working correctly.

For more context, I prefer to mount my custom .psqlrc file for local development, to have my common functions and aliases always ready when I need them.

Proposed solution

From my local testing, it would be enough to add --no-psqlrc flag to the query_runner variable in the docker_process_sql function.

Minimal example

.psqlrc

\set QUIET 1
\timing on
\unset QUIET

docker-compose.yml

version: "3.7"
services:
  database:
    build:
      context: .
    environment:
      POSTGRES_DB: sample
      POSTGRES_PASSWORD: postgres
    ports:
    - 5432:5432
    volumes:
    # Mount psql config file in the system configuration directory.
    - ./.psqlrc:/etc/postgresql-common/psqlrc:ro

I also have a following Dockerfile:

FROM postgres

COPY docker-entrypoint.sh /usr/local/bin/

with custom docker-entrypoint.sh where I modified the function to print extra debug info:

docker_setup_db() {
    local dbAlreadyExists
    dbAlreadyExists="$(
        POSTGRES_DB= docker_process_sql --dbname postgres --set db="$POSTGRES_DB" --tuples-only <<-'EOSQL'
	    SELECT 1 FROM pg_database WHERE datname = :'db' ;
        EOSQL
    )"
    echo "Exists: $dbAlreadyExists"
    if [ -z "$dbAlreadyExists" ]; then
	POSTGRES_DB= docker_process_sql --dbname postgres --set db="$POSTGRES_DB" <<-'EOSQL'
	    CREATE DATABASE :"db" ;
	EOSQL
	echo
    else
        echo "DB already exists"
    fi
}

Log

Building and running the above code with docker compose up will yield following log:

database_1 | 2021-10-23 20:37:19.438 UTC [49] LOG: database system is ready to accept connections
database_1 | done
database_1 | server started
database_1 | Exists:
database_1 | Time: 2.633 ms
database_1 | DB already exists

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant