init_db.py
2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# -*- coding: utf-8 -*-
"""
文件名: app/db/init_db.py
职责: 数据库初始化脚本,读取 .env 配置并执行 sql/init_all_tables.sql。
注意: 不要删除这个注释。
"""
import os
import sys
import pymysql
from pymysql.constants import CLIENT
# 确保可以导入 app 模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
from app.core.config import settings
def init_db():
print(f"[*] Connecting to {settings.DB_HOST}:{settings.DB_PORT} as {settings.DB_USER}...")
# 1. 连接数据库 (不指定 DB_NAME,因为脚本里有 CREATE DATABASE IF NOT EXISTS)
try:
conn = pymysql.connect(
host=settings.DB_HOST,
port=settings.DB_PORT,
user=settings.DB_USER,
password=settings.DB_PASSWORD,
charset='utf8mb4',
client_flag=CLIENT.MULTI_STATEMENTS, # 允许一次执行多条 SQL
autocommit=True
)
with conn.cursor() as cursor:
# 2. 读取 SQL 脚本
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
sql_file = os.path.join(base_dir, "sql/init_all_tables.sql")
if not os.path.exists(sql_file):
print(f"[X] SQL file not found: {sql_file}")
return
print(f"[*] Reading SQL script from {sql_file}...")
with open(sql_file, "r", encoding="utf-8") as f:
sql_script = f.read()
# 3. 执行全量脚本
print(f"[*] Executing all DDL statements...")
cursor.execute(sql_script)
# 4. 初始化同步元数据 (如果需要的话,脚本里其实已经包含了 _sync_meta 的创建)
# 这里可以额外插入一些初始数据
sync_meta_init = """
INSERT IGNORE INTO `_sync_meta` (source_table, target_table, sync_mode) VALUES
('ods_staff_daily_report_huawei', 'dws_staff_daily_wide', 'incremental'),
('ods_goods_order', 'dws_order_detail_wide', 'incremental');
"""
cursor.execute(sync_meta_init)
conn.close()
print("[+] Database initialization completed successfully!")
except Exception as e:
print(f"[X] Database initialization failed: {e}")
if __name__ == "__main__":
init_db()