bash - 如何使用 shell 脚本判断 postgres 数据库表是否存在
问题描述
我需要使用入口点来确定数据库是否可用以及表是否存在。
我使用以下shell来确定表是否存在
部分dockerfile内容
ENTRYPOINT ["bash","docker-entrypoint.sh"]
Shell 脚本内容
until PGPASSWORD=postgres psql -h "db" -U "postgres" -c '\q'; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
# Prepare variables
TABLE=web_user
SQL_EXISTS=$(printf '\dt "%s"' "$TABLE")
# Credentials
USERNAME=postgres
PASSWORD=postgres
DATABASE=postgres
echo "Checking if table <$TABLE> exists ..."
# Check if table exists
PGPASSWORD="$PASSWORD" psql -h "db" -U $USERNAME -d $DATABASE -c "$SQL_EXISTS"
# using #!/bin/bash
if [[ $(PGPASSWORD="$PASSWORD" psql -h "db" -U $USERNAME -d $DATABASE -c "$SQL_EXISTS") ]]
then
echo "Table exists ..."
else
echo "Table not exists ..., init database"
python3 manage.py makemigrations web
python3 manage.py migrate
fi
db
是service name
compose 中的 postgres 容器的
我要的是容器第一次启动,确定用户表不存在,然后create a new database
,再重启容器发现用户表已经存在without creating a new data table
但是当我在 Ubuntu16.04 基础镜像上使用它时,它只是table exists...
在容器第一次启动时输出
psql: FATAL: the database system is starting up
Postgres is unavailable - sleeping
Checking if table <web_user> exists ...
No matching relations found.
Table exists ...
但我期望的是打印table not exists..., the init database
和后续命令
使用python alpine
基础镜像的输出如下
Checking if table <web_user> exists ...
Did not find any relation named ""web_user"".
Table not exists ..., init database
Migrations for 'web':
区别如下:
No matching relations found.
是基于输出的ubuntu image
,
Did not find any relation named ""web_user"".
基于输出的python:3.6.9-alpine image
为什么不是 else 部分呢?
如果您能告诉我为什么会发生此错误以及如何解决,我将不胜感激?
解决方案
我似乎已经通过将base image
from更改ubuntu16.04
为ubuntu 18.04
. 但我不知道是什么原因造成的。
推荐阅读
- java - android中的链式LiveData转换
- r - 定位和减少线标签
- javascript - 从 React Native 中的 blob 获取图像尺寸
- angular - 在 Angular 的 CanActivate 路由保护中读取 cookie
- python - 如何将具有多个 python 脚本和图像的 pygame 程序转换为 exe?
- solidity - node_modules 中缺少开放的 zeppelin 合约
- html - CSS 未按预期出现或运行
- c++ - 如何使用命令提示符、记事本和 MinGW 编译带有主文件、头文件和实现文件的 C++ 程序?
- apostrophe-cms - 撇号 CMS 和富文本
- ajax - 在 google sheet 中实现 Ajax 实时搜索以输入数据