From 902ef36976019d6a828abf12d636d6e1e774578e Mon Sep 17 00:00:00 2001 From: vipg Date: Fri, 26 Dec 2025 17:06:47 +0800 Subject: [PATCH] add --- create/README.md | 223 ++++++++++++++++++++++--- create/create.sh | 2 +- create/create_src_dockerfile.py | 0 infra/postgres/sql/03_create_table.sql | 56 +++++++ 4 files changed, 261 insertions(+), 20 deletions(-) create mode 100644 create/create_src_dockerfile.py diff --git a/create/README.md b/create/README.md index f52b5c5..78f9652 100644 --- a/create/README.md +++ b/create/README.md @@ -1,21 +1,206 @@ +代码一: + +```python +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +create_src.py - 在services目录下创建服务文件夹和文件结构 +""" + +import os +import sys + +def create_service_structure(table_name): + """创建服务文件夹结构""" + + # 获取项目根目录 + project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + services_dir = os.path.join(project_root, 'services') + + # 创建服务目录 + service_dir = os.path.join(services_dir, table_name) + + print(f"🚀 开始创建服务结构: {table_name}") + print(f"📁 目标目录: {service_dir}") + + try: + # 创建主目录 + os.makedirs(service_dir, exist_ok=True) + print(f"✅ 创建主目录: {service_dir}") + + # 创建子目录 + subdirs = ['src', 'src/crud', 'src/infra', 'src/model'] + for subdir in subdirs: + dir_path = os.path.join(service_dir, subdir) + os.makedirs(dir_path, exist_ok=True) + print(f"✅ 创建子目录: {dir_path}") + + # 定义要创建的文件列表 + files_to_create = [ + 'dev.sh', + 'README.md', + 'src/Dockerfile', + 'src/go.mod', + 'src/go.sum', + 'src/main.go', + 'src/crud/create.go', + 'src/crud/read.go', + 'src/crud/update.go', + 'src/crud/delete.go', + 'src/infra/launch.go', + 'src/infra/logger.go', + 'src/infra/postgres.go', + 'src/model/payload.go' + ] + + # 创建所有文件 + for file_path in files_to_create: + full_path = os.path.join(service_dir, file_path) + os.makedirs(os.path.dirname(full_path), exist_ok=True) # 确保目录存在 + + # 创建空文件 + with open(full_path, 'w', encoding='utf-8') as f: + f.write('') # 创建空文件 + + print(f"✅ 创建文件: {full_path}") + + print(f"🎉 服务结构创建完成: {table_name}") + return True + + except Exception as e: + print(f"❌ 创建服务结构时出错: {e}") + return False + +if __name__ == "__main__": + # 从环境变量获取表名 + table_name = os.environ.get('TABLE_NAME') + + if not table_name: + print("❌ 错误: 未设置 TABLE_NAME 环境变量") + sys.exit(1) + + print(f"📋 接收到的表名: {table_name}") + success = create_service_structure(table_name) + + if success: + sys.exit(0) + else: + sys.exit(1) ``` -TableName -├── dev.sh -├── README.md -└── src - ├── crud - │   └── create.go - │   └── read.go - │   └── update.go - │   └── delete.go - ├── Dockerfile - ├── go.mod - ├── go.sum - ├── infra - │   ├── launch.go - │   ├── logger.go - │   └── postgres.go - ├── main.go - └── model - └── payload.go + + + +代码二: + +```python +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +create.py - 动态生成PostgreSQL建表SQL语句 +""" + +import os +import re + +# 1. 从环境变量获取表名,如果没有设置则使用默认值 +table_name = os.environ.get('TABLE_NAME', 'records') + +# 2. 定义SQL模板 +sql_template = f"""DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.tables + WHERE table_schema = 'public' + AND table_name = '{table_name}' + ) THEN + CREATE TABLE {table_name} ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, -- id + payload JSONB NOT NULL, -- 数据 + deleted BOOLEAN NOT NULL DEFAULT FALSE, -- 删除状态 + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, -- 记录创建时间 + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP -- 记录修改时间 + ); + + -- 3 触发器:自动刷新 updated_at + CREATE TRIGGER trg_{table_name}_at + BEFORE UPDATE ON {table_name} + FOR EACH ROW + EXECUTE FUNCTION moddatetime(updated_at); + + RAISE NOTICE '{table_name} 表已创建'; + ELSE + RAISE NOTICE '{table_name} 表已存在,跳过'; + END IF; +END $$;""" + +def normalize_blank_lines(text): + """规范化空行:确保END $$;和DO $$之间只有一个空行""" + # 将多个空行替换为单个空行 + text = re.sub(r'\n{3,}', '\n\n', text) + + # 确保END $$;后面有一个空行再接DO $$ + text = re.sub(r'END \$\$;(\s*)DO \$\$', r'END $$;\n\nDO $$', text) + + # 清理开头和结尾的多余空行 + text = text.strip() + '\n' + + return text + +def update_sql_file(): + """将生成的SQL语句追加到03_create_table.sql文件中""" + + # 定义文件路径 + sql_file_path = os.path.join( + os.path.dirname(os.path.dirname(__file__)), + 'infra', + 'postgres', + 'sql', + '03_create_table.sql' + ) + + try: + # 读取现有文件内容 + with open(sql_file_path, 'r', encoding='utf-8') as f: + content = f.read() + + # 查找插入位置(在\"部署完成\"日志前) + insert_pattern = r'(DO \$\$.*?RAISE NOTICE \'🚀============ 数据库表部署开始 ============🚀\'.*?END \$\$;)(.*?)(DO \$\$.*?RAISE NOTICE \'✅============ 数据库表部署完成 ============✅\'.*?END \$\$;)' + + match = re.search(insert_pattern, content, re.DOTALL) + + if match: + # 分割内容 + before_insert = match.group(1) + existing_middle = match.group(2) + after_insert = match.group(3) + + # 规范化空行 + existing_middle = normalize_blank_lines(existing_middle) + + # 组合新内容 + new_content = f"""{before_insert}\n\n{sql_template}\n\n{existing_middle}\n{after_insert}""" + + # 规范化整个内容的空行 + new_content = normalize_blank_lines(new_content) + + # 写回文件 + with open(sql_file_path, 'w', encoding='utf-8') as f: + f.write(new_content) + + print(f"✅ 成功更新 {sql_file_path}") + print(f"📋 生成的表名: {table_name}") + print(f"📝 SQL内容已追加到文件中") + + else: + print("❌ 无法找到插入位置,请检查文件格式") + + except FileNotFoundError: + print(f"❌ 文件 {sql_file_path} 不存在") + except Exception as e: + print(f"❌ 处理文件时出错: {e}") + +if __name__ == "__main__": + print(f"🚀 开始生成表 '{table_name}' 的SQL语句...") + update_sql_file() ``` \ No newline at end of file diff --git a/create/create.sh b/create/create.sh index 1836741..b1be94e 100644 --- a/create/create.sh +++ b/create/create.sh @@ -4,7 +4,7 @@ set -e # 遇到错误立即退出 # 定义表名变量,可以根据需要修改 -TABLE_NAME="cn_pmi_234_aaarecords" +TABLE_NAME="cn_pmi_records1" echo "🚀 开始创建流程,表名: ${TABLE_NAME}" echo "==========================================" diff --git a/create/create_src_dockerfile.py b/create/create_src_dockerfile.py new file mode 100644 index 0000000..e69de29 diff --git a/infra/postgres/sql/03_create_table.sql b/infra/postgres/sql/03_create_table.sql index 8ac4b5e..1b0d24c 100644 --- a/infra/postgres/sql/03_create_table.sql +++ b/infra/postgres/sql/03_create_table.sql @@ -3,6 +3,62 @@ BEGIN RAISE NOTICE '🚀============ 数据库表部署开始 ============🚀'; END $$; +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.tables + WHERE table_schema = 'public' + AND table_name = 'cn_pmi_records1' + ) THEN + CREATE TABLE cn_pmi_records1 ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, -- id + payload JSONB NOT NULL, -- 数据 + deleted BOOLEAN NOT NULL DEFAULT FALSE, -- 删除状态 + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, -- 记录创建时间 + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP -- 记录修改时间 + ); + + -- 3 触发器:自动刷新 updated_at + CREATE TRIGGER trg_cn_pmi_records1_at + BEFORE UPDATE ON cn_pmi_records1 + FOR EACH ROW + EXECUTE FUNCTION moddatetime(updated_at); + + RAISE NOTICE 'cn_pmi_records1 表已创建'; + ELSE + RAISE NOTICE 'cn_pmi_records1 表已存在,跳过'; + END IF; +END $$; + +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.tables + WHERE table_schema = 'public' + AND table_name = 'cn_pmi_records' + ) THEN + CREATE TABLE cn_pmi_records ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, -- id + payload JSONB NOT NULL, -- 数据 + deleted BOOLEAN NOT NULL DEFAULT FALSE, -- 删除状态 + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, -- 记录创建时间 + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP -- 记录修改时间 + ); + + -- 3 触发器:自动刷新 updated_at + CREATE TRIGGER trg_cn_pmi_records_at + BEFORE UPDATE ON cn_pmi_records + FOR EACH ROW + EXECUTE FUNCTION moddatetime(updated_at); + + RAISE NOTICE 'cn_pmi_records 表已创建'; + ELSE + RAISE NOTICE 'cn_pmi_records 表已存在,跳过'; + END IF; +END $$; + DO $$ BEGIN RAISE NOTICE '✅============ 数据库表部署完成 ============✅';