atquery 2.14.2__tar.gz → 2.17.0__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.
Files changed (71) hide show
  1. {atquery-2.14.2 → atquery-2.17.0}/PKG-INFO +1 -1
  2. {atquery-2.14.2 → atquery-2.17.0}/pyproject.toml +3 -1
  3. {atquery-2.14.2 → atquery-2.17.0}/pyproject.toml.orig +2 -2
  4. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/__init__.py +2 -2
  5. atquery-2.17.0/src/atquery/aio/__init__.py +31 -0
  6. atquery-2.17.0/src/atquery/aio/api.py +191 -0
  7. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/api_v2.py +37 -4
  8. atquery-2.17.0/src/atquery/cli/csv.py +113 -0
  9. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/cli/main.py +42 -1
  10. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/__init__.py +1 -31
  11. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/mysql/__init__.py +2 -0
  12. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/mysql/core.py +67 -0
  13. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/sqlite.py +62 -0
  14. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/factory.py +0 -38
  15. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/type.py +4 -2
  16. atquery-2.14.2/src/atquery/aio/__init__.py +0 -101
  17. {atquery-2.14.2 → atquery-2.17.0}/LICENSE +0 -0
  18. {atquery-2.14.2 → atquery-2.17.0}/README.md +0 -0
  19. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/aio/engine.py +0 -0
  20. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/aio/query.py +0 -0
  21. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/atquery2.py +0 -0
  22. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/cli/__init__.py +0 -0
  23. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/cli/columns.py +0 -0
  24. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/cli/ddl.py +0 -0
  25. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/cli/diff.py +0 -0
  26. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/cli/ecd.py +0 -0
  27. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/cli/migrate.py +0 -0
  28. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/cli/routines.py +0 -0
  29. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/cli/scenario.py +0 -0
  30. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/cli/schemas.py +0 -0
  31. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/cli/tables.py +0 -0
  32. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/duckdb.py +0 -0
  33. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/mysql/aio.py +0 -0
  34. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/mysql/dump/__init__.py +0 -0
  35. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/mysql/dump/__main__.py +0 -0
  36. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/mysql/dump/core.py +0 -0
  37. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/mysql/meta.py +0 -0
  38. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/mysql/pooling.py +0 -0
  39. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/mysql/restore/__init__.py +0 -0
  40. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/mysql/restore/__main__.py +0 -0
  41. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/dialect/mysql/restore/core.py +0 -0
  42. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/diff/__init__.py +0 -0
  43. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/diff/comparator.py +0 -0
  44. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/diff/generator.py +0 -0
  45. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/diff/git_integration.py +0 -0
  46. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/diff/models.py +0 -0
  47. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/diff/parser.py +0 -0
  48. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/__init__.py +0 -0
  49. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/_toml.py +0 -0
  50. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/catalog.py +0 -0
  51. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/ddl.py +0 -0
  52. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/diff.py +0 -0
  53. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/erd.py +0 -0
  54. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/errors.py +0 -0
  55. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/model.py +0 -0
  56. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/parser.py +0 -0
  57. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/resolver.py +0 -0
  58. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/seed.py +0 -0
  59. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/ecd/skeleton.py +0 -0
  60. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/engine.py +0 -0
  61. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/migration/__init__.py +0 -0
  62. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/migration/_migrator.py +0 -0
  63. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/migration/_protocol.py +0 -0
  64. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/migration/_standard.py +0 -0
  65. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/migration/_types.py +0 -0
  66. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/py.typed +0 -0
  67. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/testing/__init__.py +0 -0
  68. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/testing/creator.py +0 -0
  69. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/testing/loader.py +0 -0
  70. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/testing/schema.py +0 -0
  71. {atquery-2.14.2 → atquery-2.17.0}/src/atquery/testing/validator.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: atquery
3
- Version: 2.14.2
3
+ Version: 2.17.0
4
4
  Summary: A Python module for simplifying DBAPI usage with one-query-per-file SQL management.
5
5
  Keywords: sql,database,dbapi,mysql,sqlite,duckdb
6
6
  Author: alpine
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "atquery"
7
- version = "2.14.2"
7
+ version = "2.17.0"
8
8
  description = "A Python module for simplifying DBAPI usage with one-query-per-file SQL management."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -98,6 +98,8 @@ exclude = [
98
98
  "**/__pycache__",
99
99
  "**/.*",
100
100
  ".venv",
101
+ "var",
102
+ "work",
101
103
  ]
102
104
  venvPath = "."
103
105
  venv = ".venv"
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "atquery"
7
- version = "2.14.2"
7
+ version = "2.17.0"
8
8
  description = "A Python module for simplifying DBAPI usage with one-query-per-file SQL management."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -113,7 +113,7 @@ select = [
113
113
  [tool.pyright]
114
114
  # https://microsoft.github.io/pyright/#/configuration
115
115
  include = ["src"]
116
- exclude = ["tests", "**/node_modules", "**/__pycache__", "**/.*", ".venv"]
116
+ exclude = ["tests", "**/node_modules", "**/__pycache__", "**/.*", ".venv", "var", "work"]
117
117
  venvPath = "."
118
118
  venv = ".venv"
119
119
  typeCheckingMode = "basic"
@@ -10,7 +10,6 @@ from .api_v2 import (
10
10
  ATString,
11
11
  ATWarning,
12
12
  Resource,
13
- create_async_datasource,
14
13
  create_datasource,
15
14
  escape4like,
16
15
  execute,
@@ -18,6 +17,7 @@ from .api_v2 import (
18
17
  export_csv,
19
18
  insert_csv,
20
19
  load,
20
+ replace_csv,
21
21
  sql,
22
22
  upsert_csv,
23
23
  )
@@ -34,7 +34,6 @@ __all__ = [
34
34
  "ATString",
35
35
  "ATWarning",
36
36
  "Resource",
37
- "create_async_datasource",
38
37
  "create_datasource",
39
38
  "escape4like",
40
39
  "execute",
@@ -42,6 +41,7 @@ __all__ = [
42
41
  "insert_csv",
43
42
  "load",
44
43
  "sql",
44
+ "replace_csv",
45
45
  "upsert_csv",
46
46
  "export_csv",
47
47
  ]
@@ -0,0 +1,31 @@
1
+ from .api import (
2
+ NULL,
3
+ ATAsyncConnection,
4
+ ATAsyncConnectionPool,
5
+ ATAsyncDataSource,
6
+ ATAsyncQuery,
7
+ ATAsyncResult,
8
+ ATAsyncTypedQueryProxy,
9
+ Resource,
10
+ create_datasource,
11
+ execute,
12
+ execute_script,
13
+ load,
14
+ sql,
15
+ )
16
+
17
+ __all__ = [
18
+ "NULL",
19
+ "ATAsyncConnection",
20
+ "ATAsyncConnectionPool",
21
+ "ATAsyncDataSource",
22
+ "ATAsyncResult",
23
+ "ATAsyncQuery",
24
+ "ATAsyncTypedQueryProxy",
25
+ "Resource",
26
+ "create_datasource",
27
+ "execute",
28
+ "execute_script",
29
+ "load",
30
+ "sql",
31
+ ]
@@ -0,0 +1,191 @@
1
+ """atquery.aio - async 専用 DataSource / Query の公開 API
2
+
3
+ Usage:
4
+ import atquery.aio
5
+
6
+ async_ds = atquery.aio.create_datasource("mysql://user:pass@host/db")
7
+ async_ds = atquery.aio.create_datasource("mysql://user:pass@host/db", pool_size=10)
8
+
9
+ async with async_ds.connect() as conn:
10
+ aat = atquery.aio.Resource(__file__)
11
+ users = await aat("SELECT__users.sql").getall(conn, {"status": "active"})
12
+ """
13
+ from importlib import import_module
14
+ from textwrap import dedent
15
+
16
+ from atquery.aio.engine import (
17
+ ATAsyncConnection,
18
+ ATAsyncConnectionPool,
19
+ ATAsyncDataSource,
20
+ ATAsyncResult,
21
+ )
22
+ from atquery.aio.query import ATAsyncQuery, ATAsyncTypedQueryProxy
23
+ from atquery.atquery2 import ATQuery
24
+ from atquery.dialect import _parse_uri
25
+ from atquery.factory import Resource as _SyncResource
26
+ from atquery.type import NULL
27
+
28
+ __all__ = [
29
+ "NULL",
30
+ "ATAsyncConnection",
31
+ "ATAsyncConnectionPool",
32
+ "ATAsyncDataSource",
33
+ "ATAsyncResult",
34
+ "ATAsyncQuery",
35
+ "ATAsyncTypedQueryProxy",
36
+ "Resource",
37
+ "create_datasource",
38
+ "execute",
39
+ "execute_script",
40
+ "load",
41
+ "sql",
42
+ ]
43
+
44
+ ASYNC_DATASOURCE_TYPES = {
45
+ "mysql": ("atquery.dialect.mysql.aio", "ATMySQLAsyncDataSource"),
46
+ "mysql+mysqlconnector": ("atquery.dialect.mysql.aio", "ATMySQLAsyncDataSource"),
47
+ "mysql+mysqlconnector#poolable": ("atquery.dialect.mysql.aio", "ATMySQLAsyncPoolableDataSource"),
48
+ "mysql#poolable": ("atquery.dialect.mysql.aio", "ATMySQLAsyncPoolableDataSource"),
49
+ }
50
+
51
+
52
+ def _lookup_async_datasource_class(scheme: str) -> type[ATAsyncDataSource]:
53
+ info = ASYNC_DATASOURCE_TYPES.get(scheme, None)
54
+ if info is None:
55
+ raise ValueError(f'scheme "{scheme}" is not found.')
56
+ return getattr(import_module(info[0]), info[1])
57
+
58
+
59
+ def create_datasource(
60
+ uri: str,
61
+ pool_size: int | None = None,
62
+ max_connections: int | None = None,
63
+ max_idle_connections: int | None = None,
64
+ acquire_timeout: float | None = None,
65
+ ) -> ATAsyncDataSource:
66
+ """async 専用 DataSource を生成する。
67
+
68
+ Args:
69
+ uri: 接続URI。例: "mysql://user:pass@host/db"
70
+ pool_size: コネクションプールサイズ。未指定の場合はプールなし。
71
+ max_connections: プール内の最大コネクション数。
72
+ max_idle_connections: プール内の最大アイドルコネクション数。
73
+ acquire_timeout: コネクション取得のタイムアウト秒数。
74
+
75
+ Returns:
76
+ ATAsyncDataSource: async専用DataSource
77
+ """
78
+ username, password, sr, scheme, params = _parse_uri(uri, pool_size, max_connections, max_idle_connections, acquire_timeout)
79
+ cls = _lookup_async_datasource_class(scheme)
80
+ return cls(
81
+ user=username,
82
+ password=password,
83
+ host=sr.hostname,
84
+ port=sr.port,
85
+ database=sr.path[1:],
86
+ **params,
87
+ )
88
+
89
+
90
+ def load(py: str, filepath: str, use_cache: bool = True) -> ATAsyncQuery:
91
+ """SQLファイルを読み込んで ATAsyncQuery のインスタンスを生成する。
92
+
93
+ Args:
94
+ py: ファイル検索の起点モジュール(通常は __file__)
95
+ filepath: SQLファイルの相対パス
96
+ use_cache: キャッシュを使用するか
97
+
98
+ Returns:
99
+ ATAsyncQuery: インスタンス
100
+ """
101
+ q = _SyncResource.load(py, filepath, use_cache=use_cache)
102
+ return ATAsyncQuery._from_atquery(q)
103
+
104
+
105
+ def sql(sql_text: str) -> ATAsyncQuery:
106
+ """SQL文字列から ATAsyncQuery のインスタンスを生成する。
107
+
108
+ SQL文字列は自動的にdedent・stripされる。
109
+
110
+ Args:
111
+ sql_text: SQL文(ATQuery書式を使用できます)
112
+
113
+ Returns:
114
+ ATAsyncQuery: インスタンス
115
+ """
116
+ return ATAsyncQuery._from_atquery(ATQuery(dedent(sql_text).strip()))
117
+
118
+
119
+ async def execute(conn: ATAsyncConnection, sql: str, params: dict | None = None) -> ATAsyncResult:
120
+ """SQLを実行する。ATQuery書式(コードブロック等)が使用できる。
121
+
122
+ SQLは自動的にdedent・stripされる。
123
+
124
+ Args:
125
+ conn: コネクション
126
+ sql: SQL文(ATQuery書式を使用できます)
127
+ params: パラメータ
128
+
129
+ Returns:
130
+ ATAsyncResult: 結果セット
131
+ """
132
+ return await ATAsyncQuery._from_atquery(ATQuery(dedent(sql).strip())).execute(conn, params)
133
+
134
+
135
+ async def execute_script(conn: ATAsyncConnection, script: str, params: dict | None = None) -> None:
136
+ """SQLスクリプトを実行する。ATQuery書式(コードブロック等)が使用できる。
137
+
138
+ SQLは自動的にdedent・stripされる。
139
+
140
+ Args:
141
+ conn: 書き込み可能なコネクション
142
+ script: SQLスクリプト(セミコロン区切り) ATQuery書式を使用できます。
143
+ params: パラメータ
144
+ """
145
+ await ATAsyncQuery._from_atquery(ATQuery(dedent(script).strip())).execute_script(conn, params)
146
+
147
+
148
+ class Resource(_SyncResource):
149
+ """__file__ をアンカーとした非同期リソース読み込みヘルパー。
150
+
151
+ `atquery.factory.Resource`(sync)のサブクラス。依存は一方通行(aio → core)。
152
+ `path`/`text`/`json` は親クラスから継承(ローカルファイルI/Oのため非同期化しない)。
153
+
154
+ Example:
155
+ ```python
156
+ import atquery.aio
157
+
158
+ aat = atquery.aio.Resource(__file__)
159
+ users = await aat("sql/SELECT__users.sql").getall(conn, params)
160
+
161
+ config = aat.json("config/settings.json")
162
+ ```
163
+ """
164
+
165
+ @classmethod
166
+ def load(cls, py: str, filepath: str, use_cache: bool = True) -> ATAsyncQuery:
167
+ """SQLファイルを読み込んでATAsyncQueryのインスタンスを生成します。
168
+
169
+ Args:
170
+ py (str): ファイル検索の起点モジュール
171
+ filepath (str): ファイルパス
172
+ use_cache (bool, optional): キャッシュを使用するか. Defaults to True.
173
+
174
+ Returns:
175
+ ATAsyncQuery: インスタンス
176
+ """
177
+ return load(py, filepath, use_cache=use_cache)
178
+
179
+ def __call__(self, filepath: str, use_cache: bool = not __debug__) -> ATAsyncQuery:
180
+ """SQLファイルを指定してATAsyncQueryインスタンスを取得します。
181
+ Args:
182
+ filepath (str): SQLファイルの相対パス
183
+ """
184
+ return self.query(filepath, use_cache=use_cache)
185
+
186
+ def query(self, filepath: str, use_cache: bool = not __debug__) -> ATAsyncQuery:
187
+ """SQLファイルを指定してATAsyncQueryインスタンスを取得します。
188
+ Args:
189
+ filepath (str): SQLファイルの相対パス
190
+ """
191
+ return self.__class__.load(self.py, filepath, use_cache=use_cache)
@@ -4,7 +4,7 @@ from textwrap import dedent
4
4
  from typing import Union
5
5
 
6
6
  from .atquery2 import ATQuery
7
- from .dialect import create_async_datasource, create_datasource
7
+ from .dialect import create_datasource
8
8
  from .engine import (
9
9
  ATConnection,
10
10
  ATDataSource,
@@ -28,7 +28,6 @@ __all__ = [
28
28
  "ATSQLError",
29
29
  "ATString",
30
30
  "ATWarning",
31
- "create_async_datasource",
32
31
  "create_datasource",
33
32
  "escape4like",
34
33
  "execute",
@@ -36,6 +35,7 @@ __all__ = [
36
35
  "export_csv",
37
36
  "insert_csv",
38
37
  "load",
38
+ "replace_csv",
39
39
  "Resource",
40
40
  "sql",
41
41
  "upsert_csv",
@@ -136,7 +136,40 @@ def insert_csv(conn: ATConnection, table: str, file: Union[str, Path]) -> int:
136
136
 
137
137
 
138
138
  def upsert_csv(conn: ATConnection, table: str, file: Union[str, Path]) -> int:
139
- """CSVファイルをテーブルにUPSERTします。
139
+ """CSVファイルの内容でテーブルの行をUPSERTします(列保持、キー衝突時は指定列のみ更新)。
140
+
141
+ テーブルのPRIMARY KEY(MySQLはUNIQUE制約も可)に基づいてキー衝突を判定し、
142
+ CSVヘッダーに含まれる列だけをSETします。CSVに含まれない列の既存値は変更されません
143
+ (行全体を置き換える `replace_csv()` とは異なります)。
144
+
145
+ Args:
146
+ conn (ATConnection): コネクション
147
+ table (str): テーブル名
148
+ file (Union[str, Path]): CSVファイルのパス
149
+
150
+ Raises:
151
+ ValueError: テーブルにPRIMARY KEY(またはUNIQUE制約)が無い場合
152
+ NotImplementedError: 接続中のDBに対しては機能が実装されていません
153
+
154
+ Returns:
155
+ int: 更新・挿入した行数
156
+ """
157
+ if conn.dialect == "mysql":
158
+ from .dialect import mysql
159
+ return mysql.upsert_data_csv(conn, table, str(file))
160
+ elif conn.dialect == "sqlite":
161
+ from .dialect import sqlite
162
+ return sqlite.upsert_csv(conn, table, str(file))
163
+ raise NotImplementedError(f"upsert_csv is not supported for dialect '{conn.dialect}'. Supported dialects: mysql, sqlite")
164
+
165
+
166
+ def replace_csv(conn: ATConnection, table: str, file: Union[str, Path]) -> int:
167
+ """CSVファイルの内容でテーブルの行を REPLACE します。
168
+
169
+ キーが衝突した行は一旦DELETEしてから改めてINSERTされるため、CSVに含まれていない
170
+ 列はテーブルのDEFAULT値(またはNULL)にリセットされます。一部の列だけを更新したい
171
+ 場合はこの関数を使わず、列を保持する `upsert_csv()` を使ってください
172
+ (atquery-manual.md 8.2節・8.3節参照)。
140
173
 
141
174
  Args:
142
175
  conn (ATConnection): コネクション
@@ -155,7 +188,7 @@ def upsert_csv(conn: ATConnection, table: str, file: Union[str, Path]) -> int:
155
188
  elif conn.dialect == "sqlite":
156
189
  from .dialect import sqlite
157
190
  return sqlite.import_csv(conn, table, str(file), ifconflict="REPLACE")
158
- raise NotImplementedError(f"upsert_csv is not supported for dialect '{conn.dialect}'. Supported dialects: mysql, sqlite")
191
+ raise NotImplementedError(f"replace_csv is not supported for dialect '{conn.dialect}'. Supported dialects: mysql, sqlite")
159
192
 
160
193
 
161
194
  def export_csv(conn: ATConnection, table: str, file: Union[str, Path]) -> int:
@@ -0,0 +1,113 @@
1
+ """atquery csv サブコマンド - CSVファイルのインポート・エクスポート"""
2
+ import argparse
3
+ import sys
4
+
5
+ from atquery.cli.main import (
6
+ EXIT_ERROR,
7
+ EXIT_SUCCESS,
8
+ format_error_for_cli,
9
+ resolve_datasource_uri,
10
+ )
11
+ from atquery.dialect import create_datasource
12
+
13
+
14
+ def _add_common_args(parser: argparse.ArgumentParser) -> None:
15
+ """insert/upsert/export共通のオプションを追加する
16
+
17
+ default=argparse.SUPPRESS: ルートパーサの -d/-s (例: `atquery -d ... csv insert`) が
18
+ このサブパーサの未指定引数で上書き(Noneでリセット)されるのを防ぐ。
19
+ """
20
+ parser.add_argument(
21
+ "-d",
22
+ "--datasource",
23
+ required=False,
24
+ default=argparse.SUPPRESS,
25
+ help="Database connection string (or set ATQUERY_DATASOURCE env var)",
26
+ )
27
+ parser.add_argument(
28
+ "-s",
29
+ "--schema",
30
+ required=False,
31
+ default=argparse.SUPPRESS,
32
+ help="Override the schema/database segment of the resolved connection URI",
33
+ )
34
+ parser.add_argument("-t", "--table", required=True, help="Target table name")
35
+ parser.add_argument("-f", "--file", required=True, help="CSV file path")
36
+
37
+
38
+ def setup_parser(parser: argparse.ArgumentParser) -> None:
39
+ """csv サブコマンドのパーサーを設定する。"""
40
+ parser.formatter_class = argparse.RawDescriptionHelpFormatter
41
+ parser.epilog = """
42
+ Supported dialects: mysql, sqlite
43
+
44
+ Examples:
45
+ # Insert rows from a CSV file (rows with an existing PK are skipped)
46
+ atquery csv insert -t users -f users.csv -d sqlite:///data.db
47
+
48
+ # Replace rows from a CSV file (rows with an existing PK are overwritten; columns missing from the CSV are reset to DEFAULT/NULL)
49
+ atquery csv replace -t users -f users.csv -d mysql://root@localhost/mydb
50
+
51
+ # Upsert rows from a CSV file, preserving columns missing from the CSV (key = table's PRIMARY KEY/UNIQUE)
52
+ atquery csv upsert -t users -f users.csv -d mysql://root@localhost/mydb
53
+
54
+ # Export a table to a CSV file
55
+ atquery csv export -t users -f users.csv -d sqlite:///data.db
56
+ """
57
+
58
+ sub = parser.add_subparsers(dest="csv_command", help="csv commands")
59
+
60
+ insert_parser = sub.add_parser("insert", help="Insert CSV rows into a table (skip rows with an existing PK)")
61
+ _add_common_args(insert_parser)
62
+
63
+ replace_parser = sub.add_parser("replace", help="Replace CSV rows into a table (rows with an existing PK are deleted then re-inserted; columns missing from the CSV are reset to DEFAULT/NULL)")
64
+ _add_common_args(replace_parser)
65
+
66
+ upsert_parser = sub.add_parser("upsert", help="Upsert CSV rows into a table (only columns present in the CSV are set; other columns are preserved)")
67
+ _add_common_args(upsert_parser)
68
+
69
+ export_parser = sub.add_parser("export", help="Export a table to a CSV file")
70
+ _add_common_args(export_parser)
71
+
72
+
73
+ def execute_csv(args: argparse.Namespace) -> int:
74
+ """csv サブコマンドをディスパッチする。"""
75
+ if not args.csv_command:
76
+ print("Usage: atquery csv <insert|replace|upsert|export> -t TABLE -f FILE ...", file=sys.stderr)
77
+ print(" atquery csv --help", file=sys.stderr)
78
+ return EXIT_ERROR
79
+
80
+ database_uri = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
81
+ if not database_uri:
82
+ print(
83
+ "Error: the following arguments are required: -d/--datasource or ATQUERY_DATASOURCE environment variable",
84
+ file=sys.stderr,
85
+ )
86
+ return EXIT_ERROR
87
+
88
+ import atquery
89
+
90
+ try:
91
+ datasource = create_datasource(database_uri)
92
+
93
+ if args.csv_command == "export":
94
+ with datasource.connect() as conn:
95
+ count = atquery.export_csv(conn, args.table, args.file)
96
+ print(f"Exported {count} row(s) from '{args.table}' to {args.file}", file=sys.stderr)
97
+ return EXIT_SUCCESS
98
+
99
+ funcs = {"insert": atquery.insert_csv, "replace": atquery.replace_csv, "upsert": atquery.upsert_csv}
100
+ verbs = {"insert": "Inserted", "replace": "Replaced", "upsert": "Upserted"}
101
+ func = funcs[args.csv_command]
102
+ verb = verbs[args.csv_command]
103
+ with datasource.begin() as conn:
104
+ count = func(conn, args.table, args.file)
105
+ print(f"{verb} {count} row(s) from {args.file} into '{args.table}'", file=sys.stderr)
106
+ return EXIT_SUCCESS
107
+
108
+ except FileNotFoundError as e:
109
+ print(f"Error: {format_error_for_cli(e)}", file=sys.stderr)
110
+ return EXIT_ERROR
111
+ except Exception as e:
112
+ print(f"Error: {format_error_for_cli(e)}", file=sys.stderr)
113
+ return EXIT_ERROR
@@ -309,7 +309,10 @@ class OutputWriter:
309
309
  if output_format in ("csv", "tsv"):
310
310
  delimiter = "\t" if output_format == "tsv" else ","
311
311
  self.csv_output = StringIO()
312
- self.csv_writer = csv.writer(self.csv_output, delimiter=delimiter)
312
+ # lineterminatorは"\n"に固定する。標準出力はテキストモードで開かれており、
313
+ # print()時に"\n"はos.linesep(Windowsでは"\r\n")へ自動変換される。
314
+ # ここでデフォルトの"\r\n"のまま渡すと、Windows環境で"\r\r\n"に二重変換されてしまう。
315
+ self.csv_writer = csv.writer(self.csv_output, delimiter=delimiter, lineterminator="\n")
313
316
 
314
317
  def _parse_json_columns(self, row_dict: dict) -> dict:
315
318
  """JSON文字列カラムをパースする"""
@@ -605,9 +608,18 @@ Examples:
605
608
  atquery -f query.sql --ndjson
606
609
  atquery -f query.sql --format json --with-types
607
610
 
611
+ # Force LF line endings for CSV output on Windows
612
+ atquery -f query.sql --eol lf > out.csv
613
+
608
614
  # Retrieve database structure
609
615
  atquery columns -d sqlite:///data.db
610
616
  atquery routines -d mysql://root:@localhost/mydb
617
+
618
+ # Import/export CSV files
619
+ atquery csv insert -t users -f users.csv -d sqlite:///data.db
620
+ atquery csv replace -t users -f users.csv -d mysql://root:@localhost/mydb
621
+ atquery csv upsert -t users -f users.csv -d mysql://root:@localhost/mydb
622
+ atquery csv export -t users -f users.csv -d sqlite:///data.db
611
623
  """,
612
624
  )
613
625
 
@@ -659,6 +671,15 @@ Examples:
659
671
  )
660
672
  setup_schemas_parser(schemas_parser)
661
673
 
674
+ # csv サブコマンドの追加
675
+ from atquery.cli.csv import setup_parser as setup_csv_parser
676
+ csv_parser = subparsers.add_parser(
677
+ "csv",
678
+ help="Import/export CSV files (insert/upsert/export)",
679
+ description="Import/export CSV files (insert/upsert/export)",
680
+ )
681
+ setup_csv_parser(csv_parser)
682
+
662
683
  # scenario サブコマンドの追加
663
684
  from atquery.cli.scenario import setup_parser as setup_scenario_parser
664
685
  scenario_parser = subparsers.add_parser(
@@ -735,6 +756,15 @@ Examples:
735
756
 
736
757
  add_output_format_arguments(parser)
737
758
 
759
+ parser.add_argument(
760
+ "--eol",
761
+ choices=["auto", "lf", "crlf"],
762
+ default="auto",
763
+ help="Line ending for stdout output (csv/tsv/plain text): "
764
+ "auto=OS native (default; CRLF on Windows, LF elsewhere), "
765
+ "lf=force LF even on Windows, crlf=force CRLF even on non-Windows",
766
+ )
767
+
738
768
  parser.add_argument("--limit", type=int, help="Limit number of results")
739
769
 
740
770
  parser.add_argument(
@@ -772,6 +802,13 @@ Examples:
772
802
 
773
803
  args = parser.parse_args()
774
804
 
805
+ # --eol で明示指定された場合のみ改行変換を上書きする。
806
+ # "auto"(デフォルト)は最初のreconfigure(encoding="utf-8")で設定済みのOSネイティブ変換のまま。
807
+ if args.eol == "lf":
808
+ cast(io.TextIOWrapper, sys.stdout).reconfigure(newline="\n")
809
+ elif args.eol == "crlf":
810
+ cast(io.TextIOWrapper, sys.stdout).reconfigure(newline="\r\n")
811
+
775
812
  # 引数なし(かつ標準入力がパイプでない)場合はヘルプを表示
776
813
  if len(sys.argv) == 1 and sys.stdin.isatty():
777
814
  parser.print_help()
@@ -798,6 +835,10 @@ Examples:
798
835
  from atquery.cli.schemas import execute_schemas
799
836
  return execute_schemas(args)
800
837
 
838
+ if args.subcommand == "csv":
839
+ from atquery.cli.csv import execute_csv
840
+ return execute_csv(args)
841
+
801
842
  if args.subcommand == "scenario":
802
843
  from atquery.cli.scenario import execute_scenario
803
844
  return execute_scenario(args)
@@ -3,7 +3,6 @@ from importlib import import_module
3
3
  from typing import Any
4
4
  from urllib.parse import parse_qsl, urlparse
5
5
 
6
- from atquery.aio.engine import ATAsyncDataSource
7
6
  from atquery.engine import ATDataSource
8
7
 
9
8
  DATASOURCE_TYPES = {
@@ -14,12 +13,6 @@ DATASOURCE_TYPES = {
14
13
  "duckdb": ("atquery.dialect.duckdb", "ATDuckDBDataSource"),
15
14
  }
16
15
 
17
- ASYNC_DATASOURCE_TYPES = {
18
- "mysql": ("atquery.dialect.mysql.aio", "ATMySQLAsyncDataSource"),
19
- "mysql+mysqlconnector": ("atquery.dialect.mysql.aio", "ATMySQLAsyncDataSource"),
20
- "mysql+mysqlconnector#poolable": ("atquery.dialect.mysql.aio", "ATMySQLAsyncPoolableDataSource"),
21
- }
22
-
23
16
 
24
17
  def _lookup_datasource_class(scheme: str) -> type[ATDataSource]:
25
18
  info = DATASOURCE_TYPES.get(scheme, None)
@@ -28,13 +21,6 @@ def _lookup_datasource_class(scheme: str) -> type[ATDataSource]:
28
21
  return getattr(import_module(info[0]), info[1])
29
22
 
30
23
 
31
- def _lookup_async_datasource_class(scheme: str) -> type[ATAsyncDataSource]:
32
- info = ASYNC_DATASOURCE_TYPES.get(scheme, None)
33
- if info is None:
34
- raise ValueError(f'scheme "{scheme}" is not found.')
35
- return getattr(import_module(info[0]), info[1])
36
-
37
-
38
24
  USER = re.compile(r"^.+:\/\/([^:]+:[^@]+@)")
39
25
 
40
26
 
@@ -88,20 +74,4 @@ def create_datasource(
88
74
  )
89
75
 
90
76
 
91
- def create_async_datasource(
92
- uri: str,
93
- pool_size: int | None = None,
94
- max_connections: int | None = None,
95
- max_idle_connections: int | None = None,
96
- acquire_timeout: float | None = None,
97
- ) -> ATAsyncDataSource:
98
- username, password, sr, scheme, params = _parse_uri(uri, pool_size, max_connections, max_idle_connections, acquire_timeout)
99
- cls = _lookup_async_datasource_class(scheme)
100
- return cls(
101
- user=username,
102
- password=password,
103
- host=sr.hostname,
104
- port=sr.port,
105
- database=sr.path[1:],
106
- **params
107
- )
77
+
@@ -27,6 +27,7 @@ from atquery.dialect.mysql.core import (
27
27
  load_data_csv,
28
28
  named2pyformat,
29
29
  normalize_delimiters,
30
+ upsert_data_csv,
30
31
  )
31
32
 
32
33
  # Lazy imports for pooling (rarely used in production)
@@ -53,6 +54,7 @@ __all__ = [
53
54
  "load_data_csv",
54
55
  "named2pyformat",
55
56
  "normalize_delimiters",
57
+ "upsert_data_csv",
56
58
  ]
57
59
 
58
60
 
@@ -368,6 +368,73 @@ def load_data_csv(conn: ATConnection, table: str, file: str, ifconflict: str = "
368
368
  return conn.execute(sql, {"file": file}).rowcount
369
369
 
370
370
 
371
+ def _split_qualified_table(conn: ATConnection, table: str) -> tuple[str, str]:
372
+ """"schema.table" 形式から (schema, table) を取り出す。schema省略時は接続先DBを使う。"""
373
+ parts = table.split(".", 1)
374
+ if len(parts) == 2:
375
+ return parts[0].strip("`"), parts[1].strip("`")
376
+ return conn.connection.database, table.strip("`") # type: ignore[attr-defined]
377
+
378
+
379
+ def _mysql_conflict_key_columns(conn: ATConnection, schema: str, table: str, display_name: str) -> list[str]:
380
+ """UPSERTの衝突キーとなる列名を取得する。PRIMARY KEYを優先し、無ければ最初のUNIQUE制約を使う。"""
381
+ rows = conn.meta.columns(schema=schema, table=table).fetchall()
382
+ pk_columns = [r.column_name for r in rows if r.column_key == "PRI"]
383
+ if pk_columns:
384
+ return pk_columns
385
+ unique_columns = [r.column_name for r in rows if r.column_key == "UNI"]
386
+ if unique_columns:
387
+ return unique_columns
388
+ raise ValueError(
389
+ f"upsert_csv requires a table with a PRIMARY KEY or UNIQUE constraint: '{display_name}' has none"
390
+ )
391
+
392
+
393
+ def upsert_data_csv(conn: ATConnection, table: str, file: str) -> int:
394
+ """CSVファイルの内容でテーブルの行をUPSERTします(列保持、キー衝突時は指定列のみ更新)。
395
+
396
+ LOAD DATA は ON DUPLICATE KEY UPDATE をサポートしないため、一旦一時テーブルへ
397
+ LOAD DATA LOCAL INFILE した上で `INSERT ... SELECT ... ON DUPLICATE KEY UPDATE` で
398
+ 本テーブルへ反映する。CSVヘッダーに含まれない列の既存値は変更されない
399
+ (`replace_csv()` と異なりDEFAULT/NULLにリセットされない)。
400
+
401
+ Args:
402
+ conn (ATConnection): 書き込み可能なコネクション
403
+ table (str): 対象テーブル名(schema.table 形式可)
404
+ file (str): CSVファイルのパス
405
+
406
+ Raises:
407
+ ValueError: テーブルにPRIMARY KEY/UNIQUE制約が無い場合
408
+ NotImplementedError: 接続中のDBに対しては機能が実装されていません
409
+
410
+ Returns:
411
+ int: `INSERT ... ON DUPLICATE KEY UPDATE` のrowcount
412
+ (MySQLの仕様上、挿入行は1、更新行は2としてカウントされる)
413
+ """
414
+ schema, bare_table = _split_qualified_table(conn, table)
415
+ key_columns = _mysql_conflict_key_columns(conn, schema, bare_table, table)
416
+
417
+ with open(file, encoding="utf-8") as f:
418
+ headers = next(csv.reader(f))
419
+
420
+ update_columns = [h for h in headers if h not in key_columns] or headers
421
+ col_list = ", ".join(bquote(h) for h in headers)
422
+ set_clause = ", ".join(f"{bquote(c)} = VALUES({bquote(c)})" for c in update_columns)
423
+ target = bquote_identifier(table)
424
+ staging = bquote_identifier("_atquery_upsert_staging")
425
+
426
+ conn.execute(f"CREATE TEMPORARY TABLE {staging} LIKE {target}")
427
+ try:
428
+ load_data_csv(conn, "_atquery_upsert_staging", file, ifconflict="REPLACE")
429
+ return conn.execute(
430
+ f"INSERT INTO {target} ({col_list})"
431
+ f" SELECT {col_list} FROM {staging}"
432
+ f" ON DUPLICATE KEY UPDATE {set_clause}"
433
+ ).rowcount
434
+ finally:
435
+ conn.execute(f"DROP TEMPORARY TABLE IF EXISTS {staging}")
436
+
437
+
371
438
  def export_csv(conn: ATConnection, table: str, file: str) -> int:
372
439
  """テーブルの内容をCSVファイルにエクスポートします。
373
440
 
@@ -367,6 +367,68 @@ def import_csv(conn: ATConnection, table: str, file: Union[str, Path], ifconflic
367
367
  return rowcount
368
368
 
369
369
 
370
+ def _sqlite_primary_key_columns(conn: ATConnection, table: str) -> list[str]:
371
+ """テーブルのPRIMARY KEY列名を宣言順に取得する。"""
372
+ rows = conn.execute(f"PRAGMA table_info({dquote_identifier(table)})").fetchall()
373
+ pk_rows = sorted((r for r in rows if r["pk"] > 0), key=lambda r: r["pk"])
374
+ return [r["name"] for r in pk_rows]
375
+
376
+
377
+ def upsert_csv(conn: ATConnection, table: str, file: Union[str, Path]) -> int:
378
+ """CSVファイルの内容でテーブルの行をUPSERTします(列保持、キー衝突時は指定列のみ更新)。
379
+
380
+ `INSERT ... SELECT ... ON CONFLICT(pk) DO UPDATE` を使用する。CSVヘッダーに含まれない
381
+ 列の既存値は変更されない(`import_csv(ifconflict="REPLACE")` と異なりDEFAULT/NULLに
382
+ リセットされない)。重複判定はテーブルのPRIMARY KEYに従う(SQLiteのUNIQUE制約は
383
+ 本実装では衝突キーとして使用しない)。
384
+
385
+ Args:
386
+ conn (ATConnection): 書き込み可能なコネクション
387
+ table (str): 対象テーブル名
388
+ file (Union[str, Path]): CSVファイルのパス
389
+
390
+ Raises:
391
+ ValueError: テーブルにPRIMARY KEYが無い場合
392
+
393
+ Returns:
394
+ int: 挿入・更新された行数
395
+ """
396
+ pk_columns = _sqlite_primary_key_columns(conn, table)
397
+ if not pk_columns:
398
+ raise ValueError(f"upsert_csv requires a table with a PRIMARY KEY: '{table}' has none")
399
+
400
+ with open(file, "r", encoding="utf-8") as f:
401
+ reader = csv.reader(f)
402
+ headers = next(reader)
403
+
404
+ table_id = dquote_identifier(table)
405
+ col_list = ", ".join(dquote_identifier(h) for h in headers)
406
+ placeholders = ", ".join(["?"] * len(headers))
407
+ staging = "_atquery_upsert_staging"
408
+ staging_id = dquote_identifier(staging)
409
+
410
+ conn.execute(f"CREATE TEMP TABLE {staging_id} AS SELECT {col_list} FROM {table_id} WHERE 0")
411
+ try:
412
+ cursor = conn.connection.cursor()
413
+ insert_sql = f"INSERT INTO {staging_id} ({col_list}) VALUES ({placeholders})"
414
+ cursor.executemany(insert_sql, reader)
415
+
416
+ update_columns = [h for h in headers if h not in pk_columns] or headers
417
+ conflict_cols = ", ".join(dquote_identifier(c) for c in pk_columns)
418
+ set_clause = ", ".join(f"{dquote_identifier(c)} = excluded.{dquote_identifier(c)}" for c in update_columns)
419
+
420
+ result = conn.execute(
421
+ f"INSERT INTO {table_id} ({col_list})"
422
+ # "WHERE 1 = 1" は省略不可: SQLiteのパーサーはSELECT直後のON句をJOINのONと
423
+ # 誤認しうるため、SELECT文を明示的に終端させてUPSERT句のONと区別する。
424
+ f" SELECT {col_list} FROM {staging_id} WHERE 1 = 1"
425
+ f" ON CONFLICT({conflict_cols}) DO UPDATE SET {set_clause}"
426
+ )
427
+ return result.rowcount
428
+ finally:
429
+ conn.execute(f"DROP TABLE IF EXISTS {staging_id}")
430
+
431
+
370
432
  def export_csv(conn: ATConnection, table: str, file: str) -> int:
371
433
  """テーブルの内容をCSVファイルにエクスポートします。
372
434
 
@@ -2,31 +2,15 @@ import copy
2
2
  import json
3
3
  from functools import lru_cache
4
4
  from pathlib import Path
5
- from typing import TYPE_CHECKING
6
5
 
7
6
  from .atquery2 import ATQuery
8
7
 
9
- if TYPE_CHECKING:
10
- from atquery.aio.query import ATAsyncQuery
11
-
12
8
 
13
9
  @lru_cache(maxsize=None)
14
10
  def _load_cached(sql_file: str) -> ATQuery:
15
11
  return ATQuery(Path(sql_file).read_text(encoding="UTF-8"))
16
12
 
17
13
 
18
- def _load_async_query(sql_file: str, use_cache: bool) -> "ATAsyncQuery":
19
- """ATAsyncQuery を生成する。use_cache=True の場合は ATQuery のキャッシュを再利用する。"""
20
- from atquery.aio.query import ATAsyncQuery
21
-
22
- if use_cache:
23
- q = copy.deepcopy(_load_cached(sql_file))
24
- else:
25
- q = ATQuery(Path(sql_file).read_text(encoding="UTF-8"))
26
- q._sql_file = sql_file
27
- return ATAsyncQuery._from_atquery(q)
28
-
29
-
30
14
  class Resource:
31
15
  """__file__ をアンカーとしたリソース読み込みヘルパー。
32
16
 
@@ -88,28 +72,6 @@ class Resource:
88
72
  """
89
73
  return self.__class__.load(self.py, filepath, use_cache=use_cache)
90
74
 
91
- @classmethod
92
- def aload(cls, py: str, filepath: str, use_cache: bool = True) -> "ATAsyncQuery":
93
- """SQLファイルを読み込んで ATAsyncQuery のインスタンスを生成します。
94
-
95
- Args:
96
- py (str): ファイル検索の起点モジュール
97
- filepath (str): ファイルパス
98
- use_cache (bool, optional): キャッシュを使用するか. Defaults to True.
99
-
100
- Returns:
101
- ATAsyncQuery: インスタンス
102
- """
103
- sql_file = str(Path(py).parent / filepath)
104
- return _load_async_query(sql_file, use_cache)
105
-
106
- def aquery(self, filepath: str, use_cache: bool = not __debug__) -> "ATAsyncQuery":
107
- """SQLファイルを指定して ATAsyncQuery インスタンスを取得します。
108
- Args:
109
- filepath (str): SQLファイルの相対パス
110
- """
111
- return self.__class__.aload(self.py, filepath, use_cache=use_cache)
112
-
113
75
  def path(self, filepath: str) -> Path:
114
76
  """ファイルのパスを取得します。
115
77
  Args:
@@ -79,7 +79,9 @@ def json_serializer(obj):
79
79
  ```
80
80
  """
81
81
  if isinstance(obj, datetime.datetime):
82
- return obj.isoformat(sep=" ", timespec="seconds") # MySQL compliant
82
+ if obj.tzinfo is not None:
83
+ return obj.isoformat() # tzinfoあり: 標準ISO8601(Tセパレータ+オフセット)
84
+ return obj.isoformat(sep=" ", timespec="seconds") # tzinfoなし: MySQL compliant
83
85
  elif isinstance(obj, (datetime.date, datetime.time)):
84
86
  return obj.isoformat()
85
87
  elif isinstance(obj, decimal.Decimal):
@@ -91,7 +93,7 @@ def json_serializer(obj):
91
93
  return str(obj)
92
94
 
93
95
 
94
- _TRANSLATION__ESCAPE_FOR_LIKE = str.maketrans({"%": r"\%", "_": r"\_"})
96
+ _TRANSLATION__ESCAPE_FOR_LIKE = str.maketrans({"\\": r"\\", "%": r"\%", "_": r"\_"})
95
97
  def escape4like(value: str) -> str | None:
96
98
  """LIKEの値として使用するためのエスケープ処理を行います。
97
99
 
@@ -1,101 +0,0 @@
1
- """atquery.aio - async 専用 DataSource / Query の公開 API
2
-
3
- Usage:
4
- import atquery.aio
5
-
6
- async_ds = atquery.aio.create_datasource("mysql://user:pass@host/db")
7
- async_ds = atquery.aio.create_datasource("mysql://user:pass@host/db", pool_size=10)
8
-
9
- async with async_ds.connect() as conn:
10
- users = await at.aquery("SELECT__users.sql").getall(conn, {"status": "active"})
11
- """
12
- import re
13
- from importlib import import_module
14
- from typing import Any
15
- from urllib.parse import parse_qsl, urlparse
16
-
17
- from atquery.aio.engine import (
18
- ATAsyncConnection,
19
- ATAsyncConnectionPool,
20
- ATAsyncDataSource,
21
- ATAsyncResult,
22
- )
23
- from atquery.aio.query import ATAsyncQuery, ATAsyncTypedQueryProxy
24
-
25
- _ASYNC_DATASOURCE_TYPES: dict[str, tuple[str, str]] = {
26
- "mysql": ("atquery.dialect.mysql.aio", "ATMySQLAsyncDataSource"),
27
- "mysql+mysqlconnector": ("atquery.dialect.mysql.aio", "ATMySQLAsyncDataSource"),
28
- "mysql+mysqlconnector#poolable": ("atquery.dialect.mysql.aio", "ATMySQLAsyncPoolableDataSource"),
29
- "mysql#poolable": ("atquery.dialect.mysql.aio", "ATMySQLAsyncPoolableDataSource"),
30
- }
31
-
32
- _USER = re.compile(r"^.+:\/\/([^:]+:[^@]+@)")
33
-
34
-
35
- def create_datasource(uri: str, pool_size: int = 0) -> ATAsyncDataSource:
36
- """async 専用 DataSource を生成する。
37
-
38
- Args:
39
- uri: 接続URI。例: "mysql://user:pass@host/db"
40
- pool_size: コネクションプールサイズ。0の場合はプールなし。
41
-
42
- Returns:
43
- ATAsyncDataSource: async専用DataSource
44
- """
45
- username = None
46
- password = None
47
- if match := _USER.match(uri):
48
- user = match.group(1)
49
- (username, password) = user.split(":", 1)
50
- password = password[:-1] # '@' を除く
51
- uri = uri.replace(user, "", 1)
52
-
53
- sr = urlparse(uri)
54
- scheme = sr.scheme
55
- params: dict[str, Any] = dict(parse_qsl(sr.query))
56
-
57
- if pool_size:
58
- scheme += "#poolable"
59
- params["pool_size"] = pool_size
60
-
61
- info = _ASYNC_DATASOURCE_TYPES.get(scheme)
62
- if info is None:
63
- raise ValueError(f'scheme "{scheme}" は async DataSource でサポートされていません。')
64
-
65
- cls = getattr(import_module(info[0]), info[1])
66
- return cls(
67
- user=username or sr.username,
68
- password=password or sr.password,
69
- host=sr.hostname,
70
- port=sr.port,
71
- database=sr.path[1:],
72
- **params,
73
- )
74
-
75
-
76
- def load(py: str, filepath: str, use_cache: bool = True) -> ATAsyncQuery:
77
- """SQLファイルを読み込んで ATAsyncQuery のインスタンスを生成する。
78
-
79
- Args:
80
- py: ファイル検索の起点モジュール(通常は __file__)
81
- filepath: SQLファイルの相対パス
82
- use_cache: キャッシュを使用するか
83
-
84
- Returns:
85
- ATAsyncQuery: インスタンス
86
- """
87
- from atquery.factory import Resource
88
-
89
- return Resource.aload(py, filepath, use_cache=use_cache)
90
-
91
-
92
- __all__ = [
93
- "ATAsyncConnection",
94
- "ATAsyncConnectionPool",
95
- "ATAsyncDataSource",
96
- "ATAsyncResult",
97
- "ATAsyncQuery",
98
- "ATAsyncTypedQueryProxy",
99
- "create_datasource",
100
- "load",
101
- ]
File without changes
File without changes
File without changes
File without changes