atquery 2.18.0__tar.gz → 2.20.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 (89) hide show
  1. {atquery-2.18.0 → atquery-2.20.0}/PKG-INFO +6 -6
  2. {atquery-2.18.0 → atquery-2.20.0}/pyproject.toml +4 -4
  3. {atquery-2.18.0 → atquery-2.20.0}/pyproject.toml.orig +4 -4
  4. atquery-2.20.0/src/atquery/cli/delta.py +253 -0
  5. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/main.py +23 -10
  6. atquery-2.20.0/src/atquery/cli/patch.py +135 -0
  7. atquery-2.20.0/src/atquery/delta/__init__.py +6 -0
  8. atquery-2.20.0/src/atquery/delta/_schema.py +70 -0
  9. {atquery-2.18.0/src/atquery/iceberg → atquery-2.20.0/src/atquery/delta}/cutoff.py +30 -43
  10. atquery-2.20.0/src/atquery/delta/exporter.py +331 -0
  11. atquery-2.20.0/src/atquery/patch/__init__.py +56 -0
  12. atquery-2.20.0/src/atquery/patch/_apply.py +317 -0
  13. atquery-2.20.0/src/atquery/patch/_convert.py +220 -0
  14. atquery-2.20.0/src/atquery/patch/_errors.py +52 -0
  15. atquery-2.20.0/src/atquery/patch/_log.py +182 -0
  16. atquery-2.20.0/src/atquery/patch/_meta.py +231 -0
  17. atquery-2.20.0/src/atquery/patch/_model.py +153 -0
  18. atquery-2.20.0/src/atquery/patch/_sql.py +135 -0
  19. atquery-2.18.0/src/atquery/cli/iceberg.py +0 -241
  20. atquery-2.18.0/src/atquery/iceberg/__init__.py +0 -6
  21. atquery-2.18.0/src/atquery/iceberg/_catalog.py +0 -478
  22. atquery-2.18.0/src/atquery/iceberg/_schema.py +0 -87
  23. atquery-2.18.0/src/atquery/iceberg/exporter.py +0 -252
  24. {atquery-2.18.0 → atquery-2.20.0}/LICENSE +0 -0
  25. {atquery-2.18.0 → atquery-2.20.0}/README.md +0 -0
  26. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/__init__.py +0 -0
  27. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/aio/__init__.py +0 -0
  28. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/aio/api.py +0 -0
  29. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/aio/engine.py +0 -0
  30. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/aio/query.py +0 -0
  31. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/api_v2.py +0 -0
  32. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/atquery2.py +0 -0
  33. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/__init__.py +0 -0
  34. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/columns.py +0 -0
  35. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/csv.py +0 -0
  36. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/ddl.py +0 -0
  37. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/diff.py +0 -0
  38. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/ecd.py +0 -0
  39. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/migrate.py +0 -0
  40. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/routines.py +0 -0
  41. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/scenario.py +0 -0
  42. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/schemas.py +0 -0
  43. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/cli/tables.py +0 -0
  44. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/__init__.py +0 -0
  45. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/duckdb.py +0 -0
  46. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/mysql/__init__.py +0 -0
  47. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/mysql/aio.py +0 -0
  48. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/mysql/core.py +0 -0
  49. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/mysql/dump/__init__.py +0 -0
  50. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/mysql/dump/__main__.py +0 -0
  51. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/mysql/dump/core.py +0 -0
  52. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/mysql/meta.py +0 -0
  53. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/mysql/pooling.py +0 -0
  54. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/mysql/restore/__init__.py +0 -0
  55. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/mysql/restore/__main__.py +0 -0
  56. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/mysql/restore/core.py +0 -0
  57. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/dialect/sqlite.py +0 -0
  58. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/diff/__init__.py +0 -0
  59. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/diff/comparator.py +0 -0
  60. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/diff/generator.py +0 -0
  61. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/diff/git_integration.py +0 -0
  62. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/diff/models.py +0 -0
  63. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/diff/parser.py +0 -0
  64. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/__init__.py +0 -0
  65. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/_toml.py +0 -0
  66. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/catalog.py +0 -0
  67. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/ddl.py +0 -0
  68. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/diff.py +0 -0
  69. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/erd.py +0 -0
  70. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/errors.py +0 -0
  71. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/model.py +0 -0
  72. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/parser.py +0 -0
  73. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/resolver.py +0 -0
  74. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/seed.py +0 -0
  75. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/ecd/skeleton.py +0 -0
  76. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/engine.py +0 -0
  77. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/factory.py +0 -0
  78. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/migration/__init__.py +0 -0
  79. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/migration/_migrator.py +0 -0
  80. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/migration/_protocol.py +0 -0
  81. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/migration/_standard.py +0 -0
  82. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/migration/_types.py +0 -0
  83. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/py.typed +0 -0
  84. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/testing/__init__.py +0 -0
  85. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/testing/creator.py +0 -0
  86. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/testing/loader.py +0 -0
  87. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/testing/schema.py +0 -0
  88. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/testing/validator.py +0 -0
  89. {atquery-2.18.0 → atquery-2.20.0}/src/atquery/type.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: atquery
3
- Version: 2.18.0
3
+ Version: 2.20.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
@@ -18,19 +18,19 @@ Classifier: Programming Language :: Python :: 3.14
18
18
  Classifier: Topic :: Database
19
19
  Requires-Dist: tomli>=2.0.1 ; python_full_version < '3.11'
20
20
  Requires-Dist: python-dotenv>=1.2.2 ; extra == 'all'
21
- Requires-Dist: atquery[mysql,duckdb,testing,diff,iceberg-export] ; extra == 'all'
21
+ Requires-Dist: atquery[mysql,duckdb,testing,diff,delta-export] ; extra == 'all'
22
+ Requires-Dist: mysql-connector-python>=8.0,<10 ; extra == 'delta-export'
23
+ Requires-Dist: deltalake>=1.6.6 ; extra == 'delta-export'
24
+ Requires-Dist: pyarrow>=15.0.0 ; extra == 'delta-export'
22
25
  Requires-Dist: sqlglot>=30.4.2 ; extra == 'diff'
23
26
  Requires-Dist: duckdb>=0.10.0 ; extra == 'duckdb'
24
- Requires-Dist: mysql-connector-python>=8.0,<10 ; extra == 'iceberg-export'
25
- Requires-Dist: pyiceberg>=0.12.0 ; extra == 'iceberg-export'
26
- Requires-Dist: pyarrow>=15.0.0 ; extra == 'iceberg-export'
27
27
  Requires-Dist: mysql-connector-python>=8.0,<10 ; extra == 'mysql'
28
28
  Requires-Dist: json5>=0.12.1 ; extra == 'testing'
29
29
  Requires-Python: >=3.10
30
30
  Provides-Extra: all
31
+ Provides-Extra: delta-export
31
32
  Provides-Extra: diff
32
33
  Provides-Extra: duckdb
33
- Provides-Extra: iceberg-export
34
34
  Provides-Extra: mysql
35
35
  Provides-Extra: testing
36
36
  Description-Content-Type: text/markdown
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "atquery"
7
- version = "2.18.0"
7
+ version = "2.20.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"
@@ -41,16 +41,16 @@ atquery = "atquery.cli.main:main"
41
41
  [project.optional-dependencies]
42
42
  mysql = ["mysql-connector-python>=8.0,<10"]
43
43
  duckdb = ["duckdb>=0.10.0"]
44
- iceberg-export = [
44
+ delta-export = [
45
45
  "mysql-connector-python>=8.0,<10",
46
- "pyiceberg>=0.12.0",
46
+ "deltalake>=1.6.6",
47
47
  "pyarrow>=15.0.0",
48
48
  ]
49
49
  testing = ["json5>=0.12.1"]
50
50
  diff = ["sqlglot>=30.4.2"]
51
51
  all = [
52
52
  "python-dotenv>=1.2.2",
53
- "atquery[mysql,duckdb,testing,diff,iceberg-export]",
53
+ "atquery[mysql,duckdb,testing,diff,delta-export]",
54
54
  ]
55
55
 
56
56
  [dependency-groups]
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "atquery"
7
- version = "2.18.0"
7
+ version = "2.20.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"
@@ -40,9 +40,9 @@ mysql = [
40
40
  duckdb = [
41
41
  "duckdb>=0.10.0",
42
42
  ]
43
- iceberg-export = [
43
+ delta-export = [
44
44
  "mysql-connector-python>=8.0,<10",
45
- "pyiceberg>=0.12.0",
45
+ "deltalake>=1.6.6",
46
46
  "pyarrow>=15.0.0",
47
47
  ]
48
48
  testing = [
@@ -53,7 +53,7 @@ diff = [
53
53
  ]
54
54
  all = [
55
55
  "python-dotenv>=1.2.2",
56
- "atquery[mysql,duckdb,testing,diff,iceberg-export]"
56
+ "atquery[mysql,duckdb,testing,diff,delta-export]"
57
57
  ]
58
58
 
59
59
  [dependency-groups]
@@ -0,0 +1,253 @@
1
+ """atquery delta サブコマンド - MySQLテーブルのDelta Lakeエクスポート(requires atquery[delta-export])"""
2
+ import argparse
3
+ import os
4
+ import re
5
+ import sys
6
+ from datetime import datetime, timedelta
7
+
8
+ from atquery.cli.main import (
9
+ EXIT_ERROR,
10
+ EXIT_SUCCESS,
11
+ format_error_for_cli,
12
+ resolve_datasource_uri,
13
+ )
14
+ from atquery.dialect import create_datasource
15
+
16
+ _IMPORT_ERROR_MESSAGE = "Error: delta サブコマンドには atquery[delta-export] が必要です: pip install 'atquery[delta-export]'"
17
+
18
+
19
+ def _add_common_args(parser: argparse.ArgumentParser) -> None:
20
+ """各リーフコマンド共通のオプションを追加する。各オプションは対応する環境変数を default として参照する。"""
21
+ parser.add_argument(
22
+ "-d",
23
+ "--datasource",
24
+ default=argparse.SUPPRESS,
25
+ help="MySQL connection string (env: ATQUERY_DATASOURCE)",
26
+ )
27
+ parser.add_argument(
28
+ "-s",
29
+ "--schema",
30
+ default=argparse.SUPPRESS,
31
+ help="Override the schema/database segment of the resolved connection URI (applies to this command only)",
32
+ )
33
+ parser.add_argument(
34
+ "--warehouse",
35
+ default=os.environ.get("ATQUERY_DELTA_WAREHOUSE"),
36
+ metavar="URI",
37
+ help="Table location, e.g. s3://bucket/warehouse (env: ATQUERY_DELTA_WAREHOUSE)",
38
+ )
39
+ parser.add_argument(
40
+ "--namespace",
41
+ default=os.environ.get("ATQUERY_DELTA_NAMESPACE"),
42
+ help="Directory under the warehouse (env: ATQUERY_DELTA_NAMESPACE, "
43
+ "default: schema of table_name if given as schema.table, otherwise 'default')",
44
+ )
45
+ parser.add_argument(
46
+ "--storage-option",
47
+ action="append",
48
+ dest="storage_options",
49
+ default=[],
50
+ metavar="KEY=VALUE",
51
+ help="Storage option, e.g. AWS_ENDPOINT_URL=http://localhost:9000 (repeatable)",
52
+ )
53
+
54
+
55
+ def _add_output_name_arg(parser: argparse.ArgumentParser, help_text: str) -> None:
56
+ parser.add_argument("--output-name", dest="output_name", metavar="NAME", help=help_text)
57
+
58
+
59
+ def setup_parser(parser: argparse.ArgumentParser) -> None:
60
+ """delta サブコマンドのパーサーを設定する。"""
61
+ parser.formatter_class = argparse.RawDescriptionHelpFormatter
62
+ parser.epilog = """
63
+ Examples:
64
+ # Export a whole table (the Delta table is created automatically)
65
+ atquery delta export access_logs -d mysql://root@localhost/mydb --warehouse s3://bucket/warehouse
66
+
67
+ # Export a table in another schema (namespace defaults to the schema name: sails)
68
+ atquery delta export sails.activity_logs -d mysql://root@localhost/mydb --warehouse s3://bucket/warehouse
69
+
70
+ # Export the result of a query
71
+ atquery delta export access_logs --query "SELECT * FROM access_logs WHERE created_datetime < '2026-01-01'"
72
+
73
+ # Export under a different Delta table name
74
+ atquery delta export access_logs --output-name access_logs_2026
75
+
76
+ # Export rows older than the cutoff, then delete them from MySQL (safe to re-run)
77
+ atquery delta cutoff run access_logs --time-column created_datetime --cutoff-at 2026-01-01T00:00:00
78
+
79
+ # Rewrite small data files into fewer, larger ones
80
+ atquery delta compact access_logs
81
+
82
+ # Physically delete data files removed more than 7 days ago
83
+ atquery delta vacuum access_logs --older-than 7d
84
+
85
+ Notes:
86
+ Times are interpreted in the session time zone of the MySQL connection
87
+ (e.g. -d "mysql://.../mydb?time_zone=+09:00"). --cutoff-at must not carry a UTC offset.
88
+ Environment variables: ATQUERY_DATASOURCE, ATQUERY_DELTA_WAREHOUSE, ATQUERY_DELTA_NAMESPACE
89
+ """
90
+
91
+ sub = parser.add_subparsers(dest="delta_command", help="delta commands")
92
+
93
+ export_parser = sub.add_parser("export", help="Export a MySQL table (or query result) to a Delta Lake table")
94
+ export_parser.add_argument("table_name", help="Source MySQL table (also the Delta table name)")
95
+ export_parser.add_argument("--query", help="SELECT statement to export (default: all rows of table_name)")
96
+ _add_output_name_arg(export_parser, "Delta table name to write to, without namespace (default: table_name)")
97
+ _add_common_args(export_parser)
98
+
99
+ cutoff_parser = sub.add_parser("cutoff", help="Cutoff management for periodic log offloading")
100
+ cutoff_sub = cutoff_parser.add_subparsers(dest="cutoff_command", help="cutoff commands")
101
+ cutoff_run_parser = cutoff_sub.add_parser(
102
+ "run", help="Export rows older than the cutoff to Delta Lake, then delete them from MySQL"
103
+ )
104
+ cutoff_run_parser.add_argument("table_name", help="Source MySQL table (also the Delta table name)")
105
+ cutoff_run_parser.add_argument(
106
+ "--cutoff-at",
107
+ required=True,
108
+ dest="cutoff_at",
109
+ metavar="DATETIME",
110
+ help="Rows with time_column < DATETIME are offloaded (ISO 8601, e.g. 2026-01-01T00:00:00)",
111
+ )
112
+ cutoff_run_parser.add_argument(
113
+ "--time-column",
114
+ required=True,
115
+ dest="time_column",
116
+ metavar="COLUMN",
117
+ help="DATETIME/TIMESTAMP column used for the cutoff",
118
+ )
119
+ cutoff_run_parser.add_argument(
120
+ "--purge-batch-size",
121
+ type=int,
122
+ default=10_000,
123
+ dest="purge_batch_size",
124
+ metavar="N",
125
+ help="Max rows per DELETE statement (default: 10000)",
126
+ )
127
+ _add_common_args(cutoff_run_parser)
128
+
129
+ compact_parser = sub.add_parser("compact", help="Rewrite small data files into fewer, larger ones")
130
+ compact_parser.add_argument("table_name", help="Source MySQL table (also the Delta table name)")
131
+ _add_output_name_arg(compact_parser, "Delta table name to compact, without namespace (default: table_name)")
132
+ _add_common_args(compact_parser)
133
+
134
+ vacuum_parser = sub.add_parser("vacuum", help="Physically delete data files no longer referenced")
135
+ vacuum_parser.add_argument("table_name", help="Source MySQL table (also the Delta table name)")
136
+ vacuum_parser.add_argument(
137
+ "--older-than",
138
+ required=True,
139
+ dest="older_than",
140
+ metavar="VALUE",
141
+ help="Delete files removed before this (at least 24h ago). Relative (7d, 24h) or ISO 8601 datetime",
142
+ )
143
+ _add_output_name_arg(vacuum_parser, "Delta table name to target, without namespace (default: table_name)")
144
+ vacuum_parser.add_argument(
145
+ "--dry-run",
146
+ action="store_true",
147
+ dest="dry_run",
148
+ help="Only report what would be deleted, without making changes",
149
+ )
150
+ _add_common_args(vacuum_parser)
151
+
152
+
153
+ def execute_delta(args: argparse.Namespace) -> int:
154
+ """delta コマンドをディスパッチする。"""
155
+ command = args.delta_command
156
+ if command == "export":
157
+ return _run(args, _execute_export)
158
+ if command == "cutoff" and getattr(args, "cutoff_command", None) == "run":
159
+ return _run(args, _execute_cutoff_run)
160
+ if command == "compact":
161
+ return _run(args, _execute_compact)
162
+ if command == "vacuum":
163
+ return _run(args, _execute_vacuum)
164
+ print("usage: atquery delta {export,cutoff run,compact,vacuum} [options]", file=sys.stderr)
165
+ print("Run 'atquery delta --help' for more information.", file=sys.stderr)
166
+ return EXIT_ERROR
167
+
168
+
169
+ def _run(args: argparse.Namespace, func) -> int:
170
+ uri = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
171
+ if not uri:
172
+ print("Error: -d/--datasource または ATQUERY_DATASOURCE 環境変数を指定してください", file=sys.stderr)
173
+ return EXIT_ERROR
174
+ try:
175
+ storage_options = _parse_storage_options(args.storage_options)
176
+ with create_datasource(uri) as datasource:
177
+ func(args, _make_exporter(args, datasource, storage_options))
178
+ return EXIT_SUCCESS
179
+ except ImportError as e:
180
+ print(f"{_IMPORT_ERROR_MESSAGE} ({e})", file=sys.stderr)
181
+ return EXIT_ERROR
182
+ except Exception as e:
183
+ print(f"Error: {format_error_for_cli(e)}", file=sys.stderr)
184
+ return EXIT_ERROR
185
+
186
+
187
+ def _parse_storage_options(values: list[str]) -> dict[str, str]:
188
+ options: dict[str, str] = {}
189
+ for value in values:
190
+ key, sep, val = value.partition("=")
191
+ if not sep or not key:
192
+ raise ValueError(f"--storage-option は KEY=VALUE 形式で指定してください: {value!r}")
193
+ options[key] = val
194
+ return options
195
+
196
+
197
+ def _make_exporter(args: argparse.Namespace, datasource, storage_options: dict[str, str]):
198
+ from atquery.delta import DeltaExporter
199
+
200
+ if not args.warehouse:
201
+ raise ValueError("--warehouse または ATQUERY_DELTA_WAREHOUSE 環境変数を指定してください")
202
+ return DeltaExporter(args.warehouse, datasource, namespace=args.namespace, storage_options=storage_options)
203
+
204
+
205
+ def _execute_export(args: argparse.Namespace, exporter) -> None:
206
+ exporter.export(args.table_name, query=args.query, output_name=args.output_name)
207
+ print("exported: " + ".".join(exporter.table_identifier(args.table_name, args.output_name)))
208
+
209
+
210
+ def _execute_cutoff_run(args: argparse.Namespace, exporter) -> None:
211
+ from atquery.delta import DeltaCutoffOffloader
212
+
213
+ cutoff_at = _parse_datetime(args.cutoff_at)
214
+ DeltaCutoffOffloader(
215
+ exporter, time_column=args.time_column, purge_batch_size=args.purge_batch_size
216
+ ).run(args.table_name, cutoff_at)
217
+ print(f"offloaded: {'.'.join(exporter.table_identifier(args.table_name))} (cutoff_at < {args.cutoff_at})")
218
+
219
+
220
+ def _execute_compact(args: argparse.Namespace, exporter) -> None:
221
+ result = exporter.compact(args.table_name, output_name=args.output_name)
222
+ identifier = ".".join(exporter.table_identifier(args.table_name, args.output_name))
223
+ print(
224
+ f"compacted: {identifier} "
225
+ f"(files_added={result.get('numFilesAdded', 0)}, files_removed={result.get('numFilesRemoved', 0)})"
226
+ )
227
+
228
+
229
+ def _execute_vacuum(args: argparse.Namespace, exporter) -> None:
230
+ older_than = _parse_older_than(args.older_than)
231
+ deleted = exporter.vacuum(args.table_name, older_than=older_than, output_name=args.output_name, dry_run=args.dry_run)
232
+ identifier = ".".join(exporter.table_identifier(args.table_name, args.output_name))
233
+ prefix = "would delete" if args.dry_run else "deleted"
234
+ print(f"{prefix}: {identifier} (older_than={older_than.isoformat()}, files={len(deleted)})")
235
+
236
+
237
+ def _parse_datetime(value: str) -> datetime:
238
+ try:
239
+ return datetime.fromisoformat(value)
240
+ except ValueError:
241
+ raise ValueError(f"--cutoff-at は ISO 8601 形式で指定してください: {value!r}") from None
242
+
243
+
244
+ def _parse_older_than(value: str) -> datetime:
245
+ """'7d'/'24h'/'30m' の相対指定、またはISO 8601文字列をdatetimeへ変換する。"""
246
+ if m := re.fullmatch(r"(\d+)([dhm])", value):
247
+ amount, unit = int(m.group(1)), m.group(2)
248
+ delta = {"d": timedelta(days=amount), "h": timedelta(hours=amount), "m": timedelta(minutes=amount)}[unit]
249
+ return datetime.now().astimezone() - delta
250
+ try:
251
+ return datetime.fromisoformat(value)
252
+ except ValueError:
253
+ raise ValueError(f"--older-than は '7d'/'24h'/'30m' もしくはISO 8601 形式で指定してください: {value!r}") from None
@@ -707,6 +707,15 @@ Examples:
707
707
  )
708
708
  setup_migrate_parser(migrate_parser)
709
709
 
710
+ # patch サブコマンドの追加
711
+ from atquery.cli.patch import setup_parser as setup_patch_parser
712
+ patch_parser = subparsers.add_parser(
713
+ "patch",
714
+ help="Apply JSON change sets (PK-based insert/replace/delete) with an audit log",
715
+ description="Apply JSON change sets (PK-based insert/replace/delete) with an audit log",
716
+ )
717
+ setup_patch_parser(patch_parser)
718
+
710
719
  # ecd サブコマンドの追加
711
720
  from atquery.cli.ecd import setup_parser as setup_ecd_parser
712
721
  ecd_parser = subparsers.add_parser(
@@ -716,14 +725,14 @@ Examples:
716
725
  )
717
726
  setup_ecd_parser(ecd_parser)
718
727
 
719
- # iceberg サブコマンドの追加
720
- from atquery.cli.iceberg import setup_parser as setup_iceberg_parser
721
- iceberg_parser = subparsers.add_parser(
722
- "iceberg",
723
- help="Export MySQL tables to Iceberg: export/cutoff/catalog (requires atquery[iceberg-export])",
724
- description="Export MySQL tables to Iceberg: export/cutoff/catalog",
728
+ # delta サブコマンドの追加
729
+ from atquery.cli.delta import setup_parser as setup_delta_parser
730
+ delta_parser = subparsers.add_parser(
731
+ "delta",
732
+ help="Export MySQL tables to Delta Lake: export/cutoff/compact/vacuum (requires atquery[delta-export])",
733
+ description="Export MySQL tables to Delta Lake: export/cutoff/compact/vacuum",
725
734
  )
726
- setup_iceberg_parser(iceberg_parser)
735
+ setup_delta_parser(delta_parser)
727
736
 
728
737
  parser.add_argument(
729
738
  "-d",
@@ -860,13 +869,17 @@ Examples:
860
869
  from atquery.cli.migrate import execute_migrate
861
870
  return execute_migrate(args)
862
871
 
872
+ if args.subcommand == "patch":
873
+ from atquery.cli.patch import execute_patch
874
+ return execute_patch(args)
875
+
863
876
  if args.subcommand == "ecd":
864
877
  from atquery.cli.ecd import execute_ecd
865
878
  return execute_ecd(args)
866
879
 
867
- if args.subcommand == "iceberg":
868
- from atquery.cli.iceberg import execute_iceberg
869
- return execute_iceberg(args)
880
+ if args.subcommand == "delta":
881
+ from atquery.cli.delta import execute_delta
882
+ return execute_delta(args)
870
883
 
871
884
  # データベース接続文字列の取得(優先順位: 引数 > 環境変数)、-s/--schemaがあればschema部分を上書き
872
885
  database_uri = resolve_datasource_uri(args.datasource, args.schema)
@@ -0,0 +1,135 @@
1
+ """atquery patch サブコマンド - JSON change set によるデータパッチの適用(ADR-0045)"""
2
+ import argparse
3
+ import os
4
+ import sys
5
+
6
+ from atquery.cli.main import EXIT_ERROR, EXIT_SUCCESS, resolve_datasource_uri
7
+ from atquery.dialect import create_datasource
8
+
9
+
10
+ def _add_apply_args(parser: argparse.ArgumentParser) -> None:
11
+ parser.add_argument("file", help="change set のJSONファイル('-' で標準入力)")
12
+ parser.add_argument(
13
+ "-d",
14
+ "--datasource",
15
+ default=argparse.SUPPRESS,
16
+ help="Database connection string (env: ATQUERY_DATASOURCE)",
17
+ )
18
+ parser.add_argument(
19
+ "-s",
20
+ "--schema",
21
+ default=argparse.SUPPRESS,
22
+ help="Override the schema/database segment of the resolved connection URI (applies to this command only)",
23
+ )
24
+ parser.add_argument(
25
+ "--idempotency-key",
26
+ default=None,
27
+ metavar="KEY",
28
+ help="Skip if a change set with the same key has already been applied (e.g. a queue message ID)",
29
+ )
30
+ parser.add_argument(
31
+ "--dry-run",
32
+ action="store_true",
33
+ dest="dry_run",
34
+ help="Execute inside a transaction, print the generated SQL and roll back (side effects such as triggers can still occur)",
35
+ )
36
+ parser.add_argument(
37
+ "--patch-table-prefix",
38
+ default=os.environ.get("ATQUERY_PATCH_TABLE_PREFIX", "atquery"),
39
+ dest="patch_table_prefix",
40
+ help="Prefix for the log table name (env: ATQUERY_PATCH_TABLE_PREFIX, default: atquery)",
41
+ )
42
+ parser.add_argument(
43
+ "--patch-schema",
44
+ default=os.environ.get("ATQUERY_PATCH_SCHEMA"),
45
+ dest="patch_schema",
46
+ metavar="SCHEMA",
47
+ help="Schema for the log table (env: ATQUERY_PATCH_SCHEMA)",
48
+ )
49
+
50
+
51
+ def setup_parser(parser: argparse.ArgumentParser) -> None:
52
+ """patch サブコマンドのパーサーを設定する。"""
53
+ parser.formatter_class = argparse.RawDescriptionHelpFormatter
54
+ parser.epilog = """
55
+ A change set is a JSON file of PK-based insert / replace / delete operations applied in one transaction.
56
+
57
+ Examples:
58
+ # Show the generated SQL without committing
59
+ atquery patch apply fix.json --dry-run -d mysql://root@localhost/mydb
60
+
61
+ # Apply (the result is recorded in atquery_patch_logs)
62
+ atquery patch apply fix.json -d mysql://root@localhost/mydb
63
+
64
+ # Apply once per message even if delivered repeatedly
65
+ atquery patch apply fix.json --idempotency-key "$MESSAGE_ID"
66
+ """
67
+ sub = parser.add_subparsers(dest="patch_command", help="patch commands")
68
+ apply_parser = sub.add_parser("apply", help="Apply a change set (JSON file)")
69
+ _add_apply_args(apply_parser)
70
+
71
+
72
+ def execute_patch(args: argparse.Namespace) -> int:
73
+ """patch コマンドをディスパッチする。"""
74
+ if args.patch_command == "apply":
75
+ return _execute_apply(args)
76
+ print("usage: atquery patch apply FILE [options]", file=sys.stderr)
77
+ print("Run 'atquery patch --help' for more information.", file=sys.stderr)
78
+ return EXIT_ERROR
79
+
80
+
81
+ def _execute_apply(args: argparse.Namespace) -> int:
82
+ from atquery.patch import PatchError, PatchTransientError, apply, loads
83
+
84
+ uri = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
85
+ if not uri:
86
+ print("Error: -d/--datasource または ATQUERY_DATASOURCE 環境変数を指定してください", file=sys.stderr)
87
+ return EXIT_ERROR
88
+
89
+ try:
90
+ if args.file == "-":
91
+ text = sys.stdin.read()
92
+ else:
93
+ with open(args.file, encoding="utf-8") as f:
94
+ text = f.read()
95
+ loads(text) # 構造エラーをDB接続前に検出する
96
+
97
+ with create_datasource(uri).connect() as conn:
98
+ result = apply(
99
+ conn,
100
+ text,
101
+ idempotency_key=args.idempotency_key,
102
+ dry_run=args.dry_run,
103
+ table_prefix=args.patch_table_prefix,
104
+ schema=args.patch_schema,
105
+ )
106
+ except PatchTransientError as e:
107
+ print(f"Error (transient, retryable): {e}", file=sys.stderr)
108
+ return EXIT_ERROR
109
+ except PatchError as e:
110
+ print(f"Error: {e}", file=sys.stderr)
111
+ return EXIT_ERROR
112
+ except Exception as e:
113
+ print(f"Error: {e}", file=sys.stderr)
114
+ return EXIT_ERROR
115
+
116
+ _print_result(result)
117
+ return EXIT_SUCCESS
118
+
119
+
120
+ def _print_result(result) -> None:
121
+ if result.status == "skipped":
122
+ print(f"Skipped: idempotency key {result.idempotency_key!r} has already been applied (log id: {result.log_id})")
123
+ return
124
+
125
+ if result.status == "dry_run":
126
+ print(f"Dry run: {len(result.operations)} operation(s) executed and rolled back")
127
+ else:
128
+ print(f"Applied: {len(result.operations)} operation(s) (log id: {result.log_id}, {result.execution_time_ms} ms)")
129
+
130
+ for op in result.operations:
131
+ print(f" [{op.index}] {op.op} {op.table}")
132
+ if result.status == "dry_run":
133
+ for line in op.sql.splitlines():
134
+ print(f" {line}")
135
+ print(f" params: {dict(op.params)}")
@@ -0,0 +1,6 @@
1
+ """MySQLテーブルのDelta Lakeエクスポート(`atquery[delta-export]`)。"""
2
+
3
+ from atquery.delta.cutoff import DeltaCutoffOffloader
4
+ from atquery.delta.exporter import DeltaExporter
5
+
6
+ __all__ = ["DeltaCutoffOffloader", "DeltaExporter"]
@@ -0,0 +1,70 @@
1
+ """MySQLの列定義からArrowスキーマを導く(非公開)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable, Sequence
6
+ from typing import Any
7
+
8
+ import pyarrow as pa
9
+
10
+ _MYSQL_TYPE_TO_ARROW: dict[str, pa.DataType] = {
11
+ "char": pa.string(),
12
+ "varchar": pa.string(),
13
+ "text": pa.string(),
14
+ "tinytext": pa.string(),
15
+ "mediumtext": pa.string(),
16
+ "longtext": pa.string(),
17
+ "json": pa.string(),
18
+ "enum": pa.string(),
19
+ "binary": pa.binary(),
20
+ "varbinary": pa.binary(),
21
+ "smallint": pa.int32(),
22
+ "mediumint": pa.int32(),
23
+ "int": pa.int32(),
24
+ "bigint": pa.int64(),
25
+ "float": pa.float32(),
26
+ "double": pa.float64(),
27
+ "timestamp": pa.timestamp("us"),
28
+ "datetime": pa.timestamp("us"),
29
+ }
30
+
31
+
32
+ def arrow_type_for_mysql_column(data_type: str, column_type: str) -> pa.DataType:
33
+ """MySQLの列型をArrowの型へ変換する。対応外の型は`ValueError`。
34
+
35
+ - `tinyint(1)`はbool、それ以外の`tinyint`はint32
36
+ - `json`/`enum`/`char`/`varchar`/`text`系はstring(jsonはJSON文字列のまま保持)
37
+ - `binary`/`varbinary`は幅に関わらず可変長binary
38
+ - `datetime`/`timestamp`はタイムゾーン無しのtimestamp(Delta Lakeでは`timestampNtz`)
39
+ """
40
+ data_type = data_type.lower()
41
+ if data_type == "tinyint":
42
+ return pa.bool_() if column_type.lower() == "tinyint(1)" else pa.int32()
43
+ try:
44
+ return _MYSQL_TYPE_TO_ARROW[data_type]
45
+ except KeyError:
46
+ raise ValueError(f"未対応のMySQL型です: {column_type}(`{data_type}`)") from None
47
+
48
+
49
+ def infer_arrow_schema(columns: Iterable[Sequence[str]]) -> pa.Schema:
50
+ """`(column_name, data_type, column_type)`の列定義(定義順)からArrowスキーマを作る。"""
51
+ fields = [
52
+ pa.field(name, arrow_type_for_mysql_column(data_type, column_type), nullable=True)
53
+ for name, data_type, column_type in columns
54
+ ]
55
+ if not fields:
56
+ raise ValueError("列が1つもありません")
57
+ return pa.schema(fields)
58
+
59
+
60
+ def convert_value(value: Any, arrow_type: pa.DataType) -> Any:
61
+ """MySQLドライバが返したPython値を、Arrow配列へ詰められる値へ揃える。"""
62
+ if value is None:
63
+ return None
64
+ if pa.types.is_boolean(arrow_type):
65
+ return bool(value)
66
+ if pa.types.is_binary(arrow_type) or pa.types.is_large_binary(arrow_type):
67
+ return bytes(value)
68
+ if pa.types.is_string(arrow_type) or pa.types.is_large_string(arrow_type):
69
+ return bytes(value).decode("utf-8") if isinstance(value, (bytes, bytearray)) else str(value)
70
+ return value