cdmduck 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cdmduck-0.0.1/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
cdmduck-0.0.1/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ cdmduck
2
+ Copyright 2026 cdmduck authors
3
+
4
+ This product includes software and data derived from OHDSI SqlRender
5
+ (https://github.com/OHDSI/SqlRender), Copyright Observational Health Data
6
+ Sciences and Informatics, licensed under the Apache License, Version 2.0:
7
+ - src/cdmduck/sqlrender (Python port of org.ohdsi.sql.*)
8
+ - src/cdmduck/sqlrender/csv/replacementPatterns.csv (verbatim)
9
+ - ref/java, tests/java/org (verbatim Java reference sources)
cdmduck-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: cdmduck
3
+ Version: 0.0.1
4
+ Summary: OMOP CDM / OHDSI ATLAS-compatible tools on DuckDB: SqlRender, Circe and a WebAPI-compatible server in pure Python
5
+ Author-email: Hyung-Chul Lee <lucid80@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/vitaldb/cdmduck
8
+ Project-URL: Source, https://github.com/vitaldb/cdmduck
9
+ Keywords: omop,cdm,ohdsi,atlas,sqlrender,circe,duckdb
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Healthcare Industry
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Database
15
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ License-File: NOTICE
20
+ Provides-Extra: server
21
+ Requires-Dist: duckdb>=1.0; extra == "server"
22
+ Requires-Dist: fastapi; extra == "server"
23
+ Requires-Dist: uvicorn; extra == "server"
24
+ Dynamic: license-file
25
+
26
+ <p align="center"><img src="https://raw.githubusercontent.com/vitaldb/cdmduck/main/docs/logo.png" alt="cdmduck" width="320"></p>
27
+
28
+ # cdmduck
29
+
30
+ **OMOP data. Simpler. Faster. Everywhere.** — OHDSI ATLAS-compatible tools for the OMOP CDM,
31
+ in pure Python on DuckDB. No Java, no Postgres, no Docker.
32
+
33
+ OMOP CDM · OHDSI ATLAS 호환 도구를 DuckDB 위에서, 순수 파이썬으로.
34
+
35
+ ```
36
+ pip install cdmduck
37
+ ```
38
+
39
+ | 모듈 | 원본 (OHDSI, Apache 2.0) | 상태 |
40
+ |---|---|---|
41
+ | `cdmduck.sqlrender` | SqlRender (Java) | 이식 완료 — Java 판과 58,440 건 글자 단위 일치 |
42
+ | `cdmduck.circe` | circe-be (Java) | 예정 |
43
+ | `cdmduck.webapi` | WebAPI 3.0 (Java) — ATLAS 3.0 화면이 부르는 API | 예정 |
44
+
45
+ ```python
46
+ from cdmduck.sqlrender import render, translate
47
+ sql = render("SELECT TOP 10 * FROM @cdm.person {@adult}?{WHERE year_of_birth < 2000};", cdm="main", adult=True)
48
+ translate(sql, "duckdb") # SELECT * FROM main.person WHERE year_of_birth < 2000 LIMIT 10;
49
+ ```
50
+
51
+ ```
52
+ cdmduck translate query.sql duckdb -p cdm=main
53
+ cdmduck dialects
54
+ ```
55
+
56
+ ## Java 판과의 동등성 검증
57
+
58
+ `tests/equiv/` — SqlRender R 테스트 문자열 2,009개, Circe·WebAPI SQL 763개(×16 방언·렌더·분할),
59
+ 합성 조건식 3,000개를 Java 원본(`tests/java`, JDK 22+ 소스 실행)과 이 이식본에 넣어 결과를 비교한다.
60
+
61
+ ```
62
+ python3 tests/equiv/build_corpus.py <클론 디렉터리> cases.tsv
63
+ python3 tests/equiv/run_java.py cases.tsv java.out 24
64
+ PYTHONPATH=src python3 tests/equiv/py_harness.py cases.tsv py.out 32
65
+ python3 tests/equiv/diff.py cases.tsv java.out py.out
66
+ ```
67
+
68
+ 알려진 차이: Java 내부 예외(EmptyStack, ArrayIndexOutOfBounds)의 메시지 문구만 다르다(예외가 나는 자리는 같다).
69
+ BMP 밖 문자(이모지 등)는 Java 가 UTF-16 대리쌍 둘로 보므로 위치가 달라질 수 있다.
70
+
71
+ ## 라이선스
72
+
73
+ Apache 2.0. `src/cdmduck/sqlrender/csv/replacementPatterns.csv` 와 `ref/java`, `tests/java/org` 는
74
+ OHDSI SqlRender 에서 가져왔다(`third_party/`, `NOTICE`).
@@ -0,0 +1,49 @@
1
+ <p align="center"><img src="https://raw.githubusercontent.com/vitaldb/cdmduck/main/docs/logo.png" alt="cdmduck" width="320"></p>
2
+
3
+ # cdmduck
4
+
5
+ **OMOP data. Simpler. Faster. Everywhere.** — OHDSI ATLAS-compatible tools for the OMOP CDM,
6
+ in pure Python on DuckDB. No Java, no Postgres, no Docker.
7
+
8
+ OMOP CDM · OHDSI ATLAS 호환 도구를 DuckDB 위에서, 순수 파이썬으로.
9
+
10
+ ```
11
+ pip install cdmduck
12
+ ```
13
+
14
+ | 모듈 | 원본 (OHDSI, Apache 2.0) | 상태 |
15
+ |---|---|---|
16
+ | `cdmduck.sqlrender` | SqlRender (Java) | 이식 완료 — Java 판과 58,440 건 글자 단위 일치 |
17
+ | `cdmduck.circe` | circe-be (Java) | 예정 |
18
+ | `cdmduck.webapi` | WebAPI 3.0 (Java) — ATLAS 3.0 화면이 부르는 API | 예정 |
19
+
20
+ ```python
21
+ from cdmduck.sqlrender import render, translate
22
+ sql = render("SELECT TOP 10 * FROM @cdm.person {@adult}?{WHERE year_of_birth < 2000};", cdm="main", adult=True)
23
+ translate(sql, "duckdb") # SELECT * FROM main.person WHERE year_of_birth < 2000 LIMIT 10;
24
+ ```
25
+
26
+ ```
27
+ cdmduck translate query.sql duckdb -p cdm=main
28
+ cdmduck dialects
29
+ ```
30
+
31
+ ## Java 판과의 동등성 검증
32
+
33
+ `tests/equiv/` — SqlRender R 테스트 문자열 2,009개, Circe·WebAPI SQL 763개(×16 방언·렌더·분할),
34
+ 합성 조건식 3,000개를 Java 원본(`tests/java`, JDK 22+ 소스 실행)과 이 이식본에 넣어 결과를 비교한다.
35
+
36
+ ```
37
+ python3 tests/equiv/build_corpus.py <클론 디렉터리> cases.tsv
38
+ python3 tests/equiv/run_java.py cases.tsv java.out 24
39
+ PYTHONPATH=src python3 tests/equiv/py_harness.py cases.tsv py.out 32
40
+ python3 tests/equiv/diff.py cases.tsv java.out py.out
41
+ ```
42
+
43
+ 알려진 차이: Java 내부 예외(EmptyStack, ArrayIndexOutOfBounds)의 메시지 문구만 다르다(예외가 나는 자리는 같다).
44
+ BMP 밖 문자(이모지 등)는 Java 가 UTF-16 대리쌍 둘로 보므로 위치가 달라질 수 있다.
45
+
46
+ ## 라이선스
47
+
48
+ Apache 2.0. `src/cdmduck/sqlrender/csv/replacementPatterns.csv` 와 `ref/java`, `tests/java/org` 는
49
+ OHDSI SqlRender 에서 가져왔다(`third_party/`, `NOTICE`).
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "cdmduck"
7
+ version = "0.0.1"
8
+ description = "OMOP CDM / OHDSI ATLAS-compatible tools on DuckDB: SqlRender, Circe and a WebAPI-compatible server in pure Python"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.8"
12
+ authors = [{ name = "Hyung-Chul Lee", email = "lucid80@gmail.com" }]
13
+ keywords = ["omop", "cdm", "ohdsi", "atlas", "sqlrender", "circe", "duckdb"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Healthcare Industry",
17
+ "Intended Audience :: Science/Research",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Database",
20
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
21
+ ]
22
+ dependencies = []
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/vitaldb/cdmduck"
26
+ Source = "https://github.com/vitaldb/cdmduck"
27
+
28
+ [project.optional-dependencies]
29
+ server = ["duckdb>=1.0", "fastapi", "uvicorn"]
30
+
31
+ [project.scripts]
32
+ cdmduck = "cdmduck.cli:main"
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["src"]
36
+
37
+ [tool.setuptools.package-data]
38
+ "cdmduck.sqlrender" = ["csv/*.csv"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,2 @@
1
+ """cdmduck — OMOP CDM · OHDSI ATLAS 호환 도구를 DuckDB 위에서, 순수 파이썬으로."""
2
+ __version__ = '0.0.1'
@@ -0,0 +1,28 @@
1
+ """명령어 `cdmduck`."""
2
+ import argparse
3
+ import sys
4
+
5
+
6
+ def main(argv=None):
7
+ ap = argparse.ArgumentParser(prog='cdmduck', description='OMOP CDM / ATLAS-compatible tools on DuckDB')
8
+ sub = ap.add_subparsers(dest='cmd', required=True)
9
+ t = sub.add_parser('translate', help='SQL Server 방언 SQL 을 대상 방언으로 번역')
10
+ t.add_argument('file', help="SQL 파일 ('-' 는 표준입력)")
11
+ t.add_argument('dialect')
12
+ t.add_argument('--temp-schema')
13
+ t.add_argument('-p', '--param', action='append', default=[], metavar='KEY=VALUE', help='번역 전에 렌더할 파라미터')
14
+ sub.add_parser('dialects', help='지원 방언 목록')
15
+ a = ap.parse_args(argv)
16
+ from .sqlrender import dialects, render, translate
17
+ if a.cmd == 'dialects':
18
+ print('\n'.join(dialects()))
19
+ elif a.cmd == 'translate':
20
+ sql = sys.stdin.read() if a.file == '-' else open(a.file, encoding='utf-8').read()
21
+ if a.param:
22
+ sql = render(sql, **dict(p.split('=', 1) for p in a.param))
23
+ sys.stdout.write(translate(sql, a.dialect, temp_emulation_schema=a.temp_schema))
24
+ return 0
25
+
26
+
27
+ if __name__ == '__main__':
28
+ sys.exit(main())
@@ -0,0 +1,37 @@
1
+ """OHDSI SqlRender 의 파이썬 이식 — Java 판과 출력이 글자 단위로 같도록 맞춘다.
2
+
3
+ from cdmduck.sqlrender import render, translate
4
+ sql = render("SELECT * FROM @cdm.person {@limit}?{LIMIT 10}", cdm="main", limit=True)
5
+ sql = translate(sql, "duckdb")
6
+ """
7
+ from ._java import JavaError
8
+ from ._render import check as check_render
9
+ from ._render import render_sql
10
+ from ._strings import split_sql
11
+ from ._translate import (check as check_translate, dialects, generate_session_id, set_replacement_patterns,
12
+ translate_single_statement_sql, translate_sql)
13
+
14
+ __all__ = ['render', 'translate', 'translate_single_statement', 'split_sql', 'render_sql', 'translate_sql',
15
+ 'translate_single_statement_sql', 'dialects', 'generate_session_id', 'set_replacement_patterns',
16
+ 'check_render', 'check_translate', 'JavaError']
17
+
18
+
19
+ def _value(v):
20
+ """R SqlRender 와 같은 값 변환: 논리값은 TRUE/FALSE, 목록은 쉼표로 잇는다."""
21
+ if isinstance(v, bool):
22
+ return 'TRUE' if v else 'FALSE'
23
+ if isinstance(v, (list, tuple, set)):
24
+ return ','.join(_value(x) for x in v)
25
+ return str(v)
26
+
27
+
28
+ def render(sql, **params):
29
+ return render_sql(sql, list(params), [_value(v) for v in params.values()])
30
+
31
+
32
+ def translate(sql, target_dialect, temp_emulation_schema=None, session_id=None):
33
+ return translate_sql(sql, target_dialect, session_id, temp_emulation_schema)
34
+
35
+
36
+ def translate_single_statement(sql, target_dialect, temp_emulation_schema=None, session_id=None):
37
+ return translate_single_statement_sql(sql, target_dialect, session_id, temp_emulation_schema)
@@ -0,0 +1,207 @@
1
+ """org.ohdsi.sql.BigQuerySparkTranslate 포팅 (DB 연결이 필요한 sparkHandleInsert 는 제외)."""
2
+ import re
3
+
4
+ from ._java import JavaError, split, substring, trim
5
+ from ._strings import split_sql, tokenize_sql
6
+ from ._translate import parse_search_pattern, search
7
+
8
+ SELECT, GROUP_BY, ORDER_BY, WITH_COLUMNS, IN = range(5)
9
+
10
+
11
+ class _CommaListIterator:
12
+ def __init__(self, expression_list, list_type):
13
+ self.list_type = list_type
14
+ self.expression_list = expression_list
15
+ self._split_list()
16
+ self.expression_list = ',' + self.expression_list + ','
17
+ self.pattern = parse_search_pattern(', @@a ,')
18
+ self.cur = search(self.expression_list, self.pattern, 0)
19
+ if self.cur.start != -1:
20
+ self._split_expression()
21
+
22
+ def done(self):
23
+ return self.cur.start == -1
24
+
25
+ def next(self):
26
+ n = len(tokenize_sql(substring(self.expression_list, self.cur.start, self.cur.end)))
27
+ self.cur = search(self.expression_list, self.pattern, self.cur.start_token + n - 1)
28
+ if self.cur.start != -1:
29
+ self._split_expression()
30
+
31
+ def full(self):
32
+ return _s(self.prefix) + _s(self.suffix)
33
+
34
+ def _split_list(self):
35
+ self.list_prefix = ''
36
+ self.list_suffix = ''
37
+ if self.list_type == SELECT:
38
+ m = search('^' + _s(self.expression_list) + '$', parse_search_pattern('^ distinct @@a $'), 0)
39
+ if m.start != -1:
40
+ self.list_prefix = 'distinct '
41
+ self.expression_list = m.variable_to_value.get('@@a')
42
+ m = search('^' + _s(self.expression_list) + '$', parse_search_pattern('^@@a into @@b$'), 0)
43
+ if m.start != -1:
44
+ self.expression_list = m.variable_to_value.get('@@a')
45
+ self.list_suffix = ' into ' + _s(m.variable_to_value.get('@@b'))
46
+ elif self.list_type == GROUP_BY:
47
+ m = search('^' + _s(self.expression_list) + '$', parse_search_pattern('^@@a order by @@b$'), 0)
48
+ if m.start != -1:
49
+ self.expression_list = m.variable_to_value.get('@@a')
50
+ self.list_suffix = ' order by ' + _s(m.variable_to_value.get('@@b'))
51
+
52
+ def _split_expression(self):
53
+ self.prefix = self.cur.variable_to_value.get('@@a')
54
+ self.suffix = ''
55
+ if self.list_type == SELECT:
56
+ self._split_alias()
57
+ elif self.list_type == ORDER_BY:
58
+ tokens = tokenize_sql(self.full())
59
+ if not tokens:
60
+ raise JavaError('IndexOutOfBoundsException')
61
+ last = tokens[-1]
62
+ if last.text.lower() in ('asc', 'desc'):
63
+ self.prefix = substring(self.full(), 0, last.start - 1)
64
+ self.suffix = ' ' + last.text
65
+
66
+ def _split_alias(self):
67
+ tokens = tokenize_sql(self.prefix)
68
+ m = search('^' + self.prefix + '$', parse_search_pattern('^ @@a as @@b $'), 0)
69
+ if m.start == -1:
70
+ if len(tokens) >= 2:
71
+ alias = tokens[-1]
72
+ preceding = tokens[-2].text
73
+ if alias.is_identifier() and preceding != '.' and preceding != '+':
74
+ self.prefix = substring(self.prefix, 0, alias.start)
75
+ self.suffix = alias.text
76
+ else:
77
+ self.prefix = m.variable_to_value.get('@@a')
78
+ self.suffix = m.variable_to_value.get('@@b')
79
+
80
+ def is_single_column_reference(self):
81
+ t = tokenize_sql(self.prefix)
82
+ return len(t) == 3 and t[0].is_identifier() and t[1].text == '.' and t[2].is_identifier()
83
+
84
+
85
+ def _s(x):
86
+ """Java 문자열 연결: null 은 "null"."""
87
+ return 'null' if x is None else x
88
+
89
+
90
+ def _alias_ctes(sql, pattern):
91
+ pp = parse_search_pattern(pattern)
92
+ m = search(sql, pp, 0)
93
+ while m.start != -1:
94
+ vv = m.variable_to_value
95
+ with_it = _CommaListIterator(vv.get('@@b'), WITH_COLUMNS)
96
+ sel_it = _CommaListIterator(vv.get('@@c'), SELECT)
97
+ repl = ''
98
+ while not with_it.done():
99
+ if sel_it.done():
100
+ break
101
+ expr = _s(sel_it.prefix) + ' as ' + with_it.full()
102
+ if repl:
103
+ repl += ','
104
+ repl += expr
105
+ with_it.next()
106
+ sel_it.next()
107
+ repl = sel_it.list_prefix + repl + sel_it.list_suffix
108
+ a = vv.get('@@a')
109
+ if a is None:
110
+ raise JavaError('NullPointerException')
111
+ body = pattern.replace('@@a', a).replace('(@@b)', '').replace('@@c', repl).replace('@@d', vv.get('@@d') or '')
112
+ sql = substring(sql, 0, m.start) + body + substring(sql, m.end)
113
+ m = search(sql, pp, m.start_token + 1)
114
+ return sql
115
+
116
+
117
+ def _convert_select_list_references(sql, select_pattern, list_type):
118
+ pp = parse_search_pattern(select_pattern)
119
+ m = search(sql, pp, 0)
120
+ while m.start != -1:
121
+ vv = m.variable_to_value
122
+ select_list = vv.get('@@s')
123
+ repl = ''
124
+ it = _CommaListIterator(vv.get('@@r'), list_type)
125
+ while not it.done():
126
+ expr, suffix = it.prefix, it.suffix
127
+ expr_pp = parse_search_pattern(expr)
128
+ if it.is_single_column_reference():
129
+ repl += ', ' + expr + suffix
130
+ else:
131
+ sel_it = _CommaListIterator(select_list, SELECT)
132
+ found = False
133
+ i = 1
134
+ while not sel_it.done():
135
+ if search(sel_it.prefix, expr_pp, 0).start != -1:
136
+ found = True
137
+ repl += ', ' + str(i) + suffix
138
+ break
139
+ i += 1
140
+ sel_it.next()
141
+ if not found:
142
+ repl += ', ' + expr + suffix
143
+ it.next()
144
+ repl = it.list_prefix + substring(repl, 1) + it.list_suffix
145
+ tail = substring(sql, m.end)
146
+ sql = substring(sql, 0, m.start)
147
+ for block in pp:
148
+ if sql:
149
+ sql += ' '
150
+ if block.is_variable:
151
+ sql += repl if block.text == '@@r' else _s(vv.get(block.text))
152
+ else:
153
+ sql += block.text
154
+ sql += tail
155
+ m = search(sql, pp, m.start_token + 1)
156
+ return sql
157
+
158
+
159
+ def _lower_case(sql):
160
+ for t in tokenize_sql(sql):
161
+ if not t.in_quotes and not t.text.startswith('@'):
162
+ sql = substring(sql, 0, t.start) + t.text.lower() + substring(sql, t.end)
163
+ return sql
164
+
165
+
166
+ def translate_bigquery(sql):
167
+ sql = _lower_case(sql)
168
+ sql = _alias_ctes(sql, 'with @@a (@@b) as (select @@c from @@d)')
169
+ sql = _alias_ctes(sql, 'with @@a (@@b) as (select @@c union @@d)')
170
+ sql = _alias_ctes(sql, 'with @@a (@@b) as (select @@c)')
171
+ sql = _alias_ctes(sql, ', @@a (@@b) as (select @@c from @@d)')
172
+ g = 'select @@s from @@b group by @@r'
173
+ for suffix in (';', ')', ' having', ' order by'):
174
+ sql = _convert_select_list_references(sql, g + suffix, GROUP_BY)
175
+ o = 'select @@s from @@b order by @@r'
176
+ for suffix in (';', ')'):
177
+ sql = _convert_select_list_references(sql, o + suffix, ORDER_BY)
178
+ return sql
179
+
180
+
181
+ def _spark_create_table(sql):
182
+ if not sql.endswith(';'):
183
+ sql += ';'
184
+ pp = parse_search_pattern('CREATE TABLE @@table (@@definition)')
185
+ sql = re.sub(' +', ' ', trim(sql).replace('\t', ' '))
186
+ m = search(sql, pp, 0)
187
+ table = m.variable_to_value.get('@@table')
188
+ definition = m.variable_to_value.get('@@definition')
189
+ if table is not None and definition is not None:
190
+ table = table.replace('\r\n', '')
191
+ definition = definition.lower().replace('\r\n', '').replace(' as ', ' ')
192
+ cols = []
193
+ for f in split(definition, ','):
194
+ parts = split(trim(f), ' ')
195
+ if len(parts) < 2:
196
+ raise JavaError('ArrayIndexOutOfBoundsException')
197
+ cols.append('\tCAST(NULL AS ' + parts[1] + ') AS ' + parts[0])
198
+ sql = substring(sql, 0, m.start) + 'SELECT ' + ',\r\n'.join(cols) + ' INTO ' + table + ' WHERE 1 = 0'
199
+ return sql.replace(';', '')
200
+
201
+
202
+ def translate_spark(sql):
203
+ parts = [_spark_create_table(p) for p in split_sql(sql)]
204
+ joined = trim(';\r\n'.join(parts))
205
+ if len(parts) > 1 or trim(sql).endswith(';'):
206
+ return joined + ';'
207
+ return joined