atquery 2.18.0__tar.gz → 2.19.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.
- {atquery-2.18.0 → atquery-2.19.0}/PKG-INFO +1 -1
- {atquery-2.18.0 → atquery-2.19.0}/pyproject.toml +1 -1
- {atquery-2.18.0 → atquery-2.19.0}/pyproject.toml.orig +1 -1
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/main.py +13 -0
- atquery-2.19.0/src/atquery/cli/patch.py +135 -0
- atquery-2.19.0/src/atquery/patch/__init__.py +56 -0
- atquery-2.19.0/src/atquery/patch/_apply.py +317 -0
- atquery-2.19.0/src/atquery/patch/_convert.py +220 -0
- atquery-2.19.0/src/atquery/patch/_errors.py +52 -0
- atquery-2.19.0/src/atquery/patch/_log.py +182 -0
- atquery-2.19.0/src/atquery/patch/_meta.py +231 -0
- atquery-2.19.0/src/atquery/patch/_model.py +153 -0
- atquery-2.19.0/src/atquery/patch/_sql.py +135 -0
- {atquery-2.18.0 → atquery-2.19.0}/LICENSE +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/README.md +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/aio/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/aio/api.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/aio/engine.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/aio/query.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/api_v2.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/atquery2.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/columns.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/csv.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/ddl.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/diff.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/ecd.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/iceberg.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/migrate.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/routines.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/scenario.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/schemas.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/cli/tables.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/duckdb.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/mysql/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/mysql/aio.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/mysql/core.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/mysql/dump/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/mysql/dump/__main__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/mysql/dump/core.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/mysql/meta.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/mysql/pooling.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/mysql/restore/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/mysql/restore/__main__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/mysql/restore/core.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/dialect/sqlite.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/diff/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/diff/comparator.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/diff/generator.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/diff/git_integration.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/diff/models.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/diff/parser.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/_toml.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/catalog.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/ddl.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/diff.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/erd.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/errors.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/model.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/parser.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/resolver.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/seed.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/ecd/skeleton.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/engine.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/factory.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/iceberg/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/iceberg/_catalog.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/iceberg/_schema.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/iceberg/cutoff.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/iceberg/exporter.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/migration/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/migration/_migrator.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/migration/_protocol.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/migration/_standard.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/migration/_types.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/py.typed +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/testing/__init__.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/testing/creator.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/testing/loader.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/testing/schema.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/testing/validator.py +0 -0
- {atquery-2.18.0 → atquery-2.19.0}/src/atquery/type.py +0 -0
|
@@ -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(
|
|
@@ -860,6 +869,10 @@ 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)
|
|
@@ -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,56 @@
|
|
|
1
|
+
"""atquery.patch - JSON change set によるデータパッチ(ADR-0045)
|
|
2
|
+
|
|
3
|
+
PK指定のDML(insert / replace / delete)だけを許す、制約付きのデータ変更の仕組み。
|
|
4
|
+
WHERE条件による更新・式・DDLは意図的にサポートしない。
|
|
5
|
+
|
|
6
|
+
基本的な使い方:
|
|
7
|
+
from atquery.patch import apply
|
|
8
|
+
|
|
9
|
+
patch = {
|
|
10
|
+
"meta": {"applied_by": "U0001 山田太郎", "reason": "表記ゆれの修正"},
|
|
11
|
+
"operations": [
|
|
12
|
+
{
|
|
13
|
+
"op": "replace",
|
|
14
|
+
"table": "users",
|
|
15
|
+
"pk": {"id": 1},
|
|
16
|
+
"value": {"name": "新しい名前"},
|
|
17
|
+
"old_value": {"name": "古い名前"},
|
|
18
|
+
},
|
|
19
|
+
],
|
|
20
|
+
}
|
|
21
|
+
with datasource.connect() as conn:
|
|
22
|
+
result = apply(conn, patch, idempotency_key=message_id)
|
|
23
|
+
|
|
24
|
+
dry run(実行してロールバックする):
|
|
25
|
+
result = apply(conn, patch, dry_run=True)
|
|
26
|
+
|
|
27
|
+
SQS等から受けた JSON 文字列は number を Decimal として読み込む ``loads`` / ``load`` で dict にするか、
|
|
28
|
+
そのまま ``apply`` に渡せる。
|
|
29
|
+
"""
|
|
30
|
+
from atquery.patch._apply import OperationResult, PatchResult, apply
|
|
31
|
+
from atquery.patch._errors import (
|
|
32
|
+
PatchConflictError,
|
|
33
|
+
PatchError,
|
|
34
|
+
PatchExecutionError,
|
|
35
|
+
PatchPermanentError,
|
|
36
|
+
PatchTransientError,
|
|
37
|
+
PatchValidationError,
|
|
38
|
+
)
|
|
39
|
+
from atquery.patch._model import ChangeSet, Operation, load, loads, parse
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"apply",
|
|
43
|
+
"load",
|
|
44
|
+
"loads",
|
|
45
|
+
"parse",
|
|
46
|
+
"ChangeSet",
|
|
47
|
+
"Operation",
|
|
48
|
+
"OperationResult",
|
|
49
|
+
"PatchResult",
|
|
50
|
+
"PatchError",
|
|
51
|
+
"PatchTransientError",
|
|
52
|
+
"PatchPermanentError",
|
|
53
|
+
"PatchValidationError",
|
|
54
|
+
"PatchConflictError",
|
|
55
|
+
"PatchExecutionError",
|
|
56
|
+
]
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""change set の適用(apply)
|
|
2
|
+
|
|
3
|
+
流れ:
|
|
4
|
+
1. DSLをパースして構造を検証する(DB不要)。
|
|
5
|
+
2. スキーマのメタデータを取得し、全operationを実行前にまとめて型変換・SQL生成する。
|
|
6
|
+
3. 1トランザクション内で適用記録の挿入 → 各operationの実行 → コミット。
|
|
7
|
+
途中で失敗したら本体をロールバックし、別トランザクションで FAILED を記録する。
|
|
8
|
+
|
|
9
|
+
``conn`` は未開始のトランザクションを持たない非autocommit接続であること。
|
|
10
|
+
``apply`` がトランザクションの開始・コミット・ロールバックを管理する。
|
|
11
|
+
"""
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import sqlite3
|
|
16
|
+
import time
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from decimal import Decimal
|
|
19
|
+
from typing import Any, Literal, Mapping
|
|
20
|
+
|
|
21
|
+
from atquery.engine import ATConnection, ATSQLError
|
|
22
|
+
from atquery.patch._convert import Converter
|
|
23
|
+
from atquery.patch._errors import (
|
|
24
|
+
PatchConflictError,
|
|
25
|
+
PatchError,
|
|
26
|
+
PatchExecutionError,
|
|
27
|
+
PatchTransientError,
|
|
28
|
+
PatchValidationError,
|
|
29
|
+
)
|
|
30
|
+
from atquery.patch._log import STATUS_SUCCESS, PatchLog, uuid7
|
|
31
|
+
from atquery.patch._meta import SchemaCache
|
|
32
|
+
from atquery.patch._model import ChangeSet, loads, parse
|
|
33
|
+
from atquery.patch._sql import Statement, build_statement
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger("atquery.patch")
|
|
36
|
+
|
|
37
|
+
_IDEMPOTENCY_KEY_MAX_LENGTH = 255
|
|
38
|
+
|
|
39
|
+
# 一時的エラー(リトライすれば成功しうる)として扱うMySQLのエラー番号
|
|
40
|
+
_MYSQL_TRANSIENT_ERRNOS = frozenset({
|
|
41
|
+
1205, # ER_LOCK_WAIT_TIMEOUT
|
|
42
|
+
1213, # ER_LOCK_DEADLOCK
|
|
43
|
+
1053, # ER_SERVER_SHUTDOWN
|
|
44
|
+
1927, # ER_CONNECTION_KILLED
|
|
45
|
+
2006, # CR_SERVER_GONE_ERROR
|
|
46
|
+
2013, # CR_SERVER_LOST
|
|
47
|
+
2055, # CR_SERVER_LOST_EXTENDED
|
|
48
|
+
})
|
|
49
|
+
_MYSQL_ER_DUP_ENTRY = 1062
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class OperationResult:
|
|
54
|
+
"""1 operation の実行結果
|
|
55
|
+
|
|
56
|
+
Attributes:
|
|
57
|
+
rowcount: 対象行数。各operationはちょうど1件を対象にするため常に1(同値のreplaceも1として扱う)
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
index: int
|
|
61
|
+
op: str
|
|
62
|
+
table: str
|
|
63
|
+
sql: str
|
|
64
|
+
params: Mapping[str, Any]
|
|
65
|
+
rowcount: int
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class PatchResult:
|
|
70
|
+
"""apply の結果
|
|
71
|
+
|
|
72
|
+
Attributes:
|
|
73
|
+
status: ``applied``(適用してコミット)/ ``skipped``(同じ idempotency_key が適用済み)/
|
|
74
|
+
``dry_run``(実行してロールバック)
|
|
75
|
+
log_id: 適用記録の id(dry_run では None)
|
|
76
|
+
operations: 各operationの結果(skipped では空)
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
status: Literal["applied", "skipped", "dry_run"]
|
|
80
|
+
operations: tuple[OperationResult, ...]
|
|
81
|
+
log_id: str | None
|
|
82
|
+
idempotency_key: str | None
|
|
83
|
+
execution_time_ms: int
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _json_default(obj: Any) -> Any:
|
|
87
|
+
if isinstance(obj, Decimal):
|
|
88
|
+
return str(obj) # 厳密な値を保つため文字列で記録する
|
|
89
|
+
raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _normalize(patch: "Mapping[str, Any] | str | bytes | os.PathLike") -> tuple[dict, str]:
|
|
93
|
+
"""change set を (dict, 記録用JSON文字列) に正規化する。"""
|
|
94
|
+
if isinstance(patch, os.PathLike):
|
|
95
|
+
with open(patch, encoding="utf-8") as f:
|
|
96
|
+
patch = f.read()
|
|
97
|
+
if isinstance(patch, (str, bytes)):
|
|
98
|
+
text = patch.decode("utf-8") if isinstance(patch, bytes) else patch
|
|
99
|
+
return loads(text), text
|
|
100
|
+
if isinstance(patch, Mapping):
|
|
101
|
+
try:
|
|
102
|
+
return dict(patch), json.dumps(patch, ensure_ascii=False, default=_json_default)
|
|
103
|
+
except (TypeError, ValueError) as ex:
|
|
104
|
+
raise PatchValidationError(f"change set is not JSON serializable: {ex}") from ex
|
|
105
|
+
raise PatchValidationError(f"unsupported change set type: {type(patch).__name__}")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _is_duplicate_key(ex: BaseException) -> bool:
|
|
109
|
+
orig = getattr(ex, "orig", ex)
|
|
110
|
+
if getattr(orig, "errno", None) == _MYSQL_ER_DUP_ENTRY:
|
|
111
|
+
return True
|
|
112
|
+
return isinstance(orig, sqlite3.IntegrityError) and "UNIQUE" in str(orig).upper()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _is_transient(ex: BaseException, conn: ATConnection) -> bool:
|
|
116
|
+
orig = getattr(ex, "orig", ex)
|
|
117
|
+
errno = getattr(orig, "errno", None)
|
|
118
|
+
if errno in _MYSQL_TRANSIENT_ERRNOS:
|
|
119
|
+
return True
|
|
120
|
+
if isinstance(orig, sqlite3.OperationalError):
|
|
121
|
+
message = str(orig).lower()
|
|
122
|
+
return "locked" in message or "busy" in message
|
|
123
|
+
return errno is None and conn.dialect == "mysql" and not conn.is_connected()
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _to_patch_error(ex: Exception, conn: ATConnection, *, op_index: int | None = None, sql: str | None = None) -> PatchError:
|
|
127
|
+
"""任意の例外を PatchError に変換する(PatchError はそのまま)。"""
|
|
128
|
+
if isinstance(ex, PatchError):
|
|
129
|
+
return ex
|
|
130
|
+
orig = getattr(ex, "orig", ex)
|
|
131
|
+
message = str(orig)
|
|
132
|
+
if _is_transient(ex, conn):
|
|
133
|
+
return PatchTransientError(message, op_index=op_index)
|
|
134
|
+
return PatchExecutionError(message, op_index=op_index, sql=sql or getattr(ex, "sql", None))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _rollback_quietly(conn: ATConnection) -> None:
|
|
138
|
+
try:
|
|
139
|
+
conn.rollback()
|
|
140
|
+
except Exception:
|
|
141
|
+
logger.warning("rollback failed", exc_info=True)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _execute(conn: ATConnection, stmt: Statement) -> OperationResult:
|
|
145
|
+
"""1 operation を実行し、影響行数を検証する。
|
|
146
|
+
|
|
147
|
+
各operationは対象行をちょうど1件に絞るため、影響行数は1でなければならない。
|
|
148
|
+
ただしMySQLの影響行数は「変更された行数」(CLIENT_FOUND_ROWS 未指定時)であり、同値のUPDATEは0になる。
|
|
149
|
+
接続フラグに依存しないよう、replace で0件のときは「pk・old_value・新しい値のすべてに一致する行が
|
|
150
|
+
1件ある(すでに目的の状態)」かをSELECTで確かめ、同値更新と対象なし/old_value不一致を区別する。
|
|
151
|
+
"""
|
|
152
|
+
result = conn.execute(stmt.sql, stmt.params)
|
|
153
|
+
rowcount = result.rowcount
|
|
154
|
+
|
|
155
|
+
if rowcount == 0 and stmt.verify_sql is not None:
|
|
156
|
+
count = conn.execute(stmt.verify_sql, stmt.params, buffered=True).scalar()
|
|
157
|
+
if count == 1:
|
|
158
|
+
rowcount = 1 # すでに目的の状態(同値更新)
|
|
159
|
+
if rowcount == 0:
|
|
160
|
+
raise PatchConflictError(
|
|
161
|
+
f"no row matched ({stmt.op} {stmt.table}): the row does not exist or old_value does not match",
|
|
162
|
+
op_index=stmt.op_index,
|
|
163
|
+
)
|
|
164
|
+
if rowcount != 1:
|
|
165
|
+
raise PatchExecutionError(
|
|
166
|
+
f"unexpected affected rows ({stmt.op} {stmt.table}): {rowcount}", op_index=stmt.op_index, sql=stmt.sql
|
|
167
|
+
)
|
|
168
|
+
return OperationResult(stmt.op_index, stmt.op, stmt.table, stmt.sql, stmt.params, rowcount)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _begin_attempt(
|
|
172
|
+
conn: ATConnection, log: PatchLog, changeset: ChangeSet, payload: str, key: str | None
|
|
173
|
+
) -> tuple[str | None, str | None]:
|
|
174
|
+
"""適用記録の行を確保する。戻り値は (適用に使う記録id, スキップ時の既存記録id)。
|
|
175
|
+
|
|
176
|
+
同じキーが適用済みなら記録idは None(スキップ)。トランザクションは閉じた状態で返る。
|
|
177
|
+
記録の挿入を本体の前に行うことで、UNIQUE制約が並行実行に対する排他として働く
|
|
178
|
+
(同じキーの並行処理は先行トランザクションの完了を待ち、後続は「適用済み」と判定される)。
|
|
179
|
+
"""
|
|
180
|
+
log_id = uuid7()
|
|
181
|
+
try:
|
|
182
|
+
log.insert_success(log_id, key, changeset.applied_by, changeset.reason, payload)
|
|
183
|
+
return log_id, None
|
|
184
|
+
except ATSQLError as ex:
|
|
185
|
+
if key is None or not _is_duplicate_key(ex):
|
|
186
|
+
raise
|
|
187
|
+
|
|
188
|
+
conn.rollback()
|
|
189
|
+
entry = log.find(key)
|
|
190
|
+
if entry is None:
|
|
191
|
+
raise PatchTransientError("idempotency key conflict could not be resolved; retry")
|
|
192
|
+
if entry.status == STATUS_SUCCESS:
|
|
193
|
+
conn.rollback()
|
|
194
|
+
return None, entry.id
|
|
195
|
+
# 過去に失敗した同じキーの再試行。他で先に再試行が成功していれば False
|
|
196
|
+
if not log.reopen_failed(entry.id, changeset.applied_by, changeset.reason, payload):
|
|
197
|
+
conn.rollback()
|
|
198
|
+
return None, entry.id
|
|
199
|
+
return entry.id, None
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _record_failure(
|
|
203
|
+
conn: ATConnection, log: PatchLog, changeset: ChangeSet, payload: str, key: str | None,
|
|
204
|
+
error: PatchError, started: float,
|
|
205
|
+
) -> None:
|
|
206
|
+
"""失敗を別トランザクションで記録する(記録自体の失敗は元のエラーを隠さないよう握りつぶす)。"""
|
|
207
|
+
try:
|
|
208
|
+
conn.rollback()
|
|
209
|
+
log.record_failure(
|
|
210
|
+
key, changeset.applied_by, changeset.reason, payload,
|
|
211
|
+
f"{type(error).__name__}: {error}", int((time.monotonic() - started) * 1000),
|
|
212
|
+
)
|
|
213
|
+
conn.commit()
|
|
214
|
+
except Exception:
|
|
215
|
+
logger.warning("failed to record the patch failure", exc_info=True)
|
|
216
|
+
_rollback_quietly(conn)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def apply(
|
|
220
|
+
conn: ATConnection,
|
|
221
|
+
patch: "Mapping[str, Any] | str | bytes | os.PathLike",
|
|
222
|
+
*,
|
|
223
|
+
idempotency_key: str | None = None,
|
|
224
|
+
dry_run: bool = False,
|
|
225
|
+
table_prefix: str = "atquery",
|
|
226
|
+
schema: str | None = None,
|
|
227
|
+
) -> PatchResult:
|
|
228
|
+
"""change set を適用する。
|
|
229
|
+
|
|
230
|
+
Args:
|
|
231
|
+
conn: データベース接続(MySQL / SQLite)。未開始のトランザクションを持たない非autocommit接続。
|
|
232
|
+
apply がトランザクションを管理(コミット/ロールバック)する。
|
|
233
|
+
MySQLでは適用記録テーブルの作成(DDL)により暗黙コミットが発生する。
|
|
234
|
+
patch: change set。dict、JSON文字列/bytes、またはJSONファイルのパス(``os.PathLike``)。
|
|
235
|
+
JSON文字列は number を ``Decimal`` として読み込む。dictを渡す場合、DECIMALカラムの値は
|
|
236
|
+
文字列で渡すこと(floatは ``repr`` 経由で Decimal に変換される)。
|
|
237
|
+
idempotency_key: 重複排除キー(例: SQSのMessageId)。同じキーが適用済みなら ``skipped`` を返す。
|
|
238
|
+
None なら重複排除せず毎回適用する。キーは本体と同じトランザクションで記録される。
|
|
239
|
+
dry_run: True なら適用記録を書かず、トランザクション内で実行して結果を返しロールバックする。
|
|
240
|
+
実際に実行するため、トリガーの動作やAUTO_INCREMENTの消費などの副作用は起こりうる。
|
|
241
|
+
table_prefix: 適用記録テーブル名のプレフィックス(``{prefix}_patch_logs``)。
|
|
242
|
+
schema: 適用記録テーブルのスキーマ(省略時は接続の現在のデータベース)。
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
PatchResult
|
|
246
|
+
|
|
247
|
+
Raises:
|
|
248
|
+
PatchValidationError: DSLの構造・型変換のエラー(恒久)
|
|
249
|
+
PatchConflictError: 対象行がない、または old_value が一致しない(恒久)
|
|
250
|
+
PatchExecutionError: SQL実行エラー(恒久)
|
|
251
|
+
PatchTransientError: デッドロック・ロック待ちタイムアウト・接続断など(リトライ可)
|
|
252
|
+
"""
|
|
253
|
+
started = time.monotonic()
|
|
254
|
+
|
|
255
|
+
data, payload = _normalize(patch)
|
|
256
|
+
changeset = parse(data)
|
|
257
|
+
if idempotency_key is not None and (
|
|
258
|
+
not isinstance(idempotency_key, str) or not 0 < len(idempotency_key) <= _IDEMPOTENCY_KEY_MAX_LENGTH
|
|
259
|
+
):
|
|
260
|
+
raise PatchValidationError(f"idempotency_key must be a string of 1-{_IDEMPOTENCY_KEY_MAX_LENGTH} characters")
|
|
261
|
+
if conn.dialect not in ("mysql", "sqlite"):
|
|
262
|
+
raise PatchValidationError(f"unsupported dialect: {conn.dialect}")
|
|
263
|
+
if conn.dialect == "mysql" and getattr(conn.connection, "autocommit", False):
|
|
264
|
+
raise ValueError("atquery.patch requires a connection with autocommit disabled")
|
|
265
|
+
|
|
266
|
+
log = PatchLog(conn, table_prefix=table_prefix, schema=schema)
|
|
267
|
+
try:
|
|
268
|
+
if not dry_run:
|
|
269
|
+
log.ensure_table()
|
|
270
|
+
except Exception as ex:
|
|
271
|
+
raise _to_patch_error(ex, conn) from ex
|
|
272
|
+
|
|
273
|
+
def elapsed_ms() -> int:
|
|
274
|
+
return int((time.monotonic() - started) * 1000)
|
|
275
|
+
|
|
276
|
+
try:
|
|
277
|
+
schema_cache = SchemaCache(conn)
|
|
278
|
+
converter = Converter(conn)
|
|
279
|
+
statements = [build_statement(op, schema_cache, converter) for op in changeset.operations]
|
|
280
|
+
|
|
281
|
+
if dry_run:
|
|
282
|
+
existing = log.find(idempotency_key) if idempotency_key and log.table_exists() else None
|
|
283
|
+
if existing is not None and existing.status == STATUS_SUCCESS:
|
|
284
|
+
conn.rollback()
|
|
285
|
+
return PatchResult("skipped", (), existing.id, idempotency_key, elapsed_ms())
|
|
286
|
+
log_id = None
|
|
287
|
+
else:
|
|
288
|
+
log_id, skipped_id = _begin_attempt(conn, log, changeset, payload, idempotency_key)
|
|
289
|
+
if log_id is None:
|
|
290
|
+
return PatchResult("skipped", (), skipped_id, idempotency_key, elapsed_ms())
|
|
291
|
+
|
|
292
|
+
results: list[OperationResult] = []
|
|
293
|
+
for stmt in statements:
|
|
294
|
+
try:
|
|
295
|
+
results.append(_execute(conn, stmt))
|
|
296
|
+
except PatchError:
|
|
297
|
+
raise
|
|
298
|
+
except Exception as ex:
|
|
299
|
+
raise _to_patch_error(ex, conn, op_index=stmt.op_index, sql=stmt.sql) from ex
|
|
300
|
+
|
|
301
|
+
if dry_run:
|
|
302
|
+
conn.rollback()
|
|
303
|
+
return PatchResult("dry_run", tuple(results), None, idempotency_key, elapsed_ms())
|
|
304
|
+
|
|
305
|
+
assert log_id is not None
|
|
306
|
+
log.set_execution_time(log_id, elapsed_ms())
|
|
307
|
+
conn.commit()
|
|
308
|
+
return PatchResult("applied", tuple(results), log_id, idempotency_key, elapsed_ms())
|
|
309
|
+
|
|
310
|
+
except Exception as ex:
|
|
311
|
+
_rollback_quietly(conn)
|
|
312
|
+
error = _to_patch_error(ex, conn)
|
|
313
|
+
if not dry_run:
|
|
314
|
+
_record_failure(conn, log, changeset, payload, idempotency_key, error, started)
|
|
315
|
+
if error is ex:
|
|
316
|
+
raise
|
|
317
|
+
raise error from ex
|