首页 > 解决方案 > 如何使用 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

dbservice namecompose 中的 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 部分呢?

如果您能告诉我为什么会发生此错误以及如何解决,我将不胜感激?

标签: bashpostgresqlshelldockerdockerfile

解决方案


我似乎已经通过将base imagefrom更改ubuntu16.04ubuntu 18.04. 但我不知道是什么原因造成的。


推荐阅读