diff --git a/README.md b/README.md index a5cc1f5..43c9702 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). -_1622 TILs and counting..._ +_1623 TILs and counting..._ See some of the other learning resources I work on: - [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators) @@ -230,6 +230,7 @@ If you've learned something here, support my efforts writing daily TILs by - [List Running Docker Containers](docker/list-running-docker-containers.md) - [Prevent Containers From Running On Startup](docker/prevent-containers-from-running-on-startup.md) - [Run A Basic PostgreSQL Server In Docker](docker/run-a-basic-postgresql-server-in-docker.md) +- [Run SQL Script Against Postgres Container](docker/run-sql-script-against-postgres-container.md) ### Drizzle diff --git a/docker/run-sql-script-against-postgres-container.md b/docker/run-sql-script-against-postgres-container.md new file mode 100644 index 0000000..acd8a43 --- /dev/null +++ b/docker/run-sql-script-against-postgres-container.md @@ -0,0 +1,42 @@ +# Run SQL Script Against Postgres Container + +I've been using dockerized Postgres for local development with several projects +lately. This is typically with framework tooling (like Rails) where schema +migrations and query execution are handled by the tooling using the specified +connection parameters. + +However, I was experimenting with and iterating on some Postgres functions +outside of any framework tooling. I needed a way to run the SQL script that +(re)creates the function via `psql` on the docker container. + +With a local, non-containerized Postgres instance, I'd redirect the file to +`psql` like so: + +```bash +$ psql -U postgres -d postgres < experimental-functions.sql +``` + +When I tried doing this with `docker exec` though, it was silently failing / +doing nothing. As far as I can tell, there was a mismatch with redirection +handling across the bounds of the container. + +To get around this, I first copy the file into the `/tmp` directory on the +container: + +```bash +$ docker cp experimental-functions.sql still-postgres-1:/tmp/experimental-functions.sql +``` + +Then the `psql` command that docker executes can be pointed directly at a +local-to-it SQL file. + +```bash +$ docker exec still-postgres-1 psql \ + -U postgres \ + -d postgres \ + -f /tmp/experimental-functions.sql +``` + +There are probably other ways to handle this, but I got into a nice rhythm with +this file full of `create or replace function ...` definitions where I could +modify, copy over, execute, run some SQL to verify, and repeat.