-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglot
More file actions
executable file
·60 lines (45 loc) · 1.6 KB
/
glot
File metadata and controls
executable file
·60 lines (45 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env python3
import argparse
from pathlib import Path
import sqlglot
from sqlglot.optimizer import optimize
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class SqlFileChangeHandler(FileSystemEventHandler):
def __init__(self, src, tgt):
self.src_path = Path(f'{src}.sql').resolve()
self.tgt_path = Path(f'{tgt}.sql').resolve()
self.src = src
self.tgt = tgt
def on_modified(self, event):
if Path(event.src_path).resolve() == self.src_path:
self.transpile_and_format_sql()
def transpile_and_format_sql(self):
with open(self.src_path, 'r') as file:
sql = file.read()
optimized = optimize(sqlglot.parse_one(sql)).sql(pretty=True)
transpiled = '\n'.join(sqlglot.transpile(optimized, read=self.src, write=self.tgt, pretty=True))
with open(self.tgt_path, 'w') as file:
file.write(transpiled)
print(f'\t{self.src_path.name} ▸ {self.tgt_path.name}')
def main():
parser = argparse.ArgumentParser(description='Monitor and transpile SQL files.')
parser.add_argument('src_dialect', default='duckdb', nargs='?', help='Source SQL dialect')
parser.add_argument('tgt_dialect', default='mysql', nargs='?', help='Target SQL dialect')
args = parser.parse_args()
src = args.src_dialect
tgt = args.tgt_dialect
Path(f'{src}.sql').touch()
event_handler = SqlFileChangeHandler(src, tgt)
observer = Observer()
observer.schedule(event_handler, path=Path(src).parent)
observer.start()
print(f'Monitoring {src}.sql for changes...')
try:
while True:
pass
except KeyboardInterrupt:
observer.stop()
observer.join()
if __name__ == '__main__':
main()