• 数据库:Hive转Presto(三)


    继续上节代码。

    1. import re
    2. import os
    3. import tkinter.filedialog
    4. from tkinter import *
    5. class Hive2Presto:
    6. def __int__(self):
    7. self.t_funcs = ['substr', 'nvl', 'substring', 'unix_timestamp'] + \
    8. ['to_date', 'concat', 'sum', 'avg', 'abs', 'year', 'month', 'ceiling', 'floor']
    9. self.time_funcs = ['date_add', 'datediff', 'add_months']
    10. self.funcs = self.t_funcs + self.time_funcs
    11. self.current_path = os.path.abspath(__file__)
    12. self.dir = os.path.dirname(self.current_path)
    13. self.result = []
    14. self.error = []
    15. self.filename = ''
    16. def main(self):
    17. self.root = Tk()
    18. self.root.config(bg='#ff741d') # 背景颜色设置为公司主题色^_^
    19. self.root.title('Hive转Presto')
    20. self.win_width = 550
    21. self.win_height = 500
    22. self.screen_width = self.root.winfo_screenwidth()
    23. self.screen_height = self.root.winfo_screenheight()
    24. self.x = (self.screen_width - self.win_width) // 2
    25. self.y = (self.screen_height - self.win_height) // 2
    26. self.root.geometry(f'{self.win_width}x{self.win_height}+{self.x}+{self.y}')
    27. font = ('楷体', 11)
    28. self.button = Button(self.root, text='转换', command=self.trans, bg='#ffcc8c', font=font, anchor='e')
    29. self.button.grid(row=0, column=0, padx=100, pady=10, sticky=W)
    30. self.file_button = Button(self.root, text='选择文件', command=self.choose_file, bg='#ffcc8c', font=font,
    31. anchor='e')
    32. self.file_button.grid(row=0, column=1, padx=0, pady=10, sticky=W)
    33. self.entry = Entry(self.root, width=65, font=font)
    34. self.entry.insert(0, '输入Hive代码')
    35. self.entry.grid(row=1, column=0, padx=10, pady=10, columnspan=2)
    36. self.entry.bind('', self.delete_text)
    37. self.text = Text(self.root, width=75, height=20)
    38. self.text.grid(row=2, column=0, padx=10, pady=10, columnspan=2)
    39. self.des_label = Label(self.root, text='可以复制结果,也有生成的文件,与选取的文件同文件夹', bg='#ffcc8c',
    40. font=('楷体', 10))
    41. self.des_label.grid(row=3, column=0, padx=10, pady=10, columnspan=2)
    42. s = ''
    43. for i in range(0, (n := len(self.funcs)), 4):
    44. if i + 4 <= n:
    45. s += ','.join(self.funcs[i:i + 4]) + '\n'
    46. else:
    47. s += ','.join(self.funcs[i:]) + '\n'
    48. s = s[:-1]
    49. self.des_label1 = Label(self.root, text=s, bg='#ffcc8c',
    50. font=('楷体', 10))
    51. self.des_label1.grid(row=4, column=0, padx=10, pady=10, columnspan=2)
    52. self.root.columnconfigure(0, minsize=10)
    53. self.root.columnconfigure(1, minsize=10)
    54. self.root.columnconfigure(0, pad=5)
    55. self.root.mainloop()
    56. def replace_func(self, s, res):
    57. """
    58. 把搜索到函数整体取出来,处理括号中的参数
    59. :param s:
    60. :param res:
    61. :return:
    62. """
    63. for f in res:
    64. f1 = f.replace('\n', '').strip()
    65. f1 = re.sub(r'(\s*)', '(', f1)
    66. # 搜索括号里的字符串
    67. if re.findall(r'(\w*)\(', f1):
    68. func_name = re.findall(r'(\w*)\(', f1)[0].strip()
    69. else:
    70. continue
    71. try:
    72. if 'date_add' == func_name.lower():
    73. date, date_num = self.extact_func(f1, func_name)
    74. s_n = f"date_add('day',{date_num},cast(substr(cast{date} as varchar,1,10) as date))"
    75. s = s.replace(f, s_n)
    76. elif 'datediff' == func_name.lower():
    77. date1, date2 = self.extact_func(f1, func_name)
    78. s_n = f"date_add('day',{date2},cast(substr(cast{date} as varchar,1,10) as date),cast(substr(cast{date1} as varchar),1,10) as date))"
    79. s = s.replace(f, s_n)
    80. elif 'nvl' == func_name.lower():
    81. s1, s2 = self.extact_func(f1, func_name)
    82. s_n = f"coalesce({s1},{s2})"
    83. s = s.replace(f, s_n)
    84. elif 'substr' == func_name.lower():
    85. date, start, end = self.extact_func(f1, func_name)
    86. s_n = f"substr(cast({date} as varchar),{start},{end}"
    87. s = s.replace(f, s_n)
    88. elif 'substring' == func_name.lower():
    89. date, start, end = self.extact_func(f1, func_name)
    90. s_n = f"substring(cast({date} as varchar),{start},{end}"
    91. s = s.replace(f, s_n)
    92. elif 'unit_timestamp' == func_name.lower():
    93. date = self.extact_func(f1, func_name)[0]
    94. s_n = f"to_unixtime(cast({date} as timestanp))"
    95. s = s.replace(f, s_n)
    96. elif 'to_date' == func_name.lower():
    97. date = self.extact_func(f1, func_name)[0]
    98. s_n = f"cast({date} as date)"
    99. s = s.replace(f, s_n)
    100. elif 'concat' == func_name.lower():
    101. res = self.extact_func(f1, func_name)[0]
    102. s_n = f'concat('
    103. for r in res:
    104. r = r.strip().replace('\n', '')
    105. s_n += f"cast({r} as varchar),"
    106. s_n = s_n[:-1] + ')'
    107. s = s.replace(f, s_n)
    108. elif 'sum' == func_name.lower():
    109. if 'unix_timestamp' in f1 or 'to_unixtime' in f1:
    110. continue
    111. ss = self.extact_func(f1, func_name)[0]
    112. if 'if(' in ss.replace(' ', ''):
    113. continue
    114. s = self.func_trans(f, f1, func_name, ss, s)
    115. elif 'avg' == func_name.lower():
    116. if 'unix_timestamp' in f1 or 'to_unixtime' in f1:
    117. continue
    118. ss = self.extact_func(f1, func_name)[0]
    119. if 'if(' in ss.replace(' ', ''):
    120. continue
    121. s = self.func_trans(f, f1, func_name, ss, s)
    122. elif 'abs' == func_name.lower():
    123. if 'unix_timestamp' in f1 or 'to_unixtime' in f1:
    124. continue
    125. ss = self.extact_func(f1, func_name)[0]
    126. if 'if(' in ss.replace(' ', ''):
    127. continue
    128. s = self.func_trans(f, f1, func_name, ss, s)
    129. elif 'ceiling' == func_name.lower():
    130. if 'unix_timestamp' in f1 or 'to_unixtime' in f1:
    131. continue
    132. ss = self.extact_func(f1, func_name)[0]
    133. if 'if(' in ss.replace(' ', ''):
    134. continue
    135. s = self.func_trans(f, f1, func_name, ss, s)
    136. elif 'floor' == func_name.lower():
    137. if 'unix_timestamp' in f1 or 'to_unixtime' in f1:
    138. continue
    139. ss = self.extact_func(f1, func_name)[0]
    140. if 'if(' in ss.replace(' ', ''):
    141. continue
    142. s = self.func_trans(f, f1, func_name, ss, s)
    143. elif 'year' == func_name.lower():
    144. date = self.extact_func(f1, func_name)[0]
    145. s_n = f"year(cast(substr(cast({date} as varchar,1,10) as date))"
    146. s = s.replace(f, s_n)
    147. elif 'month' == func_name.lower():
    148. date = self.extact_func(f1, func_name)[0]
    149. s_n = f"month(cast(substr(cast({date} as varchar,1,10) as date))"
    150. s = s.replace(f, s_n)
    151. except:
    152. self.error.append(f"源代码中{func_name}函数参数输入可能有错误,具体为:{f1}")
    153. continue
    154. if self.error:
    155. self.entry.delete(0, END)
    156. self.text.delete("1.0", END)
    157. self.text.insert("end", f"{s}")
    158. self.error.insert(0, '转换失败,有部分没有转成功\n')
    159. root_ex = Tk()
    160. root_ex.title('错误')
    161. win_width = 600
    162. win_height = 200
    163. screen_width = root_ex.winfo_screenwidth()
    164. screen_height = root_ex.winfo_screenheight()
    165. x = (screen_width - win_width) // 2
    166. y = (screen_height - win_height) // 2
    167. root_ex.geometry(f'{win_width}x{win_height}+{x}+{y}')
    168. label_ex = Label(root_ex, text="\n".join(self.error), font=("楷体", 10))
    169. label_ex.pack()
    170. root_ex.mainloop()
    171. return s
    172. def func_trans(self, f, f1, func_name, ss, s):
    173. if not ('+' in ss or '-' in ss or '*' in ss or '/' in ss):
    174. date = self.extact_func(f1, func_name)[0]
    175. s_n = f'{func_name}(cast{date} as double))'
    176. s = s.replace(f, s_n)
    177. else:
    178. res1 = self.mysplit(f1)
    179. s_n = f
    180. n = len(s_n)
    181. for item in res1:
    182. if any(c.isalpha() for c in item.replace(' ', '')):
    183. idxs = s_n.find(item)
    184. idxs = [idxs] if type(idxs) != list else idxs
    185. for idx in idxs:
    186. if idx + len(item) + 3 <= n:
    187. if not 'as' in s_n[idx:idx + len(item) + 4]:
    188. s_n = re.sub(rf'\b{item}\b', f'cast({item} as double)', s_n)
    189. else:
    190. s_n = re.sub(rf'\b{item}\b', f'cast({item} as double)', s_n)
    191. s = s.replace(f, s_n)
    192. return s
    193. def choose_file(self):
    194. """
    195. 如果代码太多,从text中输入会很卡,直接选择代码文件输入会很快
    196. :return:
    197. """
    198. self.filename = tkinter.filedialog.askopenfilename()
    199. if '/' in self.filename:
    200. self.filename = self.filename.replace('/', '\\')
    201. self.entry.delete(0, END)
    202. self.entry.insert(0, self.filename)
    203. def findvar(self, ss):
    204. """
    205. 搜索与计算有关的字段
    206. :param ss:
    207. :return:
    208. """
    209. b = ['+', '-', '*', '/', '=', '!=', '>', '<', '<=', '>=', '<>']
    210. result1 = []
    211. result2 = []
    212. result1_n = []
    213. result1_n = []
    214. res_ops = []
    215. res1_ops = []
    216. res_adj = []
    217. res1_adj = []
    218. def mysplit(self, s):
    219. """
    220. 分割字段
    221. :param s:
    222. :return:
    223. """
    224. pass
    225. def extact_func(self, s, func_name):
    226. pass
    227. def delete_text(self, event):
    228. pass
    229. def trans(self):
    230. pass
    231. if __name__ == '__main__':
    232. pro = Hive2Presto()
    233. pro.__int__()
    234. pro.main()

  • 相关阅读:
    SpringBoot 测试实践 - 1:常用的工具
    HarmonyOS UI 开发
    1.UEFI环境搭建
    java计算机毕业设计在线影院系统源码+系统+mysql数据库+lw文档+部署
    Flutter 高级教程之如何开发iOS Widget小组件展示SQLite本地数据库数据(教程含完整源码)
    查看Visual Studio软件_MSC_VER值(MSVC编译器版本)的方法
    Ubuntu18保姆级教程及其jdk和hadoop安装含资源
    怎么制作一个网站?怎样搭建一个高质量的网站?
    halcon之区域:多种区域(Region)特征(6)
    【JQuery】JQuery入门——模拟用户分组以及页面换肤
  • 原文地址:https://blog.csdn.net/Sanfenpai6/article/details/133637214