├── .coveragerc
├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── mybatis_mapper2sql
├── __init__.py
├── convert.py
├── generate.py
└── params.py
├── setup.py
└── tests
├── __init__.py
├── expected.xml
├── test.py
└── test.xml
/.coveragerc:
--------------------------------------------------------------------------------
1 | [run]
2 | include = *mybatis_mapper2sql*
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 | .pytest_cache/
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 | local_settings.py
57 | db.sqlite3
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
105 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 |
3 | python:
4 | - "3.4"
5 | - "3.5"
6 | - "3.6"
7 |
8 | matrix:
9 | include:
10 | - python: '3.7'
11 | dist: xenial # required for Python >= 3.7 (travis-ci/travis-ci#9069)
12 |
13 | install:
14 | - pip install sqlparse
15 | - pip install coverage
16 | - pip install codecov
17 |
18 | script:
19 | - coverage run -m unittest
20 |
21 | after_success:
22 | - codecov
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | mybatis-mapper2sql
2 | ==================
3 | [](https://travis-ci.org/hhyo/mybatis-mapper2sql)
4 | [](https://codecov.io/gh/hhyo/mybatis-mapper2sql)
5 | [](https://pypi.org/project/mybatis-mapper2sql/)
6 | [](https://github.com/hhyo/mybatis-mapper2sql/blob/master/LICENSE)
7 | [](https://pypi.org/project/mybatis-mapper2sql/)
8 |
9 | Generate SQL Statements from the MyBatis3 Mapper XML file
10 | **Just for SQL Review https://github.com/hhyo/archery/issues/3**
11 |
12 | Installation
13 | ------------
14 | `pip install mybatis-mapper2sql`
15 |
16 |
17 | Usage
18 | -------------
19 |
20 | ```python
21 | import mybatis_mapper2sql
22 | # Parse Mybatis Mapper XML files
23 | mapper, xml_raw_text = mybatis_mapper2sql.create_mapper(xml='mybatis_mapper.xml')
24 | # Get All SQL Statements from Mapper
25 | statement = mybatis_mapper2sql.get_statement(mapper)
26 | # Get SQL Statement By SQLId
27 | statement = mybatis_mapper2sql.get_child_statement(mapper, sql_id)
28 | ```
29 |
30 | Examples
31 | -------------
32 | > https://github.com/OldBlackJoe/mybatis-mapper
33 |
34 | #### test.xml ####
35 | ```xml
36 |
37 |
38 |
39 |
40 | fruits
41 |
42 |
43 | WHERE
44 | category = #{category}
45 |
46 |
47 | FROM
48 |
49 |
50 |
51 |
62 |
72 |
91 |
103 |
117 |
118 | UPDATE
119 | fruits
120 |
121 |
122 | category = #{category},
123 |
124 |
125 | price = ${price},
126 |
127 |
128 | WHERE
129 | name = #{name}
130 |
131 |
155 |
171 |
172 | INSERT INTO
173 | fruits
174 | (
175 | name,
176 | category,
177 | price
178 | )
179 | VALUES
180 |
181 | (
182 | #{fruit.name},
183 | #{fruit.category},
184 | ${fruit.price}
185 | )
186 |
187 |
188 |
199 |
200 | ```
201 | #### test.py ####
202 | Get All SQL Statements from Mapper
203 |
204 | ```python
205 | import mybatis_mapper2sql
206 | mapper, xml_raw_text = mybatis_mapper2sql.create_mapper(xml='test.xml')
207 | statement = mybatis_mapper2sql.get_statement(mapper, result_type='raw', reindent=True, strip_comments=True)
208 | print(statement)
209 | ```
210 |
211 | ```SQL
212 | SELECT name,
213 | category,
214 | price
215 | FROM fruits
216 | WHERE category = ?
217 | AND price > ?;
218 |
219 |
220 | SELECT name,
221 | category,
222 | price
223 | FROM fruits
224 | WHERE category = ?;
225 |
226 |
227 | SELECT name,
228 | category,
229 | price
230 | FROM fruits
231 | WHERE 1=1
232 | AND category = ?
233 | AND price = ?
234 | AND name = 'Fuji';
235 |
236 |
237 | SELECT name,
238 | category,
239 | price
240 | FROM fruits
241 | WHERE category = 'apple'
242 | OR price = 200;
243 |
244 |
245 | SELECT name,
246 | category,
247 | price
248 | FROM fruits
249 | WHERE category = 'apple'
250 | AND price = ?;
251 |
252 |
253 | UPDATE fruits
254 | SET category = ?,
255 | price = ?
256 | WHERE name = ?;
257 |
258 |
259 | SELECT name,
260 | category,
261 | price
262 | FROM fruits
263 | WHERE name = ?
264 | AND category = ?
265 | AND price = ?
266 | AND category = 'apple';
267 |
268 |
269 | SELECT name,
270 | category,
271 | price
272 | FROM fruits
273 | WHERE categy = 'apple'
274 | AND (name = ?
275 | OR name = ?);
276 |
277 |
278 | INSERT INTO fruits (name, category, price)
279 | VALUES (?,
280 | ?,
281 | ?) , (?,
282 | ?,
283 | ?);
284 |
285 |
286 | SELECT name,
287 | category,
288 | price
289 | FROM fruits
290 | WHERE name like ?;
291 | ```
292 | Get SQL Statement By SQLId
293 |
294 | ```python
295 | import mybatis_mapper2sql
296 | mapper, xml_raw_text = mybatis_mapper2sql.create_mapper(xml='test.xml')
297 | statement = mybatis_mapper2sql.get_child_statement(mapper,'testForeach', reindent=True, strip_comments=False)
298 | print(statement)
299 | ```
300 |
301 |
302 | ```SQL
303 | SELECT name,
304 | category,
305 | price
306 | FROM fruits
307 | WHERE categy = 'apple'
308 | AND ( name = ? -- if(name == 'Jonathan' or name == 'Fuji')
309 | OR name = ? -- if(name == 'Jonathan' or name == 'Fuji')
310 | )
311 | ```
312 |
313 | Running the tests
314 | -----------------
315 | `python setup.py test`
316 |
317 | Known Limitations
318 | -----------------
319 | - Doesn't support custom parameters
320 | - All sql parameters will be replace to '?'
321 | - All of the conditionals to apply in \ \ \ \ element
322 |
323 | Acknowledgments
324 | -----------------
325 | This project was inspired by the following projects and websites:
326 | - https://github.com/OldBlackJoe/mybatis-mapper
327 | - http://www.mybatis.org/mybatis-3/dynamic-sql.html
328 | - http://www.enmoedu.com/article-205.html
329 |
--------------------------------------------------------------------------------
/mybatis_mapper2sql/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | """
3 | mybatis-mapper2sql
4 | ----------------------
5 | Generate SQL Statements from the MyBatis3 Mapper XML file
6 | usage:
7 | >>> import mybatis_mapper2sql
8 | >>> mapper, xml_raw_text = mybatis_mapper2sql.create_mapper(xml='mybatis_mapper.xml')
9 | >>> statement = mybatis_mapper2sql.get_statement(mapper)
10 | >>> print(statement)
11 | """
12 | from .generate import create_mapper, get_statement, get_child_statement
13 |
--------------------------------------------------------------------------------
/mybatis_mapper2sql/convert.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | from .params import get_params
4 |
5 | query_types = ['sql', 'select', 'insert', 'update', 'delete']
6 |
7 |
8 | def convert_children(mybatis_mapper, child, **kwargs):
9 | """
10 | Get children info
11 | :param mybatis_mapper:
12 | :param child:
13 | :param kwargs: native: parse follow the native rules
14 | :return:
15 | """
16 | if child.tag in query_types:
17 | return convert_parameters(child, text=True, tail=True)
18 | elif child.tag == 'include':
19 | return convert_include(mybatis_mapper, child, **kwargs)
20 | elif child.tag == 'if':
21 | return convert_if(mybatis_mapper, child, **kwargs)
22 | elif child.tag in ('choose', 'when', 'otherwise'):
23 | return convert_choose_when_otherwise(mybatis_mapper, child, **kwargs)
24 | elif child.tag in ('trim', 'where', 'set'):
25 | return convert_trim_where_set(mybatis_mapper, child, **kwargs)
26 | elif child.tag == 'foreach':
27 | return convert_foreach(mybatis_mapper, child, **kwargs)
28 | elif child.tag == 'bind':
29 | return convert_bind(child, **kwargs)
30 | else:
31 | return ''
32 |
33 |
34 | def convert_parameters(child, text=False, tail=False):
35 | """
36 | Get child text or tail
37 | :param child:
38 | :param text:
39 | :param tail:
40 | :return:
41 | """
42 | p = re.compile(r'\S')
43 | # Remove empty info
44 | child_text = child.text if child.text else ''
45 | child_tail = child.tail if child.tail else ''
46 | child_text = child_text if p.search(child_text) else ''
47 | child_tail = child_tail if p.search(child_tail) else ''
48 | # all
49 | if text and tail:
50 | convert_string = child_text + child_tail
51 | # only_text
52 | elif text:
53 | convert_string = child_text
54 | # only_tail
55 | elif tail:
56 | convert_string = child_tail
57 | else:
58 | convert_string = ''
59 | # replace params
60 | params = get_params(child)
61 | params['all'] = params['#'] + params['$']
62 | for param in params['all']:
63 | convert_string = convert_string.replace(param['full_name'], str(param['mock_value']))
64 | # convert CDATA string
65 | convert_cdata(convert_string)
66 | return convert_string
67 |
68 |
69 | def convert_include(mybatis_mapper, child, **kwargs):
70 | # Add Properties
71 | properties = kwargs.get('properties') if kwargs.get('properties') else dict()
72 | for next_child in child:
73 | if next_child.tag == 'property':
74 | properties[next_child.attrib.get('name')] = next_child.attrib.get('value')
75 | convert_string = ''
76 | include_child_id = child.attrib.get('refid')
77 | for change in ['#', '$']:
78 | string_regex = '\\' + change + '\{.+?\}'
79 | if re.match(string_regex, include_child_id):
80 | include_child_id = include_child_id.replace(change + '{', '').replace('}', '')
81 | include_child_id = properties.get(include_child_id)
82 | break
83 | include_child = mybatis_mapper.get(include_child_id)
84 | convert_string += convert_children(mybatis_mapper, include_child, **kwargs)
85 | # add include text
86 | convert_string += convert_parameters(child, text=True)
87 | for next_child in include_child:
88 | kwargs['properties'] = properties
89 | convert_string += convert_children(mybatis_mapper, next_child, **kwargs)
90 | # add include tail
91 | convert_string += convert_parameters(child, tail=True)
92 | return convert_string
93 |
94 |
95 | def convert_if(mybatis_mapper, child, **kwargs):
96 | convert_string = ''
97 | test = child.attrib.get('test')
98 | # Add if text
99 | convert_string += convert_parameters(child, text=True)
100 | for next_child in child:
101 | convert_string += convert_children(mybatis_mapper, next_child, **kwargs)
102 | convert_string += '-- if(' + test + ')\n'
103 | # Add if tail
104 | convert_string += convert_parameters(child, tail=True)
105 | return convert_string
106 |
107 |
108 | def convert_choose_when_otherwise(mybatis_mapper, child, **kwargs):
109 | # native
110 | native = kwargs.get('native')
111 | when_element_cnt = kwargs.get('when_element_cnt', 0)
112 |
113 | convert_string = ''
114 | if child.tag == 'choose':
115 | convert_string += convert_parameters(child, text=True)
116 |
117 | for next_child in child:
118 | if next_child.tag == 'when':
119 | if native and when_element_cnt >= 1:
120 | break
121 | else:
122 | test = next_child.attrib.get('test')
123 | convert_string += convert_parameters(next_child, text=True, tail=True)
124 | convert_string += '-- if(' + test + ')'
125 | when_element_cnt += 1
126 | kwargs['when_element_cnt'] = when_element_cnt
127 | elif next_child.tag == 'otherwise':
128 | convert_string += convert_parameters(next_child, text=True, tail=True)
129 | convert_string += '-- otherwise'
130 | convert_string += convert_children(mybatis_mapper, next_child, **kwargs)
131 |
132 | if child.tag == 'choose':
133 | convert_string += convert_parameters(child, tail=True)
134 |
135 | return convert_string
136 |
137 |
138 | def convert_trim_where_set(mybatis_mapper, child, **kwargs):
139 | if child.tag == 'trim':
140 | prefix = child.attrib.get('prefix')
141 | suffix = child.attrib.get('suffix')
142 | prefix_overrides = child.attrib.get('prefixOverrides')
143 | suffix_overrides = child.attrib.get('suffixOverrides')
144 | elif child.tag == 'set':
145 | prefix = 'SET'
146 | suffix = None
147 | prefix_overrides = None
148 | suffix_overrides = ','
149 | elif child.tag == 'where':
150 | prefix = 'WHERE'
151 | suffix = None
152 | prefix_overrides = 'and|or'
153 | suffix_overrides = None
154 | else:
155 | return ''
156 |
157 | convert_string = ''
158 | # Add trim/where/set text
159 | convert_string += convert_parameters(child, text=True)
160 | # Convert children first
161 | for next_child in child:
162 | convert_string += convert_children(mybatis_mapper, next_child, **kwargs)
163 | # Remove prefixOverrides
164 | if prefix_overrides:
165 | regex = r'^[\s]*?({})'.format(prefix_overrides)
166 | convert_string = re.sub(regex, '', convert_string, count=1, flags=re.I)
167 | # Remove suffixOverrides
168 | if suffix_overrides:
169 | regex = r'({})(\s+--.+)?$'.format(suffix_overrides)
170 | convert_string = re.sub(regex, r'', convert_string, count=1, flags=re.I)
171 | # Add Prefix if String is not empty
172 | if re.search(r'\S', convert_string):
173 | if prefix:
174 | convert_string = prefix + ' ' + convert_string
175 | if suffix:
176 | convert_string = convert_string + ' ' + suffix
177 | # Add trim/where/set tail
178 | convert_string += convert_parameters(child, tail=True)
179 | return convert_string
180 |
181 |
182 | def convert_foreach(mybatis_mapper, child, **kwargs):
183 | collection = child.attrib.get('collection')
184 | item = child.attrib.get('item')
185 | index = child.attrib.get('index')
186 | open = child.attrib.get('open', '')
187 | close = child.attrib.get('close', '')
188 | separator = child.attrib.get('separator', '')
189 | convert_string = ''
190 | # Add foreach text
191 | convert_string += convert_parameters(child, text=True)
192 | for next_child in child:
193 | convert_string += convert_children(mybatis_mapper, next_child, **kwargs)
194 | # Add two items
195 | convert_string = open + convert_string + separator + convert_string + close
196 | # Add foreach tail
197 | convert_string += convert_parameters(child, tail=True)
198 | return convert_string
199 |
200 |
201 | def convert_bind(child, **kwargs):
202 | """
203 | :param child:
204 | :return:
205 | """
206 | name = child.attrib.get('name')
207 | value = child.attrib.get('value')
208 | convert_string = ''
209 | convert_string += convert_parameters(child, tail=True)
210 | convert_string = convert_string.replace(name, value)
211 | return convert_string
212 |
213 |
214 | def convert_cdata(string, reverse=False):
215 | """
216 | Replace CDATA String
217 | :param string:
218 | :param reverse:
219 | :return:
220 | """
221 | if reverse:
222 | string = string.replace('&', '&')
223 | string = string.replace('<', '<')
224 | string = string.replace('>', '>')
225 | string = string.replace('"', '"')
226 | else:
227 | string = string.replace('&', '&')
228 | string = string.replace('<', '<')
229 | string = string.replace('>', '>', )
230 | string = string.replace('"', '"')
231 | return string
232 |
--------------------------------------------------------------------------------
/mybatis_mapper2sql/generate.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | import re
3 | import sqlparse
4 | from .convert import query_types, convert_children, convert_cdata
5 | import xml.etree.ElementTree as ET
6 |
7 |
8 | def create_mapper(xml=None, xml_raw_text=None):
9 | """
10 | Parse XML files
11 | Get mybatis mapper
12 | :return:
13 | """
14 | if xml_raw_text is None:
15 | with open(xml, "r") as f:
16 | xml_raw_text = f.read()
17 | mapper = {}
18 | raw_text = __replace_cdata(xml_raw_text)
19 | root = ET.fromstring(raw_text)
20 | for child in root:
21 | if child.tag in query_types:
22 | child_id = child.attrib.get('id')
23 | mapper[child_id] = child
24 | return mapper, xml_raw_text
25 |
26 |
27 | def get_statement(mybatis_mapper, result_type='raw', **kwargs):
28 | """
29 | Get SQL Statements from Mapper
30 | :param mybatis_mapper:
31 | :param kwargs: sqlparse format kwargs /native: parse follow the native rules
32 | :param result_type: raw|list
33 | :return:
34 | """
35 | # format kwargs
36 | kwargs = kwargs if kwargs else {'reindent': True, 'strip_comments': True}
37 | # result_type
38 | if result_type == 'list':
39 | statement = []
40 | for child_id, child in mybatis_mapper.items():
41 | if child.tag not in ['sql']:
42 | child_statement = dict()
43 | child_statement[child_id] = get_child_statement(mybatis_mapper, child_id=child_id, **kwargs)
44 | statement.append(child_statement)
45 | return statement
46 | elif result_type == 'raw':
47 | statement = ''
48 | for child_id, child in mybatis_mapper.items():
49 | if child.tag not in ['sql']:
50 | statement += get_child_statement(mybatis_mapper, child_id=child_id, **kwargs) + ';'
51 | return sqlparse.format(statement, **kwargs)
52 | else:
53 | raise RuntimeError('Invalid value for sql_type: raw|list')
54 |
55 |
56 | def get_child_statement(mybatis_mapper, child_id, **kwargs):
57 | """
58 | Get SQL Statement By child_id
59 | Formatting of SQL Statements
60 | :return:
61 | """
62 | # format kwargs
63 | kwargs = kwargs if kwargs else {'reindent': True, 'strip_comments': True}
64 | # get sql
65 | statement = ''
66 | child = mybatis_mapper.get(child_id)
67 | statement += convert_children(mybatis_mapper, child, **kwargs)
68 | # The child element has children
69 | for next_child in child:
70 | statement += convert_children(mybatis_mapper, next_child, **kwargs)
71 | return sqlparse.format(statement, **kwargs)
72 |
73 |
74 | def __replace_cdata(raw_text):
75 | """
76 | Replace CDATA String
77 | :param raw_text:
78 | :return:
79 | """
80 | cdata_regex = '()'
81 | pattern = re.compile(cdata_regex)
82 | match = pattern.search(raw_text)
83 | if match:
84 | cdata_text = match.group(2)
85 | cdata_text = convert_cdata(cdata_text, reverse=True)
86 | raw_text = raw_text.replace(match.group(), cdata_text)
87 | return raw_text
88 |
--------------------------------------------------------------------------------
/mybatis_mapper2sql/params.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | import re
3 |
4 | jdbc_type = {
5 | 'NUM': ['TINYINT', 'SMALLINT', 'INTEGER', 'BIGINT', 'BIT', 'DECIMAL', 'DOUBLE', 'FLOAT', 'NUMERIC'],
6 | 'BOOLEAN': ['BOOLEAN'],
7 | 'DATE': ['DATE', 'TIME', 'TIMESTAMP'],
8 | 'STRING': ['CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR', 'LONGNVARCHAR', 'LONGVARCHAR'],
9 | 'BINARY': ['BINARY', 'VARBINARY', 'LONGVARBINARY', 'BLOB'],
10 | 'OTHER': ['ARRAY', 'CLOB', 'CURSOR', 'DATALINK', 'DATETIMEOFFSET', 'DISTINCT', 'JAVA_OBJECT', 'NCLOB',
11 | 'NULL', 'OTHER', 'REAL', 'REF', 'ROWID', 'SQLXML', 'STRUCT', 'UNDEFINED']
12 |
13 | }
14 |
15 |
16 | def get_params(child):
17 | """
18 | Get SQL Params
19 | example: #{age,javaType=int,jdbcType=NUMERIC,typeHandler=MyTypeHandler}
20 | change: '#','$'
21 | :return:
22 | """
23 | p = re.compile('\S')
24 | # Remove empty info
25 | child_text = child.text if child.text else ''
26 | child_tail = child.tail if child.tail else ''
27 | child_text = child_text if p.search(child_text) else ''
28 | child_tail = child_tail if p.search(child_tail) else ''
29 | convert_string = child_text + child_tail
30 |
31 | params = {'#': [], '$': []}
32 | for change in ['#', '$']:
33 | tmp_params = []
34 | string_regex = '\\' + change + '\{.+?\}'
35 | pattern = re.compile(string_regex)
36 | match = pattern.findall(convert_string)
37 | # tmp_unique_params
38 | tmp_params += sorted(set(match), key=match.index)
39 | # get jdbcType、javaType
40 | for param in tmp_params:
41 | param_dict = dict()
42 | param_dict['full_name'] = param
43 | param = param.replace(change + '{', '').replace('}', '')
44 | param_dict['name'] = param.split(',')[0]
45 | m = re.search('(\s*jdbcType\s*=\s*)(?P\w+)?', param)
46 | param_dict['jdbc_type'] = m.group('jdbc_type').strip() if m else None
47 | m = re.search('(\s*javaType\s*=\s*)(?P\w+)?', param)
48 | param_dict['java_type'] = m.group('java_type').strip() if m else None
49 | # Replace SQL Params
50 | replace_params(param_dict)
51 | params[change].append(param_dict)
52 | return params
53 |
54 |
55 | def replace_params(param):
56 | """
57 | Replace SQL Params
58 | :return:
59 | """
60 | param_jdbc_type = param['jdbc_type']
61 | if param_jdbc_type in jdbc_type['NUM']:
62 | param['mock_value'] = '?'
63 | elif param_jdbc_type in jdbc_type['BOOLEAN']:
64 | param['mock_value'] = '?'
65 | elif param_jdbc_type in jdbc_type['BINARY']:
66 | param['mock_value'] = '?'
67 | elif param_jdbc_type in jdbc_type['STRING']:
68 | param['mock_value'] = '?'
69 | else:
70 | param['mock_value'] = '?'
71 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | import os
3 |
4 | from setuptools import setup
5 | from setuptools.command.test import test
6 | from codecs import open
7 |
8 | setup_dir = os.path.abspath(os.path.dirname(__file__))
9 |
10 |
11 | def read(file_name):
12 | return open(os.path.join(setup_dir, file_name), 'r', encoding='utf-8').read()
13 |
14 |
15 | class Test(test):
16 |
17 | def run_tests(self):
18 | import unittest
19 |
20 | test_loader = unittest.defaultTestLoader
21 | test_runner = unittest.TextTestRunner()
22 | test_suite = test_loader.discover(setup_dir)
23 | test_runner.run(test_suite)
24 |
25 |
26 | setup(
27 | name='mybatis-mapper2sql',
28 | version='0.1.9',
29 | author='hhyo',
30 | author_email='rtttte@qq.com',
31 | url='http://github.com/hhyo/mybatis-mapper2sql',
32 | description='Generate SQL Statements from the MyBatis3 Mapper XML file',
33 | long_description=read('README.md'),
34 | long_description_content_type='text/markdown',
35 | keywords='mybatis mapper2sql mybatis-mapper2sql',
36 | packages=['mybatis_mapper2sql'],
37 | include_package_data=True,
38 | install_requires=[
39 | 'sqlparse>=0.2.4'
40 | ],
41 | license='Apache 2.0',
42 | zip_safe=False,
43 | classifiers=[
44 | 'Development Status :: 3 - Alpha',
45 | 'Intended Audience :: Developers',
46 | 'License :: OSI Approved :: Apache Software License',
47 | 'Operating System :: OS Independent',
48 | 'Programming Language :: Python :: 3',
49 | 'Programming Language :: Python :: 3.4',
50 | 'Programming Language :: Python :: 3.5',
51 | 'Programming Language :: Python :: 3.6',
52 | 'Programming Language :: Python :: 3.7',
53 | ],
54 | cmdclass={'test': Test}
55 | )
56 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hhyo/mybatis-mapper2sql/31b9753c9c038efd36f270902611783c0e4b2cd5/tests/__init__.py
--------------------------------------------------------------------------------
/tests/expected.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | SELECT name,
5 | category,
6 | price
7 | FROM fruits
8 | WHERE name = ? -- if(name != null)
9 |
10 | AND category = ? -- if(category == 'banana')
11 |
12 | AND price = ? -- if(price != null and price !='')
13 |
14 | AND category = 'apple' -- otherwise
15 |
16 | AND category IS NOT NULL
17 |
18 | SELECT name,
19 | category,
20 | price
21 | FROM fruits
22 | WHERE name = ? -- if(name != null)
23 |
24 | AND category IS NOT NULL
25 |
--------------------------------------------------------------------------------
/tests/test.py:
--------------------------------------------------------------------------------
1 | import os
2 | import unittest
3 | import mybatis_mapper2sql
4 | import xml.etree.ElementTree as ET
5 |
6 |
7 | base_dir = os.path.abspath(os.path.dirname(__file__))
8 | xml = os.path.join(base_dir, 'test.xml')
9 | expected_xml = os.path.join(base_dir, 'expected.xml')
10 |
11 |
12 | class Mapper2SqlTest(unittest.TestCase):
13 |
14 | @classmethod
15 | def setUpClass(cls):
16 | cls.mapper, cls.xml_raw_text = mybatis_mapper2sql.create_mapper(xml=xml)
17 | print("============XML_RAW_TEXT============")
18 | print(cls.xml_raw_text)
19 |
20 | with open(expected_xml, "r") as f:
21 | xml_raw_text = f.read()
22 | cls.expected_results = ET.fromstring(xml_raw_text)
23 |
24 | def test_all(self):
25 | statement = mybatis_mapper2sql.get_statement(self.mapper, result_type='raw', strip_comments=True)
26 | print(statement)
27 |
28 | def test_all_result(self):
29 | statement = mybatis_mapper2sql.get_statement(self.mapper, result_type='list', strip_comments=True)
30 | print(statement)
31 |
32 | def test_all_wrong_result(self):
33 | try:
34 | mybatis_mapper2sql.get_statement(self.mapper, result_type='sql', strip_comments=True)
35 | except RuntimeError as e:
36 | self.assertEqual(str(e), 'Invalid value for sql_type: raw|list')
37 | else:
38 | self.fail('IOError not raised')
39 |
40 | def test_base(self):
41 | self.child_id = 'testBasic'
42 | print("============{}============".format(self.child_id))
43 | self.statement = mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id, reindent=True)
44 | print(self.statement)
45 |
46 | def test_parameters(self):
47 | self.child_id = 'testParameters'
48 | print("============{}============".format(self.child_id))
49 | self.statement = mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id, reindent=True)
50 | print(self.statement)
51 |
52 | def test_include(self):
53 | self.child_id = 'testInclude'
54 | print("============{}============".format(self.child_id))
55 | self.statement = mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id, reindent=True)
56 | print(self.statement)
57 |
58 | def test_if(self):
59 | self.child_id = 'testIf'
60 | print("============{}============".format(self.child_id))
61 | self.statement = mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id, reindent=True)
62 | print(self.statement)
63 |
64 | def test_trim(self):
65 | self.child_id = 'testTrim'
66 | print("============{}============".format(self.child_id))
67 | self.statement = mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id, reindent=True)
68 | print(self.statement)
69 |
70 | def test_where(self):
71 | self.child_id = 'testWhere'
72 | print("============{}============".format(self.child_id))
73 | self.statement = mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id, reindent=True)
74 | print(self.statement)
75 |
76 | def test_set(self):
77 | self.child_id = 'testSet'
78 | print("============{}============".format(self.child_id))
79 | self.statement = mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id, reindent=True)
80 | print(self.statement)
81 |
82 | def test_choose(self):
83 | self.child_id = 'testChoose'
84 | print("============{}============".format(self.child_id))
85 | self.statement = mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id, reindent=True)
86 | print(self.statement)
87 | self.assertEqual(self.expected_results.find(self.child_id).text, self.statement)
88 |
89 | def test_foreach(self):
90 | self.child_id = 'testForeach'
91 | print("============{}============".format(self.child_id))
92 | self.statement = mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id, reindent=True)
93 | print(self.statement)
94 |
95 | def test_bind(self):
96 | self.child_id = 'testBind'
97 | print("============{}============".format(self.child_id))
98 | self.statement = mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id, reindent=True)
99 | print(self.statement)
100 |
101 | def test_choose_native(self):
102 | self.child_id = 'testChooseNative'
103 | print("============{}============".format(self.child_id))
104 | self.statement = mybatis_mapper2sql.get_child_statement(self.mapper, child_id=self.child_id,
105 | reindent=True, native=True)
106 | print(self.statement)
107 | self.assertEqual(self.expected_results.find(self.child_id).text, self.statement)
108 |
109 |
110 | if __name__ == '__main__':
111 | unittest.main()
112 |
--------------------------------------------------------------------------------
/tests/test.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | fruits
6 |
7 |
8 | WHERE
9 | category = #{category}
10 |
11 |
12 | FROM
13 |
14 |
15 |
16 |
27 |
40 |
51 |
70 |
82 |
98 |
113 |
114 | UPDATE
115 | fruits
116 |
117 |
118 | category = #{category},
119 |
120 |
121 | price = ${price},
122 |
123 |
124 | WHERE
125 | name = #{name}
126 |
127 |
152 |
168 |
169 | INSERT INTO
170 | fruits
171 | (
172 | name,
173 | category,
174 | price
175 | )
176 | VALUES
177 |
178 | (
179 | #{fruit.name},
180 | #{fruit.category},
181 | ${fruit.price}
182 | )
183 |
184 |
185 |
196 |
197 | insert into fruits
198 |
199 |
200 | name,
201 |
202 |
203 | category,
204 |
205 |
206 | price,
207 |
208 |
209 |
210 |
211 | #{name},
212 |
213 |
214 | #{category},
215 |
216 |
217 | #{price},
218 |
219 |
220 |
221 |
246 |
247 |
--------------------------------------------------------------------------------