gpt4 book ai didi

postgresql - 如何将环境变量传递到 .sql 文件中?

转载 作者:行者123 更新时间:2023-11-29 13:40:11 33 4
gpt4 key购买 nike

我在 Dockerfile 中设置环境变量,我想在 .sql 文件中引用它。该文件位于 /docker-entrypoint-initdb.d 中,因为 initdb 将运行它。

如何传递环境变量? (例如 SELECT * FROM $myEnvironmentVariableHere;)

最佳答案

有几种方法可以做到这一点,但最简单的可能是使用带有 HEREDOC 的简单 shell 脚本:

这是脚本,在 scripts/test.sh 中调用

#!/bin/bash

psql << EOF
SELECT * FROM $MYVAR LIMIT 1;
EOF

运行方法如下:

docker run --rm  --name test_pg -v $PWD/scripts:/docker-entrypoint-initdb.d -e "MYVAR=pg_class" postgres:latest

在各种启动消息中,您会看到以下几行:

/usr/local/bin/docker-entrypoint.sh: sourcing /docker-entrypoint-initdb.d/test.sh
relname | relnamespace | reltype | reloftype | relowner | relam | relfilenode | reltablespace | relpages | reltuples | relallvisible | reltoastrelid | relhasindex | relisshared | relpersistence | relkind | relnatts | relchecks | relhasoids | relhasrules | relhastriggers | relhassubclass | relrowsecurity | relforcerowsecurity | relispopulated | relreplident | relispartition | relrewrite | relfrozenxid | relminmxid | relacl | reloptions | relpartbound
--------------+--------------+---------+-----------+----------+-------+-------------+---------------+----------+-----------+---------------+---------------+-------------+-------------+----------------+---------+----------+-----------+------------+-------------+----------------+----------------+----------------+---------------------+----------------+--------------+----------------+------------+--------------+------------+-----------------------------+------------+--------------
pg_statistic | 11 | 11319 | 0 | 10 | 0 | 2619 | 0 | 16 | 398 | 16 | 2840 | t | f | p | r | 26 | 0 | f | f | f | f | f | f | t | n | f | 0 | 562 | 1 | {postgres=arwdDxt/postgres} | |
(1 row)

关于postgresql - 如何将环境变量传递到 .sql 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56772235/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com