convertor.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. # encoding=utf8
  2. """芋道系统数据库迁移工具
  3. Author: dhb52 (https://gitee.com/dhb52)
  4. pip install simple-ddl-parser
  5. """
  6. import argparse
  7. import pathlib
  8. import re
  9. import time
  10. from abc import ABC, abstractmethod
  11. from typing import Dict, Generator, Optional, Tuple, Union
  12. from simple_ddl_parser import DDLParser
  13. PREAMBLE = """/*
  14. Yudao Database Transfer Tool
  15. Source Server Type : MySQL
  16. Target Server Type : {db_type}
  17. Date: {date}
  18. */
  19. """
  20. def load_and_clean(sql_file: str) -> str:
  21. """加载源 SQL 文件,并清理内容方便下一步 ddl 解析
  22. Args:
  23. sql_file (str): sql文件路径
  24. Returns:
  25. str: 清理后的sql文件内容
  26. """
  27. REPLACE_PAIR_LIST = (
  28. (" CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ", " "),
  29. (" KEY `", " INDEX `"),
  30. ("UNIQUE INDEX", "UNIQUE KEY"),
  31. ("b'0'", "'0'"),
  32. ("b'1'", "'1'"),
  33. )
  34. content = open(sql_file).read()
  35. for replace_pair in REPLACE_PAIR_LIST:
  36. content = content.replace(*replace_pair)
  37. content = re.sub(r"ENGINE.*COMMENT", "COMMENT", content)
  38. content = re.sub(r"ENGINE.*;", ";", content)
  39. return content
  40. class Convertor(ABC):
  41. def __init__(self, src: str, db_type) -> None:
  42. self.src = src
  43. self.db_type = db_type
  44. self.content = load_and_clean(self.src)
  45. self.table_script_list = re.findall(r"CREATE TABLE [^;]*;", self.content)
  46. @abstractmethod
  47. def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]) -> str:
  48. """字段类型转换
  49. Args:
  50. type (str): 字段类型
  51. size (Optional[Union[int, Tuple[int]]]): 字段长度描述, 如varchar(255), decimal(10,2)
  52. Returns:
  53. str: 类型定义
  54. """
  55. pass
  56. @abstractmethod
  57. def gen_create(self, table_ddl: Dict) -> str:
  58. """生成 create 脚本
  59. Args:
  60. table_ddl (Dict): 表DDL
  61. Returns:
  62. str: 生成脚本
  63. """
  64. pass
  65. @abstractmethod
  66. def gen_pk(self, table_name: str) -> str:
  67. """生成主键定义
  68. Args:
  69. table_name (str): 表名
  70. Returns:
  71. str: 生成脚本
  72. """
  73. pass
  74. @abstractmethod
  75. def gen_index(self, ddl: Dict) -> str:
  76. """生成索引定义
  77. Args:
  78. table_ddl (Dict): 表DDL
  79. Returns:
  80. str: 生成脚本
  81. """
  82. pass
  83. @abstractmethod
  84. def gen_comment(self, table_sql: str, table_name: str) -> str:
  85. """生成字段/表注释
  86. Args:
  87. table_sql (str): 原始表SQL
  88. table_name (str): 表名
  89. Returns:
  90. str: 生成脚本
  91. """
  92. pass
  93. @abstractmethod
  94. def gen_insert(self, table_name: str) -> str:
  95. """生成 insert 语句块
  96. Args:
  97. table_name (str): 表名
  98. Returns:
  99. str: 生成脚本
  100. """
  101. pass
  102. def gen_dual(self) -> str:
  103. """生成虚拟 dual 表
  104. Returns:
  105. str: 生成脚本, 默认返回空脚本, 表示当前数据库无需手工创建
  106. """
  107. return ""
  108. @staticmethod
  109. def inserts(table_name: str, script_content: str) -> Generator:
  110. PREFIX = f"INSERT INTO `{table_name}`"
  111. # 收集 `table_name` 对应的 insert 语句
  112. for line in script_content.split("\n"):
  113. if line.startswith(PREFIX):
  114. head, tail = line.replace(PREFIX, "").split(" VALUES ", maxsplit=1)
  115. head = head.strip().replace("`", "").lower()
  116. tail = tail.strip().replace(r"\"", '"')
  117. # tail = tail.replace("b'0'", "'0'").replace("b'1'", "'1'")
  118. yield f"INSERT INTO {table_name.lower()} {head} VALUES {tail}"
  119. @staticmethod
  120. def index(ddl: Dict) -> Generator:
  121. """生成索引定义
  122. Args:
  123. ddl (Dict): 表DDL
  124. Yields:
  125. Generator[str]: create index 语句
  126. """
  127. def generate_columns(columns):
  128. keys = [
  129. f"{col['name'].lower()}{' ' + col['order'].lower() if col['order'] != 'ASC' else ''}"
  130. for col in columns[0]
  131. ]
  132. return ", ".join(keys)
  133. for no, index in enumerate(ddl["index"], 1):
  134. columns = generate_columns(index["columns"])
  135. table_name = ddl["table_name"].lower()
  136. yield f"CREATE INDEX idx_{table_name}_{no:02d} ON {table_name} ({columns})"
  137. @staticmethod
  138. def filed_comments(table_sql: str) -> Generator:
  139. for line in table_sql.split("\n"):
  140. match = re.match(r"^`([^`]+)`.* COMMENT '([^']+)'", line.strip())
  141. if match:
  142. field = match.group(1)
  143. comment_string = match.group(2).replace("\\n", "\n")
  144. yield field, comment_string
  145. def table_comment(self, table_sql: str) -> str:
  146. match = re.search(r"COMMENT \= '([^']+)';", table_sql)
  147. return match.group(1) if match else None
  148. def print(self):
  149. """打印转换后的sql脚本到终端"""
  150. print(
  151. PREAMBLE.format(
  152. db_type=self.db_type,
  153. date=time.strftime("%Y-%m-%d %H:%M:%S"),
  154. )
  155. )
  156. dual = self.gen_dual()
  157. if dual:
  158. print(
  159. f"""-- ----------------------------
  160. -- Table structure for dual
  161. -- ----------------------------
  162. {dual}
  163. """
  164. )
  165. error_scripts = []
  166. for table_sql in self.table_script_list:
  167. ddl = DDLParser(table_sql.replace("`", "")).run()
  168. # 如果parse失败, 需要跟进
  169. if len(ddl) == 0:
  170. error_scripts.append(table_sql)
  171. continue
  172. table_ddl = ddl[0]
  173. table_name = table_ddl["table_name"]
  174. # 忽略 quartz 的内容
  175. if table_name.lower().startswith("qrtz"):
  176. continue
  177. # 为每个表生成个5个基本部分
  178. create = self.gen_create(table_ddl)
  179. pk = self.gen_pk(table_name)
  180. index = self.gen_index(table_ddl)
  181. comment = self.gen_comment(table_sql, table_name)
  182. inserts = self.gen_insert(table_name)
  183. # 组合当前表的DDL脚本
  184. script = f"""{create}
  185. {pk}
  186. {index}
  187. {comment}
  188. {inserts}
  189. """
  190. # 清理
  191. script = re.sub("\n{3,}", "\n\n", script).strip() + "\n"
  192. print(script)
  193. # 将parse失败的脚本打印出来
  194. if error_scripts:
  195. for script in error_scripts:
  196. print(script)
  197. class PostgreSQLConvertor(Convertor):
  198. def __init__(self, src):
  199. super().__init__(src, "PostgreSQL")
  200. def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]):
  201. """类型转换"""
  202. type = type.lower()
  203. if type == "varchar":
  204. return f"varchar({size})"
  205. if type == "int":
  206. return "int4"
  207. if type == "bigint" or type == "bigint unsigned":
  208. return "int8"
  209. if type == "datetime":
  210. return "timestamp"
  211. if type == "bit":
  212. return "bool"
  213. if type in ("tinyint", "smallint"):
  214. return "int2"
  215. if type == "text":
  216. return "text"
  217. if type in ("blob", "mediumblob"):
  218. return "bytea"
  219. if type == "decimal":
  220. return (
  221. f"numeric({','.join(str(s) for s in size)})" if len(size) else "numeric"
  222. )
  223. def gen_create(self, ddl: Dict) -> str:
  224. """生成 create"""
  225. def _generate_column(col):
  226. name = col["name"].lower()
  227. if name == "deleted":
  228. return "deleted int2 NOT NULL DEFAULT 0"
  229. type = col["type"].lower()
  230. full_type = self.translate_type(type, col["size"])
  231. nullable = "NULL" if col["nullable"] else "NOT NULL"
  232. default = f"DEFAULT {col['default']}" if col["default"] is not None else ""
  233. return f"{name} {full_type} {nullable} {default}"
  234. table_name = ddl["table_name"].lower()
  235. columns = [f"{_generate_column(col).strip()}" for col in ddl["columns"]]
  236. filed_def_list = ",\n ".join(columns)
  237. script = f"""-- ----------------------------
  238. -- Table structure for {table_name}
  239. -- ----------------------------
  240. DROP TABLE IF EXISTS {table_name};
  241. CREATE TABLE {table_name} (
  242. {filed_def_list}
  243. );"""
  244. return script
  245. def gen_index(self, ddl: Dict) -> str:
  246. return "\n".join(f"{script};" for script in self.index(ddl))
  247. def gen_comment(self, table_sql: str, table_name: str) -> str:
  248. """生成字段及表的注释"""
  249. script = ""
  250. for field, comment_string in self.filed_comments(table_sql):
  251. script += (
  252. f"COMMENT ON COLUMN {table_name}.{field} IS '{comment_string}';" + "\n"
  253. )
  254. table_comment = self.table_comment(table_sql)
  255. if table_comment:
  256. script += f"COMMENT ON TABLE {table_name} IS '{table_comment}';\n"
  257. return script
  258. def gen_pk(self, table_name) -> str:
  259. """生成主键定义"""
  260. return f"ALTER TABLE {table_name} ADD CONSTRAINT pk_{table_name} PRIMARY KEY (id);\n"
  261. def gen_insert(self, table_name: str) -> str:
  262. """生成 insert 语句,以及根据最后的 insert id+1 生成 Sequence"""
  263. inserts = list(Convertor.inserts(table_name, self.content))
  264. ## 生成 insert 脚本
  265. script = ""
  266. last_id = 0
  267. if inserts:
  268. inserts_lines = "\n".join(inserts)
  269. script += f"""\n\n-- ----------------------------
  270. -- Records of {table_name.lower()}
  271. -- ----------------------------
  272. -- @formatter:off
  273. BEGIN;
  274. {inserts_lines}
  275. COMMIT;
  276. -- @formatter:on"""
  277. match = re.search(r"VALUES \((\d+),", inserts[-1])
  278. if match:
  279. last_id = int(match.group(1))
  280. # 生成 Sequence
  281. script += (
  282. "\n\n"
  283. + f"""DROP SEQUENCE IF EXISTS {table_name}_seq;
  284. CREATE SEQUENCE {table_name}_seq
  285. START {last_id + 1};"""
  286. )
  287. return script
  288. def gen_dual(self) -> str:
  289. return """DROP TABLE IF EXISTS dual;
  290. CREATE TABLE dual
  291. (
  292. );"""
  293. class OracleConvertor(Convertor):
  294. def __init__(self, src):
  295. super().__init__(src, "Oracle")
  296. def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]):
  297. """类型转换"""
  298. type = type.lower()
  299. if type == "varchar":
  300. return f"varchar2({size if size < 4000 else 4000})"
  301. if type == "int":
  302. return "number"
  303. if type == "bigint" or type == "bigint unsigned":
  304. return "number"
  305. if type == "datetime":
  306. return "date"
  307. if type == "bit":
  308. return "number(1,0)"
  309. if type in ("tinyint", "smallint"):
  310. return "smallint"
  311. if type == "text":
  312. return "clob"
  313. if type in ("blob", "mediumblob"):
  314. return "blob"
  315. if type == "decimal":
  316. return (
  317. f"number({','.join(str(s) for s in size)})" if len(size) else "number"
  318. )
  319. def gen_create(self, ddl) -> str:
  320. """生成 CREATE 语句"""
  321. def generate_column(col):
  322. name = col["name"].lower()
  323. if name == "deleted":
  324. return "deleted number(1,0) DEFAULT 0 NOT NULL"
  325. type = col["type"].lower()
  326. full_type = self.translate_type(type, col["size"])
  327. nullable = "NULL" if col["nullable"] else "NOT NULL"
  328. default = f"DEFAULT {col['default']}" if col["default"] is not None else ""
  329. # Oracle 中 size 不能作为字段名
  330. field_name = '"size"' if name == "size" else name
  331. # Oracle DEFAULT 定义在 NULLABLE 之前
  332. return f"{field_name} {full_type} {default} {nullable}"
  333. table_name = ddl["table_name"].lower()
  334. columns = [f"{generate_column(col).strip()}" for col in ddl["columns"]]
  335. field_def_list = ",\n ".join(columns)
  336. script = f"""-- ----------------------------
  337. -- Table structure for {table_name}
  338. -- ----------------------------
  339. CREATE TABLE {table_name} (
  340. {field_def_list}
  341. );"""
  342. # oracle INSERT '' 不能通过 NOT NULL 校验
  343. script = script.replace("DEFAULT '' NOT NULL", "DEFAULT '' NULL")
  344. return script
  345. def gen_index(self, ddl: Dict) -> str:
  346. return "\n".join(f"{script};" for script in self.index(ddl))
  347. def gen_comment(self, table_sql: str, table_name: str) -> str:
  348. script = ""
  349. for field, comment_string in self.filed_comments(table_sql):
  350. script += (
  351. f"COMMENT ON COLUMN {table_name}.{field} IS '{comment_string}';" + "\n"
  352. )
  353. table_comment = self.table_comment(table_sql)
  354. if table_comment:
  355. script += f"COMMENT ON TABLE {table_name} IS '{table_comment}';\n"
  356. return script
  357. def gen_pk(self, table_name: str) -> str:
  358. """生成主键定义"""
  359. return f"ALTER TABLE {table_name} ADD CONSTRAINT pk_{table_name} PRIMARY KEY (id);\n"
  360. def gen_index(self, ddl: Dict) -> str:
  361. return "\n".join(f"{script};" for script in self.index(ddl))
  362. def gen_insert(self, table_name: str) -> str:
  363. """拷贝 INSERT 语句"""
  364. inserts = []
  365. for insert_script in Convertor.inserts(table_name, self.content):
  366. # 对日期数据添加 TO_DATE 转换
  367. insert_script = re.sub(
  368. r"('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}')",
  369. r"to_date(\g<1>, 'SYYYY-MM-DD HH24:MI:SS')",
  370. insert_script,
  371. )
  372. inserts.append(insert_script)
  373. ## 生成 insert 脚本
  374. script = ""
  375. last_id = 0
  376. if inserts:
  377. inserts_lines = "\n".join(inserts)
  378. script += f"""\n\n-- ----------------------------
  379. -- Records of {table_name.lower()}
  380. -- ----------------------------
  381. -- @formatter:off
  382. {inserts_lines}
  383. COMMIT;
  384. -- @formatter:on"""
  385. match = re.search(r"VALUES \((\d+),", inserts[-1])
  386. if match:
  387. last_id = int(match.group(1))
  388. # 生成 Sequence
  389. script += f"""
  390. CREATE SEQUENCE {table_name}_seq
  391. START WITH {last_id + 1};"""
  392. return script
  393. class SQLServerConvertor(Convertor):
  394. """_summary_
  395. Args:
  396. Convertor (_type_): _description_
  397. """
  398. def __init__(self, src):
  399. super().__init__(src, "Microsoft SQL Server")
  400. def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]):
  401. """类型转换"""
  402. type = type.lower()
  403. if type == "varchar":
  404. return f"nvarchar({size if size < 4000 else 4000})"
  405. if type == "int":
  406. return "int"
  407. if type == "bigint" or type == "bigint unsigned":
  408. return "bigint"
  409. if type == "datetime":
  410. return "datetime2"
  411. if type == "bit":
  412. return "varchar(1)"
  413. if type in ("tinyint", "smallint"):
  414. return "tinyint"
  415. if type == "text":
  416. return "nvarchar(max)"
  417. if type in ("blob", "mediumblob"):
  418. return "varbinary(max)"
  419. if type == "decimal":
  420. return (
  421. f"numeric({','.join(str(s) for s in size)})" if len(size) else "numeric"
  422. )
  423. def gen_create(self, ddl: Dict) -> str:
  424. """生成 create"""
  425. def _generate_column(col):
  426. name = col["name"].lower()
  427. if name == "id":
  428. return "id bigint NOT NULL PRIMARY KEY IDENTITY"
  429. if name == "deleted":
  430. return "deleted bit DEFAULT 0 NOT NULL"
  431. type = col["type"].lower()
  432. full_type = self.translate_type(type, col["size"])
  433. nullable = "NULL" if col["nullable"] else "NOT NULL"
  434. default = f"DEFAULT {col['default']}" if col["default"] is not None else ""
  435. return f"{name} {full_type} {default} {nullable}"
  436. table_name = ddl["table_name"].lower()
  437. columns = [f"{_generate_column(col).strip()}" for col in ddl["columns"]]
  438. filed_def_list = ",\n ".join(columns)
  439. script = f"""-- ----------------------------
  440. -- Table structure for {table_name}
  441. -- ----------------------------
  442. DROP TABLE IF EXISTS {table_name};
  443. CREATE TABLE {table_name} (
  444. {filed_def_list}
  445. )
  446. GO"""
  447. return script
  448. def gen_comment(self, table_sql: str, table_name: str) -> str:
  449. """生成字段及表的注释"""
  450. script = ""
  451. for field, comment_string in self.filed_comments(table_sql):
  452. script += f"""EXEC sp_addextendedproperty
  453. 'MS_Description', N'{comment_string}',
  454. 'SCHEMA', N'dbo',
  455. 'TABLE', N'{table_name}',
  456. 'COLUMN', N'{field}'
  457. GO
  458. """
  459. table_comment = self.table_comment(table_sql)
  460. if table_comment:
  461. script += f"""EXEC sp_addextendedproperty
  462. 'MS_Description', N'{table_comment}',
  463. 'SCHEMA', N'dbo',
  464. 'TABLE', N'{table_name}'
  465. GO
  466. """
  467. return script
  468. def gen_pk(self, table_name: str) -> str:
  469. """生成主键定义"""
  470. return ""
  471. def gen_index(self, ddl: Dict) -> str:
  472. """生成 index"""
  473. return "\n".join(f"{script}\nGO" for script in self.index(ddl))
  474. def gen_insert(self, table_name: str) -> str:
  475. """生成 insert 语句"""
  476. # 收集 `table_name` 对应的 insert 语句
  477. inserts = []
  478. for insert_script in Convertor.inserts(table_name, self.content):
  479. # SQLServer: 字符串前加N,hack,是否存在替换字符串内容的风险
  480. insert_script = insert_script.replace(", '", ", N'").replace(
  481. "VALUES ('", "VALUES (N')"
  482. )
  483. # 删除 insert 的结尾分号
  484. insert_script = re.sub(";$", r"\nGO", insert_script)
  485. inserts.append(insert_script)
  486. ## 生成 insert 脚本
  487. script = ""
  488. if inserts:
  489. inserts_lines = "\n".join(inserts)
  490. script += f"""\n\n-- ----------------------------
  491. -- Records of {table_name.lower()}
  492. -- ----------------------------
  493. -- @formatter:off
  494. BEGIN TRANSACTION
  495. GO
  496. SET IDENTITY_INSERT {table_name.lower()} ON
  497. GO
  498. {inserts_lines}
  499. SET IDENTITY_INSERT {table_name.lower()} OFF
  500. GO
  501. COMMIT
  502. GO
  503. -- @formatter:on"""
  504. return script
  505. def gen_dual(self) -> str:
  506. return """DROP TABLE IF EXISTS dual
  507. GO
  508. CREATE TABLE dual
  509. (
  510. id int NULL
  511. )
  512. GO
  513. EXEC sp_addextendedproperty
  514. 'MS_Description', N'数据库连接的表',
  515. 'SCHEMA', N'dbo',
  516. 'TABLE', N'dual'
  517. GO"""
  518. class DM8Convertor(Convertor):
  519. def __init__(self, src):
  520. super().__init__(src, "DM8")
  521. def translate_type(self, type: str, size: Optional[Union[int, Tuple[int]]]):
  522. """类型转换"""
  523. type = type.lower()
  524. if type == "varchar":
  525. return f"varchar({size})"
  526. if type == "int":
  527. return "int"
  528. if type == "bigint" or type == "bigint unsigned":
  529. return "bigint"
  530. if type == "datetime":
  531. return "datetime"
  532. if type == "bit":
  533. return "bit"
  534. if type in ("tinyint", "smallint"):
  535. return "smallint"
  536. if type == "text":
  537. return "text"
  538. if type == "blob":
  539. return "blob"
  540. if type == "mediumblob":
  541. return "varchar(10240)"
  542. if type == "decimal":
  543. return (
  544. f"decimal({','.join(str(s) for s in size)})" if len(size) else "decimal"
  545. )
  546. def gen_create(self, ddl) -> str:
  547. """生成 CREATE 语句"""
  548. def generate_column(col):
  549. name = col["name"].lower()
  550. if name == "id":
  551. return "id bigint NOT NULL PRIMARY KEY IDENTITY"
  552. type = col["type"].lower()
  553. full_type = self.translate_type(type, col["size"])
  554. nullable = "NULL" if col["nullable"] else "NOT NULL"
  555. default = f"DEFAULT {col['default']}" if col["default"] is not None else ""
  556. return f"{name} {full_type} {default} {nullable}"
  557. table_name = ddl["table_name"].lower()
  558. columns = [f"{generate_column(col).strip()}" for col in ddl["columns"]]
  559. field_def_list = ",\n ".join(columns)
  560. script = f"""-- ----------------------------
  561. -- Table structure for {table_name}
  562. -- ----------------------------
  563. CREATE TABLE {table_name} (
  564. {field_def_list}
  565. );"""
  566. # oracle INSERT '' 不能通过 NOT NULL 校验
  567. script = script.replace("DEFAULT '' NOT NULL", "DEFAULT '' NULL")
  568. return script
  569. def gen_index(self, ddl: Dict) -> str:
  570. return "\n".join(f"{script};" for script in self.index(ddl))
  571. def gen_comment(self, table_sql: str, table_name: str) -> str:
  572. script = ""
  573. for field, comment_string in self.filed_comments(table_sql):
  574. script += (
  575. f"COMMENT ON COLUMN {table_name}.{field} IS '{comment_string}';" + "\n"
  576. )
  577. table_comment = self.table_comment(table_sql)
  578. if table_comment:
  579. script += f"COMMENT ON TABLE {table_name} IS '{table_comment}';\n"
  580. return script
  581. def gen_pk(self, table_name: str) -> str:
  582. """生成主键定义"""
  583. return ""
  584. def gen_index(self, ddl: Dict) -> str:
  585. return "\n".join(f"{script};" for script in self.index(ddl))
  586. def gen_insert(self, table_name: str) -> str:
  587. """拷贝 INSERT 语句"""
  588. inserts = list(Convertor.inserts(table_name, self.content))
  589. ## 生成 insert 脚本
  590. script = ""
  591. if inserts:
  592. inserts_lines = "\n".join(inserts)
  593. script += f"""\n\n-- ----------------------------
  594. -- Records of {table_name.lower()}
  595. -- ----------------------------
  596. -- @formatter:off
  597. SET IDENTITY_INSERT {table_name.lower()} ON;
  598. {inserts_lines}
  599. COMMIT;
  600. SET IDENTITY_INSERT {table_name.lower()} OFF;
  601. -- @formatter:on"""
  602. return script
  603. def main():
  604. parser = argparse.ArgumentParser(description="芋道系统数据库转换工具")
  605. parser.add_argument(
  606. "type",
  607. type=str,
  608. help="目标数据库类型",
  609. choices=["postgres", "oracle", "sqlserver", "dm8"],
  610. )
  611. args = parser.parse_args()
  612. sql_file = pathlib.Path("../mysql/ruoyi-vue-pro.sql").resolve().as_posix()
  613. convertor = None
  614. if args.type == "postgres":
  615. convertor = PostgreSQLConvertor(sql_file)
  616. elif args.type == "oracle":
  617. convertor = OracleConvertor(sql_file)
  618. elif args.type == "sqlserver":
  619. convertor = SQLServerConvertor(sql_file)
  620. elif args.type == "dm8":
  621. convertor = DM8Convertor(sql_file)
  622. else:
  623. raise NotImplementedError(f"不支持目标数据库类型: {args.type}")
  624. convertor.print()
  625. if __name__ == "__main__":
  626. main()