59 lines
1.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# PostgreSQL 初始化脚本说明
## 目录说明
`./postgresql/init/` 目录下的脚本会在 PostgreSQL 容器**首次启动**时自动执行。
## 执行规则
1. **仅执行一次**:只有当数据目录为空时才会执行
2. **执行顺序**:按文件名字母顺序执行
3. **支持格式**
- `.sh` - Shell 脚本
- `.sql` - SQL 脚本
- `.sql.gz` - 压缩的 SQL 脚本
## 用户说明
### postgres 用户
- **默认超级用户**,总是存在,无法删除
- 拥有所有权限
- 用于数据库管理操作
### iotmanage 用户
- **应用程序用户**,通过初始化脚本创建
- 拥有指定数据库的权限
- 用于应用程序连接
## 文件命名建议
建议使用数字前缀来确保执行顺序:
- `01-create-user.sql` - 创建用户
- `02-create-schema.sql` - 创建 schema
- `03-create-tables.sql` - 创建表结构
- `04-insert-data.sql` - 插入初始数据
## 注意事项
1. 如果数据目录已有数据,这些脚本**不会再次执行**
2. 如果需要重新初始化,需要删除数据目录:`rm -rf ./postgresql/data/*`
3. 脚本中的密码建议使用环境变量,不要硬编码
4. 确保脚本具有幂等性(可以安全地重复执行)
## 示例:使用环境变量
```sql
-- 从环境变量读取密码(需要在脚本中处理)
CREATE USER iotmanage WITH PASSWORD :'IOTMANAGE_PASSWORD';
```
## 验证用户
```bash
# 查看所有用户
docker exec -it postgres psql -U postgres -c "\du"
# 测试 iotmanage 用户连接
docker exec -it postgres psql -U iotmanage -d jisheiotprodb -c "SELECT current_user;"
```