atquery 2.14.0__tar.gz → 2.14.2__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 (68) hide show
  1. {atquery-2.14.0 → atquery-2.14.2}/PKG-INFO +1 -1
  2. {atquery-2.14.0 → atquery-2.14.2}/pyproject.toml +1 -1
  3. {atquery-2.14.0 → atquery-2.14.2}/pyproject.toml.orig +1 -1
  4. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/cli/ecd.py +58 -3
  5. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/cli/main.py +18 -6
  6. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/__init__.py +8 -1
  7. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/ddl.py +56 -0
  8. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/errors.py +5 -0
  9. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/seed.py +15 -3
  10. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/engine.py +51 -3
  11. {atquery-2.14.0 → atquery-2.14.2}/LICENSE +0 -0
  12. {atquery-2.14.0 → atquery-2.14.2}/README.md +0 -0
  13. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/__init__.py +0 -0
  14. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/aio/__init__.py +0 -0
  15. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/aio/engine.py +0 -0
  16. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/aio/query.py +0 -0
  17. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/api_v2.py +0 -0
  18. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/atquery2.py +0 -0
  19. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/cli/__init__.py +0 -0
  20. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/cli/columns.py +0 -0
  21. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/cli/ddl.py +0 -0
  22. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/cli/diff.py +0 -0
  23. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/cli/migrate.py +0 -0
  24. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/cli/routines.py +0 -0
  25. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/cli/scenario.py +0 -0
  26. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/cli/schemas.py +0 -0
  27. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/cli/tables.py +0 -0
  28. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/__init__.py +0 -0
  29. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/duckdb.py +0 -0
  30. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/mysql/__init__.py +0 -0
  31. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/mysql/aio.py +0 -0
  32. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/mysql/core.py +0 -0
  33. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/mysql/dump/__init__.py +0 -0
  34. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/mysql/dump/__main__.py +0 -0
  35. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/mysql/dump/core.py +0 -0
  36. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/mysql/meta.py +0 -0
  37. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/mysql/pooling.py +0 -0
  38. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/mysql/restore/__init__.py +0 -0
  39. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/mysql/restore/__main__.py +0 -0
  40. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/mysql/restore/core.py +0 -0
  41. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/dialect/sqlite.py +0 -0
  42. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/diff/__init__.py +0 -0
  43. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/diff/comparator.py +0 -0
  44. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/diff/generator.py +0 -0
  45. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/diff/git_integration.py +0 -0
  46. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/diff/models.py +0 -0
  47. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/diff/parser.py +0 -0
  48. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/_toml.py +0 -0
  49. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/catalog.py +0 -0
  50. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/diff.py +0 -0
  51. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/erd.py +0 -0
  52. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/model.py +0 -0
  53. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/parser.py +0 -0
  54. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/resolver.py +0 -0
  55. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/ecd/skeleton.py +0 -0
  56. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/factory.py +0 -0
  57. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/migration/__init__.py +0 -0
  58. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/migration/_migrator.py +0 -0
  59. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/migration/_protocol.py +0 -0
  60. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/migration/_standard.py +0 -0
  61. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/migration/_types.py +0 -0
  62. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/py.typed +0 -0
  63. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/testing/__init__.py +0 -0
  64. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/testing/creator.py +0 -0
  65. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/testing/loader.py +0 -0
  66. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/testing/schema.py +0 -0
  67. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/testing/validator.py +0 -0
  68. {atquery-2.14.0 → atquery-2.14.2}/src/atquery/type.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: atquery
3
- Version: 2.14.0
3
+ Version: 2.14.2
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.0"
7
+ version = "2.14.2"
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"
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "atquery"
7
- version = "2.14.0"
7
+ version = "2.14.2"
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"
@@ -21,6 +21,12 @@
21
21
  # VIEWのCREATE文だけを別ファイルに分離出力(毎回作り直すroutineファイル扱いにする場合など)
22
22
  atquery ecd ddl docs/ecd -o schema.sql --output-view views.sql
23
23
 
24
+ # 外部リンク(links の ref)の解決にのみ他ファイルを使い、そのファイル自体のCREATE文は出力しない
25
+ atquery ecd ddl docs/ecd/orders.ecd.md -o orders.sql --context docs/ecd/customers.ecd.md
26
+
27
+ # ["columns:X"]展開の解決にのみ他ファイルを使い、そのファイル自体のUPSERT文は出力しない
28
+ atquery ecd seed docs/ecd/orders.ecd.md -o seed.sql --context docs/ecd/common/audit.ecd.md
29
+
24
30
  # ECDファイルからER図(SVG)を生成
25
31
  atquery ecd erd docs/ecd -o schema.svg
26
32
 
@@ -68,6 +74,14 @@ def setup_parser(parser: argparse.ArgumentParser) -> None:
68
74
  help="VIEWのCREATE文の出力先。指定するとVIEWはこのファイルに分離出力され、"
69
75
  "-oにはテーブルのCREATE文のみ出力される(省略時はテーブルと同じ出力にまとめて出力される)",
70
76
  )
77
+ ddl_parser.add_argument(
78
+ "--context",
79
+ action="append",
80
+ metavar="PATH",
81
+ dest="context",
82
+ help="DDL出力には含めないが、links(fk=true)の参照先解決・[\"columns:X\"]展開にのみ使うECDファイル/"
83
+ "ディレクトリ/globパターン(複数回指定可)。PATHとの重複指定はPATH側を優先する",
84
+ )
71
85
 
72
86
  erd_parser = subparsers.add_parser(
73
87
  "erd",
@@ -94,6 +108,14 @@ def setup_parser(parser: argparse.ArgumentParser) -> None:
94
108
  help="全テーブル共通の固定値を持つ列を追加指定する(監査列`created_by`等向け、複数回指定可)。"
95
109
  "対象列が存在しないテーブルには書き込まれない",
96
110
  )
111
+ seed_parser.add_argument(
112
+ "--context",
113
+ action="append",
114
+ metavar="PATH",
115
+ dest="context",
116
+ help="UPSERT出力には含めないが、[\"columns:X\"]展開の解決にのみ使うECDファイル/ディレクトリ/glob"
117
+ "パターン(複数回指定可)。PATHとの重複指定はPATH側を優先する",
118
+ )
97
119
 
98
120
  catalog_parser = subparsers.add_parser(
99
121
  "catalog",
@@ -231,15 +253,31 @@ def _execute_ddl(args: argparse.Namespace) -> int:
231
253
  if documents is None:
232
254
  return EXIT_ERROR
233
255
 
256
+ primary_paths = {doc.path for doc in documents}
257
+
258
+ context_documents = ()
259
+ if getattr(args, "context", None):
260
+ context_documents = _load_ecd_documents_from_patterns(args.context)
261
+ if context_documents is None:
262
+ return EXIT_ERROR
263
+ context_documents = tuple(doc for doc in context_documents if doc.path not in primary_paths)
264
+
265
+ all_documents = documents + context_documents
266
+
234
267
  from atquery.ecd import (
235
268
  ECDError,
236
269
  generate_table_ddl,
237
270
  generate_view_ddl,
238
271
  resolve_documents,
272
+ sort_tables_by_fk_dependency,
239
273
  )
240
274
 
241
275
  try:
242
- table_parts = [generate_table_ddl(table, documents=documents) for table in resolve_documents(documents)]
276
+ output_tables = [table for table in resolve_documents(all_documents) if table.source_file in primary_paths]
277
+ table_parts = [
278
+ generate_table_ddl(table, documents=all_documents)
279
+ for table in sort_tables_by_fk_dependency(output_tables, documents=all_documents)
280
+ ]
243
281
  view_parts = [
244
282
  generate_view_ddl(view, schema=doc.frontmatter.schema) for doc in documents for view in doc.views
245
283
  ]
@@ -268,13 +306,25 @@ def _execute_seed(args: argparse.Namespace) -> int:
268
306
  if documents is None:
269
307
  return EXIT_ERROR
270
308
 
309
+ primary_paths = {doc.path for doc in documents}
310
+
311
+ context_documents = ()
312
+ if getattr(args, "context", None):
313
+ context_documents = _load_ecd_documents_from_patterns(args.context)
314
+ if context_documents is None:
315
+ return EXIT_ERROR
316
+ context_documents = tuple(doc for doc in context_documents if doc.path not in primary_paths)
317
+
318
+ all_documents = documents + context_documents
319
+
271
320
  from atquery.ecd import ECDError, generate_seed_sql, resolve_documents
272
321
 
273
322
  static_columns = dict(args.columns) if getattr(args, "columns", None) else {}
274
323
 
275
324
  try:
325
+ output_tables = [table for table in resolve_documents(all_documents) if table.source_file in primary_paths]
276
326
  sql, warnings = generate_seed_sql(
277
- resolve_documents(documents), dialect=args.dialect, static_columns=static_columns
327
+ output_tables, dialect=args.dialect, static_columns=static_columns, documents=all_documents
278
328
  )
279
329
  except ECDError as e:
280
330
  print(f"Error: {e}", file=sys.stderr)
@@ -418,7 +468,12 @@ def _execute_diff(args: argparse.Namespace) -> int:
418
468
 
419
469
  def _load_ecd_documents(args: argparse.Namespace):
420
470
  """位置引数(ファイル/ディレクトリ/globパターン)で指定されたECDファイルをすべてパースする。"""
421
- paths = _resolve_ecd_paths(args.paths)
471
+ return _load_ecd_documents_from_patterns(args.paths)
472
+
473
+
474
+ def _load_ecd_documents_from_patterns(patterns: list[str]):
475
+ """ファイル/ディレクトリ/globパターンの一覧で指定されたECDファイルをすべてパースする。"""
476
+ paths = _resolve_ecd_paths(patterns)
422
477
  if paths is None:
423
478
  return None
424
479
 
@@ -13,7 +13,7 @@ from urllib.parse import urlparse, urlunparse
13
13
 
14
14
  from atquery.atquery2 import ATQuery
15
15
  from atquery.dialect import create_datasource
16
- from atquery.engine import ATConnection, is_multi_statement_sql
16
+ from atquery.engine import ATConnection, ATSQLError, is_multi_statement_sql
17
17
 
18
18
  try:
19
19
  from dotenv import load_dotenv
@@ -28,6 +28,18 @@ EXIT_ERROR = 1
28
28
  EXIT_INTERRUPTED = 130 # 128 + SIGINT(2)
29
29
 
30
30
 
31
+ def format_error_for_cli(e: Exception) -> str:
32
+ """CLI表示用にエラーメッセージを整形する。
33
+
34
+ ATSQLError の場合、`str(e)` はライブラリ利用者向けに常に全文表示だが、
35
+ CLIでは巨大なDDL/スクリプトのSQL本文が端末を埋め尽くしてエラー本文が
36
+ 読めなくなるのを防ぐため、`format_for_terminal()` で省略表示にする。
37
+ """
38
+ if isinstance(e, ATSQLError):
39
+ return e.format_for_terminal()
40
+ return str(e)
41
+
42
+
31
43
  def resolve_datasource_uri(
32
44
  datasource_arg: Optional[str],
33
45
  schema_override: Optional[str],
@@ -459,7 +471,7 @@ def execute_script(conn: ATConnection, query: ATQuery, params: dict[str, Any]) -
459
471
  print("Script executed successfully", file=sys.stderr)
460
472
  return EXIT_SUCCESS
461
473
  except Exception as e:
462
- print(f"Error executing script: {e}", file=sys.stderr)
474
+ print(f"Error executing script: {format_error_for_cli(e)}", file=sys.stderr)
463
475
  return EXIT_ERROR
464
476
 
465
477
 
@@ -546,7 +558,7 @@ def execute_query(
546
558
  return EXIT_INTERRUPTED
547
559
 
548
560
  except Exception as e:
549
- print(f"Error executing query: {e}", file=sys.stderr)
561
+ print(f"Error executing query: {format_error_for_cli(e)}", file=sys.stderr)
550
562
  return EXIT_ERROR
551
563
 
552
564
 
@@ -893,13 +905,13 @@ Examples:
893
905
  )
894
906
 
895
907
  except FileNotFoundError as e:
896
- print(f"Error: {e}", file=sys.stderr)
908
+ print(f"Error: {format_error_for_cli(e)}", file=sys.stderr)
897
909
  return EXIT_ERROR
898
910
  except ValueError as e:
899
- print(f"Error: {e}", file=sys.stderr)
911
+ print(f"Error: {format_error_for_cli(e)}", file=sys.stderr)
900
912
  return EXIT_ERROR
901
913
  except Exception as e:
902
- print(f"Error: {e}", file=sys.stderr)
914
+ print(f"Error: {format_error_for_cli(e)}", file=sys.stderr)
903
915
  return EXIT_ERROR
904
916
 
905
917
 
@@ -4,11 +4,16 @@
4
4
  """
5
5
 
6
6
  from atquery.ecd.catalog import generate_catalog_markdown
7
- from atquery.ecd.ddl import generate_table_ddl, generate_view_ddl
7
+ from atquery.ecd.ddl import (
8
+ generate_table_ddl,
9
+ generate_view_ddl,
10
+ sort_tables_by_fk_dependency,
11
+ )
8
12
  from atquery.ecd.diff import SchemaDiff, compare_schema, generate_diff_sql
9
13
  from atquery.ecd.erd import generate_erd_svg
10
14
  from atquery.ecd.errors import (
11
15
  ECDCollisionError,
16
+ ECDCyclicReferenceError,
12
17
  ECDError,
13
18
  ECDParseError,
14
19
  ECDUnresolvedReferenceError,
@@ -38,6 +43,7 @@ __all__ = [
38
43
  "ColumnsBlock",
39
44
  "ColumnsBlockRef",
40
45
  "ECDCollisionError",
46
+ "ECDCyclicReferenceError",
41
47
  "ECDDocument",
42
48
  "ECDError",
43
49
  "ECDParseError",
@@ -61,4 +67,5 @@ __all__ = [
61
67
  "parse_file",
62
68
  "parse_text",
63
69
  "resolve_documents",
70
+ "sort_tables_by_fk_dependency",
64
71
  ]
@@ -13,12 +13,19 @@
13
13
  指定されていれば`CREATE TABLE`を`schema.table`として出力する。`REFERENCES`は参照元と参照先の
14
14
  `schema`が異なる場合のみ修飾し(同一なら無修飾)、クロススキーマの物理FKも制限なく生成する(MySQLは
15
15
  同一サーバ内ならクロスデータベースFKをサポートするため)。
16
+ - `sort_tables_by_fk_dependency`:`links`(`fk = true`)の依存関係に基づき、渡された`tables`同士の中でのみ
17
+ 参照先が先に来るようトポロジカルソートする(`tables`に含まれない参照先=`--context`等で解決にのみ
18
+ 使うテーブルは無視する)。自己参照(`parent_id`が自テーブルを指す等)は同一`CREATE TABLE`文内で
19
+ 解決できるためソート対象外。`tables`内で循環参照が見つかった場合は`ECDCyclicReferenceError`
20
+ (自動では解決しない。片方を`fk = false`にする等、モデル側での解決が必要)。
16
21
  """
17
22
 
23
+ import heapq
18
24
  import re
19
25
 
20
26
  from atquery.ecd.errors import (
21
27
  ECDCollisionError,
28
+ ECDCyclicReferenceError,
22
29
  ECDParseError,
23
30
  ECDUnresolvedReferenceError,
24
31
  )
@@ -64,6 +71,55 @@ def generate_view_ddl(view: ViewBlock, *, schema: str | None = None) -> str:
64
71
  return f"CREATE OR REPLACE VIEW {_quote_qualified_ident(schema, view.name)} AS\n{view.sql}\n;"
65
72
 
66
73
 
74
+ def sort_tables_by_fk_dependency(
75
+ tables: list[ResolvedTable], *, documents: tuple[ECDDocument, ...] = ()
76
+ ) -> list[ResolvedTable]:
77
+ """`tables`同士のFK依存関係(`fk = true`)に基づき、参照先が先に来るようトポロジカルソートする。
78
+
79
+ `tables`に含まれない参照先(`--context`専用ファイル等)への依存は無視する(並び替え不要なため)。
80
+ 自己参照は同一`CREATE TABLE`文内で解決できるため依存として扱わない。
81
+ 循環参照が`tables`内で見つかった場合は`ECDCyclicReferenceError`を送出する。
82
+ """
83
+ schema_by_file = _schema_by_file(documents)
84
+ index_by_key = {(schema_by_file.get(t.source_file), t.name): i for i, t in enumerate(tables)}
85
+
86
+ children: list[list[int]] = [[] for _ in tables]
87
+ indegree = [0] * len(tables)
88
+ for i, table in enumerate(tables):
89
+ depends_on: set[int] = set()
90
+ for link in table.links:
91
+ if not link.fk:
92
+ continue
93
+ ref_schema, ref_table, _ref_column = _parse_ref(link.ref)
94
+ dep_index = index_by_key.get((ref_schema, ref_table))
95
+ if dep_index is not None and dep_index != i:
96
+ depends_on.add(dep_index)
97
+ for dep_index in depends_on:
98
+ children[dep_index].append(i)
99
+ indegree[i] += 1
100
+
101
+ # Kahn法。同時に選択可能なノードの中では常に元の並び順(index)が最小のものを優先し、
102
+ # 依存関係が無いテーブル同士の並びが無用に変化しないようにする(安定ソート)
103
+ heap = [i for i, deg in enumerate(indegree) if deg == 0]
104
+ heapq.heapify(heap)
105
+ order: list[int] = []
106
+ while heap:
107
+ i = heapq.heappop(heap)
108
+ order.append(i)
109
+ for child in children[i]:
110
+ indegree[child] -= 1
111
+ if indegree[child] == 0:
112
+ heapq.heappush(heap, child)
113
+
114
+ if len(order) != len(tables):
115
+ remaining = sorted(f"{tables[i].source_file}: {tables[i].name}" for i in range(len(tables)) if indegree[i] > 0)
116
+ raise ECDCyclicReferenceError(
117
+ "table間のFK参照(fk=true)が循環しているため出力順序を決定できません: " + ", ".join(remaining)
118
+ )
119
+
120
+ return [tables[i] for i in order]
121
+
122
+
67
123
  def _column_def_with_comment(col: ColumnDef) -> str:
68
124
  if "COMMENT" in col.sql_def.upper():
69
125
  return col.sql_def # 著者が既にCOMMENTを書いている場合は上書きしない
@@ -15,3 +15,8 @@ class ECDUnresolvedReferenceError(ECDError):
15
15
 
16
16
  class ECDCollisionError(ECDError):
17
17
  """`columns` ブロック名や `sql` ブロック名がツリー内で重複している場合(候補2件以上)。"""
18
+
19
+
20
+ class ECDCyclicReferenceError(ECDError):
21
+ """DDL出力対象のテーブル同士でFK参照(`fk = true`)が循環しており、出力順序を決定できない場合。"""
22
+
@@ -14,13 +14,17 @@
14
14
  複数テーブルへのブロードキャストを前提とした仕様のため)。`values`由来の列名と衝突する場合は
15
15
  `--column`側を無視して警告する。INSERT/UPDATE両方に一律で含める(更新を防ぎたい場合は利用者が
16
16
  別途差分migrationを作成する想定)。
17
+ - 出力順序: `values`を持つテーブル同士のFK依存関係(`fk = true`)に基づき、参照先が先に来るよう
18
+ `sort_tables_by_fk_dependency`(`atquery.ecd.ddl`)でトポロジカルソートする(`ddl`と同じ理由:
19
+ UPSERTも参照先の行が先に存在しないとFK制約違反になるため)。循環参照時は`ECDCyclicReferenceError`。
17
20
  """
18
21
 
19
22
  import re
20
23
  from collections.abc import Iterable
21
24
  from typing import Any
22
25
 
23
- from atquery.ecd.model import CodeValue, ColumnDef
26
+ from atquery.ecd.ddl import sort_tables_by_fk_dependency
27
+ from atquery.ecd.model import CodeValue, ColumnDef, ECDDocument
24
28
  from atquery.ecd.resolver import ResolvedTable
25
29
 
26
30
  # MySQLの裸識別子として許可される文字(ddl.pyの規則に合わせる)
@@ -31,7 +35,11 @@ _DATE_SQL_TYPES = {"DATE", "DATETIME", "TIMESTAMP", "TIME", "YEAR"}
31
35
 
32
36
 
33
37
  def generate_seed_sql(
34
- tables: Iterable[ResolvedTable], *, dialect: str = "mysql", static_columns: dict[str, str] | None = None
38
+ tables: Iterable[ResolvedTable],
39
+ *,
40
+ dialect: str = "mysql",
41
+ static_columns: dict[str, str] | None = None,
42
+ documents: tuple[ECDDocument, ...] = (),
35
43
  ) -> tuple[str, list[str]]:
36
44
  """`values`を持つ全テーブル分のUPSERT文を生成する。
37
45
 
@@ -40,14 +48,18 @@ def generate_seed_sql(
40
48
  dialect: 出力するSQL方言("mysql" | "sqlite")
41
49
  static_columns: `--column NAME VALUE`で指定された全テーブル共通の固定値
42
50
  (例: 監査列`created_by`/`created_id`)。対象列が無いテーブルはサイレントにスキップする。
51
+ documents: FK参照の`schema`解決に使う`ECDDocument`一覧(出力順序のトポロジカルソートに使用)。
43
52
 
44
53
  Returns:
45
54
  tuple: (UPSERT文を`\\n\\n`で連結したSQL文字列, 警告メッセージのリスト)
46
55
  """
56
+ seed_tables = [table for table in tables if any(col.values for col in table.columns)]
57
+ seed_tables = sort_tables_by_fk_dependency(seed_tables, documents=documents)
58
+
47
59
  sql_parts: list[str] = []
48
60
  warnings: list[str] = []
49
61
 
50
- for table in tables:
62
+ for table in seed_tables:
51
63
  result = _generate_table_seed(table, dialect=dialect, static_columns=static_columns or {})
52
64
  if result is None:
53
65
  continue
@@ -655,8 +655,14 @@ class ATSQLError(Exception):
655
655
 
656
656
  super().__init__(message)
657
657
 
658
- def _format_concise(self) -> str:
659
- """簡潔なエラー出力フォーマット(AI Ready)"""
658
+ def _format_concise(self, max_sql_lines: int | None = None) -> str:
659
+ """簡潔なエラー出力フォーマット(AI Ready)
660
+
661
+ Args:
662
+ max_sql_lines: SQL本文の表示上限行数。Noneの場合は省略せず全文を表示する
663
+ (ライブラリとしての既定動作。ログ収集等で全文が必要なケースを壊さないため)。
664
+ CLIでの表示など、省略が望ましい場面でのみ明示的に指定する。
665
+ """
660
666
  lines = [str(self.orig)]
661
667
 
662
668
  # ファイルがある場合のみ表示(無駄な情報を削減)
@@ -668,10 +674,51 @@ class ATSQLError(Exception):
668
674
  if self.sql:
669
675
  # SQL本文を区切り線で分離
670
676
  lines.append("-----")
671
- lines.append(self.sql)
677
+ sql_text = self.sql if max_sql_lines is None else self._truncate_sql(self.sql, max_sql_lines)
678
+ lines.append(sql_text)
672
679
 
673
680
  return "\n".join(lines)
674
681
 
682
+ @staticmethod
683
+ def _truncate_sql(sql: str, max_lines: int) -> str:
684
+ """SQL本文が長い場合、先頭・末尾のみ残して中間を省略します。
685
+
686
+ 巨大なDDL/スクリプトをそのまま表示すると、末尾に大量の行が続き、
687
+ 直前に表示されているエラー本文が画面外に押し流されて読めなくなる。
688
+ `.sql` 属性には省略前の全文が保持されるため、情報自体は失われない。
689
+ """
690
+ sql_lines = sql.splitlines()
691
+ if max_lines <= 0 or len(sql_lines) <= max_lines:
692
+ return sql
693
+
694
+ head = max_lines // 2
695
+ tail = max_lines - head
696
+ omitted = len(sql_lines) - head - tail
697
+ return "\n".join([
698
+ *sql_lines[:head],
699
+ f"... ({omitted} lines omitted; see `.sql` attribute or set ATQUERY_ERROR_SQL_MAX_LINES=0 for full text) ...",
700
+ *sql_lines[-tail:],
701
+ ])
702
+
703
+ def format_for_terminal(self, max_sql_lines: int | None = None) -> str:
704
+ """ターミナル表示用の簡潔フォーマットを返します(CLI専用)。
705
+
706
+ `str(error)` はライブラリ利用者(ログ収集・Sentry連携等)のために常に全文を返すが、
707
+ こちらはCLIでの視認性を優先し、巨大なSQL本文を省略する。
708
+ `max_sql_lines` を省略した場合、環境変数 `ATQUERY_ERROR_SQL_MAX_LINES`(既定40、0以下で無制限)に従う。
709
+ """
710
+ import os
711
+ if os.getenv("ATQUERY_DEBUG_MODE") == "1":
712
+ return self.message
713
+
714
+ if max_sql_lines is None:
715
+ try:
716
+ max_sql_lines = int(os.getenv("ATQUERY_ERROR_SQL_MAX_LINES", "40"))
717
+ except ValueError:
718
+ max_sql_lines = 40
719
+
720
+ return self._format_concise(max_sql_lines=max_sql_lines)
721
+
675
722
  @property
676
723
  def errno(self) -> int | None:
677
724
  """元のデータベースエラーからエラー番号を取得します。
@@ -695,6 +742,7 @@ class ATSQLError(Exception):
695
742
  import os
696
743
  if os.getenv("ATQUERY_DEBUG_MODE") == "1":
697
744
  return self.message
745
+ # ライブラリの既定動作としては全文表示(ログ収集等で情報を失わないため)
698
746
  return self._format_concise()
699
747
 
700
748
 
File without changes
File without changes
File without changes
File without changes
File without changes