dmpython-jdbc 2.5.32__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Darley
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,5 @@
1
+ include README.md
2
+ include LICENSE
3
+ include NOTICE
4
+ include pyproject.toml
5
+ recursive-include _dmPython_jdbc *.jar
@@ -0,0 +1,7 @@
1
+ This project redistributes the Dameng JDBC driver:
2
+
3
+ _dmPython_jdbc/DmJdbcDriver18-*.jar
4
+
5
+ That JAR is copyright 达梦数据库有限公司 (Dameng). It is included for
6
+ convenience so `pip install dmpython-jdbc` works on macOS without a separate
7
+ driver download. It is not licensed under the MIT license of this repository.
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: dmpython-jdbc
3
+ Version: 2.5.32
4
+ Summary: macOS dmPython compatibility shim backed by JayDeBeApi
5
+ Author-email: Darley <darley.wey@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Darley-Wey/dmpython-jdbc
8
+ Project-URL: Repository, https://github.com/Darley-Wey/dmpython-jdbc
9
+ Project-URL: Issues, https://github.com/Darley-Wey/dmpython-jdbc/issues
10
+ Keywords: dameng,dmPython,jdbc,macos
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Database
18
+ Requires-Python: >=3.12
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: JayDeBeApi>=1.2.3
22
+ Dynamic: license-file
23
+
24
+ # dmpython-jdbc
25
+
26
+ macOS 上的达梦 `dmPython` 兼容层。官方驱动没有 macOS 版,这里用 JayDeBeApi + 达梦 JDBC 实现 DBAPI 子集,让 `dmSQLAlchemy` 的 `dm+dmPython://` 方言能在本机跑起来。
27
+
28
+ **发行名是 `dmpython-jdbc`,import 名仍是 `dmPython`。** 业务代码不用改。
29
+
30
+ - macOS:使用本包的 JDBC shim
31
+ - 其它平台:把 `import dmPython` 转发给已安装的官方驱动
32
+
33
+ ## 安装
34
+
35
+ PyPI:
36
+
37
+ ```bash
38
+ pip install dmpython-jdbc
39
+ ```
40
+
41
+ 跨平台项目(Linux/Windows 用官方驱动,macOS 用本包):
42
+
43
+ ```toml
44
+ [project]
45
+ dependencies = [
46
+ "dmpython>=2.5.32; sys_platform != 'darwin'",
47
+ "dmpython-jdbc>=2.5.32; sys_platform == 'darwin'",
48
+ ]
49
+ ```
50
+
51
+ 从 GitHub 安装:
52
+
53
+ ```bash
54
+ pip install "dmpython-jdbc @ git+https://github.com/Darley-Wey/dmpython-jdbc.git"
55
+ ```
56
+
57
+ uv:
58
+
59
+ ```toml
60
+ [tool.uv.sources]
61
+ dmpython-jdbc = { git = "https://github.com/Darley-Wey/dmpython-jdbc.git" }
62
+ ```
63
+
64
+ 需要钉到某个提交或 tag 时,在 URL 后加 `@<ref>`,例如 `@main` 或 `@v2.5.32`。
65
+
66
+ ## 运行依赖
67
+
68
+ - Python >= 3.12
69
+ - JDK(macOS 可用 `brew install openjdk`)。`JAVA_HOME` 会自动探测 `/opt/homebrew/opt/openjdk` 和 `/usr/local/opt/openjdk`
70
+ - 达梦 JDBC 驱动已打包进 wheel;也可用环境变量 `DM_JDBC_JAR` 覆盖
71
+
72
+ ## 限制
73
+
74
+ 不支持存储过程出参(`cursor.var`)、LOB 流式读写等高级特性,覆盖 ORM CRUD 即可。
75
+
76
+ ## 许可证
77
+
78
+ Python 兼容层使用 MIT。仓库中的 `DmJdbcDriver18-*.jar` 是达梦官方 JDBC 驱动,版权归达梦数据库所有,不受 MIT 覆盖。
@@ -0,0 +1,55 @@
1
+ # dmpython-jdbc
2
+
3
+ macOS 上的达梦 `dmPython` 兼容层。官方驱动没有 macOS 版,这里用 JayDeBeApi + 达梦 JDBC 实现 DBAPI 子集,让 `dmSQLAlchemy` 的 `dm+dmPython://` 方言能在本机跑起来。
4
+
5
+ **发行名是 `dmpython-jdbc`,import 名仍是 `dmPython`。** 业务代码不用改。
6
+
7
+ - macOS:使用本包的 JDBC shim
8
+ - 其它平台:把 `import dmPython` 转发给已安装的官方驱动
9
+
10
+ ## 安装
11
+
12
+ PyPI:
13
+
14
+ ```bash
15
+ pip install dmpython-jdbc
16
+ ```
17
+
18
+ 跨平台项目(Linux/Windows 用官方驱动,macOS 用本包):
19
+
20
+ ```toml
21
+ [project]
22
+ dependencies = [
23
+ "dmpython>=2.5.32; sys_platform != 'darwin'",
24
+ "dmpython-jdbc>=2.5.32; sys_platform == 'darwin'",
25
+ ]
26
+ ```
27
+
28
+ 从 GitHub 安装:
29
+
30
+ ```bash
31
+ pip install "dmpython-jdbc @ git+https://github.com/Darley-Wey/dmpython-jdbc.git"
32
+ ```
33
+
34
+ uv:
35
+
36
+ ```toml
37
+ [tool.uv.sources]
38
+ dmpython-jdbc = { git = "https://github.com/Darley-Wey/dmpython-jdbc.git" }
39
+ ```
40
+
41
+ 需要钉到某个提交或 tag 时,在 URL 后加 `@<ref>`,例如 `@main` 或 `@v2.5.32`。
42
+
43
+ ## 运行依赖
44
+
45
+ - Python >= 3.12
46
+ - JDK(macOS 可用 `brew install openjdk`)。`JAVA_HOME` 会自动探测 `/opt/homebrew/opt/openjdk` 和 `/usr/local/opt/openjdk`
47
+ - 达梦 JDBC 驱动已打包进 wheel;也可用环境变量 `DM_JDBC_JAR` 覆盖
48
+
49
+ ## 限制
50
+
51
+ 不支持存储过程出参(`cursor.var`)、LOB 流式读写等高级特性,覆盖 ORM CRUD 即可。
52
+
53
+ ## 许可证
54
+
55
+ Python 兼容层使用 MIT。仓库中的 `DmJdbcDriver18-*.jar` 是达梦官方 JDBC 驱动,版权归达梦数据库所有,不受 MIT 覆盖。
@@ -0,0 +1,482 @@
1
+ """
2
+ dmPython 兼容 shim(仅 macOS 本地开发用)。
3
+
4
+ 达梦官方没有 macOS 版 dmPython(缺少 libdmdpi 闭源库无法本地编译),
5
+ 本模块用 JayDeBeApi + DmJdbcDriver 实现 dmPython 的 DBAPI 子集,
6
+ 让 dmSQLAlchemy 的 `dm+dmPython://` 方言在 mac 上可用。
7
+
8
+ 依赖:
9
+ - pip/uv 安装本包时会自动拉 JayDeBeApi(jpype1 会一并安装)
10
+ - brew install openjdk (JAVA_HOME 自动探测 /opt/homebrew/opt/openjdk)
11
+ - 达梦 JDBC 驱动 jar 已随包发布;可用环境变量 DM_JDBC_JAR 覆盖
12
+
13
+ 限制: 不支持存储过程出参(cursor.var)、LOB 流式读写等高级特性, 满足 ORM CRUD 即可。
14
+ """
15
+ import datetime as _datetime
16
+ import glob
17
+ import os
18
+ import re
19
+ import sys
20
+
21
+ version = "2.5.32" # 伪装成官方版本号, dmSQLAlchemy 会解析它
22
+ apilevel = "2.0"
23
+ threadsafety = 1
24
+ paramstyle = "qmark" # 编译成 ? 占位符, 与 JDBC 原生一致; dialect do_execute 也按位置索引参数
25
+
26
+
27
+ # ---------------------------------------------------------------- 异常体系
28
+ class Warning(Exception): pass
29
+ class Error(Exception): pass
30
+ class InterfaceError(Error): pass
31
+ class DatabaseError(Error): pass
32
+ class DataError(DatabaseError): pass
33
+ class OperationalError(DatabaseError): pass
34
+ class IntegrityError(DatabaseError): pass
35
+ class InternalError(DatabaseError): pass
36
+ class ProgrammingError(DatabaseError): pass
37
+ class NotSupportedError(DatabaseError): pass
38
+
39
+
40
+ # ---------------------------------------------------------------- 类型哨兵
41
+ # 官方 dmPython 中这些符号本身是类, dmSQLAlchemy 会拿来做 isinstance 判断
42
+ # (如 isinstance(value, dialect.dbapi.LOB)), 所以必须是类而不是实例。
43
+ class _DBType:
44
+ def __init__(self, name):
45
+ self.name = name
46
+
47
+ def __repr__(self):
48
+ return f"<dmPython.{self.name}>"
49
+
50
+
51
+ def _make_type(name):
52
+ return type(name, (_DBType,), {"_type_name": name})
53
+
54
+
55
+ STRING = _make_type("STRING")
56
+ UNICODE = _make_type("UNICODE")
57
+ LONG_STRING = _make_type("LONG_STRING")
58
+ FIXED_CHAR = _make_type("FIXED_CHAR")
59
+ VARCHAR = _make_type("VARCHAR")
60
+ CLOB = _make_type("CLOB")
61
+ NCLOB = _make_type("NCLOB")
62
+ BLOB = _make_type("BLOB")
63
+ BFILE = _make_type("BFILE")
64
+ BINARY = _make_type("BINARY")
65
+ LONG_BINARY = _make_type("LONG_BINARY")
66
+ NUMBER = _make_type("NUMBER")
67
+ NATIVE_FLOAT = _make_type("NATIVE_FLOAT")
68
+ DATETIME = _make_type("DATETIME")
69
+ DATE = _make_type("DATE")
70
+ TIME = _make_type("TIME")
71
+ TIMESTAMP = _make_type("TIMESTAMP")
72
+ INTERVAL = _make_type("INTERVAL")
73
+ ROWID = _make_type("ROWID")
74
+ LOB = _make_type("LOB")
75
+ CURSOR = _make_type("CURSOR")
76
+ BOOLEAN = _make_type("BOOLEAN")
77
+ TupleCursor = _make_type("TupleCursor")
78
+
79
+
80
+ def _jdbc_timestamp_to_datetime(result_set, column):
81
+ """将 JDBC TIMESTAMP 转为与官方 dmPython 一致的 Python datetime。"""
82
+ value = result_set.getTimestamp(column)
83
+ if value is None:
84
+ return None
85
+
86
+ parsed = _datetime.datetime.strptime(str(value)[:19], "%Y-%m-%d %H:%M:%S")
87
+ return parsed.replace(microsecond=int(value.getNanos()) // 1000)
88
+
89
+
90
+ def _find_jar():
91
+ jar = os.environ.get("DM_JDBC_JAR")
92
+ if jar and os.path.exists(jar):
93
+ return jar
94
+ here = os.path.dirname(os.path.abspath(__file__))
95
+ packaged = sorted(glob.glob(os.path.join(here, "DmJdbcDriver*.jar")))
96
+ if packaged:
97
+ return packaged[-1]
98
+ for base in (os.path.dirname(here), os.getcwd()):
99
+ hits = sorted(glob.glob(os.path.join(base, "libs", "DmJdbcDriver*.jar"))) \
100
+ or sorted(glob.glob(os.path.join(base, "DmJdbcDriver*.jar")))
101
+ if hits:
102
+ return hits[-1]
103
+ raise InterfaceError("找不到达梦 JDBC 驱动 jar, 请设置环境变量 DM_JDBC_JAR")
104
+
105
+
106
+ def _ensure_java_home():
107
+ if os.environ.get("JAVA_HOME"):
108
+ return
109
+ for cand in ("/opt/homebrew/opt/openjdk", "/usr/local/opt/openjdk"):
110
+ if os.path.exists(os.path.join(cand, "bin", "java")):
111
+ os.environ["JAVA_HOME"] = cand
112
+ return
113
+
114
+
115
+ # :name 占位符 → JDBC '?' 占位符。跳过字符串字面量与 :: 转换。
116
+ _BIND_RE = re.compile(r"(?<![:\w]):([A-Za-z_][A-Za-z0-9_]*)")
117
+
118
+
119
+ def _named_to_qmark(sql):
120
+ names = []
121
+ out = []
122
+ pos = 0
123
+ in_str = False
124
+ i = 0
125
+ buf = sql
126
+ # 简单状态机: 单引号字符串内不做替换
127
+ result = []
128
+ last = 0
129
+ for m in _BIND_RE.finditer(sql):
130
+ seg = sql[last:m.start()]
131
+ # 统计该占位符之前未闭合的单引号数
132
+ if (sql[:m.start()].count("'") % 2) == 1:
133
+ continue
134
+ result.append(seg)
135
+ result.append("?")
136
+ names.append(m.group(1))
137
+ last = m.end()
138
+ result.append(sql[last:])
139
+ return "".join(result), names
140
+
141
+
142
+ class Cursor:
143
+ def __init__(self, jcur, conn):
144
+ self._cur = jcur
145
+ self._conn = conn
146
+ self.arraysize = 50
147
+ self.outputtypehandler = None
148
+ self.inputtypehandler = None
149
+ self.output_stream = 0
150
+ self.rowfactory = None
151
+ self._lastrowid = None
152
+ self._closed = False
153
+
154
+ def _check_conn_open(self):
155
+ # dmSQLAlchemy.is_disconnect 只把 InterfaceError("not connected") 判成断线;
156
+ # 把 JDBC 的“连接尚未建立或已经关闭”映射成这一形态, 连接池才能自动丢弃旧连接并重建。
157
+ if self._closed or getattr(self._conn, "_closed", False):
158
+ raise InterfaceError("not connected")
159
+
160
+ # -- DBAPI --
161
+ @property
162
+ def description(self):
163
+ desc = self._cur.description
164
+ if not desc:
165
+ return desc
166
+ # jaydebeapi 用 getColumnName(底层列名)而非 getColumnLabel(SQL 别名),
167
+ # 会丢掉 `id as "tab_id"` 这类别名; 这里用 label 修正。
168
+ # 另: DM 服务端把未加引号的标识符统一大写返回, 官方 dmPython 返回小写,
169
+ # dmSQLAlchemy 反射代码按小写取列, 全大写时转小写保持一致。
170
+ meta = getattr(self._cur, "_meta", None)
171
+ names = []
172
+ for i, d in enumerate(desc):
173
+ name = d[0]
174
+ if meta is not None:
175
+ try:
176
+ name = str(meta.getColumnLabel(i + 1))
177
+ except Exception:
178
+ pass
179
+ if isinstance(name, str) and name.isupper():
180
+ name = name.lower()
181
+ names.append(name)
182
+ return [(names[i],) + tuple(d[1:]) for i, d in enumerate(desc)]
183
+
184
+ @property
185
+ def rowcount(self):
186
+ return self._cur.rowcount
187
+
188
+ def _prepare(self, operation, parameters):
189
+ if parameters is None:
190
+ return operation, None
191
+ if isinstance(parameters, (list, tuple)):
192
+ return operation, list(parameters)
193
+ # dict → named 转 qmark
194
+ sql, names = _named_to_qmark(operation)
195
+ return sql, [parameters.get(n) for n in names]
196
+
197
+ def execute(self, operation, parameters=None, **kw):
198
+ self._check_conn_open()
199
+ sql, params = self._prepare(operation, parameters)
200
+ try:
201
+ self._cur.execute(sql, params)
202
+ except Exception as e:
203
+ msg = str(e)
204
+ if "尚未建立" in msg or "已经关闭" in msg or "not connected" in msg.lower() or "connection closed" in msg.lower():
205
+ raise InterfaceError("not connected") from e
206
+ raise DatabaseError(msg) from e
207
+ self._capture_identity(sql)
208
+ return self
209
+
210
+ def executemany(self, operation, seq_of_parameters, **kw):
211
+ self._check_conn_open()
212
+ first = seq_of_parameters[0] if seq_of_parameters else None
213
+ if isinstance(first, dict):
214
+ sql, names = _named_to_qmark(operation)
215
+ rows = [[p.get(n) for n in names] for p in seq_of_parameters]
216
+ else:
217
+ sql, rows = operation, [list(p) for p in seq_of_parameters]
218
+ try:
219
+ self._cur.executemany(sql, rows)
220
+ except Exception as e:
221
+ msg = str(e)
222
+ if "尚未建立" in msg or "已经关闭" in msg or "not connected" in msg.lower() or "connection closed" in msg.lower():
223
+ raise InterfaceError("not connected") from e
224
+ raise DatabaseError(msg) from e
225
+ return self
226
+
227
+ def _capture_identity(self, sql):
228
+ # 仅 INSERT 后按需取自增值(get_lastrowid 会读取)
229
+ self._lastrowid = None
230
+ if re.match(r"\s*insert\b", sql, re.I):
231
+ self._pending_identity = True
232
+ else:
233
+ self._pending_identity = False
234
+
235
+ @property
236
+ def lastrowid(self):
237
+ if getattr(self, "_pending_identity", False):
238
+ c = self._conn._jconn.cursor()
239
+ try:
240
+ c.execute("SELECT SCOPE_IDENTITY()")
241
+ row = c.fetchone()
242
+ self._lastrowid = int(row[0]) if row and row[0] is not None else None
243
+ except Exception:
244
+ self._lastrowid = None
245
+ finally:
246
+ c.close()
247
+ self._pending_identity = False
248
+ return self._lastrowid
249
+
250
+ def _convert_row(self, row):
251
+ """jaydebeapi 把 CLOB/BLOB 列返回为 java.sql.Clob/Blob 对象,
252
+ 官方 dmPython 返回 str/bytes, 这里统一转换避免 ORM 赋值时报错。"""
253
+ if row is None:
254
+ return None
255
+ items = []
256
+ for v in row:
257
+ # jpype1 代理对象的类名形如 _jp_java.sql.Clob, 或是接口类型 java.sql.Clob
258
+ cls_name = type(v).__name__
259
+ if not isinstance(v, (str, bytes, int, float, bool, type(None))):
260
+ try:
261
+ simple = ''
262
+ if hasattr(v, 'getClass'):
263
+ try:
264
+ simple = str(v.getClass().getSimpleName())
265
+ except Exception:
266
+ simple = cls_name
267
+ else:
268
+ simple = cls_name
269
+ if 'Clob' in simple or 'NClob' in simple:
270
+ v = v.getSubString(1, int(v.length()))
271
+ elif 'Blob' in simple:
272
+ v = bytes(v.getBytes(1, int(v.length())))
273
+ elif cls_name.startswith('_jp_java') or cls_name.startswith('_jp_'):
274
+ v = str(v)
275
+ except Exception:
276
+ pass
277
+ items.append(v)
278
+ return tuple(items)
279
+
280
+ def fetchone(self):
281
+ return self._convert_row(self._cur.fetchone())
282
+
283
+ def fetchmany(self, size=None):
284
+ return [self._convert_row(r) for r in self._cur.fetchmany(size or self.arraysize)]
285
+
286
+ def fetchall(self):
287
+ return [self._convert_row(r) for r in self._cur.fetchall()]
288
+
289
+ def setinputsizes(self, *args, **kw):
290
+ pass
291
+
292
+ def setoutputsize(self, *args, **kw):
293
+ pass
294
+
295
+ def var(self, *args, **kw):
296
+ raise NotSupportedError("JDBC shim 不支持 cursor.var/出参")
297
+
298
+ def close(self):
299
+ try:
300
+ self._cur.close()
301
+ except Exception:
302
+ pass
303
+ self._closed = True
304
+
305
+ def __iter__(self):
306
+ while True:
307
+ row = self.fetchone()
308
+ if row is None:
309
+ return
310
+ yield row
311
+
312
+ def __enter__(self):
313
+ return self
314
+
315
+ def __exit__(self, *exc):
316
+ self.close()
317
+
318
+
319
+ class Connection:
320
+ def __init__(self, jconn, schema=None):
321
+ self._jconn = jconn
322
+ self.outputtypehandler = None
323
+ self.inputtypehandler = None
324
+ self.autocommit = False
325
+ self.server_version = "8.1.3.140"
326
+ self.current_schema = schema # dmSQLAlchemy 取默认 schema 用
327
+ self.local_code = 1 # 1 = utf-8, dmSQLAlchemy 会读取
328
+ self._closed = False
329
+ try:
330
+ cur = self._jconn.cursor()
331
+ cur.execute("SELECT CASE_SENSITIVE()")
332
+ row = cur.fetchone()
333
+ cur.close()
334
+ self.str_case_sensitive = bool(row and row[0] in (1, 'Y', 'y', True))
335
+ except Exception:
336
+ self.str_case_sensitive = True
337
+
338
+ def _check_open(self):
339
+ if self._closed:
340
+ raise InterfaceError("not connected")
341
+
342
+ def cursor(self, *args, **kw):
343
+ self._check_open()
344
+ return Cursor(self._jconn.cursor(), self)
345
+
346
+ def commit(self):
347
+ self._check_open()
348
+ self._jconn.commit()
349
+
350
+ def rollback(self):
351
+ if self._closed:
352
+ return
353
+ try:
354
+ self._jconn.rollback()
355
+ except Exception:
356
+ pass
357
+
358
+ def close(self):
359
+ try:
360
+ self._jconn.close()
361
+ except Exception:
362
+ pass
363
+ self._closed = True
364
+
365
+ def ping(self, *a, **kw):
366
+ cur = self.cursor()
367
+ try:
368
+ cur.execute("SELECT 1")
369
+ cur.fetchone()
370
+ finally:
371
+ cur.close()
372
+
373
+ def __enter__(self):
374
+ return self
375
+
376
+ def __exit__(self, *exc):
377
+ self.close()
378
+
379
+
380
+ def _patch_dialect_no_returning():
381
+ """RETURNING 依赖 cursor.var 出参, JDBC shim 不支持;
382
+ 关闭方言的 returning 能力, 让 SQLAlchemy 回退到 lastrowid 取自增主键。"""
383
+ mod = sys.modules.get("dmSQLAlchemy.dmpython")
384
+ if mod is None:
385
+ return
386
+ cls = getattr(mod, "DMDialect_dmPython", None)
387
+ if cls is None or getattr(cls, "_jdbc_shim_patched", False):
388
+ return
389
+ cls.insert_returning = False
390
+ cls.update_returning = False
391
+ cls.delete_returning = False
392
+ cls.insert_executemany_returning = False
393
+ cls.favor_returning_over_lastrowid = False
394
+
395
+ # JDBC 的 SCOPE_IDENTITY() 返回单列自增主键值;dmSQLAlchemy 官方驱动
396
+ # 则将 lastrowid 视为物理 ROWID 再查询。为 JDBC shim 直接回填该主键值。
397
+ def _get_cols_from_lastrowid(self, table, primary_columns, lastrowid):
398
+ if len(primary_columns) == 1:
399
+ return (lastrowid,)
400
+ return super(cls.execution_ctx_cls, self).get_cols_from_lastrowid(
401
+ table, primary_columns, lastrowid
402
+ )
403
+
404
+ cls.execution_ctx_cls.get_cols_from_lastrowid = _get_cols_from_lastrowid
405
+
406
+ # 官方 do_executemany 会拼 `RETURNING ... INTO ?` 出参取回自增主键,
407
+ # JDBC 无此机制; 改为普通 executemany, 主键由服务端自增, ORM 批量插入
408
+ # 后如需主键请单条 add + flush。
409
+ import datetime as _dt
410
+ import json as _json
411
+
412
+ def _do_executemany(self, cursor, statement, parameters, context=None):
413
+ rows = [list(p) for p in parameters]
414
+ for row in rows:
415
+ for j, v in enumerate(row):
416
+ if isinstance(v, _dt.datetime):
417
+ row[j] = v.strftime("%Y-%m-%d %H:%M:%S.%f")
418
+ elif isinstance(v, list):
419
+ row[j] = _json.dumps(v) if v else ''
420
+ cursor.executemany(statement, rows)
421
+
422
+ cls.do_executemany = _do_executemany
423
+ cls._jdbc_shim_patched = True
424
+
425
+
426
+ def connect(*args, **kw):
427
+ """兼容 dmPython.connect(user=..., password=..., dsn='host:port', schema=..., ...)"""
428
+ import jaydebeapi
429
+
430
+ _patch_dialect_no_returning()
431
+ _ensure_java_home()
432
+ user = kw.get("user") or kw.get("username") or "SYSDBA"
433
+ password = kw.get("password", "")
434
+ dsn = kw.get("dsn")
435
+ if dsn:
436
+ host, _, port = dsn.partition(":")
437
+ else:
438
+ host, port = kw.get("host", "localhost"), str(kw.get("port", 5236))
439
+ schema = kw.get("schema")
440
+ url = f"jdbc:dm://{host}:{port}"
441
+ props = {}
442
+ if schema:
443
+ props["schema"] = schema
444
+ if kw.get("local_code") is not None:
445
+ pass # 编码由 JDBC 自动处理
446
+ if props:
447
+ url += "?" + "&".join(f"{k}={v}" for k, v in props.items())
448
+ try:
449
+ jconn = jaydebeapi.connect(
450
+ "dm.jdbc.driver.DmDriver", url, [user, password], _find_jar()
451
+ )
452
+ timestamp_type = jaydebeapi._jdbc_name_to_const["TIMESTAMP"]
453
+ jconn._converters[timestamp_type] = _jdbc_timestamp_to_datetime
454
+ except Exception as e:
455
+ raise OperationalError(f"达梦 JDBC 连接失败: {e}") from e
456
+ autocommit = kw.get("autoCommit", kw.get("autocommit", False))
457
+ jconn.jconn.setAutoCommit(bool(autocommit))
458
+ conn = Connection(jconn, schema=schema)
459
+ if conn.current_schema is None:
460
+ try:
461
+ cur = conn.cursor()
462
+ cur.execute("SELECT SYS_CONTEXT('userenv','current_schema') FROM dual")
463
+ row = cur.fetchone()
464
+ cur.close()
465
+ conn.current_schema = row[0] if row else user
466
+ except Exception:
467
+ conn.current_schema = user
468
+ conn.autocommit = bool(autocommit)
469
+ return conn
470
+
471
+
472
+ # dmSQLAlchemy 反射用到的可选符号, 提供占位实现
473
+ def parse_mysql_stmt(*a, **kw):
474
+ raise NotSupportedError("shim 不支持 parse_mysql_stmt")
475
+
476
+
477
+ def parse_tsql_stmt(*a, **kw):
478
+ raise NotSupportedError("shim 不支持 parse_tsql_stmt")
479
+
480
+
481
+ class objedctvar: # dmSQLAlchemy 引用了这个拼写
482
+ pass
@@ -0,0 +1,27 @@
1
+ """按平台选择达梦官方驱动或 macOS JDBC 兼容实现。"""
2
+
3
+ import importlib.machinery
4
+ import importlib.util
5
+ import sys
6
+ from pathlib import Path
7
+
8
+
9
+ if sys.platform == "darwin":
10
+ from _dmPython_jdbc import * # noqa: F403
11
+ else:
12
+ shim_dir = Path(__file__).resolve().parent
13
+ search_paths = [
14
+ path
15
+ for path in sys.path
16
+ if Path(path or ".").resolve() != shim_dir
17
+ ]
18
+ spec = importlib.machinery.PathFinder.find_spec(__name__, search_paths)
19
+ if spec is None or spec.loader is None:
20
+ raise ImportError(
21
+ "当前平台需要安装达梦官方 dmPython 驱动,但未在虚拟环境中找到"
22
+ )
23
+
24
+ native_module = importlib.util.module_from_spec(spec)
25
+ spec.loader.exec_module(native_module)
26
+ sys.modules[__name__] = native_module
27
+ globals().update(native_module.__dict__)
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: dmpython-jdbc
3
+ Version: 2.5.32
4
+ Summary: macOS dmPython compatibility shim backed by JayDeBeApi
5
+ Author-email: Darley <darley.wey@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Darley-Wey/dmpython-jdbc
8
+ Project-URL: Repository, https://github.com/Darley-Wey/dmpython-jdbc
9
+ Project-URL: Issues, https://github.com/Darley-Wey/dmpython-jdbc/issues
10
+ Keywords: dameng,dmPython,jdbc,macos
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Database
18
+ Requires-Python: >=3.12
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: JayDeBeApi>=1.2.3
22
+ Dynamic: license-file
23
+
24
+ # dmpython-jdbc
25
+
26
+ macOS 上的达梦 `dmPython` 兼容层。官方驱动没有 macOS 版,这里用 JayDeBeApi + 达梦 JDBC 实现 DBAPI 子集,让 `dmSQLAlchemy` 的 `dm+dmPython://` 方言能在本机跑起来。
27
+
28
+ **发行名是 `dmpython-jdbc`,import 名仍是 `dmPython`。** 业务代码不用改。
29
+
30
+ - macOS:使用本包的 JDBC shim
31
+ - 其它平台:把 `import dmPython` 转发给已安装的官方驱动
32
+
33
+ ## 安装
34
+
35
+ PyPI:
36
+
37
+ ```bash
38
+ pip install dmpython-jdbc
39
+ ```
40
+
41
+ 跨平台项目(Linux/Windows 用官方驱动,macOS 用本包):
42
+
43
+ ```toml
44
+ [project]
45
+ dependencies = [
46
+ "dmpython>=2.5.32; sys_platform != 'darwin'",
47
+ "dmpython-jdbc>=2.5.32; sys_platform == 'darwin'",
48
+ ]
49
+ ```
50
+
51
+ 从 GitHub 安装:
52
+
53
+ ```bash
54
+ pip install "dmpython-jdbc @ git+https://github.com/Darley-Wey/dmpython-jdbc.git"
55
+ ```
56
+
57
+ uv:
58
+
59
+ ```toml
60
+ [tool.uv.sources]
61
+ dmpython-jdbc = { git = "https://github.com/Darley-Wey/dmpython-jdbc.git" }
62
+ ```
63
+
64
+ 需要钉到某个提交或 tag 时,在 URL 后加 `@<ref>`,例如 `@main` 或 `@v2.5.32`。
65
+
66
+ ## 运行依赖
67
+
68
+ - Python >= 3.12
69
+ - JDK(macOS 可用 `brew install openjdk`)。`JAVA_HOME` 会自动探测 `/opt/homebrew/opt/openjdk` 和 `/usr/local/opt/openjdk`
70
+ - 达梦 JDBC 驱动已打包进 wheel;也可用环境变量 `DM_JDBC_JAR` 覆盖
71
+
72
+ ## 限制
73
+
74
+ 不支持存储过程出参(`cursor.var`)、LOB 流式读写等高级特性,覆盖 ORM CRUD 即可。
75
+
76
+ ## 许可证
77
+
78
+ Python 兼容层使用 MIT。仓库中的 `DmJdbcDriver18-*.jar` 是达梦官方 JDBC 驱动,版权归达梦数据库所有,不受 MIT 覆盖。
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ NOTICE
4
+ README.md
5
+ dmPython.py
6
+ pyproject.toml
7
+ _dmPython_jdbc/DmJdbcDriver18-8.1.3.140.jar
8
+ _dmPython_jdbc/__init__.py
9
+ dmpython_jdbc.egg-info/PKG-INFO
10
+ dmpython_jdbc.egg-info/SOURCES.txt
11
+ dmpython_jdbc.egg-info/dependency_links.txt
12
+ dmpython_jdbc.egg-info/requires.txt
13
+ dmpython_jdbc.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ JayDeBeApi>=1.2.3
@@ -0,0 +1,2 @@
1
+ _dmPython_jdbc
2
+ dmPython
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["setuptools>=83.0.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "dmpython-jdbc"
7
+ version = "2.5.32"
8
+ description = "macOS dmPython compatibility shim backed by JayDeBeApi"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ { name = "Darley", email = "darley.wey@gmail.com" },
15
+ ]
16
+ keywords = ["dameng", "dmPython", "jdbc", "macos"]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Intended Audience :: Developers",
20
+ "Operating System :: MacOS",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Database",
25
+ ]
26
+ dependencies = [
27
+ "JayDeBeApi>=1.2.3",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/Darley-Wey/dmpython-jdbc"
32
+ Repository = "https://github.com/Darley-Wey/dmpython-jdbc"
33
+ Issues = "https://github.com/Darley-Wey/dmpython-jdbc/issues"
34
+
35
+ [tool.setuptools]
36
+ py-modules = ["dmPython"]
37
+ packages = ["_dmPython_jdbc"]
38
+ include-package-data = true
39
+
40
+ [tool.setuptools.package-data]
41
+ _dmPython_jdbc = ["*.jar"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+