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
9
10
11
12
13
14
|
or with uv
uv run --with simple-ddl-parser convertor.py postgres > ../postgresql/ruoyi-vue-pro.sql 239ms 四 5/22 21:03:16 2025
uv run --with simple-ddl-parser convertor.py sqlserver > ../sqlserver/ruoyi-vue-pro.sql
uv run --with simple-ddl-parser convertor.py kingbase > ../kingbase/ruoyi-vue-pro.sql
uv run --with simple-ddl-parser convertor.py opengauss > ../opengauss/ruoyi-vue-pro.sql
uv run --with simple-ddl-parser convertor.py oracle > ../oracle/ruoyi-vue-pro.sql
uv run --with simple-ddl-parser convertor.py dm8 > ../dm/ruoyi-vue-pro-dm8.sql
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
15
16
|
"""
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
17
|
import argparse
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
18
19
|
import pathlib
import re
|
57add7b6
dhb52
feat: sql/tools ...
|
20
|
import sys
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
21
22
|
import time
from abc import ABC, abstractmethod
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
23
|
from typing import Dict, Generator, Optional, Tuple, Union
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
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
|
from simple_ddl_parser import DDLParser
PREAMBLE = """/*
Yudao Database Transfer Tool
Source Server Type : MySQL
Target Server Type : {db_type}
Date: {date}
*/
"""
def load_and_clean(sql_file: str) -> str:
"""加载源 SQL 文件,并清理内容方便下一步 ddl 解析
Args:
sql_file (str): sql文件路径
Returns:
str: 清理后的sql文件内容
"""
REPLACE_PAIR_LIST = (
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
50
|
(")\nVALUES ", ") VALUES "),
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
51
52
53
54
55
56
57
|
(" CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ", " "),
(" KEY `", " INDEX `"),
("UNIQUE INDEX", "UNIQUE KEY"),
("b'0'", "'0'"),
("b'1'", "'1'"),
)
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
58
|
content = open(sql_file, encoding="utf-8").read()
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
for replace_pair in REPLACE_PAIR_LIST:
content = content.replace(*replace_pair)
content = re.sub(r"ENGINE.*COMMENT", "COMMENT", content)
content = re.sub(r"ENGINE.*;", ";", content)
return content
class Convertor(ABC):
def __init__(self, src: str, db_type) -> None:
self.src = src
self.db_type = db_type
self.content = load_and_clean(self.src)
self.table_script_list = re.findall(r"CREATE TABLE [^;]*;", self.content)
@abstractmethod
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
74
|
def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]) -> str:
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
75
76
77
78
|
"""字段类型转换
Args:
type (str): 字段类型
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
79
|
size (Optional[Union[int, Tuple[int]]]): 字段长度描述, 如varchar(255), decimal(10,2)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
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 ...
|
111
|
def gen_index(self, ddl: Dict) -> str:
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
112
113
114
115
116
117
118
119
120
121
122
|
"""生成索引定义
Args:
table_ddl (Dict): 表DDL
Returns:
str: 生成脚本
"""
pass
@abstractmethod
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
123
|
def gen_comment(self, table_ddl: Dict) -> str:
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
124
125
126
|
"""生成字段/表注释
Args:
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
127
|
table_ddl (Dict): 表DDL
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
128
129
130
131
132
133
134
|
Returns:
str: 生成脚本
"""
pass
@abstractmethod
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
135
136
137
138
139
140
141
142
143
144
145
|
def gen_uk(self, table_ddl: Dict) -> str:
"""生成
Args:
table_ddl (Dict): 表DDL
Returns:
str: 生成脚本
"""
@abstractmethod
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
146
147
148
149
150
151
152
153
154
155
156
|
def gen_insert(self, table_name: str) -> str:
"""生成 insert 语句块
Args:
table_name (str): 表名
Returns:
str: 生成脚本
"""
pass
|
65651fb1
dhb52
feat: 创建虚拟dual表,达...
|
157
158
159
160
161
162
163
164
|
def gen_dual(self) -> str:
"""生成虚拟 dual 表
Returns:
str: 生成脚本, 默认返回空脚本, 表示当前数据库无需手工创建
"""
return ""
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
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
196
197
198
199
200
201
|
@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'")
yield f"INSERT INTO {table_name.lower()} {head} VALUES {tail}"
@staticmethod
def index(ddl: Dict) -> Generator:
"""生成索引定义
Args:
ddl (Dict): 表DDL
Yields:
Generator[str]: create index 语句
"""
def generate_columns(columns):
keys = [
f"{col['name'].lower()}{' ' + col['order'].lower() if col['order'] != 'ASC' else ''}"
for col in columns[0]
]
return ", ".join(keys)
for no, index in enumerate(ddl["index"], 1):
columns = generate_columns(index["columns"])
table_name = ddl["table_name"].lower()
yield f"CREATE INDEX idx_{table_name}_{no:02d} ON {table_name} ({columns})"
@staticmethod
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
202
203
204
205
206
207
208
209
210
211
|
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"]
uk_columns = uk["columns"]
yield table_name, uk_name, uk_columns
@staticmethod
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
212
213
214
215
216
217
218
219
220
|
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:
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
221
|
match = re.search(r"COMMENT \='([^']+)';", table_sql)
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
222
223
|
return match.group(1) if match else None
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
224
225
226
227
228
229
230
231
232
|
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表,达...
|
233
234
235
236
237
238
239
|
dual = self.gen_dual()
if dual:
print(
f"""-- ----------------------------
-- Table structure for dual
-- ----------------------------
{dual}
|
65651fb1
dhb52
feat: 创建虚拟dual表,达...
|
240
241
242
|
"""
)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
|
error_scripts = []
for table_sql in self.table_script_list:
ddl = DDLParser(table_sql.replace("`", "")).run()
# 如果parse失败, 需要跟进
if len(ddl) == 0:
error_scripts.append(table_sql)
continue
table_ddl = ddl[0]
table_name = table_ddl["table_name"]
# 忽略 quartz 的内容
if table_name.lower().startswith("qrtz"):
continue
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
259
260
261
262
263
264
265
266
267
268
|
# 解析注释
for column in table_ddl["columns"]:
column["comment"] = bytes(column["comment"], "utf-8").decode(
"unicode_escape"
)[1:-1]
table_ddl["comment"] = bytes(table_ddl["comment"], "utf-8").decode(
"unicode_escape"
)[1:-1]
# 为每个表生成个6个基本部分
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
269
270
|
create = self.gen_create(table_ddl)
pk = self.gen_pk(table_name)
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
271
|
uk = self.gen_uk(table_ddl)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
272
|
index = self.gen_index(table_ddl)
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
273
|
comment = self.gen_comment(table_ddl)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
274
275
276
277
278
279
280
|
inserts = self.gen_insert(table_name)
# 组合当前表的DDL脚本
script = f"""{create}
{pk}
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
281
282
|
{uk}
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
283
284
285
286
287
288
289
290
291
292
293
294
295
296
|
{index}
{comment}
{inserts}
"""
# 清理
script = re.sub("\n{3,}", "\n\n", script).strip() + "\n"
print(script)
# 将parse失败的脚本打印出来
if error_scripts:
|
57add7b6
dhb52
feat: sql/tools ...
|
297
|
print("!!! 以下内容无法正常解析", file=sys.stderr)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
298
|
for script in error_scripts:
|
57add7b6
dhb52
feat: sql/tools ...
|
299
300
|
# print to stderr
print(script, file=sys.stderr)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
301
302
303
304
305
306
|
class PostgreSQLConvertor(Convertor):
def __init__(self, src):
super().__init__(src, "PostgreSQL")
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
307
|
def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
308
309
310
311
312
313
|
"""类型转换"""
type = type.lower()
if type == "varchar":
return f"varchar({size})"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
314
|
if type in ("int", "int unsigned"):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
315
|
return "int4"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
316
|
if type in ("bigint", "bigint unsigned"):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
317
318
319
|
return "int8"
if type == "datetime":
return "timestamp"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
320
321
|
if type == "timestamp":
return f"timestamp({size})"
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
322
323
324
325
|
if type == "bit":
return "bool"
if type in ("tinyint", "smallint"):
return "int2"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
326
|
if type in ("text", "longtext"):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
|
return "text"
if type in ("blob", "mediumblob"):
return "bytea"
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()
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"
default = f"DEFAULT {col['default']}" if col["default"] is not None else ""
return f"{name} {full_type} {nullable} {default}"
table_name = ddl["table_name"].lower()
columns = [f"{_generate_column(col).strip()}" for col in ddl["columns"]]
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
351
|
filed_def_list = ",\n ".join(columns)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
352
353
354
355
356
|
script = f"""-- ----------------------------
-- Table structure for {table_name}
-- ----------------------------
DROP TABLE IF EXISTS {table_name};
CREATE TABLE {table_name} (
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
357
|
{filed_def_list}
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
358
359
360
361
|
);"""
return script
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
362
363
364
|
def gen_index(self, ddl: Dict) -> str:
return "\n".join(f"{script};" for script in self.index(ddl))
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
365
|
def gen_comment(self, table_ddl: Dict) -> str:
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
366
367
368
|
"""生成字段及表的注释"""
script = ""
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
369
370
|
for column in table_ddl["columns"]:
table_comment = column["comment"]
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
371
|
script += (
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
372
373
|
f"COMMENT ON COLUMN {table_ddl['table_name']}.{column['name']} IS '{table_comment}';"
+ "\n"
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
374
|
)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
375
|
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
376
|
table_comment = table_ddl["comment"]
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
377
|
if table_comment:
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
378
379
380
|
script += (
f"COMMENT ON TABLE {table_ddl['table_name']} IS '{table_comment}';\n"
)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
381
382
383
384
385
386
387
|
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...
|
388
389
390
391
392
393
394
395
396
|
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 ...
|
397
|
def gen_insert(self, table_name: str) -> str:
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
398
399
|
"""生成 insert 语句,以及根据最后的 insert id+1 生成 Sequence"""
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
400
|
inserts = list(Convertor.inserts(table_name, self.content))
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
401
402
403
404
|
## 生成 insert 脚本
script = ""
last_id = 0
if inserts:
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
405
|
inserts_lines = "\n".join(inserts)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
406
407
408
409
410
|
script += f"""\n\n-- ----------------------------
-- Records of {table_name.lower()}
-- ----------------------------
-- @formatter:off
BEGIN;
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
411
|
{inserts_lines}
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
|
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表,达...
|
428
429
430
431
|
def gen_dual(self) -> str:
return """DROP TABLE IF EXISTS dual;
CREATE TABLE dual
(
|
7d9e6f21
dhb52
fix: pg,mssql dua...
|
432
433
434
435
436
437
438
439
440
441
442
|
id int2
);
COMMENT ON TABLE dual IS '数据库连接的表';
-- ----------------------------
-- Records of dual
-- ----------------------------
-- @formatter:off
INSERT INTO dual VALUES (1);
-- @formatter:on"""
|
65651fb1
dhb52
feat: 创建虚拟dual表,达...
|
443
|
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
444
445
446
447
448
|
class OracleConvertor(Convertor):
def __init__(self, src):
super().__init__(src, "Oracle")
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
449
|
def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
450
451
452
453
454
|
"""类型转换"""
type = type.lower()
if type == "varchar":
return f"varchar2({size if size < 4000 else 4000})"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
455
|
if type in ("int", "int unsigned"):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
456
457
458
459
460
|
return "number"
if type == "bigint" or type == "bigint unsigned":
return "number"
if type == "datetime":
return "date"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
461
462
|
if type == "timestamp":
return f"timestamp({size})"
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
463
464
465
466
|
if type == "bit":
return "number(1,0)"
if type in ("tinyint", "smallint"):
return "smallint"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
467
|
if type in ("text", "longtext"):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
|
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...
|
487
488
|
# Oracle的 INSERT '' 不能通过NOT NULL校验,因此对文字类型字段覆写为 NULL
nullable = "NULL" if type in ("varchar", "text", "longtext") else nullable
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
489
|
default = f"DEFAULT {col['default']}" if col["default"] is not None else ""
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
490
491
492
493
|
# Oracle 中 size 不能作为字段名
field_name = '"size"' if name == "size" else name
# Oracle DEFAULT 定义在 NULLABLE 之前
return f"{field_name} {full_type} {default} {nullable}"
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
494
495
496
|
table_name = ddl["table_name"].lower()
columns = [f"{generate_column(col).strip()}" for col in ddl["columns"]]
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
497
|
field_def_list = ",\n ".join(columns)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
498
499
500
|
script = f"""-- ----------------------------
-- Table structure for {table_name}
-- ----------------------------
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
501
502
|
CREATE TABLE {table_name} (
{field_def_list}
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
503
504
505
506
507
508
509
|
);"""
# oracle INSERT '' 不能通过 NOT NULL 校验
script = script.replace("DEFAULT '' NOT NULL", "DEFAULT '' NULL")
return script
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
510
511
512
|
def gen_index(self, ddl: Dict) -> str:
return "\n".join(f"{script};" for script in self.index(ddl))
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
513
|
def gen_comment(self, table_ddl: Dict) -> str:
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
514
|
script = ""
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
515
516
|
for column in table_ddl["columns"]:
table_comment = column["comment"]
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
517
|
script += (
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
518
519
|
f"COMMENT ON COLUMN {table_ddl['table_name']}.{column['name']} IS '{table_comment}';"
+ "\n"
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
520
|
)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
521
|
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
522
|
table_comment = table_ddl["comment"]
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
523
|
if table_comment:
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
524
525
526
|
script += (
f"COMMENT ON TABLE {table_ddl['table_name']} IS '{table_comment}';\n"
)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
527
528
529
|
return script
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
530
|
def gen_pk(self, table_name: str) -> str:
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
531
532
533
|
"""生成主键定义"""
return f"ALTER TABLE {table_name} ADD CONSTRAINT pk_{table_name} PRIMARY KEY (id);\n"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
534
535
536
537
538
539
540
541
542
|
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 ...
|
543
544
|
def gen_index(self, ddl: Dict) -> str:
return "\n".join(f"{script};" for script in self.index(ddl))
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
545
|
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
546
|
def gen_insert(self, table_name: str) -> str:
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
547
|
"""拷贝 INSERT 语句"""
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
548
|
inserts = []
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
549
550
551
552
553
554
555
556
|
for insert_script in Convertor.inserts(table_name, self.content):
# 对日期数据添加 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脚本
|
557
558
559
560
561
|
## 生成 insert 脚本
script = ""
last_id = 0
if inserts:
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
562
|
inserts_lines = "\n".join(inserts)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
563
564
565
566
|
script += f"""\n\n-- ----------------------------
-- Records of {table_name.lower()}
-- ----------------------------
-- @formatter:off
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
567
|
{inserts_lines}
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
|
COMMIT;
-- @formatter:on"""
match = re.search(r"VALUES \((\d+),", inserts[-1])
if match:
last_id = int(match.group(1))
# 生成 Sequence
script += f"""
CREATE SEQUENCE {table_name}_seq
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 ...
|
593
|
def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
594
595
596
597
598
599
|
"""类型转换"""
type = type.lower()
if type == "varchar":
return f"nvarchar({size if size < 4000 else 4000})"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
600
|
if type in ("int", "int unsigned"):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
601
|
return "int"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
602
|
if type in ("bigint", "bigint unsigned"):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
603
|
return "bigint"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
604
|
if type in ("datetime", "timestamp"):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
605
606
607
608
609
|
return "datetime2"
if type == "bit":
return "varchar(1)"
if type in ("tinyint", "smallint"):
return "tinyint"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
610
|
if type in ("text", "longtext"):
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
611
612
613
614
615
616
617
618
619
620
621
622
623
|
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 ...
|
624
|
if name == "id":
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
625
626
627
628
629
630
631
632
633
634
635
636
|
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"
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"]]
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
637
|
filed_def_list = ",\n ".join(columns)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
638
639
640
|
script = f"""-- ----------------------------
-- Table structure for {table_name}
-- ----------------------------
|
0288309e
dhb52
fix: sqlserver DR...
|
641
642
|
DROP TABLE IF EXISTS {table_name}
GO
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
643
|
CREATE TABLE {table_name} (
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
644
|
{filed_def_list}
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
645
646
647
648
649
|
)
GO"""
return script
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
650
|
def gen_comment(self, table_ddl: Dict) -> str:
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
651
652
653
|
"""生成字段及表的注释"""
script = ""
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
654
655
656
657
658
|
table_name = table_ddl["table_name"]
for column in table_ddl["columns"]:
column_comment = column["comment"]
field = column["name"]
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
659
|
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
660
|
script += f"""EXEC sp_addextendedproperty
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
661
|
'MS_Description', N'{column_comment}',
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
662
663
|
'SCHEMA', N'dbo',
'TABLE', N'{table_name}',
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
664
|
'COLUMN', N'{field}'
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
665
666
667
668
|
GO
"""
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
669
|
table_comment = table_ddl["comment"]
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
670
671
672
673
674
675
676
677
|
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脚本
|
678
679
|
return script
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
680
|
def gen_pk(self, table_name: str) -> str:
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
681
682
683
|
"""生成主键定义"""
return ""
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
684
685
686
687
688
689
690
691
692
|
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 ...
|
693
|
def gen_index(self, ddl: Dict) -> str:
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
694
|
"""生成 index"""
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
695
|
return "\n".join(f"{script}\nGO" for script in self.index(ddl))
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
696
|
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
697
|
def gen_insert(self, table_name: str) -> str:
|
77408250
dhb52
feat: 达梦DM8
|
698
|
"""生成 insert 语句"""
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
699
|
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
700
701
|
# 收集 `table_name` 对应的 insert 语句
inserts = []
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
702
703
704
705
706
707
708
709
|
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脚本
|
710
711
712
713
|
## 生成 insert 脚本
script = ""
if inserts:
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
714
|
inserts_lines = "\n".join(inserts)
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
715
716
717
718
719
720
721
722
|
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 ...
|
723
|
{inserts_lines}
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
724
725
726
727
728
729
730
731
|
SET IDENTITY_INSERT {table_name.lower()} OFF
GO
COMMIT
GO
-- @formatter:on"""
return script
|
65651fb1
dhb52
feat: 创建虚拟dual表,达...
|
732
733
734
|
def gen_dual(self) -> str:
return """DROP TABLE IF EXISTS dual
GO
|
65651fb1
dhb52
feat: 创建虚拟dual表,达...
|
735
736
|
CREATE TABLE dual
(
|
7d9e6f21
dhb52
fix: pg,mssql dua...
|
737
|
id int
|
65651fb1
dhb52
feat: 创建虚拟dual表,达...
|
738
739
740
741
742
743
744
|
)
GO
EXEC sp_addextendedproperty
'MS_Description', N'数据库连接的表',
'SCHEMA', N'dbo',
'TABLE', N'dual'
|
7d9e6f21
dhb52
fix: pg,mssql dua...
|
745
746
747
748
749
750
751
752
753
|
GO
-- ----------------------------
-- Records of dual
-- ----------------------------
-- @formatter:off
INSERT INTO dual VALUES (1)
GO
-- @formatter:on"""
|
65651fb1
dhb52
feat: 创建虚拟dual表,达...
|
754
|
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
755
|
|
77408250
dhb52
feat: 达梦DM8
|
756
757
758
759
760
761
762
763
764
765
|
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":
return f"varchar({size})"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
766
|
if type in ("int", "int unsigned"):
|
77408250
dhb52
feat: 达梦DM8
|
767
|
return "int"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
768
|
if type in ("bigint", "bigint unsigned"):
|
77408250
dhb52
feat: 达梦DM8
|
769
770
771
|
return "bigint"
if type == "datetime":
return "datetime"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
772
773
|
if type == "timestamp":
return f"timestamp({size})"
|
77408250
dhb52
feat: 达梦DM8
|
774
775
776
777
|
if type == "bit":
return "bit"
if type in ("tinyint", "smallint"):
return "smallint"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
778
|
if type in ("text", "longtext"):
|
77408250
dhb52
feat: 达梦DM8
|
779
|
return "text"
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
780
|
if type in ("blob", "mediumblob"):
|
77408250
dhb52
feat: 达梦DM8
|
781
|
return "blob"
|
77408250
dhb52
feat: 达梦DM8
|
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
|
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...
|
816
|
def gen_comment(self, table_ddl: Dict) -> str:
|
77408250
dhb52
feat: 达梦DM8
|
817
|
script = ""
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
818
819
|
for column in table_ddl["columns"]:
table_comment = column["comment"]
|
77408250
dhb52
feat: 达梦DM8
|
820
|
script += (
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
821
822
|
f"COMMENT ON COLUMN {table_ddl['table_name']}.{column['name']} IS '{table_comment}';"
+ "\n"
|
77408250
dhb52
feat: 达梦DM8
|
823
824
|
)
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
825
|
table_comment = table_ddl["comment"]
|
77408250
dhb52
feat: 达梦DM8
|
826
|
if table_comment:
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
827
828
829
|
script += (
f"COMMENT ON TABLE {table_ddl['table_name']} IS '{table_comment}';\n"
)
|
77408250
dhb52
feat: 达梦DM8
|
830
831
832
833
834
835
836
|
return script
def gen_pk(self, table_name: str) -> str:
"""生成主键定义"""
return ""
|
4401c703
dhb52
feat: 增加 UNIQUE K...
|
837
838
839
840
841
842
843
844
845
|
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
|
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
|
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...
|
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
|
class KingbaseConvertor(PostgreSQLConvertor):
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...
|
886
887
|
if full_type == "text":
nullable = "NULL"
|
a6bee12f
dhb52
feat: 支持人大金仓数King...
|
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
|
default = f"DEFAULT {col['default']}" if col["default"] is not None else ""
return f"{name} {full_type} {nullable} {default}"
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支持
|
908
909
910
911
912
913
|
class OpengaussConvertor(KingbaseConvertor):
def __init__(self, src):
super().__init__(src)
self.db_type = "OpenGauss"
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
914
|
def main():
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
915
916
917
918
919
|
parser = argparse.ArgumentParser(description="芋道系统数据库转换工具")
parser.add_argument(
"type",
type=str,
help="目标数据库类型",
|
a5081b94
dhb52
feat: 华为opengauss支持
|
920
|
choices=["postgres", "oracle", "sqlserver", "dm8", "kingbase", "opengauss"],
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
921
922
923
924
925
926
927
928
929
930
931
|
)
args = parser.parse_args()
sql_file = pathlib.Path("../mysql/ruoyi-vue-pro.sql").resolve().as_posix()
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
|
932
933
|
elif args.type == "dm8":
convertor = DM8Convertor(sql_file)
|
a6bee12f
dhb52
feat: 支持人大金仓数King...
|
934
935
|
elif args.type == "kingbase":
convertor = KingbaseConvertor(sql_file)
|
a5081b94
dhb52
feat: 华为opengauss支持
|
936
937
|
elif args.type == "opengauss":
convertor = OpengaussConvertor(sql_file)
|
6d19690b
dhb52
feat: 脚本兼容Python ...
|
938
939
940
|
else:
raise NotImplementedError(f"不支持目标数据库类型: {args.type}")
|
1d4bb4d5
dhb52
feat: 添加自动转换py脚本
|
941
942
943
944
945
|
convertor.print()
if __name__ == "__main__":
main()
|