ns-pydm 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.
- ns_pydm-0.0.1/LICENSE +201 -0
- ns_pydm-0.0.1/PKG-INFO +108 -0
- ns_pydm-0.0.1/README.md +98 -0
- ns_pydm-0.0.1/pyproject.toml +20 -0
- ns_pydm-0.0.1/setup.cfg +4 -0
- ns_pydm-0.0.1/src/ns_pydm.egg-info/PKG-INFO +108 -0
- ns_pydm-0.0.1/src/ns_pydm.egg-info/SOURCES.txt +15 -0
- ns_pydm-0.0.1/src/ns_pydm.egg-info/dependency_links.txt +1 -0
- ns_pydm-0.0.1/src/ns_pydm.egg-info/requires.txt +1 -0
- ns_pydm-0.0.1/src/ns_pydm.egg-info/top_level.txt +1 -0
- ns_pydm-0.0.1/src/nspydm/__init__.py +64 -0
- ns_pydm-0.0.1/src/nspydm/dbapi.py +603 -0
- ns_pydm-0.0.1/src/nspydm/jdbc/DmJdbcDriver11.jar +0 -0
- ns_pydm-0.0.1/src/nspydm/jdbc/DmJdbcDriver6.jar +0 -0
- ns_pydm-0.0.1/src/nspydm/jdbc/DmJdbcDriver7.jar +0 -0
- ns_pydm-0.0.1/src/nspydm/jdbc/DmJdbcDriver8.jar +0 -0
- ns_pydm-0.0.1/tests/test_smoke.py +61 -0
ns_pydm-0.0.1/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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.
|
ns_pydm-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ns-pydm
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Dameng (DM) DB-API 2.0 driver implemented on top of JDBC via JPype
|
|
5
|
+
Requires-Python: >=3.7
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: JPype1<2,>=1.5.2
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# ns-pydm
|
|
12
|
+
|
|
13
|
+
基于 JDBC + JPype 的达梦(DM)Python 驱动,提供 DB-API 2.0 风格接口,跨平台使用。
|
|
14
|
+
|
|
15
|
+
## 特性
|
|
16
|
+
|
|
17
|
+
- DB-API 2.0 风格:`connect()` / `Connection` / `Cursor` / `commit()` / `rollback()`
|
|
18
|
+
- 参数绑定:支持 `?` 占位符;兼容把 SQL 中的 `%s`(非引号区域)自动转换为 `?`
|
|
19
|
+
- 内置达梦 JDBC 驱动 Jar:安装 Python 包即可使用(仍需本机存在 Java 运行时)
|
|
20
|
+
- 自动选择 Jar:根据 `java -version` 探测的 Java 主版本选择对应驱动
|
|
21
|
+
|
|
22
|
+
## 依赖
|
|
23
|
+
|
|
24
|
+
- Python 3.7+
|
|
25
|
+
- 运行环境需要安装 Java(JRE/JDK),并确保 `java` 在 PATH 中或已配置 `JAVA_HOME`
|
|
26
|
+
|
|
27
|
+
## 安装
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install ns-pydm
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## 快速开始
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import nspydm
|
|
37
|
+
|
|
38
|
+
conn = nspydm.connect(
|
|
39
|
+
user="SYSDBA",
|
|
40
|
+
password="SYSDBA",
|
|
41
|
+
server="127.0.0.1",
|
|
42
|
+
port=5236,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
cur = conn.cursor()
|
|
46
|
+
cur.execute("select ? as x", [1])
|
|
47
|
+
print(cur.fetchone())
|
|
48
|
+
conn.close()
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## 参数绑定
|
|
52
|
+
|
|
53
|
+
推荐写法(JDBC 原生):使用 `?`
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
cur.execute("select ? as x, ? as y", [1, "hello"])
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
兼容写法:使用 `%s`(会转换为 `?`)
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
cur.execute("select %s as x, %s as y", [1, "hello"])
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## 事务与自动提交
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
conn = nspydm.connect(..., autocommit=False)
|
|
69
|
+
cur = conn.cursor()
|
|
70
|
+
cur.execute("insert into t(a) values(?)", [1])
|
|
71
|
+
conn.commit()
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
也可以通过属性开关:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
conn.autocommit = True
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Schema 切换示例
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
cur.execute("set schema your_schema")
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## 连接参数
|
|
87
|
+
|
|
88
|
+
- `connect(user, password, server, port, dsn, url, autocommit, properties, jars, driver_class)`
|
|
89
|
+
- `url` 优先级最高,支持直接传入 `jdbc:dm://host:port` 形式
|
|
90
|
+
- `dsn` 传入 `host:port` 时会自动拼接为 `jdbc:dm://{dsn}`
|
|
91
|
+
|
|
92
|
+
## Jar 选择与 Java 版本识别
|
|
93
|
+
|
|
94
|
+
- 默认会通过 `java -version` 探测 Java 主版本,并自动选择内置的驱动 Jar:
|
|
95
|
+
- Java 6 -> `DmJdbcDriver6.jar`
|
|
96
|
+
- Java 7 -> `DmJdbcDriver7.jar`
|
|
97
|
+
- Java 8/9/10 -> `DmJdbcDriver8.jar`
|
|
98
|
+
- Java 11+ -> `DmJdbcDriver11.jar`
|
|
99
|
+
- 如需自定义或覆盖默认选择:
|
|
100
|
+
- 环境变量:`DM_JDBC_JAR=/abs/path/to/DmJdbcDriver8.jar`
|
|
101
|
+
- 代码传参:`connect(..., jars=["/abs/path/to/DmJdbcDriver8.jar"])`
|
|
102
|
+
|
|
103
|
+
## 常见问题
|
|
104
|
+
|
|
105
|
+
1. 提示找不到 `java`
|
|
106
|
+
- 确认已安装 JRE/JDK,并保证 `java -version` 能在命令行执行
|
|
107
|
+
2. 连接时报错但信息不全
|
|
108
|
+
- 驱动底层异常会被映射为 DB-API 异常(例如 `OperationalError`),可直接打印异常信息排查
|
ns_pydm-0.0.1/README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# ns-pydm
|
|
2
|
+
|
|
3
|
+
基于 JDBC + JPype 的达梦(DM)Python 驱动,提供 DB-API 2.0 风格接口,跨平台使用。
|
|
4
|
+
|
|
5
|
+
## 特性
|
|
6
|
+
|
|
7
|
+
- DB-API 2.0 风格:`connect()` / `Connection` / `Cursor` / `commit()` / `rollback()`
|
|
8
|
+
- 参数绑定:支持 `?` 占位符;兼容把 SQL 中的 `%s`(非引号区域)自动转换为 `?`
|
|
9
|
+
- 内置达梦 JDBC 驱动 Jar:安装 Python 包即可使用(仍需本机存在 Java 运行时)
|
|
10
|
+
- 自动选择 Jar:根据 `java -version` 探测的 Java 主版本选择对应驱动
|
|
11
|
+
|
|
12
|
+
## 依赖
|
|
13
|
+
|
|
14
|
+
- Python 3.7+
|
|
15
|
+
- 运行环境需要安装 Java(JRE/JDK),并确保 `java` 在 PATH 中或已配置 `JAVA_HOME`
|
|
16
|
+
|
|
17
|
+
## 安装
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install ns-pydm
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## 快速开始
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import nspydm
|
|
27
|
+
|
|
28
|
+
conn = nspydm.connect(
|
|
29
|
+
user="SYSDBA",
|
|
30
|
+
password="SYSDBA",
|
|
31
|
+
server="127.0.0.1",
|
|
32
|
+
port=5236,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
cur = conn.cursor()
|
|
36
|
+
cur.execute("select ? as x", [1])
|
|
37
|
+
print(cur.fetchone())
|
|
38
|
+
conn.close()
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## 参数绑定
|
|
42
|
+
|
|
43
|
+
推荐写法(JDBC 原生):使用 `?`
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
cur.execute("select ? as x, ? as y", [1, "hello"])
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
兼容写法:使用 `%s`(会转换为 `?`)
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
cur.execute("select %s as x, %s as y", [1, "hello"])
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## 事务与自动提交
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
conn = nspydm.connect(..., autocommit=False)
|
|
59
|
+
cur = conn.cursor()
|
|
60
|
+
cur.execute("insert into t(a) values(?)", [1])
|
|
61
|
+
conn.commit()
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
也可以通过属性开关:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
conn.autocommit = True
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Schema 切换示例
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
cur.execute("set schema your_schema")
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## 连接参数
|
|
77
|
+
|
|
78
|
+
- `connect(user, password, server, port, dsn, url, autocommit, properties, jars, driver_class)`
|
|
79
|
+
- `url` 优先级最高,支持直接传入 `jdbc:dm://host:port` 形式
|
|
80
|
+
- `dsn` 传入 `host:port` 时会自动拼接为 `jdbc:dm://{dsn}`
|
|
81
|
+
|
|
82
|
+
## Jar 选择与 Java 版本识别
|
|
83
|
+
|
|
84
|
+
- 默认会通过 `java -version` 探测 Java 主版本,并自动选择内置的驱动 Jar:
|
|
85
|
+
- Java 6 -> `DmJdbcDriver6.jar`
|
|
86
|
+
- Java 7 -> `DmJdbcDriver7.jar`
|
|
87
|
+
- Java 8/9/10 -> `DmJdbcDriver8.jar`
|
|
88
|
+
- Java 11+ -> `DmJdbcDriver11.jar`
|
|
89
|
+
- 如需自定义或覆盖默认选择:
|
|
90
|
+
- 环境变量:`DM_JDBC_JAR=/abs/path/to/DmJdbcDriver8.jar`
|
|
91
|
+
- 代码传参:`connect(..., jars=["/abs/path/to/DmJdbcDriver8.jar"])`
|
|
92
|
+
|
|
93
|
+
## 常见问题
|
|
94
|
+
|
|
95
|
+
1. 提示找不到 `java`
|
|
96
|
+
- 确认已安装 JRE/JDK,并保证 `java -version` 能在命令行执行
|
|
97
|
+
2. 连接时报错但信息不全
|
|
98
|
+
- 驱动底层异常会被映射为 DB-API 异常(例如 `OperationalError`),可直接打印异常信息排查
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ns-pydm"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
description = "Dameng (DM) DB-API 2.0 driver implemented on top of JDBC via JPype"
|
|
9
|
+
readme = { file = "README.md", content-type = "text/markdown" }
|
|
10
|
+
requires-python = ">=3.7"
|
|
11
|
+
dependencies = ["JPype1>=1.5.2,<2"]
|
|
12
|
+
|
|
13
|
+
[tool.setuptools]
|
|
14
|
+
package-dir = { "" = "src" }
|
|
15
|
+
|
|
16
|
+
[tool.setuptools.package-data]
|
|
17
|
+
nspydm = ["jdbc/*.jar"]
|
|
18
|
+
|
|
19
|
+
[tool.setuptools.packages.find]
|
|
20
|
+
where = ["src"]
|
ns_pydm-0.0.1/setup.cfg
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ns-pydm
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Dameng (DM) DB-API 2.0 driver implemented on top of JDBC via JPype
|
|
5
|
+
Requires-Python: >=3.7
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: JPype1<2,>=1.5.2
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# ns-pydm
|
|
12
|
+
|
|
13
|
+
基于 JDBC + JPype 的达梦(DM)Python 驱动,提供 DB-API 2.0 风格接口,跨平台使用。
|
|
14
|
+
|
|
15
|
+
## 特性
|
|
16
|
+
|
|
17
|
+
- DB-API 2.0 风格:`connect()` / `Connection` / `Cursor` / `commit()` / `rollback()`
|
|
18
|
+
- 参数绑定:支持 `?` 占位符;兼容把 SQL 中的 `%s`(非引号区域)自动转换为 `?`
|
|
19
|
+
- 内置达梦 JDBC 驱动 Jar:安装 Python 包即可使用(仍需本机存在 Java 运行时)
|
|
20
|
+
- 自动选择 Jar:根据 `java -version` 探测的 Java 主版本选择对应驱动
|
|
21
|
+
|
|
22
|
+
## 依赖
|
|
23
|
+
|
|
24
|
+
- Python 3.7+
|
|
25
|
+
- 运行环境需要安装 Java(JRE/JDK),并确保 `java` 在 PATH 中或已配置 `JAVA_HOME`
|
|
26
|
+
|
|
27
|
+
## 安装
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install ns-pydm
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## 快速开始
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import nspydm
|
|
37
|
+
|
|
38
|
+
conn = nspydm.connect(
|
|
39
|
+
user="SYSDBA",
|
|
40
|
+
password="SYSDBA",
|
|
41
|
+
server="127.0.0.1",
|
|
42
|
+
port=5236,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
cur = conn.cursor()
|
|
46
|
+
cur.execute("select ? as x", [1])
|
|
47
|
+
print(cur.fetchone())
|
|
48
|
+
conn.close()
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## 参数绑定
|
|
52
|
+
|
|
53
|
+
推荐写法(JDBC 原生):使用 `?`
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
cur.execute("select ? as x, ? as y", [1, "hello"])
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
兼容写法:使用 `%s`(会转换为 `?`)
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
cur.execute("select %s as x, %s as y", [1, "hello"])
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## 事务与自动提交
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
conn = nspydm.connect(..., autocommit=False)
|
|
69
|
+
cur = conn.cursor()
|
|
70
|
+
cur.execute("insert into t(a) values(?)", [1])
|
|
71
|
+
conn.commit()
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
也可以通过属性开关:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
conn.autocommit = True
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Schema 切换示例
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
cur.execute("set schema your_schema")
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## 连接参数
|
|
87
|
+
|
|
88
|
+
- `connect(user, password, server, port, dsn, url, autocommit, properties, jars, driver_class)`
|
|
89
|
+
- `url` 优先级最高,支持直接传入 `jdbc:dm://host:port` 形式
|
|
90
|
+
- `dsn` 传入 `host:port` 时会自动拼接为 `jdbc:dm://{dsn}`
|
|
91
|
+
|
|
92
|
+
## Jar 选择与 Java 版本识别
|
|
93
|
+
|
|
94
|
+
- 默认会通过 `java -version` 探测 Java 主版本,并自动选择内置的驱动 Jar:
|
|
95
|
+
- Java 6 -> `DmJdbcDriver6.jar`
|
|
96
|
+
- Java 7 -> `DmJdbcDriver7.jar`
|
|
97
|
+
- Java 8/9/10 -> `DmJdbcDriver8.jar`
|
|
98
|
+
- Java 11+ -> `DmJdbcDriver11.jar`
|
|
99
|
+
- 如需自定义或覆盖默认选择:
|
|
100
|
+
- 环境变量:`DM_JDBC_JAR=/abs/path/to/DmJdbcDriver8.jar`
|
|
101
|
+
- 代码传参:`connect(..., jars=["/abs/path/to/DmJdbcDriver8.jar"])`
|
|
102
|
+
|
|
103
|
+
## 常见问题
|
|
104
|
+
|
|
105
|
+
1. 提示找不到 `java`
|
|
106
|
+
- 确认已安装 JRE/JDK,并保证 `java -version` 能在命令行执行
|
|
107
|
+
2. 连接时报错但信息不全
|
|
108
|
+
- 驱动底层异常会被映射为 DB-API 异常(例如 `OperationalError`),可直接打印异常信息排查
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/ns_pydm.egg-info/PKG-INFO
|
|
5
|
+
src/ns_pydm.egg-info/SOURCES.txt
|
|
6
|
+
src/ns_pydm.egg-info/dependency_links.txt
|
|
7
|
+
src/ns_pydm.egg-info/requires.txt
|
|
8
|
+
src/ns_pydm.egg-info/top_level.txt
|
|
9
|
+
src/nspydm/__init__.py
|
|
10
|
+
src/nspydm/dbapi.py
|
|
11
|
+
src/nspydm/jdbc/DmJdbcDriver11.jar
|
|
12
|
+
src/nspydm/jdbc/DmJdbcDriver6.jar
|
|
13
|
+
src/nspydm/jdbc/DmJdbcDriver7.jar
|
|
14
|
+
src/nspydm/jdbc/DmJdbcDriver8.jar
|
|
15
|
+
tests/test_smoke.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
JPype1<2,>=1.5.2
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
nspydm
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .dbapi import (
|
|
4
|
+
BINARY,
|
|
5
|
+
DATETIME,
|
|
6
|
+
NUMBER,
|
|
7
|
+
ROWID,
|
|
8
|
+
STRING,
|
|
9
|
+
Binary,
|
|
10
|
+
Connection,
|
|
11
|
+
Cursor,
|
|
12
|
+
DataError,
|
|
13
|
+
DatabaseError,
|
|
14
|
+
Date,
|
|
15
|
+
DateFromTicks,
|
|
16
|
+
Error,
|
|
17
|
+
IntegrityError,
|
|
18
|
+
InterfaceError,
|
|
19
|
+
InternalError,
|
|
20
|
+
NotSupportedError,
|
|
21
|
+
OperationalError,
|
|
22
|
+
ProgrammingError,
|
|
23
|
+
Time,
|
|
24
|
+
TimeFromTicks,
|
|
25
|
+
Timestamp,
|
|
26
|
+
TimestampFromTicks,
|
|
27
|
+
Warning,
|
|
28
|
+
connect,
|
|
29
|
+
paramstyle,
|
|
30
|
+
threadsafety,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
apilevel = "2.0"
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"BINARY",
|
|
37
|
+
"DATETIME",
|
|
38
|
+
"NUMBER",
|
|
39
|
+
"ROWID",
|
|
40
|
+
"STRING",
|
|
41
|
+
"Binary",
|
|
42
|
+
"Connection",
|
|
43
|
+
"Cursor",
|
|
44
|
+
"DataError",
|
|
45
|
+
"DatabaseError",
|
|
46
|
+
"Date",
|
|
47
|
+
"DateFromTicks",
|
|
48
|
+
"Error",
|
|
49
|
+
"IntegrityError",
|
|
50
|
+
"InterfaceError",
|
|
51
|
+
"InternalError",
|
|
52
|
+
"NotSupportedError",
|
|
53
|
+
"OperationalError",
|
|
54
|
+
"ProgrammingError",
|
|
55
|
+
"Time",
|
|
56
|
+
"TimeFromTicks",
|
|
57
|
+
"Timestamp",
|
|
58
|
+
"TimestampFromTicks",
|
|
59
|
+
"Warning",
|
|
60
|
+
"apilevel",
|
|
61
|
+
"connect",
|
|
62
|
+
"paramstyle",
|
|
63
|
+
"threadsafety",
|
|
64
|
+
]
|
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import datetime as _dt
|
|
4
|
+
import decimal as _decimal
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple, Union
|
|
11
|
+
|
|
12
|
+
import jpype
|
|
13
|
+
|
|
14
|
+
threadsafety = 1
|
|
15
|
+
paramstyle = "qmark"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Warning(Exception):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Error(Exception):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class InterfaceError(Error):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class DatabaseError(Error):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class DataError(DatabaseError):
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class OperationalError(DatabaseError):
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class IntegrityError(DatabaseError):
|
|
43
|
+
pass
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class InternalError(DatabaseError):
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ProgrammingError(DatabaseError):
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class NotSupportedError(DatabaseError):
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class _TypeObject:
|
|
60
|
+
name: str
|
|
61
|
+
|
|
62
|
+
def __repr__(self) -> str:
|
|
63
|
+
return self.name
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
STRING = _TypeObject("STRING")
|
|
67
|
+
BINARY = _TypeObject("BINARY")
|
|
68
|
+
NUMBER = _TypeObject("NUMBER")
|
|
69
|
+
DATETIME = _TypeObject("DATETIME")
|
|
70
|
+
ROWID = _TypeObject("ROWID")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _detect_java_major() -> Optional[int]:
|
|
74
|
+
try:
|
|
75
|
+
proc = subprocess.run(
|
|
76
|
+
["java", "-version"],
|
|
77
|
+
stdout=subprocess.PIPE,
|
|
78
|
+
stderr=subprocess.PIPE,
|
|
79
|
+
universal_newlines=True,
|
|
80
|
+
check=False,
|
|
81
|
+
)
|
|
82
|
+
except Exception:
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
text = (proc.stderr or "") + "\n" + (proc.stdout or "")
|
|
86
|
+
m = re.search(r'version\s+"([^"]+)"', text)
|
|
87
|
+
if not m:
|
|
88
|
+
m = re.search(r'openjdk\s+version\s+"([^"]+)"', text)
|
|
89
|
+
if not m:
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
ver = m.group(1).strip()
|
|
93
|
+
if ver.startswith("1."):
|
|
94
|
+
parts = ver.split(".")
|
|
95
|
+
if len(parts) >= 2 and parts[1].isdigit():
|
|
96
|
+
return int(parts[1])
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
major_text = re.split(r"[+._-]", ver, maxsplit=1)[0]
|
|
100
|
+
if major_text.isdigit():
|
|
101
|
+
return int(major_text)
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _pick_driver_filename(java_major: Optional[int]) -> str:
|
|
106
|
+
if java_major is None:
|
|
107
|
+
return "DmJdbcDriver8.jar"
|
|
108
|
+
if java_major <= 6:
|
|
109
|
+
return "DmJdbcDriver6.jar"
|
|
110
|
+
if java_major == 7:
|
|
111
|
+
return "DmJdbcDriver7.jar"
|
|
112
|
+
if java_major >= 11:
|
|
113
|
+
return "DmJdbcDriver11.jar"
|
|
114
|
+
return "DmJdbcDriver8.jar"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _default_jars() -> List[str]:
|
|
118
|
+
env = os.environ.get("DM_JDBC_JAR")
|
|
119
|
+
if env:
|
|
120
|
+
jars = [p for p in env.split(os.pathsep) if p]
|
|
121
|
+
return [str(Path(p).expanduser().resolve()) for p in jars]
|
|
122
|
+
|
|
123
|
+
java_major = _detect_java_major()
|
|
124
|
+
preferred = _pick_driver_filename(java_major)
|
|
125
|
+
fallbacks = ["DmJdbcDriver11.jar", "DmJdbcDriver8.jar", "DmJdbcDriver7.jar", "DmJdbcDriver6.jar"]
|
|
126
|
+
|
|
127
|
+
here = Path(__file__).resolve()
|
|
128
|
+
|
|
129
|
+
package_jdbc = here.parent / "jdbc"
|
|
130
|
+
if package_jdbc.exists():
|
|
131
|
+
cand = package_jdbc / preferred
|
|
132
|
+
if cand.exists():
|
|
133
|
+
return [str(cand)]
|
|
134
|
+
for name in fallbacks:
|
|
135
|
+
cand = package_jdbc / name
|
|
136
|
+
if cand.exists():
|
|
137
|
+
return [str(cand)]
|
|
138
|
+
|
|
139
|
+
for parent in [here.parent, here.parent.parent, *here.parents]:
|
|
140
|
+
candidate_dir = parent / "jdbc"
|
|
141
|
+
if not candidate_dir.exists():
|
|
142
|
+
continue
|
|
143
|
+
cand = candidate_dir / preferred
|
|
144
|
+
if cand.exists():
|
|
145
|
+
return [str(cand)]
|
|
146
|
+
for name in fallbacks:
|
|
147
|
+
cand = candidate_dir / name
|
|
148
|
+
if cand.exists():
|
|
149
|
+
return [str(cand)]
|
|
150
|
+
|
|
151
|
+
return []
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _ensure_jvm(jars: Optional[Sequence[str]]) -> None:
|
|
155
|
+
jars = [p for p in (_default_jars() if jars is None else list(jars)) if p]
|
|
156
|
+
jars = [str(Path(p).expanduser().resolve()) for p in jars]
|
|
157
|
+
|
|
158
|
+
if not jars:
|
|
159
|
+
raise InterfaceError(
|
|
160
|
+
"找不到达梦 JDBC 驱动 Jar。请通过 connect(..., jars=[...]) 或环境变量 DM_JDBC_JAR 指定。"
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
if jpype.isJVMStarted():
|
|
164
|
+
for jar in jars:
|
|
165
|
+
jpype.addClassPath(jar)
|
|
166
|
+
return
|
|
167
|
+
|
|
168
|
+
jpype.startJVM(classpath=jars, convertStrings=True)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _java() -> Dict[str, Any]:
|
|
172
|
+
DriverManager = jpype.JClass("java.sql.DriverManager")
|
|
173
|
+
Class = jpype.JClass("java.lang.Class")
|
|
174
|
+
Properties = jpype.JClass("java.util.Properties")
|
|
175
|
+
Types = jpype.JClass("java.sql.Types")
|
|
176
|
+
SQLException = jpype.JClass("java.sql.SQLException")
|
|
177
|
+
Timestamp = jpype.JClass("java.sql.Timestamp")
|
|
178
|
+
Date = jpype.JClass("java.sql.Date")
|
|
179
|
+
Time = jpype.JClass("java.sql.Time")
|
|
180
|
+
BigDecimal = jpype.JClass("java.math.BigDecimal")
|
|
181
|
+
JByte = jpype.JByte
|
|
182
|
+
JArray = jpype.JArray
|
|
183
|
+
return {
|
|
184
|
+
"BigDecimal": BigDecimal,
|
|
185
|
+
"Class": Class,
|
|
186
|
+
"Date": Date,
|
|
187
|
+
"DriverManager": DriverManager,
|
|
188
|
+
"JArray": JArray,
|
|
189
|
+
"JByte": JByte,
|
|
190
|
+
"Properties": Properties,
|
|
191
|
+
"SQLException": SQLException,
|
|
192
|
+
"Time": Time,
|
|
193
|
+
"Timestamp": Timestamp,
|
|
194
|
+
"Types": Types,
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _wrap_sql_exception(exc: BaseException) -> DatabaseError:
|
|
199
|
+
try:
|
|
200
|
+
j = _java()
|
|
201
|
+
except Exception:
|
|
202
|
+
return DatabaseError(str(exc))
|
|
203
|
+
|
|
204
|
+
if isinstance(exc, j["SQLException"]):
|
|
205
|
+
message = str(exc.getMessage())
|
|
206
|
+
sqlstate = str(exc.getSQLState()) if exc.getSQLState() is not None else None
|
|
207
|
+
errorcode = int(exc.getErrorCode())
|
|
208
|
+
return OperationalError("%s (sqlstate=%s, code=%s)" % (message, sqlstate, errorcode))
|
|
209
|
+
|
|
210
|
+
return DatabaseError(str(exc))
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _adapt_paramstyle(sql: str) -> str:
|
|
214
|
+
if "?" in sql or "%s" not in sql:
|
|
215
|
+
return sql
|
|
216
|
+
|
|
217
|
+
out = []
|
|
218
|
+
i = 0
|
|
219
|
+
in_single = False
|
|
220
|
+
in_double = False
|
|
221
|
+
|
|
222
|
+
while i < len(sql):
|
|
223
|
+
ch = sql[i]
|
|
224
|
+
|
|
225
|
+
if ch == "'" and not in_double:
|
|
226
|
+
if in_single and i + 1 < len(sql) and sql[i + 1] == "'":
|
|
227
|
+
out.append("''")
|
|
228
|
+
i += 2
|
|
229
|
+
continue
|
|
230
|
+
in_single = not in_single
|
|
231
|
+
out.append(ch)
|
|
232
|
+
i += 1
|
|
233
|
+
continue
|
|
234
|
+
|
|
235
|
+
if ch == '"' and not in_single:
|
|
236
|
+
in_double = not in_double
|
|
237
|
+
out.append(ch)
|
|
238
|
+
i += 1
|
|
239
|
+
continue
|
|
240
|
+
|
|
241
|
+
if not in_single and not in_double and sql.startswith("%s", i):
|
|
242
|
+
out.append("?")
|
|
243
|
+
i += 2
|
|
244
|
+
continue
|
|
245
|
+
|
|
246
|
+
out.append(ch)
|
|
247
|
+
i += 1
|
|
248
|
+
|
|
249
|
+
return "".join(out)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _to_java_param(value: Any) -> Any:
|
|
253
|
+
j = _java()
|
|
254
|
+
|
|
255
|
+
if value is None:
|
|
256
|
+
return None
|
|
257
|
+
if isinstance(value, bool):
|
|
258
|
+
return bool(value)
|
|
259
|
+
if isinstance(value, int):
|
|
260
|
+
return int(value)
|
|
261
|
+
if isinstance(value, float):
|
|
262
|
+
return float(value)
|
|
263
|
+
if isinstance(value, _decimal.Decimal):
|
|
264
|
+
return j["BigDecimal"](str(value))
|
|
265
|
+
if isinstance(value, _dt.datetime):
|
|
266
|
+
if value.tzinfo is not None:
|
|
267
|
+
value = value.astimezone(_dt.timezone.utc).replace(tzinfo=None)
|
|
268
|
+
text = value.isoformat(sep=" ")
|
|
269
|
+
return j["Timestamp"].valueOf(text)
|
|
270
|
+
if isinstance(value, _dt.date) and not isinstance(value, _dt.datetime):
|
|
271
|
+
return j["Date"].valueOf(value.isoformat())
|
|
272
|
+
if isinstance(value, _dt.time):
|
|
273
|
+
millis = (
|
|
274
|
+
(value.hour * 3600 + value.minute * 60 + value.second) * 1000
|
|
275
|
+
+ value.microsecond // 1000
|
|
276
|
+
)
|
|
277
|
+
return j["Time"](millis)
|
|
278
|
+
if isinstance(value, (bytes, bytearray, memoryview)):
|
|
279
|
+
data = bytes(value)
|
|
280
|
+
return j["JArray"](j["JByte"])(data)
|
|
281
|
+
|
|
282
|
+
return value
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _from_java_value(value: Any) -> Any:
|
|
286
|
+
if value is None:
|
|
287
|
+
return None
|
|
288
|
+
|
|
289
|
+
j = _java()
|
|
290
|
+
|
|
291
|
+
if isinstance(value, j["Timestamp"]):
|
|
292
|
+
text = str(value.toString())
|
|
293
|
+
return _dt.datetime.fromisoformat(text.replace(" ", "T"))
|
|
294
|
+
if isinstance(value, j["Date"]):
|
|
295
|
+
return _dt.date.fromisoformat(str(value.toString()))
|
|
296
|
+
if isinstance(value, j["Time"]):
|
|
297
|
+
return _dt.time.fromisoformat(str(value.toString()))
|
|
298
|
+
if isinstance(value, j["BigDecimal"]):
|
|
299
|
+
return _decimal.Decimal(value.toPlainString())
|
|
300
|
+
|
|
301
|
+
if isinstance(value, jpype.JBoolean):
|
|
302
|
+
return bool(value)
|
|
303
|
+
if isinstance(value, (jpype.JByte, jpype.JShort, jpype.JInt, jpype.JLong)):
|
|
304
|
+
return int(value)
|
|
305
|
+
if isinstance(value, (jpype.JFloat, jpype.JDouble)):
|
|
306
|
+
return float(value)
|
|
307
|
+
|
|
308
|
+
if isinstance(value, jpype.JArray(jpype.JByte)):
|
|
309
|
+
return bytes(value)
|
|
310
|
+
|
|
311
|
+
return value
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def Binary(x: Union[bytes, bytearray, memoryview]) -> bytes:
|
|
315
|
+
return bytes(x)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def Date(year: int, month: int, day: int) -> _dt.date:
|
|
319
|
+
return _dt.date(year, month, day)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def DateFromTicks(ticks: float) -> _dt.date:
|
|
323
|
+
return _dt.date.fromtimestamp(ticks)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def Time(hour: int, minute: int, second: int) -> _dt.time:
|
|
327
|
+
return _dt.time(hour, minute, second)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def TimeFromTicks(ticks: float) -> _dt.time:
|
|
331
|
+
return _dt.datetime.fromtimestamp(ticks).time()
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def Timestamp(year: int, month: int, day: int, hour: int, minute: int, second: int) -> _dt.datetime:
|
|
335
|
+
return _dt.datetime(year, month, day, hour, minute, second)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def TimestampFromTicks(ticks: float) -> _dt.datetime:
|
|
339
|
+
return _dt.datetime.fromtimestamp(ticks)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
class Connection:
|
|
343
|
+
def __init__(self, jconn: Any):
|
|
344
|
+
self._jconn = jconn
|
|
345
|
+
self._closed = False
|
|
346
|
+
|
|
347
|
+
def close(self) -> None:
|
|
348
|
+
if self._closed:
|
|
349
|
+
return
|
|
350
|
+
try:
|
|
351
|
+
self._jconn.close()
|
|
352
|
+
finally:
|
|
353
|
+
self._closed = True
|
|
354
|
+
|
|
355
|
+
def commit(self) -> None:
|
|
356
|
+
try:
|
|
357
|
+
self._jconn.commit()
|
|
358
|
+
except BaseException as exc:
|
|
359
|
+
raise _wrap_sql_exception(exc) from exc
|
|
360
|
+
|
|
361
|
+
def rollback(self) -> None:
|
|
362
|
+
try:
|
|
363
|
+
self._jconn.rollback()
|
|
364
|
+
except BaseException as exc:
|
|
365
|
+
raise _wrap_sql_exception(exc) from exc
|
|
366
|
+
|
|
367
|
+
def cursor(self) -> "Cursor":
|
|
368
|
+
if self._closed:
|
|
369
|
+
raise InterfaceError("connection already closed")
|
|
370
|
+
return Cursor(self)
|
|
371
|
+
|
|
372
|
+
def __enter__(self) -> "Connection":
|
|
373
|
+
return self
|
|
374
|
+
|
|
375
|
+
def __exit__(self, exc_type, exc, tb) -> None:
|
|
376
|
+
if exc is None:
|
|
377
|
+
self.commit()
|
|
378
|
+
else:
|
|
379
|
+
self.rollback()
|
|
380
|
+
self.close()
|
|
381
|
+
|
|
382
|
+
@property
|
|
383
|
+
def autocommit(self) -> bool:
|
|
384
|
+
return bool(self._jconn.getAutoCommit())
|
|
385
|
+
|
|
386
|
+
@autocommit.setter
|
|
387
|
+
def autocommit(self, value: bool) -> None:
|
|
388
|
+
self._jconn.setAutoCommit(bool(value))
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
class Cursor:
|
|
392
|
+
arraysize = 1
|
|
393
|
+
|
|
394
|
+
def __init__(self, connection: Connection):
|
|
395
|
+
self.connection = connection
|
|
396
|
+
self._closed = False
|
|
397
|
+
self._rs = None
|
|
398
|
+
self._stmt = None
|
|
399
|
+
self.description = None
|
|
400
|
+
self.rowcount = -1
|
|
401
|
+
|
|
402
|
+
def close(self) -> None:
|
|
403
|
+
if self._closed:
|
|
404
|
+
return
|
|
405
|
+
self._closed = True
|
|
406
|
+
for obj in (self._rs, self._stmt):
|
|
407
|
+
try:
|
|
408
|
+
if obj is not None:
|
|
409
|
+
obj.close()
|
|
410
|
+
except Exception:
|
|
411
|
+
pass
|
|
412
|
+
self._rs = None
|
|
413
|
+
self._stmt = None
|
|
414
|
+
|
|
415
|
+
def _check_open(self) -> None:
|
|
416
|
+
if self._closed:
|
|
417
|
+
raise InterfaceError("cursor already closed")
|
|
418
|
+
|
|
419
|
+
def _clear_result(self) -> None:
|
|
420
|
+
for obj in (self._rs, self._stmt):
|
|
421
|
+
try:
|
|
422
|
+
if obj is not None:
|
|
423
|
+
obj.close()
|
|
424
|
+
except Exception:
|
|
425
|
+
pass
|
|
426
|
+
self._rs = None
|
|
427
|
+
self._stmt = None
|
|
428
|
+
|
|
429
|
+
def execute(
|
|
430
|
+
self,
|
|
431
|
+
operation: str,
|
|
432
|
+
parameters: Optional[Union[Sequence[Any], Mapping[str, Any]]] = None,
|
|
433
|
+
) -> "Cursor":
|
|
434
|
+
self._check_open()
|
|
435
|
+
if parameters is not None and isinstance(parameters, Mapping):
|
|
436
|
+
raise NotSupportedError("仅支持序列参数(qmark/format),不支持命名参数")
|
|
437
|
+
|
|
438
|
+
sql = _adapt_paramstyle(operation)
|
|
439
|
+
|
|
440
|
+
try:
|
|
441
|
+
self._clear_result()
|
|
442
|
+
if parameters is None:
|
|
443
|
+
self._stmt = self.connection._jconn.createStatement()
|
|
444
|
+
has_rs = bool(self._stmt.execute(sql))
|
|
445
|
+
else:
|
|
446
|
+
self._stmt = self.connection._jconn.prepareStatement(sql)
|
|
447
|
+
for idx, value in enumerate(parameters, start=1):
|
|
448
|
+
self._stmt.setObject(idx, _to_java_param(value))
|
|
449
|
+
has_rs = bool(self._stmt.execute())
|
|
450
|
+
|
|
451
|
+
if has_rs:
|
|
452
|
+
self._rs = self._stmt.getResultSet()
|
|
453
|
+
self.description = self._build_description(self._rs)
|
|
454
|
+
self.rowcount = -1
|
|
455
|
+
else:
|
|
456
|
+
self._rs = None
|
|
457
|
+
self.description = None
|
|
458
|
+
self.rowcount = int(self._stmt.getUpdateCount())
|
|
459
|
+
return self
|
|
460
|
+
except BaseException as exc:
|
|
461
|
+
raise _wrap_sql_exception(exc) from exc
|
|
462
|
+
|
|
463
|
+
def executemany(self, operation: str, seq_of_parameters: Iterable[Sequence[Any]]) -> "Cursor":
|
|
464
|
+
self._check_open()
|
|
465
|
+
sql = _adapt_paramstyle(operation)
|
|
466
|
+
|
|
467
|
+
try:
|
|
468
|
+
self._clear_result()
|
|
469
|
+
self._stmt = self.connection._jconn.prepareStatement(sql)
|
|
470
|
+
total = 0
|
|
471
|
+
for parameters in seq_of_parameters:
|
|
472
|
+
for idx, value in enumerate(parameters, start=1):
|
|
473
|
+
self._stmt.setObject(idx, _to_java_param(value))
|
|
474
|
+
self._stmt.addBatch()
|
|
475
|
+
results = list(self._stmt.executeBatch())
|
|
476
|
+
if results:
|
|
477
|
+
for r in results:
|
|
478
|
+
if int(r) > 0:
|
|
479
|
+
total += int(r)
|
|
480
|
+
self.rowcount = total if total else -1
|
|
481
|
+
self._rs = None
|
|
482
|
+
self.description = None
|
|
483
|
+
return self
|
|
484
|
+
except BaseException as exc:
|
|
485
|
+
raise _wrap_sql_exception(exc) from exc
|
|
486
|
+
|
|
487
|
+
def _build_description(self, rs: Any) -> Tuple[Tuple[Any, ...], ...]:
|
|
488
|
+
meta = rs.getMetaData()
|
|
489
|
+
col_count = int(meta.getColumnCount())
|
|
490
|
+
desc = []
|
|
491
|
+
for i in range(1, col_count + 1):
|
|
492
|
+
name = str(meta.getColumnLabel(i))
|
|
493
|
+
type_code = int(meta.getColumnType(i))
|
|
494
|
+
display_size = int(meta.getColumnDisplaySize(i))
|
|
495
|
+
precision = int(meta.getPrecision(i))
|
|
496
|
+
scale = int(meta.getScale(i))
|
|
497
|
+
nullable = int(meta.isNullable(i))
|
|
498
|
+
null_ok = nullable != 0
|
|
499
|
+
desc.append((name, type_code, display_size, display_size, precision, scale, null_ok))
|
|
500
|
+
return tuple(desc)
|
|
501
|
+
|
|
502
|
+
def fetchone(self):
|
|
503
|
+
self._check_open()
|
|
504
|
+
if self._rs is None:
|
|
505
|
+
return None
|
|
506
|
+
try:
|
|
507
|
+
if not self._rs.next():
|
|
508
|
+
return None
|
|
509
|
+
return self._read_row(self._rs)
|
|
510
|
+
except BaseException as exc:
|
|
511
|
+
raise _wrap_sql_exception(exc) from exc
|
|
512
|
+
|
|
513
|
+
def fetchmany(self, size: Optional[int] = None):
|
|
514
|
+
self._check_open()
|
|
515
|
+
if self._rs is None:
|
|
516
|
+
return []
|
|
517
|
+
size = self.arraysize if size is None else int(size)
|
|
518
|
+
rows = []
|
|
519
|
+
for _ in range(size):
|
|
520
|
+
row = self.fetchone()
|
|
521
|
+
if row is None:
|
|
522
|
+
break
|
|
523
|
+
rows.append(row)
|
|
524
|
+
return rows
|
|
525
|
+
|
|
526
|
+
def fetchall(self):
|
|
527
|
+
self._check_open()
|
|
528
|
+
if self._rs is None:
|
|
529
|
+
return []
|
|
530
|
+
rows = []
|
|
531
|
+
while True:
|
|
532
|
+
row = self.fetchone()
|
|
533
|
+
if row is None:
|
|
534
|
+
break
|
|
535
|
+
rows.append(row)
|
|
536
|
+
return rows
|
|
537
|
+
|
|
538
|
+
def _read_row(self, rs: Any):
|
|
539
|
+
meta = rs.getMetaData()
|
|
540
|
+
col_count = int(meta.getColumnCount())
|
|
541
|
+
row = []
|
|
542
|
+
for i in range(1, col_count + 1):
|
|
543
|
+
value = rs.getObject(i)
|
|
544
|
+
row.append(_from_java_value(value))
|
|
545
|
+
return tuple(row)
|
|
546
|
+
|
|
547
|
+
def __iter__(self) -> Iterator[Tuple[Any, ...]]:
|
|
548
|
+
while True:
|
|
549
|
+
row = self.fetchone()
|
|
550
|
+
if row is None:
|
|
551
|
+
return
|
|
552
|
+
yield row
|
|
553
|
+
|
|
554
|
+
def setinputsizes(self, sizes: Sequence[Any]) -> None:
|
|
555
|
+
self._check_open()
|
|
556
|
+
|
|
557
|
+
def setoutputsize(self, size: int, column: Optional[int] = None) -> None:
|
|
558
|
+
self._check_open()
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def connect(
|
|
562
|
+
user: Optional[str] = None,
|
|
563
|
+
password: Optional[str] = None,
|
|
564
|
+
server: str = "127.0.0.1",
|
|
565
|
+
port: int = 5236,
|
|
566
|
+
dsn: Optional[str] = None,
|
|
567
|
+
url: Optional[str] = None,
|
|
568
|
+
autocommit: bool = False,
|
|
569
|
+
jars: Optional[Sequence[str]] = None,
|
|
570
|
+
driver_class: str = "dm.jdbc.driver.DmDriver",
|
|
571
|
+
properties: Optional[Mapping[str, str]] = None,
|
|
572
|
+
) -> Connection:
|
|
573
|
+
_ensure_jvm(jars)
|
|
574
|
+
j = _java()
|
|
575
|
+
|
|
576
|
+
try:
|
|
577
|
+
j["Class"].forName(driver_class)
|
|
578
|
+
except BaseException as exc:
|
|
579
|
+
raise InterfaceError("无法加载 JDBC Driver: %s" % driver_class) from exc
|
|
580
|
+
|
|
581
|
+
if url is None:
|
|
582
|
+
if dsn is not None and dsn.startswith("jdbc:"):
|
|
583
|
+
url = dsn
|
|
584
|
+
elif dsn is not None:
|
|
585
|
+
url = "jdbc:dm://%s" % dsn
|
|
586
|
+
else:
|
|
587
|
+
url = "jdbc:dm://%s:%s" % (server, int(port))
|
|
588
|
+
|
|
589
|
+
props = j["Properties"]()
|
|
590
|
+
if user is not None:
|
|
591
|
+
props.setProperty("user", str(user))
|
|
592
|
+
if password is not None:
|
|
593
|
+
props.setProperty("password", str(password))
|
|
594
|
+
if properties:
|
|
595
|
+
for k, v in properties.items():
|
|
596
|
+
props.setProperty(str(k), str(v))
|
|
597
|
+
|
|
598
|
+
try:
|
|
599
|
+
jconn = j["DriverManager"].getConnection(url, props)
|
|
600
|
+
jconn.setAutoCommit(bool(autocommit))
|
|
601
|
+
return Connection(jconn)
|
|
602
|
+
except BaseException as exc:
|
|
603
|
+
raise _wrap_sql_exception(exc) from exc
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class TestSmoke(unittest.TestCase):
|
|
5
|
+
def test_paramstyle_adapt(self):
|
|
6
|
+
from nspydm.dbapi import _adapt_paramstyle
|
|
7
|
+
|
|
8
|
+
self.assertEqual(
|
|
9
|
+
_adapt_paramstyle("select * from t where a=%s and b=%s"),
|
|
10
|
+
"select * from t where a=? and b=?",
|
|
11
|
+
)
|
|
12
|
+
self.assertEqual(
|
|
13
|
+
_adapt_paramstyle("select '%s' as x, col from t where a=%s"),
|
|
14
|
+
"select '%s' as x, col from t where a=?",
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
def test_can_load_driver_class(self):
|
|
18
|
+
try:
|
|
19
|
+
import jpype
|
|
20
|
+
except Exception as exc:
|
|
21
|
+
self.skipTest(str(exc))
|
|
22
|
+
|
|
23
|
+
from nspydm.dbapi import _default_jars, _ensure_jvm
|
|
24
|
+
|
|
25
|
+
jars = _default_jars()
|
|
26
|
+
if not jars:
|
|
27
|
+
self.skipTest("no dm jdbc jar found")
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
_ensure_jvm(jars)
|
|
31
|
+
except Exception as exc:
|
|
32
|
+
self.skipTest(str(exc))
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
jpype.JClass("dm.jdbc.driver.DmDriver")
|
|
36
|
+
except Exception as exc:
|
|
37
|
+
self.fail(str(exc))
|
|
38
|
+
|
|
39
|
+
def test_usage_example(self):
|
|
40
|
+
import os
|
|
41
|
+
|
|
42
|
+
url = os.environ.get("DM_TEST_URL")
|
|
43
|
+
if not url:
|
|
44
|
+
self.skipTest("set DM_TEST_URL=jdbc:dm://host:port for integration test")
|
|
45
|
+
|
|
46
|
+
user = os.environ.get("DM_TEST_USER")
|
|
47
|
+
password = os.environ.get("DM_TEST_PASSWORD")
|
|
48
|
+
|
|
49
|
+
import nspydm
|
|
50
|
+
|
|
51
|
+
conn = nspydm.connect(url=url, user=user, password=password)
|
|
52
|
+
cur = conn.cursor()
|
|
53
|
+
cur.execute("select ? as x", [1])
|
|
54
|
+
row = cur.fetchone()
|
|
55
|
+
conn.close()
|
|
56
|
+
|
|
57
|
+
self.assertTrue(row is None or row[0] == 1)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
unittest.main()
|