在 Docker 中如何执行 Postgresql 的 init.sql 脚本?
时间:2024-03-07
浏览:389
作者:佚名
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《在 Docker 中如何执行 Postgresql 的 init.sql 脚本?》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
问题内容
我正在尝试运行 docker 和 postgresql。为此,我有这样一个 docker-compose。
version: '3'
services:
postgres:
image: postgres:12
restart: always
networks:
- backend
ports:
- '5432:5432'
volumes:
- ./db_data:/var/lib/postgresql/data
- ./app/config/init.sql:/docker-entrypoint-initdb.d/create_tables.sql
env_file:
- ./app/config/.env
healthcheck:
test: [ "cmd", "pg_isready", "-q", "-d", "devdb", "-u", "postgres" ]
timeout: 45s
interval: 10s
retries: 10
app:
build: app
ports:
- 3200:3200
networks:
- backend
depends_on:
postgres:
condition: service_healthy
volumes:
db_data:
networks:
backend:
driver: bridge
现在我正在创建一个 init.sql 文件:
app/config/init.sql
create table todos(
id serial primary key not null,
title varchar not null,
description varchar not null,
creating_time timestamp
);
我使用 pgx 驱动程序与 postgresql 通信:
insertQuery string = `INSERT INTO todos(title, description, creating_time) VALUES($1, $2, $3)`
dbUrl := fmt.Sprintf("postgres://%s:%s@%s:5432/%s", connInfo.User, connInfo.Password, connInfo.Host, connInfo.DBName)
db, errDB := pgxpool.Connect(context.Background(), dbUrl)
if errDB != nil {
fmt.Println(errDB)
}
conn, err := db.Acquire(context.Background())
if err != nil {
fmt.Errorf("Unable to acquire a database connection: %v\n", err)
}
defer conn.Release()
datetime := time.Now()
dt := datetime.Format(time.RFC3339)
_, err = db.Exec(context.Background(), insertQuery, "todo.Title", "todo.Description", dt)
if err != nil {
fmt.Println(err)
}
当容器启动时,一切都很顺利,直到执行请求为止。
然后我收到错误 关系“todos”在字符 13 处不存在
我以前从未这样做过,所以我无法弄清楚出了什么问题。与数据库的连接正常,因为它没有发出错误,但由于某种原因,创建表的脚本没有执行.我很乐意帮助您解决这个问题。
正确答案
最近怎么样?
您配置的此入口点仅在不存在任何配置的数据库时才起作用。正如您所看到的 here。此入口点的主要目标是配置要使用的数据库,一旦完成,再次执行就没有意义。
我给你的建议是使用这个lib。使用它非常简单。如果您愿意,我可以分享一些例子。
如果这对您有帮助,请告诉我。
今天关于《在 Docker 中如何执行 Postgresql 的 init.sql 脚本?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
