Blame view

sql/tools/convertor.py 39.3 KB
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
1
2
3
4
5
6
  # encoding=utf8
  """芋道系统数据库迁移工具
  
  Author: dhb52 (https://gitee.com/dhb52)
  
  pip install simple-ddl-parser
4401c703   dhb52   feat: 增加 UNIQUE K...
7
8
  
  or with uv
e302dfd5   DevDengChao   chore: update sho...
9
10
11
12
  uv run --with simple-ddl-parser convertor.py postgres ../mysql/ruoyi-vue-pro.sql > ../postgresql/ruoyi-vue-pro.sql
  uv run --with simple-ddl-parser convertor.py sqlserver ../mysql/ruoyi-vue-pro.sql > ../sqlserver/ruoyi-vue-pro.sql
  uv run --with simple-ddl-parser convertor.py kingbase ../mysql/ruoyi-vue-pro.sql > ../kingbase/ruoyi-vue-pro.sql
  uv run --with simple-ddl-parser convertor.py opengauss ../mysql/ruoyi-vue-pro.sql > ../opengauss/ruoyi-vue-pro.sql
61d312d2   YunaiV   feat: 支持瀚高数据库 Pos...
13
  uv run --with simple-ddl-parser convertor.py highgo ../mysql/ruoyi-vue-pro.sql > ../highgo/ruoyi-vue-pro.sql
e302dfd5   DevDengChao   chore: update sho...
14
15
  uv run --with simple-ddl-parser convertor.py oracle ../mysql/ruoyi-vue-pro.sql > ../oracle/ruoyi-vue-pro.sql
  uv run --with simple-ddl-parser convertor.py dm8 ../mysql/ruoyi-vue-pro.sql > ../dm/ruoyi-vue-pro-dm8.sql
00680ddc   YunaiV   feat(sql): 增加 Oce...
16
  uv run --with simple-ddl-parser convertor.py oceanbase ../mysql/ruoyi-vue-pro.sql > ../oceanbase/ruoyi-vue-pro.sql
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
17
18
  """
  
6d19690b   dhb52   feat: 脚本兼容Python ...
19
  import argparse
04515204   YunaiV   fix(oracle): 修复初始...
20
  import hashlib
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
21
22
  import pathlib
  import re
57add7b6   dhb52   feat: sql/tools ...
23
  import sys
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
24
25
  import time
  from abc import ABC, abstractmethod
848d4948   YunaiV   fix(sql): 修复建表语句扫...
26
  from typing import Dict, Generator, List, Optional, Tuple, Union
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
27
28
29
  
  from simple_ddl_parser import DDLParser
  
9335b7a0   DevDengChao   fix: gbk codec
30
31
32
  # 避免 Windows 系统使用默认的 GBK 编码
  sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf-8', buffering=1)
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
33
34
35
36
37
38
39
40
41
42
43
44
45
  PREAMBLE = """/*
   Yudao Database Transfer Tool
  
   Source Server Type    : MySQL
  
   Target Server Type    : {db_type}
  
   Date: {date}
  */
  
  """
  
  
848d4948   YunaiV   fix(sql): 修复建表语句扫...
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
  # 依次匹配:引号字符串(支持反斜杠转义、双写引号)、注释、语句分隔符;未闭合的引号吞掉剩余内容
  SQL_TOKEN_PATTERN = re.compile(
      r"'(?:\\[\s\S]|''|[^'\\])*'"
      r'|"(?:\\[\s\S]|""|[^"\\])*"'
      r"|`(?:``|[^`])*`"
      r"|--(?=\s|\Z)[^\n]*|#[^\n]*|/\*[\s\S]*?(?:\*/|\Z)"
      r"|['\"`][\s\S]*"
      r"|;"
  )
  # 语句开头的空白、注释
  SQL_LEADING_PATTERN = re.compile(r"(?:\s|--(?=\s|\Z)[^\n]*|#[^\n]*|/\*[\s\S]*?(?:\*/|\Z))*")
  CREATE_TABLE_PATTERN = re.compile(r"CREATE\s+TABLE\s", flags=re.IGNORECASE)
  
  
  def split_statements(content: str) -> List[str]:
      """按分号拆分 SQL 语句,忽略引号、注释内的分号
  
      仅用于定位顶层语句,不是完整的 SQL 解析器。返回的语句保留原文,去掉开头的空白、注释,以分号结尾
  
      Args:
          content (str): sql 内容
  
      Returns:
          List[str]: 语句列表
      """
      statements = []
      start = 0
      for match in SQL_TOKEN_PATTERN.finditer(content):
          if match.group() != ";":
              continue
          statement = content[start:match.end()]
          start = match.end()
          statement = statement[SQL_LEADING_PATTERN.match(statement).end():]
          if statement != ";":
              statements.append(statement)
      return statements
  
  
  def table_scripts(content: str) -> List[str]:
      """获得真实的 CREATE TABLE 语句,不包括 INSERT 数据、注释中的建表文本
  
      相关 issue:https://github.com/YunaiV/ruoyi-vue-pro/issues/1273
      """
      return [statement for statement in split_statements(content) if CREATE_TABLE_PATTERN.match(statement)]
  
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
92
93
94
95
96
97
98
99
100
  def load_and_clean(sql_file: str) -> str:
      """加载源 SQL 文件,并清理内容方便下一步 ddl 解析
  
      Args:
          sql_file (str): sql文件路径
  
      Returns:
          str: 清理后的sql文件内容
      """
848d4948   YunaiV   fix(sql): 修复建表语句扫...
101
102
103
104
105
106
107
108
109
110
111
112
113
      # utf-8-sig:只去掉文件开头的 BOM,避免首条语句无法识别
      return clean(open(sql_file, encoding="utf-8-sig").read())
  
  
  def clean(content: str) -> str:
      """清理 SQL 内容方便下一步 ddl 解析
  
      Args:
          content (str): sql 内容
  
      Returns:
          str: 清理后的sql内容
      """
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
114
      REPLACE_PAIR_LIST = (
4401c703   dhb52   feat: 增加 UNIQUE K...
115
          (")\nVALUES ", ") VALUES "),
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
116
          (" CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ", " "),
30c4be14   YunaiV   fix:【framework】co...
117
          (" CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ", " "),
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
118
119
120
121
122
123
          (" KEY `", " INDEX `"),
          ("UNIQUE INDEX", "UNIQUE KEY"),
          ("b'0'", "'0'"),
          ("b'1'", "'1'"),
      )
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
124
125
      for replace_pair in REPLACE_PAIR_LIST:
          content = content.replace(*replace_pair)
c0d991f8   LuJiaQi   fix(sql):修复conver...
126
127
128
129
      # 移除所有 CHARACTER SET / COLLATE 变体 (utf8mb3、utf8 等)
      content = re.sub(r" CHARACTER SET \w+ COLLATE \w+", "", content)
      content = re.sub(r" CHARACTER SET \w+", "", content)
      content = re.sub(r" COLLATE \w+", "", content)
30c4be14   YunaiV   fix:【framework】co...
130
131
132
133
134
      # 移除索引字段的前缀长度定义,例如: `name`(32) -> `name`
      # 移除索引定义上的 USING BTREE COMMENT 部分
      # 相关 issue:https://t.zsxq.com/96IFc 、https://t.zsxq.com/rC3A3
      content = re.sub(r'`([^`]+)`\(\d+\)', r'`\1`', content)
      content = re.sub(r'\s+USING\s+BTREE\s+COMMENT\s+\'[^\']+\'', '', content)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
135
136
137
138
139
140
      content = re.sub(r"ENGINE.*COMMENT", "COMMENT", content)
      content = re.sub(r"ENGINE.*;", ";", content)
      return content
  
  
  class Convertor(ABC):
af9b6253   YunaiV   fix(sql): 修复 conv...
141
142
143
      # 不同数据库的关键字不完全一致;子类按需声明需要转义的列名。
      reserved_column_names = set()
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
144
145
146
147
      def __init__(self, src: str, db_type) -> None:
          self.src = src
          self.db_type = db_type
          self.content = load_and_clean(self.src)
c0d991f8   LuJiaQi   fix(sql):修复conver...
148
          # original_content 保留原始 COMMENT 信息,用于注释提取
848d4948   YunaiV   fix(sql): 修复建表语句扫...
149
150
151
152
153
154
155
156
          self.original_content = open(src, encoding="utf-8-sig").read()
          # 在原始内容上扫描建表语句,避免全局清理破坏引号边界;每个建表语句再单独清理
          self.original_table_script_list = table_scripts(self.original_content)
          # 剥离列级 COMMENT,交给 DDLParser 解析
          self.table_script_list = [
              re.sub(r" COMMENT '(?:[^'\\]|\\.)*'", "", clean(table_sql))
              for table_sql in self.original_table_script_list
          ]
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
157
158
  
      @abstractmethod
6d19690b   dhb52   feat: 脚本兼容Python ...
159
      def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]) -> str:
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
160
161
162
163
          """字段类型转换
  
          Args:
              type (str): 字段类型
6d19690b   dhb52   feat: 脚本兼容Python ...
164
              size (Optional[Union[int, Tuple[int]]]): 字段长度描述, 如varchar(255), decimal(10,2)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
  
          Returns:
              str: 类型定义
          """
          pass
  
      @abstractmethod
      def gen_create(self, table_ddl: Dict) -> str:
          """生成 create 脚本
  
          Args:
              table_ddl (Dict): 表DDL
  
          Returns:
              str:  生成脚本
          """
          pass
  
      @abstractmethod
      def gen_pk(self, table_name: str) -> str:
          """生成主键定义
  
          Args:
              table_name (str): 表名
  
          Returns:
              str: 生成脚本
          """
          pass
  
      @abstractmethod
6d19690b   dhb52   feat: 脚本兼容Python ...
196
      def gen_index(self, ddl: Dict) -> str:
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
197
198
199
200
201
202
203
204
205
206
207
          """生成索引定义
  
          Args:
              table_ddl (Dict): 表DDL
  
          Returns:
              str: 生成脚本
          """
          pass
  
      @abstractmethod
4401c703   dhb52   feat: 增加 UNIQUE K...
208
      def gen_comment(self, table_ddl: Dict) -> str:
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
209
210
211
          """生成字段/表注释
  
          Args:
4401c703   dhb52   feat: 增加 UNIQUE K...
212
              table_ddl (Dict): 表DDL
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
213
214
215
216
217
218
219
  
          Returns:
              str: 生成脚本
          """
          pass
  
      @abstractmethod
4401c703   dhb52   feat: 增加 UNIQUE K...
220
221
222
223
224
225
226
227
228
229
230
      def gen_uk(self, table_ddl: Dict) -> str:
          """生成
  
          Args:
              table_ddl (Dict): 表DDL
  
          Returns:
              str: 生成脚本
          """
  
      @abstractmethod
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
231
232
233
234
235
236
237
238
239
240
241
      def gen_insert(self, table_name: str) -> str:
          """生成 insert 语句块
  
          Args:
              table_name (str): 表名
  
          Returns:
              str: 生成脚本
          """
          pass
  
65651fb1   dhb52   feat: 创建虚拟dual表,达...
242
243
244
245
246
247
248
249
      def gen_dual(self) -> str:
          """生成虚拟 dual 表
  
          Returns:
              str: 生成脚本, 默认返回空脚本, 表示当前数据库无需手工创建
          """
          return ""
  
af9b6253   YunaiV   fix(sql): 修复 conv...
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
      def escape_column_name(self, name: str) -> str:
          """转义目标库保留字列名,例如 Oracle / Kingbase 的 level。"""
  
          column_name = name.lower()
          if column_name in self.reserved_column_names:
              return f'"{column_name}"'
          return column_name
  
      def escape_insert_columns(self, insert_script: str) -> str:
          """INSERT 显式列清单需要和 CREATE / COMMENT 使用同一套列名转义。"""
  
          match = re.match(
              r"(INSERT INTO\s+\S+\s*\()([^)]+)(\)\s+VALUES\s+[\s\S]*)",
              insert_script,
              flags=re.IGNORECASE,
          )
          if not match:
              return insert_script
  
          columns = [
              self.escape_column_name(column.strip())
              for column in match.group(2).split(",")
          ]
          return f"{match.group(1)}{', '.join(columns)}{match.group(3)}"
  
6d19690b   dhb52   feat: 脚本兼容Python ...
275
276
277
278
279
280
281
282
283
284
285
      @staticmethod
      def inserts(table_name: str, script_content: str) -> Generator:
          PREFIX = f"INSERT INTO `{table_name}`"
  
          # 收集 `table_name` 对应的 insert 语句
          for line in script_content.split("\n"):
              if line.startswith(PREFIX):
                  head, tail = line.replace(PREFIX, "").split(" VALUES ", maxsplit=1)
                  head = head.strip().replace("`", "").lower()
                  tail = tail.strip().replace(r"\"", '"')
                  # tail = tail.replace("b'0'", "'0'").replace("b'1'", "'1'")
c0d991f8   LuJiaQi   fix(sql):修复conver...
286
287
                  col_part = f" {head}" if head else ""
                  yield f"INSERT INTO {table_name.lower()}{col_part} VALUES {tail}"
6d19690b   dhb52   feat: 脚本兼容Python ...
288
289
290
291
292
293
294
295
296
297
298
299
  
      @staticmethod
      def index(ddl: Dict) -> Generator:
          """生成索引定义
  
          Args:
              ddl (Dict): 表DDL
  
          Yields:
              Generator[str]: create index 语句
          """
  
af9b6253   YunaiV   fix(sql): 修复 conv...
300
301
302
303
          for no, index in enumerate(ddl.get("index", []), 1):
              columns = ", ".join(Convertor.index_columns(index.get("columns", [])))
              if not columns:
                  continue
6d19690b   dhb52   feat: 脚本兼容Python ...
304
305
306
307
              table_name = ddl["table_name"].lower()
              yield f"CREATE INDEX idx_{table_name}_{no:02d} ON {table_name} ({columns})"
  
      @staticmethod
af9b6253   YunaiV   fix(sql): 修复 conv...
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
      def index_columns(columns) -> list:
          """兼容 simple-ddl-parser 不同版本的索引列结构。"""
  
          keys = []
  
          def append(name, order="ASC"):
              if not name:
                  return
              column_name = str(name).strip("`").lower()
              column_order = str(order or "ASC").upper()
              if column_order == "DESC":
                  keys.append(f"{column_name} desc")
              else:
                  keys.append(column_name)
  
          def visit(value):
              # 普通索引常见结构:[[{'name': 'user_id', 'order': 'ASC'}]]
              if isinstance(value, (list, tuple)):
                  for item in value:
                      visit(item)
                  return
              if isinstance(value, dict):
                  name = value.get("name")
                  if isinstance(name, (dict, list, tuple)):
                      visit(name)
                      return
                  append(name, value.get("order", "ASC"))
                  return
              # 唯一索引在部分版本中会被解析成 ['mobile', 'ASC', 'tenant_id', 'ASC']。
              if isinstance(value, str):
                  token = value.strip("`")
                  order = token.upper()
                  if order in ("ASC", "DESC"):
                      if order == "DESC" and keys and not keys[-1].endswith(" desc"):
                          keys[-1] = f"{keys[-1]} desc"
                      return
                  append(token)
  
          visit(columns)
          return keys
  
      @staticmethod
4401c703   dhb52   feat: 增加 UNIQUE K...
350
351
352
353
354
355
      def unique_index(ddl: Dict) -> Generator:
          if "constraints" in ddl and "uniques" in ddl["constraints"]:
              uk_list = ddl["constraints"]["uniques"]
              for uk in uk_list:
                  table_name = ddl["table_name"]
                  uk_name = uk["constraint_name"]
af9b6253   YunaiV   fix(sql): 修复 conv...
356
357
358
                  uk_columns = Convertor.index_columns(uk["columns"])
                  if not uk_columns:
                      continue
4401c703   dhb52   feat: 增加 UNIQUE K...
359
360
361
                  yield table_name, uk_name, uk_columns
  
      @staticmethod
6d19690b   dhb52   feat: 脚本兼容Python ...
362
363
364
365
366
367
368
369
370
      def filed_comments(table_sql: str) -> Generator:
          for line in table_sql.split("\n"):
              match = re.match(r"^`([^`]+)`.* COMMENT '([^']+)'", line.strip())
              if match:
                  field = match.group(1)
                  comment_string = match.group(2).replace("\\n", "\n")
                  yield field, comment_string
  
      def table_comment(self, table_sql: str) -> str:
e2840d1c   YunaiV   fix(sql):修复 conve...
371
372
          # 兼容 COMMENT='xxx' / COMMENT = 'xxx' 等等号两侧空格变体;允许 COMMENT 内含转义单引号
          match = re.search(r"COMMENT\s*=\s*'((?:[^'\\]|\\.)*)'", table_sql)
6d19690b   dhb52   feat: 脚本兼容Python ...
373
374
          return match.group(1) if match else None
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
375
376
377
378
379
380
381
382
383
      def print(self):
          """打印转换后的sql脚本到终端"""
          print(
              PREAMBLE.format(
                  db_type=self.db_type,
                  date=time.strftime("%Y-%m-%d %H:%M:%S"),
              )
          )
  
65651fb1   dhb52   feat: 创建虚拟dual表,达...
384
385
386
387
388
389
390
          dual = self.gen_dual()
          if dual:
              print(
                  f"""-- ----------------------------
  -- Table structure for dual
  -- ----------------------------
  {dual}
65651fb1   dhb52   feat: 创建虚拟dual表,达...
391
392
393
  """
              )
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
394
          error_scripts = []
848d4948   YunaiV   fix(sql): 修复建表语句扫...
395
          for table_sql, orig_table_sql in zip(self.table_script_list, self.original_table_script_list):
c0d991f8   LuJiaQi   fix(sql):修复conver...
396
397
398
              # 剥离 COMMENT 子句避免 DDLParser 无法处理中文等特殊字符
              table_sql_for_parse = re.sub(r"\s+COMMENT\s+'[^']*'", "", table_sql)
              ddl = DDLParser(table_sql_for_parse.replace("`", "")).run()
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
399
400
401
402
403
404
405
406
407
  
              # 如果parse失败, 需要跟进
              if len(ddl) == 0:
                  error_scripts.append(table_sql)
                  continue
  
              table_ddl = ddl[0]
              table_name = table_ddl["table_name"]
  
7cab3a72   YunaiV   SQL:同步最新
408
409
410
411
412
413
              # simple-ddl-parser 1.9+ 将字符串默认值中的等号解析为 ``\\03d``。
              # 还原为原始字符,避免导出的目标库脚本出现错误默认值。
              for column in table_ddl["columns"]:
                  if isinstance(column.get("default"), str):
                      column["default"] = column["default"].replace(r"\03d", "=")
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
414
415
416
417
              # 忽略 quartz 的内容
              if table_name.lower().startswith("qrtz"):
                  continue
  
4401c703   dhb52   feat: 增加 UNIQUE K...
418
              # 解析注释
848d4948   YunaiV   fix(sql): 修复建表语句扫...
419
              # 从原始建表语句提取注释(支持中文等 DDLParser 不能处理的内容),避免 INSERT 数据中的同名建表文本干扰
c0d991f8   LuJiaQi   fix(sql):修复conver...
420
              comments_dict = dict(Convertor.filed_comments(orig_table_sql))
4401c703   dhb52   feat: 增加 UNIQUE K...
421
              for column in table_ddl["columns"]:
c0d991f8   LuJiaQi   fix(sql):修复conver...
422
423
                  column["comment"] = comments_dict.get(column["name"], "")
              table_ddl["comment"] = self.table_comment(orig_table_sql) or ""
4401c703   dhb52   feat: 增加 UNIQUE K...
424
425
  
              # 为每个表生成个6个基本部分
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
426
              create = self.gen_create(table_ddl)
c0d991f8   LuJiaQi   fix(sql):修复conver...
427
428
              has_id = any(col["name"].lower() == "id" for col in table_ddl["columns"])
              pk = self.gen_pk(table_name) if has_id else ""
4401c703   dhb52   feat: 增加 UNIQUE K...
429
              uk = self.gen_uk(table_ddl)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
430
              index = self.gen_index(table_ddl)
4401c703   dhb52   feat: 增加 UNIQUE K...
431
              comment = self.gen_comment(table_ddl)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
432
433
434
435
436
437
438
              inserts = self.gen_insert(table_name)
  
              # 组合当前表的DDL脚本
              script = f"""{create}
  
  {pk}
  
4401c703   dhb52   feat: 增加 UNIQUE K...
439
440
  {uk}
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
441
442
443
444
445
446
447
448
449
450
  {index}
  
  {comment}
  
  {inserts}
  """
  
              # 清理
              script = re.sub("\n{3,}", "\n\n", script).strip() + "\n"
  
7cab3a72   YunaiV   SQL:同步最新
451
              print(script, end="")
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
452
453
454
  
          # 将parse失败的脚本打印出来
          if error_scripts:
57add7b6   dhb52   feat: sql/tools ...
455
              print("!!! 以下内容无法正常解析", file=sys.stderr)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
456
              for script in error_scripts:
57add7b6   dhb52   feat: sql/tools ...
457
458
                  # print to stderr
                  print(script, file=sys.stderr)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
459
460
461
462
463
464
  
  
  class PostgreSQLConvertor(Convertor):
      def __init__(self, src):
          super().__init__(src, "PostgreSQL")
  
6d19690b   dhb52   feat: 脚本兼容Python ...
465
      def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
466
467
468
469
          """类型转换"""
  
          type = type.lower()
  
bcb98f4b   Ken   fix(SQL转换): 修正转po...
470
          if type in ("varchar", "char"):
85e621ea   YunaiV   fix(sql): 修复 Post...
471
472
              # MySQL 中未指定长度的 char 等同于 char(1)
              return f"varchar({size or 1})"
c0d991f8   LuJiaQi   fix(sql):修复conver...
473
          if type in ("int", "int unsigned", "int unsigned zerofill"):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
474
              return "int4"
4401c703   dhb52   feat: 增加 UNIQUE K...
475
          if type in ("bigint", "bigint unsigned"):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
476
              return "int8"
c0d991f8   LuJiaQi   fix(sql):修复conver...
477
478
479
          if type in ("tinyint", "smallint", "tinyint unsigned"):
              return "int2"
          if type in ("datetime", "timestamp null"):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
480
              return "timestamp"
c0d991f8   LuJiaQi   fix(sql):修复conver...
481
482
483
484
          if type == "date":
              return "date"
          if type == "json":
              return "jsonb"
bcb98f4b   Ken   fix(SQL转换): 修正转po...
485
486
          if type == "time":
              return "time"
c0d991f8   LuJiaQi   fix(sql):修复conver...
487
488
          if type == "double":
              return "double precision"
4401c703   dhb52   feat: 增加 UNIQUE K...
489
          if type == "timestamp":
c0d991f8   LuJiaQi   fix(sql):修复conver...
490
              return f"timestamp({size})" if size else "timestamp"
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
491
492
          if type == "bit":
              return "bool"
bcb98f4b   Ken   fix(SQL转换): 修正转po...
493
          if type in ("text", "longtext", "mediumtext"):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
494
              return "text"
c0d991f8   LuJiaQi   fix(sql):修复conver...
495
          if type in ("blob", "mediumblob", "longblob"):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
496
497
498
              return "bytea"
          if type == "decimal":
              return (
c0d991f8   LuJiaQi   fix(sql):修复conver...
499
                  f"numeric({','.join(str(s) for s in size)})" if size and len(size) else "numeric"
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
500
501
502
503
504
505
506
507
508
509
510
511
              )
  
      def gen_create(self, ddl: Dict) -> str:
          """生成 create"""
  
          def _generate_column(col):
              name = col["name"].lower()
              if name == "deleted":
                  return "deleted int2 NOT NULL DEFAULT 0"
  
              type = col["type"].lower()
              full_type = self.translate_type(type, col["size"])
c0d991f8   LuJiaQi   fix(sql):修复conver...
512
513
514
515
              if full_type is None:
                  raise NotImplementedError(
                      f"未支持的类型: '{col['type']}' (列: {name}, 表: {ddl['table_name']})"
                  )
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
516
517
              nullable = "NULL" if col["nullable"] else "NOT NULL"
              default = f"DEFAULT {col['default']}" if col["default"] is not None else ""
af9b6253   YunaiV   fix(sql): 修复 conv...
518
              return f"{self.escape_column_name(name)} {full_type} {nullable} {default}"
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
519
520
521
  
          table_name = ddl["table_name"].lower()
          columns = [f"{_generate_column(col).strip()}" for col in ddl["columns"]]
6d19690b   dhb52   feat: 脚本兼容Python ...
522
          filed_def_list = ",\n  ".join(columns)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
523
524
525
526
527
          script = f"""-- ----------------------------
  -- Table structure for {table_name}
  -- ----------------------------
  DROP TABLE IF EXISTS {table_name};
  CREATE TABLE {table_name} (
6d19690b   dhb52   feat: 脚本兼容Python ...
528
      {filed_def_list}
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
529
530
531
532
  );"""
  
          return script
  
6d19690b   dhb52   feat: 脚本兼容Python ...
533
534
535
      def gen_index(self, ddl: Dict) -> str:
          return "\n".join(f"{script};" for script in self.index(ddl))
  
4401c703   dhb52   feat: 增加 UNIQUE K...
536
      def gen_comment(self, table_ddl: Dict) -> str:
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
537
538
539
          """生成字段及表的注释"""
  
          script = ""
4401c703   dhb52   feat: 增加 UNIQUE K...
540
541
          for column in table_ddl["columns"]:
              table_comment = column["comment"]
6d19690b   dhb52   feat: 脚本兼容Python ...
542
              script += (
af9b6253   YunaiV   fix(sql): 修复 conv...
543
                  f"COMMENT ON COLUMN {table_ddl['table_name']}.{self.escape_column_name(column['name'])} IS '{table_comment}';"
4401c703   dhb52   feat: 增加 UNIQUE K...
544
                  + "\n"
6d19690b   dhb52   feat: 脚本兼容Python ...
545
              )
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
546
  
4401c703   dhb52   feat: 增加 UNIQUE K...
547
          table_comment = table_ddl["comment"]
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
548
          if table_comment:
4401c703   dhb52   feat: 增加 UNIQUE K...
549
550
551
              script += (
                  f"COMMENT ON TABLE {table_ddl['table_name']} IS '{table_comment}';\n"
              )
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
552
553
554
555
556
557
558
  
          return script
  
      def gen_pk(self, table_name) -> str:
          """生成主键定义"""
          return f"ALTER TABLE {table_name} ADD CONSTRAINT pk_{table_name} PRIMARY KEY (id);\n"
  
4401c703   dhb52   feat: 增加 UNIQUE K...
559
560
561
562
563
564
565
566
567
      def gen_uk(self, table_ddl: Dict) -> str:
          script = ""
          uk_list = list(Convertor.unique_index(table_ddl))
          for idx, (table_name, _, uk_columns) in enumerate(uk_list, 1):
              uk_name = f"uk_{table_name}_{idx:02d}"
              script += f"CREATE UNIQUE INDEX {uk_name} ON {table_name} ({', '.join(uk_columns)});\n"
  
          return script
  
6d19690b   dhb52   feat: 脚本兼容Python ...
568
      def gen_insert(self, table_name: str) -> str:
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
569
570
          """生成 insert 语句,以及根据最后的 insert id+1 生成 Sequence"""
  
6d19690b   dhb52   feat: 脚本兼容Python ...
571
          inserts = list(Convertor.inserts(table_name, self.content))
af9b6253   YunaiV   fix(sql): 修复 conv...
572
          inserts = [self.escape_insert_columns(s) for s in inserts]
c0d991f8   LuJiaQi   fix(sql):修复conver...
573
574
          # 转换 MySQL 字符串转义为 PostgreSQL 格式:\\ -> \,\' -> ''
          inserts = [re.sub(r"\\\\|\\'", lambda m: "\\" if m.group() == "\\\\" else "''", s) for s in inserts]
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
575
576
577
578
          ## 生成 insert 脚本
          script = ""
          last_id = 0
          if inserts:
6d19690b   dhb52   feat: 脚本兼容Python ...
579
              inserts_lines = "\n".join(inserts)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
580
581
582
583
584
              script += f"""\n\n-- ----------------------------
  -- Records of {table_name.lower()}
  -- ----------------------------
  -- @formatter:off
  BEGIN;
6d19690b   dhb52   feat: 脚本兼容Python ...
585
  {inserts_lines}
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
  COMMIT;
  -- @formatter:on"""
              match = re.search(r"VALUES \((\d+),", inserts[-1])
              if match:
                  last_id = int(match.group(1))
  
          # 生成 Sequence
          script += (
              "\n\n"
              + f"""DROP SEQUENCE IF EXISTS {table_name}_seq;
  CREATE SEQUENCE {table_name}_seq
      START {last_id + 1};"""
          )
  
          return script
  
65651fb1   dhb52   feat: 创建虚拟dual表,达...
602
603
604
605
      def gen_dual(self) -> str:
          return """DROP TABLE IF EXISTS dual;
  CREATE TABLE dual
  (
7d9e6f21   dhb52   fix: pg,mssql dua...
606
607
608
609
610
611
612
613
614
615
616
      id int2
  );
  
  COMMENT ON TABLE dual IS '数据库连接的表';
  
  -- ----------------------------
  -- Records of dual
  -- ----------------------------
  -- @formatter:off
  INSERT INTO dual VALUES (1);
  -- @formatter:on"""
65651fb1   dhb52   feat: 创建虚拟dual表,达...
617
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
618
619
  
  class OracleConvertor(Convertor):
af9b6253   YunaiV   fix(sql): 修复 conv...
620
      reserved_column_names = {"level", "size"}
04515204   YunaiV   fix(oracle): 修复初始...
621
622
      # Oracle 12.2 以下(或 COMPATIBLE < 12.2)标识符最长 30 字节,超出会报 ORA-00972。相关案例:https://t.zsxq.com/tbf3q
      max_identifier_length = 30
af9b6253   YunaiV   fix(sql): 修复 conv...
623
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
624
625
626
      def __init__(self, src):
          super().__init__(src, "Oracle")
  
04515204   YunaiV   fix(oracle): 修复初始...
627
628
629
630
631
632
633
634
635
636
      def shorten_identifier(self, name: str) -> str:
          """超长的索引、约束、序列名:截断后追加完整名称的哈希,保证结果稳定且不重名"""
          if len(name.encode("utf-8")) <= self.max_identifier_length:
              return name
          digest = hashlib.md5(name.encode("utf-8")).hexdigest()[:6]
          # 按字节截断,并丢弃被截断的不完整字符
          prefix_bytes = name.encode("utf-8")[: self.max_identifier_length - len(digest) - 1]
          prefix = prefix_bytes.decode("utf-8", errors="ignore").rstrip("_")
          return f"{prefix}_{digest}"
  
6d19690b   dhb52   feat: 脚本兼容Python ...
637
      def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
638
639
640
641
          """类型转换"""
          type = type.lower()
  
          if type == "varchar":
04515204   YunaiV   fix(oracle): 修复初始...
642
643
              # MySQL varchar(n) 按字符计算长度,Oracle 默认按字节,所以显式使用 CHAR 语义。相关案例:https://t.zsxq.com/tbf3q
              return f"varchar2({size if size < 4000 else 4000} char)"
4401c703   dhb52   feat: 增加 UNIQUE K...
644
          if type in ("int", "int unsigned"):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
645
646
647
648
649
              return "number"
          if type == "bigint" or type == "bigint unsigned":
              return "number"
          if type == "datetime":
              return "date"
4401c703   dhb52   feat: 增加 UNIQUE K...
650
651
          if type == "timestamp":
              return f"timestamp({size})"
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
652
653
654
655
          if type == "bit":
              return "number(1,0)"
          if type in ("tinyint", "smallint"):
              return "smallint"
4401c703   dhb52   feat: 增加 UNIQUE K...
656
          if type in ("text", "longtext"):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
              return "clob"
          if type in ("blob", "mediumblob"):
              return "blob"
          if type == "decimal":
              return (
                  f"number({','.join(str(s) for s in size)})" if len(size) else "number"
              )
  
      def gen_create(self, ddl) -> str:
          """生成 CREATE 语句"""
  
          def generate_column(col):
              name = col["name"].lower()
              if name == "deleted":
                  return "deleted number(1,0) DEFAULT 0 NOT NULL"
  
              type = col["type"].lower()
              full_type = self.translate_type(type, col["size"])
              nullable = "NULL" if col["nullable"] else "NOT NULL"
4401c703   dhb52   feat: 增加 UNIQUE K...
676
677
              # Oracle的 INSERT '' 不能通过NOT NULL校验,因此对文字类型字段覆写为 NULL
              nullable = "NULL" if type in ("varchar", "text", "longtext") else nullable
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
678
              default = f"DEFAULT {col['default']}" if col["default"] is not None else ""
6d19690b   dhb52   feat: 脚本兼容Python ...
679
              # Oracle DEFAULT 定义在 NULLABLE 之前
af9b6253   YunaiV   fix(sql): 修复 conv...
680
              return f"{self.escape_column_name(name)} {full_type} {default} {nullable}"
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
681
682
683
  
          table_name = ddl["table_name"].lower()
          columns = [f"{generate_column(col).strip()}" for col in ddl["columns"]]
6d19690b   dhb52   feat: 脚本兼容Python ...
684
          field_def_list = ",\n    ".join(columns)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
685
686
687
          script = f"""-- ----------------------------
  -- Table structure for {table_name}
  -- ----------------------------
6d19690b   dhb52   feat: 脚本兼容Python ...
688
689
  CREATE TABLE {table_name} (
      {field_def_list}
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
690
691
692
693
694
695
696
  );"""
  
          # oracle INSERT '' 不能通过 NOT NULL 校验
          script = script.replace("DEFAULT '' NOT NULL", "DEFAULT '' NULL")
  
          return script
  
4401c703   dhb52   feat: 增加 UNIQUE K...
697
      def gen_comment(self, table_ddl: Dict) -> str:
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
698
          script = ""
4401c703   dhb52   feat: 增加 UNIQUE K...
699
700
          for column in table_ddl["columns"]:
              table_comment = column["comment"]
6d19690b   dhb52   feat: 脚本兼容Python ...
701
              script += (
af9b6253   YunaiV   fix(sql): 修复 conv...
702
                  f"COMMENT ON COLUMN {table_ddl['table_name']}.{self.escape_column_name(column['name'])} IS '{table_comment}';"
4401c703   dhb52   feat: 增加 UNIQUE K...
703
                  + "\n"
6d19690b   dhb52   feat: 脚本兼容Python ...
704
              )
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
705
  
4401c703   dhb52   feat: 增加 UNIQUE K...
706
          table_comment = table_ddl["comment"]
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
707
          if table_comment:
4401c703   dhb52   feat: 增加 UNIQUE K...
708
709
710
              script += (
                  f"COMMENT ON TABLE {table_ddl['table_name']} IS '{table_comment}';\n"
              )
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
711
712
713
  
          return script
  
6d19690b   dhb52   feat: 脚本兼容Python ...
714
      def gen_pk(self, table_name: str) -> str:
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
715
          """生成主键定义"""
04515204   YunaiV   fix(oracle): 修复初始...
716
717
          pk_name = self.shorten_identifier(f"pk_{table_name}")
          return f"ALTER TABLE {table_name} ADD CONSTRAINT {pk_name} PRIMARY KEY (id);\n"
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
718
  
4401c703   dhb52   feat: 增加 UNIQUE K...
719
720
721
722
      def gen_uk(self, table_ddl: Dict) -> str:
          script = ""
          uk_list = list(Convertor.unique_index(table_ddl))
          for idx, (table_name, _, uk_columns) in enumerate(uk_list, 1):
04515204   YunaiV   fix(oracle): 修复初始...
723
              uk_name = self.shorten_identifier(f"uk_{table_name}_{idx:02d}")
4401c703   dhb52   feat: 增加 UNIQUE K...
724
725
726
727
              script += f"CREATE UNIQUE INDEX {uk_name} ON {table_name} ({', '.join(uk_columns)});\n"
  
          return script
  
6d19690b   dhb52   feat: 脚本兼容Python ...
728
      def gen_index(self, ddl: Dict) -> str:
04515204   YunaiV   fix(oracle): 修复初始...
729
730
731
732
733
734
          scripts = []
          for script in self.index(ddl):
              # 格式为 CREATE INDEX {index_name} ON ...
              index_name = script.split()[2]
              scripts.append(script.replace(index_name, self.shorten_identifier(index_name), 1) + ";")
          return "\n".join(scripts)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
735
  
6d19690b   dhb52   feat: 脚本兼容Python ...
736
      def gen_insert(self, table_name: str) -> str:
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
737
          """拷贝 INSERT 语句"""
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
738
          inserts = []
6d19690b   dhb52   feat: 脚本兼容Python ...
739
          for insert_script in Convertor.inserts(table_name, self.content):
af9b6253   YunaiV   fix(sql): 修复 conv...
740
              insert_script = self.escape_insert_columns(insert_script)
6d19690b   dhb52   feat: 脚本兼容Python ...
741
742
743
744
745
746
747
              # 对日期数据添加 TO_DATE 转换
              insert_script = re.sub(
                  r"('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}')",
                  r"to_date(\g<1>, 'SYYYY-MM-DD HH24:MI:SS')",
                  insert_script,
              )
              inserts.append(insert_script)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
748
749
750
751
752
  
          ## 生成 insert 脚本
          script = ""
          last_id = 0
          if inserts:
6d19690b   dhb52   feat: 脚本兼容Python ...
753
              inserts_lines = "\n".join(inserts)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
754
755
756
757
              script += f"""\n\n-- ----------------------------
  -- Records of {table_name.lower()}
  -- ----------------------------
  -- @formatter:off
6d19690b   dhb52   feat: 脚本兼容Python ...
758
  {inserts_lines}
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
759
760
761
762
763
764
765
  COMMIT;
  -- @formatter:on"""
              match = re.search(r"VALUES \((\d+),", inserts[-1])
              if match:
                  last_id = int(match.group(1))
  
          # 生成 Sequence
04515204   YunaiV   fix(oracle): 修复初始...
766
767
768
769
770
          seq_name = self.shorten_identifier(f"{table_name}_seq")
          if seq_name != f"{table_name}_seq":
              # 序列名会被 @KeySequence 引用,缩短后需要提示同步修改
              print(f"!!! Oracle 序列名 {table_name}_seq 超过 {self.max_identifier_length} 字节,已缩短为 {seq_name},"
                    f"如有 @KeySequence 引用需同步修改", file=sys.stderr)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
771
772
          script += f"""
  
04515204   YunaiV   fix(oracle): 修复初始...
773
  CREATE SEQUENCE {seq_name}
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
      START WITH {last_id + 1};"""
  
          return script
  
  
  class SQLServerConvertor(Convertor):
      """_summary_
  
      Args:
          Convertor (_type_): _description_
      """
  
      def __init__(self, src):
          super().__init__(src, "Microsoft SQL Server")
  
6d19690b   dhb52   feat: 脚本兼容Python ...
789
      def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
790
791
792
793
794
795
          """类型转换"""
  
          type = type.lower()
  
          if type == "varchar":
              return f"nvarchar({size if size < 4000 else 4000})"
4401c703   dhb52   feat: 增加 UNIQUE K...
796
          if type in ("int", "int unsigned"):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
797
              return "int"
4401c703   dhb52   feat: 增加 UNIQUE K...
798
          if type in ("bigint", "bigint unsigned"):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
799
              return "bigint"
4401c703   dhb52   feat: 增加 UNIQUE K...
800
          if type in ("datetime", "timestamp"):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
801
802
              return "datetime2"
          if type == "bit":
4dba84b7   YunaiV   fix: 修正 SQL Serve...
803
804
805
806
807
              # MySQL bit(1) 与 SQL Server bit 均只有 0、1、NULL;多位的位串不是布尔值,暂不支持
              if size not in (None, 1):
                  raise ValueError(f"SQL Server 转换暂不支持 bit({size}),仅支持 bit(1)")
              return "bit"
          # SQL Server 的 tinyint 为 0 ~ 255,smallint 为 -32768 ~ 32767,需要选择能容纳 MySQL 取值范围的类型
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
808
          if type in ("tinyint", "smallint"):
4dba84b7   YunaiV   fix: 修正 SQL Serve...
809
810
811
812
              # 有符号:MySQL tinyint 为 -128 ~ 127,smallint 为 -32768 ~ 32767
              return "smallint"
          if type == "tinyint unsigned":
              # 无符号:0 ~ 255
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
813
              return "tinyint"
4dba84b7   YunaiV   fix: 修正 SQL Serve...
814
815
816
          if type == "smallint unsigned":
              # 无符号:0 ~ 65535
              return "int"
4401c703   dhb52   feat: 增加 UNIQUE K...
817
          if type in ("text", "longtext"):
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
818
819
820
821
822
823
824
825
826
827
828
829
830
              return "nvarchar(max)"
          if type in ("blob", "mediumblob"):
              return "varbinary(max)"
          if type == "decimal":
              return (
                  f"numeric({','.join(str(s) for s in size)})" if len(size) else "numeric"
              )
  
      def gen_create(self, ddl: Dict) -> str:
          """生成 create"""
  
          def _generate_column(col):
              name = col["name"].lower()
6d19690b   dhb52   feat: 脚本兼容Python ...
831
              if name == "id":
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
832
833
834
835
836
837
838
                  return "id bigint NOT NULL PRIMARY KEY IDENTITY"
              if name == "deleted":
                  return "deleted bit DEFAULT 0 NOT NULL"
  
              type = col["type"].lower()
              full_type = self.translate_type(type, col["size"])
              nullable = "NULL" if col["nullable"] else "NOT NULL"
4dba84b7   YunaiV   fix: 修正 SQL Serve...
839
840
841
842
843
              default_value = col["default"]
              # bit 的默认值使用数字常量:b'0'、b'1' 在清理后为 '0'、'1'
              if full_type == "bit" and default_value in ("'0'", "'1'"):
                  default_value = default_value.strip("'")
              default = f"DEFAULT {default_value}" if default_value is not None else ""
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
844
845
846
847
              return f"{name} {full_type} {default} {nullable}"
  
          table_name = ddl["table_name"].lower()
          columns = [f"{_generate_column(col).strip()}" for col in ddl["columns"]]
6d19690b   dhb52   feat: 脚本兼容Python ...
848
          filed_def_list = ",\n    ".join(columns)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
849
850
851
          script = f"""-- ----------------------------
  -- Table structure for {table_name}
  -- ----------------------------
0288309e   dhb52   fix: sqlserver DR...
852
853
  DROP TABLE IF EXISTS {table_name}
  GO
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
854
  CREATE TABLE {table_name} (
6d19690b   dhb52   feat: 脚本兼容Python ...
855
      {filed_def_list}
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
856
857
858
859
860
  )
  GO"""
  
          return script
  
4401c703   dhb52   feat: 增加 UNIQUE K...
861
      def gen_comment(self, table_ddl: Dict) -> str:
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
862
863
864
          """生成字段及表的注释"""
  
          script = ""
4401c703   dhb52   feat: 增加 UNIQUE K...
865
866
867
868
869
          table_name = table_ddl["table_name"]
  
          for column in table_ddl["columns"]:
              column_comment = column["comment"]
              field = column["name"]
6d19690b   dhb52   feat: 脚本兼容Python ...
870
  
6d19690b   dhb52   feat: 脚本兼容Python ...
871
              script += f"""EXEC sp_addextendedproperty
4401c703   dhb52   feat: 增加 UNIQUE K...
872
      'MS_Description', N'{column_comment}',
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
873
874
      'SCHEMA', N'dbo',
      'TABLE', N'{table_name}',
6d19690b   dhb52   feat: 脚本兼容Python ...
875
      'COLUMN', N'{field}'
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
876
877
878
879
  GO
  
  """
  
4401c703   dhb52   feat: 增加 UNIQUE K...
880
          table_comment = table_ddl["comment"]
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
881
882
883
884
885
886
887
888
          if table_comment:
              script += f"""EXEC sp_addextendedproperty
      'MS_Description', N'{table_comment}',
      'SCHEMA', N'dbo',
      'TABLE', N'{table_name}'
  GO
  
  """
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
889
890
          return script
  
6d19690b   dhb52   feat: 脚本兼容Python ...
891
      def gen_pk(self, table_name: str) -> str:
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
892
893
894
          """生成主键定义"""
          return ""
  
4401c703   dhb52   feat: 增加 UNIQUE K...
895
896
897
898
899
900
901
902
903
      def gen_uk(self, table_ddl: Dict) -> str:
          script = ""
          uk_list = list(Convertor.unique_index(table_ddl))
          for idx, (table_name, _, uk_columns) in enumerate(uk_list, 1):
              uk_name = f"uk_{table_name}_{idx:02d}"
              script += f"CREATE UNIQUE INDEX {uk_name} ON {table_name} ({', '.join(uk_columns)})\nGO"
  
          return script
  
6d19690b   dhb52   feat: 脚本兼容Python ...
904
      def gen_index(self, ddl: Dict) -> str:
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
905
          """生成 index"""
6d19690b   dhb52   feat: 脚本兼容Python ...
906
          return "\n".join(f"{script}\nGO" for script in self.index(ddl))
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
907
  
6d19690b   dhb52   feat: 脚本兼容Python ...
908
      def gen_insert(self, table_name: str) -> str:
77408250   dhb52   feat: 达梦DM8
909
          """生成 insert 语句"""
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
910
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
911
912
          # 收集 `table_name` 对应的 insert 语句
          inserts = []
6d19690b   dhb52   feat: 脚本兼容Python ...
913
914
915
916
917
918
919
920
          for insert_script in Convertor.inserts(table_name, self.content):
              # SQLServer: 字符串前加N,hack,是否存在替换字符串内容的风险
              insert_script = insert_script.replace(", '", ", N'").replace(
                  "VALUES ('", "VALUES (N')"
              )
              # 删除 insert 的结尾分号
              insert_script = re.sub(";$", r"\nGO", insert_script)
              inserts.append(insert_script)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
921
922
923
924
  
          ## 生成 insert 脚本
          script = ""
          if inserts:
6d19690b   dhb52   feat: 脚本兼容Python ...
925
              inserts_lines = "\n".join(inserts)
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
926
927
928
929
930
931
932
933
              script += f"""\n\n-- ----------------------------
  -- Records of {table_name.lower()}
  -- ----------------------------
  -- @formatter:off
  BEGIN TRANSACTION
  GO
  SET IDENTITY_INSERT {table_name.lower()} ON
  GO
6d19690b   dhb52   feat: 脚本兼容Python ...
934
  {inserts_lines}
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
935
936
937
938
939
940
941
942
  SET IDENTITY_INSERT {table_name.lower()} OFF
  GO
  COMMIT
  GO
  -- @formatter:on"""
  
          return script
  
65651fb1   dhb52   feat: 创建虚拟dual表,达...
943
944
945
      def gen_dual(self) -> str:
          return """DROP TABLE IF EXISTS dual
  GO
65651fb1   dhb52   feat: 创建虚拟dual表,达...
946
947
  CREATE TABLE dual
  (
7d9e6f21   dhb52   fix: pg,mssql dua...
948
    id int
65651fb1   dhb52   feat: 创建虚拟dual表,达...
949
950
951
952
953
954
955
  )
  GO
  
  EXEC sp_addextendedproperty
      'MS_Description', N'数据库连接的表',
      'SCHEMA', N'dbo',
      'TABLE', N'dual'
7d9e6f21   dhb52   fix: pg,mssql dua...
956
957
958
959
960
961
962
963
964
  GO
  
  -- ----------------------------
  -- Records of dual
  -- ----------------------------
  -- @formatter:off
  INSERT INTO dual VALUES (1)
  GO
  -- @formatter:on"""
65651fb1   dhb52   feat: 创建虚拟dual表,达...
965
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
966
  
77408250   dhb52   feat: 达梦DM8
967
968
969
970
971
972
973
974
975
  class DM8Convertor(Convertor):
      def __init__(self, src):
          super().__init__(src, "DM8")
  
      def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]):
          """类型转换"""
          type = type.lower()
  
          if type == "varchar":
76753b32   YunaiV   fix: 修复 DM8 初始化数据...
976
977
978
              # MySQL varchar(n) is character-oriented. DM8 may treat varchar(n)
              # as bytes, so use explicit CHAR semantics for generated scripts.
              return f"varchar({size} char)"
4401c703   dhb52   feat: 增加 UNIQUE K...
979
          if type in ("int", "int unsigned"):
77408250   dhb52   feat: 达梦DM8
980
              return "int"
4401c703   dhb52   feat: 增加 UNIQUE K...
981
          if type in ("bigint", "bigint unsigned"):
77408250   dhb52   feat: 达梦DM8
982
983
984
              return "bigint"
          if type == "datetime":
              return "datetime"
4401c703   dhb52   feat: 增加 UNIQUE K...
985
986
          if type == "timestamp":
              return f"timestamp({size})"
77408250   dhb52   feat: 达梦DM8
987
988
989
990
          if type == "bit":
              return "bit"
          if type in ("tinyint", "smallint"):
              return "smallint"
4401c703   dhb52   feat: 增加 UNIQUE K...
991
          if type in ("text", "longtext"):
77408250   dhb52   feat: 达梦DM8
992
              return "text"
4401c703   dhb52   feat: 增加 UNIQUE K...
993
          if type in ("blob", "mediumblob"):
77408250   dhb52   feat: 达梦DM8
994
              return "blob"
77408250   dhb52   feat: 达梦DM8
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
          if type == "decimal":
              return (
                  f"decimal({','.join(str(s) for s in size)})" if len(size) else "decimal"
              )
  
      def gen_create(self, ddl) -> str:
          """生成 CREATE 语句"""
  
          def generate_column(col):
              name = col["name"].lower()
              if name == "id":
                  return "id bigint NOT NULL PRIMARY KEY IDENTITY"
  
              type = col["type"].lower()
              full_type = self.translate_type(type, col["size"])
              nullable = "NULL" if col["nullable"] else "NOT NULL"
              default = f"DEFAULT {col['default']}" if col["default"] is not None else ""
              return f"{name} {full_type} {default} {nullable}"
  
          table_name = ddl["table_name"].lower()
          columns = [f"{generate_column(col).strip()}" for col in ddl["columns"]]
          field_def_list = ",\n    ".join(columns)
          script = f"""-- ----------------------------
  -- Table structure for {table_name}
  -- ----------------------------
  CREATE TABLE {table_name} (
      {field_def_list}
  );"""
  
          # oracle INSERT '' 不能通过 NOT NULL 校验
          script = script.replace("DEFAULT '' NOT NULL", "DEFAULT '' NULL")
  
          return script
  
4401c703   dhb52   feat: 增加 UNIQUE K...
1029
      def gen_comment(self, table_ddl: Dict) -> str:
77408250   dhb52   feat: 达梦DM8
1030
          script = ""
4401c703   dhb52   feat: 增加 UNIQUE K...
1031
1032
          for column in table_ddl["columns"]:
              table_comment = column["comment"]
77408250   dhb52   feat: 达梦DM8
1033
              script += (
4401c703   dhb52   feat: 增加 UNIQUE K...
1034
1035
                  f"COMMENT ON COLUMN {table_ddl['table_name']}.{column['name']} IS '{table_comment}';"
                  + "\n"
77408250   dhb52   feat: 达梦DM8
1036
1037
              )
  
4401c703   dhb52   feat: 增加 UNIQUE K...
1038
          table_comment = table_ddl["comment"]
77408250   dhb52   feat: 达梦DM8
1039
          if table_comment:
4401c703   dhb52   feat: 增加 UNIQUE K...
1040
1041
1042
              script += (
                  f"COMMENT ON TABLE {table_ddl['table_name']} IS '{table_comment}';\n"
              )
77408250   dhb52   feat: 达梦DM8
1043
1044
1045
1046
1047
1048
1049
  
          return script
  
      def gen_pk(self, table_name: str) -> str:
          """生成主键定义"""
          return ""
  
4401c703   dhb52   feat: 增加 UNIQUE K...
1050
1051
1052
1053
1054
1055
1056
1057
1058
      def gen_uk(self, table_ddl: Dict) -> str:
          script = ""
          uk_list = list(Convertor.unique_index(table_ddl))
          for idx, (table_name, _, uk_columns) in enumerate(uk_list, 1):
              uk_name = f"uk_{table_name}_{idx:02d}"
              script += f"CREATE UNIQUE INDEX {uk_name} ON {table_name} ({', '.join(uk_columns)});\n"
  
          return script
  
77408250   dhb52   feat: 达梦DM8
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
      def gen_index(self, ddl: Dict) -> str:
          return "\n".join(f"{script};" for script in self.index(ddl))
  
      def gen_insert(self, table_name: str) -> str:
          """拷贝 INSERT 语句"""
          inserts = list(Convertor.inserts(table_name, self.content))
  
          ## 生成 insert 脚本
          script = ""
          if inserts:
              inserts_lines = "\n".join(inserts)
              script += f"""\n\n-- ----------------------------
  -- Records of {table_name.lower()}
  -- ----------------------------
  -- @formatter:off
  SET IDENTITY_INSERT {table_name.lower()} ON;
  {inserts_lines}
  COMMIT;
  SET IDENTITY_INSERT {table_name.lower()} OFF;
  -- @formatter:on"""
  
          return script
  
  
a6bee12f   dhb52   feat: 支持人大金仓数King...
1083
  class KingbaseConvertor(PostgreSQLConvertor):
af9b6253   YunaiV   fix(sql): 修复 conv...
1084
1085
      reserved_column_names = {"level"}
  
a6bee12f   dhb52   feat: 支持人大金仓数King...
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
      def __init__(self, src):
          super().__init__(src)
          self.db_type = "Kingbase"
  
      def gen_create(self, ddl: Dict) -> str:
          """生成 create"""
  
          def _generate_column(col):
              name = col["name"].lower()
              if name == "deleted":
                  return "deleted int2 NOT NULL DEFAULT 0"
  
              type = col["type"].lower()
              full_type = self.translate_type(type, col["size"])
              nullable = "NULL" if col["nullable"] else "NOT NULL"
4401c703   dhb52   feat: 增加 UNIQUE K...
1101
1102
              if full_type == "text":
                  nullable = "NULL"
a6bee12f   dhb52   feat: 支持人大金仓数King...
1103
              default = f"DEFAULT {col['default']}" if col["default"] is not None else ""
af9b6253   YunaiV   fix(sql): 修复 conv...
1104
              return f"{self.escape_column_name(name)} {full_type} {nullable} {default}"
a6bee12f   dhb52   feat: 支持人大金仓数King...
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
  
          table_name = ddl["table_name"].lower()
          columns = [f"{_generate_column(col).strip()}" for col in ddl["columns"]]
          filed_def_list = ",\n  ".join(columns)
          script = f"""-- ----------------------------
  -- Table structure for {table_name}
  -- ----------------------------
  DROP TABLE IF EXISTS {table_name};
  CREATE TABLE {table_name} (
      {filed_def_list}
  );"""
  
          # Kingbase INSERT '' 不能通过 NOT NULL 校验
          script = script.replace("NOT NULL DEFAULT ''", "NULL DEFAULT ''")
  
          return script
  
  
a5081b94   dhb52   feat: 华为opengauss支持
1123
  class OpengaussConvertor(KingbaseConvertor):
af9b6253   YunaiV   fix(sql): 修复 conv...
1124
1125
      reserved_column_names = set()
  
a5081b94   dhb52   feat: 华为opengauss支持
1126
1127
1128
1129
1130
      def __init__(self, src):
          super().__init__(src)
          self.db_type = "OpenGauss"
  
  
61d312d2   YunaiV   feat: 支持瀚高数据库 Pos...
1131
1132
1133
1134
1135
1136
  class HighGoConvertor(PostgreSQLConvertor):
      def __init__(self, src):
          super().__init__(src)
          self.db_type = "HighGo"
  
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
1137
  def main():
6d19690b   dhb52   feat: 脚本兼容Python ...
1138
1139
1140
1141
1142
      parser = argparse.ArgumentParser(description="芋道系统数据库转换工具")
      parser.add_argument(
          "type",
          type=str,
          help="目标数据库类型",
00680ddc   YunaiV   feat(sql): 增加 Oce...
1143
          choices=["postgres", "oracle", "sqlserver", "dm8", "kingbase", "opengauss", "highgo", "oceanbase"],
6d19690b   dhb52   feat: 脚本兼容Python ...
1144
      )
b5c2a185   DevDengChao   feat: 允许通过参数转换自定义...
1145
1146
1147
1148
      parser.add_argument(
          "path",
          type=str,
          help="源数据库脚本路径",
61d312d2   YunaiV   feat: 支持瀚高数据库 Pos...
1149
          nargs="?",
b5c2a185   DevDengChao   feat: 允许通过参数转换自定义...
1150
1151
          default="../mysql/ruoyi-vue-pro.sql"
      )
6d19690b   dhb52   feat: 脚本兼容Python ...
1152
1153
      args = parser.parse_args()
  
74884259   DevDengChao   fix: args
1154
      sql_file = pathlib.Path(args.path).resolve().as_posix()
00680ddc   YunaiV   feat(sql): 增加 Oce...
1155
1156
1157
1158
1159
      if args.type == "oceanbase":
          # OceanBase MySQL 模式直接使用原始 SQL,保留字段类型、索引和数据。
          print(pathlib.Path(sql_file).read_text(encoding="utf-8"), end="")
          return
  
6d19690b   dhb52   feat: 脚本兼容Python ...
1160
1161
1162
1163
1164
1165
1166
      convertor = None
      if args.type == "postgres":
          convertor = PostgreSQLConvertor(sql_file)
      elif args.type == "oracle":
          convertor = OracleConvertor(sql_file)
      elif args.type == "sqlserver":
          convertor = SQLServerConvertor(sql_file)
77408250   dhb52   feat: 达梦DM8
1167
1168
      elif args.type == "dm8":
          convertor = DM8Convertor(sql_file)
a6bee12f   dhb52   feat: 支持人大金仓数King...
1169
1170
      elif args.type == "kingbase":
          convertor = KingbaseConvertor(sql_file)
a5081b94   dhb52   feat: 华为opengauss支持
1171
1172
      elif args.type == "opengauss":
          convertor = OpengaussConvertor(sql_file)
61d312d2   YunaiV   feat: 支持瀚高数据库 Pos...
1173
1174
      elif args.type == "highgo":
          convertor = HighGoConvertor(sql_file)
6d19690b   dhb52   feat: 脚本兼容Python ...
1175
1176
1177
      else:
          raise NotImplementedError(f"不支持目标数据库类型: {args.type}")
  
1d4bb4d5   dhb52   feat: 添加自动转换py脚本
1178
1179
1180
1181
1182
      convertor.print()
  
  
  if __name__ == "__main__":
      main()