atquery 2.13.5__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.13.5 → atquery-2.14.2}/PKG-INFO +1 -1
  2. {atquery-2.13.5 → atquery-2.14.2}/pyproject.toml +1 -1
  3. {atquery-2.13.5 → atquery-2.14.2}/pyproject.toml.orig +1 -1
  4. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/cli/columns.py +16 -8
  5. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/cli/ddl.py +17 -6
  6. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/cli/diff.py +2 -1
  7. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/cli/ecd.py +61 -5
  8. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/cli/main.py +77 -8
  9. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/cli/migrate.py +24 -14
  10. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/cli/routines.py +17 -6
  11. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/cli/scenario.py +3 -3
  12. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/cli/schemas.py +11 -2
  13. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/cli/tables.py +16 -8
  14. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/__init__.py +8 -1
  15. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/catalog.py +9 -0
  16. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/ddl.py +56 -0
  17. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/errors.py +5 -0
  18. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/seed.py +15 -3
  19. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/engine.py +51 -3
  20. {atquery-2.13.5 → atquery-2.14.2}/LICENSE +0 -0
  21. {atquery-2.13.5 → atquery-2.14.2}/README.md +0 -0
  22. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/__init__.py +0 -0
  23. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/aio/__init__.py +0 -0
  24. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/aio/engine.py +0 -0
  25. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/aio/query.py +0 -0
  26. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/api_v2.py +0 -0
  27. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/atquery2.py +0 -0
  28. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/cli/__init__.py +0 -0
  29. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/__init__.py +0 -0
  30. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/duckdb.py +0 -0
  31. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/mysql/__init__.py +0 -0
  32. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/mysql/aio.py +0 -0
  33. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/mysql/core.py +0 -0
  34. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/mysql/dump/__init__.py +0 -0
  35. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/mysql/dump/__main__.py +0 -0
  36. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/mysql/dump/core.py +0 -0
  37. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/mysql/meta.py +0 -0
  38. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/mysql/pooling.py +0 -0
  39. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/mysql/restore/__init__.py +0 -0
  40. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/mysql/restore/__main__.py +0 -0
  41. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/mysql/restore/core.py +0 -0
  42. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/dialect/sqlite.py +0 -0
  43. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/diff/__init__.py +0 -0
  44. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/diff/comparator.py +0 -0
  45. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/diff/generator.py +0 -0
  46. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/diff/git_integration.py +0 -0
  47. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/diff/models.py +0 -0
  48. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/diff/parser.py +0 -0
  49. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/_toml.py +0 -0
  50. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/diff.py +0 -0
  51. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/erd.py +0 -0
  52. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/model.py +0 -0
  53. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/parser.py +0 -0
  54. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/resolver.py +0 -0
  55. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/ecd/skeleton.py +0 -0
  56. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/factory.py +0 -0
  57. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/migration/__init__.py +0 -0
  58. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/migration/_migrator.py +0 -0
  59. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/migration/_protocol.py +0 -0
  60. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/migration/_standard.py +0 -0
  61. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/migration/_types.py +0 -0
  62. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/py.typed +0 -0
  63. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/testing/__init__.py +0 -0
  64. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/testing/creator.py +0 -0
  65. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/testing/loader.py +0 -0
  66. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/testing/schema.py +0 -0
  67. {atquery-2.13.5 → atquery-2.14.2}/src/atquery/testing/validator.py +0 -0
  68. {atquery-2.13.5 → 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.13.5
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.13.5"
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.13.5"
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"
@@ -9,6 +9,8 @@ from atquery.cli.main import (
9
9
  EXIT_SUCCESS,
10
10
  OutputWriter,
11
11
  add_output_format_arguments,
12
+ parse_qualified_name,
13
+ resolve_datasource_uri,
12
14
  )
13
15
  from atquery.dialect import create_datasource
14
16
 
@@ -55,8 +57,11 @@ Examples:
55
57
  # Pattern matching for tables
56
58
  atquery columns -d mysql://user:pass@localhost/mydb -n "user%"
57
59
 
58
- # Pattern matching for schemas
59
- atquery columns -d mysql://user:pass@localhost/ -s "mydb%" -n "user%"
60
+ # Pattern matching across schemas (schema.table notation)
61
+ atquery columns -d mysql://user:pass@localhost/ -n "tenant_%.user%"
62
+
63
+ # Override the connection schema for this command only
64
+ atquery columns -d mysql://user:pass@localhost/ -s mydb
60
65
 
61
66
  # Output as JSON
62
67
  atquery columns -d mysql://user:pass@localhost/mydb --json
@@ -73,11 +78,13 @@ Examples:
73
78
  parser.add_argument(
74
79
  "-s",
75
80
  "--schema",
76
- help="Schema name or pattern (%%, _ wildcards supported). If not specified, uses default schema.",
81
+ required=False,
82
+ default=argparse.SUPPRESS,
83
+ help="Override the schema/database segment of the resolved connection URI (applies to this command only)",
77
84
  )
78
85
 
79
86
  parser.add_argument(
80
- "-n", "--name", help="Table name or pattern (%%, _ wildcards supported). If not specified, returns all tables."
87
+ "-n", "--name", help="Table name or pattern (%%, _ wildcards supported). Use 'schema.table' notation (e.g. 'tenant_%%.orders') to also filter by schema. If not specified, returns all tables in the connected schema."
81
88
  )
82
89
 
83
90
  add_output_format_arguments(parser)
@@ -93,8 +100,8 @@ def execute_columns(args: argparse.Namespace) -> int:
93
100
  int: 終了コード
94
101
  """
95
102
 
96
- # データベース接続文字列の取得(優先順位: 引数 > 環境変数)
97
- database_uri = args.datasource or os.environ.get("ATQUERY_DATASOURCE")
103
+ # データベース接続文字列の取得(優先順位: 引数 > 環境変数)、-sがあればschema部分を上書き
104
+ database_uri = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
98
105
 
99
106
  if not database_uri:
100
107
  print(
@@ -107,9 +114,10 @@ def execute_columns(args: argparse.Namespace) -> int:
107
114
  # データソースの作成
108
115
  datasource = create_datasource(database_uri)
109
116
 
110
- # 構造情報の取得
117
+ # 構造情報の取得(-nは 'schema.table' 形式ならschema/tableに分割)
111
118
  with datasource.connect() as conn:
112
- result = conn.meta.columns(schema=args.schema, table=args.name)
119
+ schema_filter, name_filter = parse_qualified_name(args.name)
120
+ result = conn.meta.columns(schema=schema_filter, table=name_filter)
113
121
 
114
122
  # 出力処理
115
123
  json_indent = None if args.compact else 2
@@ -9,6 +9,8 @@ from atquery.cli.main import (
9
9
  EXIT_SUCCESS,
10
10
  OutputWriter,
11
11
  add_output_format_arguments,
12
+ parse_qualified_name,
13
+ resolve_datasource_uri,
12
14
  )
13
15
  from atquery.dialect import create_datasource
14
16
 
@@ -50,6 +52,12 @@ Examples:
50
52
  # Get DDL for routines (procedures/functions)
51
53
  atquery ddl -d mysql://user:pass@localhost/mydb -n "my_proc%"
52
54
 
55
+ # Pattern matching across schemas (schema.object notation)
56
+ atquery ddl -d mysql://user:pass@localhost/ -n "tenant_%.user%"
57
+
58
+ # Override the connection schema for this command only
59
+ atquery ddl -d mysql://user:pass@localhost/ -s mydb -n users
60
+
53
61
  # Output as JSON
54
62
  atquery ddl -d mysql://user:pass@localhost/mydb -n users --json
55
63
  """
@@ -65,11 +73,13 @@ Examples:
65
73
  parser.add_argument(
66
74
  "-s",
67
75
  "--schema",
68
- help="Schema name or pattern (%%, _ wildcards supported). If not specified, uses default schema.",
76
+ required=False,
77
+ default=argparse.SUPPRESS,
78
+ help="Override the schema/database segment of the resolved connection URI (applies to this command only)",
69
79
  )
70
80
 
71
81
  parser.add_argument(
72
- "-n", "--name", help="Object name or pattern (%%, _ wildcards supported). If not specified, returns all objects (tables, views, routines)."
82
+ "-n", "--name", help="Object name or pattern (%%, _ wildcards supported). Use 'schema.object' notation (e.g. 'tenant_%%.orders') to also filter by schema. If not specified, returns all objects (tables, views, routines) in the connected schema."
73
83
  )
74
84
 
75
85
  add_output_format_arguments(parser)
@@ -85,8 +95,8 @@ def execute_ddl(args: argparse.Namespace) -> int:
85
95
  int: 終了コード
86
96
  """
87
97
 
88
- # データベース接続文字列の取得(優先順位: 引数 > 環境変数)
89
- database_uri = args.datasource or os.environ.get("ATQUERY_DATASOURCE")
98
+ # データベース接続文字列の取得(優先順位: 引数 > 環境変数)、-sがあればschema部分を上書き
99
+ database_uri = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
90
100
 
91
101
  if not database_uri:
92
102
  print(
@@ -99,9 +109,10 @@ def execute_ddl(args: argparse.Namespace) -> int:
99
109
  # データソースの作成
100
110
  datasource = create_datasource(database_uri)
101
111
 
102
- # CREATE文の取得
112
+ # CREATE文の取得(-nは 'schema.object' 形式ならschema/objectに分割)
103
113
  with datasource.connect() as conn:
104
- result = conn.meta.ddl(schema=args.schema, name=args.name)
114
+ schema_filter, name_filter = parse_qualified_name(args.name)
115
+ result = conn.meta.ddl(schema=schema_filter, name=name_filter)
105
116
 
106
117
  # 出力処理
107
118
  json_indent = None if args.compact else 2
@@ -83,7 +83,8 @@ Note:
83
83
  "--schema",
84
84
  type=str,
85
85
  metavar="SCHEMA",
86
- help="データソースモード: DB側の比較対象スキーマ名",
86
+ default=argparse.SUPPRESS,
87
+ help="データソースモード: DB側の比較対象スキーマ名(ルートの -s/--schema と共通、省略時は継承される)",
87
88
  )
88
89
  parser.add_argument(
89
90
  "-o", "--output",
@@ -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
 
@@ -52,7 +58,7 @@ def setup_parser(parser: argparse.ArgumentParser) -> None:
52
58
  help="Generate an ECD skeleton from an existing database schema",
53
59
  )
54
60
  _add_datasource_arg(skeleton_parser)
55
- skeleton_parser.add_argument("-s", "--schema", help="Schema name")
61
+ skeleton_parser.add_argument("-s", "--schema", default=argparse.SUPPRESS, help="Schema name(ルートの -s/--schema と共通、省略時は継承される)")
56
62
  skeleton_parser.add_argument("-n", "--name", help="Table/view name or pattern (%%, _ wildcards supported)")
57
63
  skeleton_parser.add_argument("-o", "--output", help="出力先ファイル(省略時は標準出力)")
58
64
 
@@ -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",
@@ -120,7 +142,7 @@ def setup_parser(parser: argparse.ArgumentParser) -> None:
120
142
  )
121
143
  _add_ecd_source_args(diff_parser)
122
144
  _add_datasource_arg(diff_parser)
123
- diff_parser.add_argument("-s", "--schema", help="Schema name(DB側の比較対象スキーマ)")
145
+ diff_parser.add_argument("-s", "--schema", default=argparse.SUPPRESS, help="Schema name(DB側の比較対象スキーマ。ルートの -s/--schema と共通、省略時は継承される)")
124
146
  diff_parser.add_argument(
125
147
  "--rename",
126
148
  action="append",
@@ -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)
@@ -347,6 +397,7 @@ def _execute_catalog(args: argparse.Namespace) -> int:
347
397
  no_diagram=args.no_diagram,
348
398
  diagram_theme=args.diagram_theme,
349
399
  all_source_files=[doc.path for doc in documents],
400
+ schema_by_file={doc.path: doc.frontmatter.schema for doc in documents},
350
401
  )
351
402
  except ECDError as e:
352
403
  print(f"Error: {e}", file=sys.stderr)
@@ -417,7 +468,12 @@ def _execute_diff(args: argparse.Namespace) -> int:
417
468
 
418
469
  def _load_ecd_documents(args: argparse.Namespace):
419
470
  """位置引数(ファイル/ディレクトリ/globパターン)で指定されたECDファイルをすべてパースする。"""
420
- 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)
421
477
  if paths is None:
422
478
  return None
423
479
 
@@ -9,10 +9,11 @@ import sys
9
9
  from io import StringIO
10
10
  from pathlib import Path
11
11
  from typing import Any, Optional, Sequence, cast
12
+ from urllib.parse import urlparse, urlunparse
12
13
 
13
14
  from atquery.atquery2 import ATQuery
14
15
  from atquery.dialect import create_datasource
15
- from atquery.engine import ATConnection, is_multi_statement_sql
16
+ from atquery.engine import ATConnection, ATSQLError, is_multi_statement_sql
16
17
 
17
18
  try:
18
19
  from dotenv import load_dotenv
@@ -27,6 +28,63 @@ EXIT_ERROR = 1
27
28
  EXIT_INTERRUPTED = 130 # 128 + SIGINT(2)
28
29
 
29
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
+
43
+ def resolve_datasource_uri(
44
+ datasource_arg: Optional[str],
45
+ schema_override: Optional[str],
46
+ env_var: str = "ATQUERY_DATASOURCE",
47
+ ) -> Optional[str]:
48
+ """-d/環境変数からURIを解決し、-s指定があればschema(database)部分だけ差し替える
49
+
50
+ ADR-0039: -s/--schema はCLI全体で「接続URIのschema/database部分の上書き」を意味する。
51
+ クエリパラメータ・ポート・認証情報は保ったまま、path部分だけを置き換える。
52
+
53
+ Args:
54
+ datasource_arg: -d/--datasource で渡された値(未指定ならNone)
55
+ schema_override: -s/--schema で渡された値(未指定ならNone)
56
+ env_var: フォールバック先の環境変数名
57
+
58
+ Returns:
59
+ str | None: 解決済みのURI(datasource_arg・環境変数のいずれも無ければNone)
60
+ """
61
+ uri = datasource_arg or os.environ.get(env_var)
62
+ if uri and schema_override:
63
+ parsed = urlparse(uri)
64
+ uri = urlunparse(parsed._replace(path="/" + schema_override))
65
+ return uri
66
+
67
+
68
+ def parse_qualified_name(name: Optional[str]) -> tuple[Optional[str], Optional[str]]:
69
+ """-n/--name の値を 'schema.table' 形式ならschemaとtableに分割する(ADR-0039)
70
+
71
+ 最初の '.' で分割する。ドットが含まれない場合はschema側をNoneとし、
72
+ 値全体をtable側のパターンとして扱う(従来通り、接続中のデフォルトスキーマが対象)。
73
+
74
+ Args:
75
+ name: -n/--name で渡された値
76
+
77
+ Returns:
78
+ tuple[str | None, str | None]: (schemaパターン, table/routine/objectパターン)
79
+ """
80
+ if name is None:
81
+ return None, None
82
+ if "." in name:
83
+ schema, _, rest = name.partition(".")
84
+ return schema, rest
85
+ return None, name
86
+
87
+
30
88
  def get_version() -> str:
31
89
  """パッケージのバージョンを取得
32
90
 
@@ -413,7 +471,7 @@ def execute_script(conn: ATConnection, query: ATQuery, params: dict[str, Any]) -
413
471
  print("Script executed successfully", file=sys.stderr)
414
472
  return EXIT_SUCCESS
415
473
  except Exception as e:
416
- print(f"Error executing script: {e}", file=sys.stderr)
474
+ print(f"Error executing script: {format_error_for_cli(e)}", file=sys.stderr)
417
475
  return EXIT_ERROR
418
476
 
419
477
 
@@ -500,7 +558,7 @@ def execute_query(
500
558
  return EXIT_INTERRUPTED
501
559
 
502
560
  except Exception as e:
503
- print(f"Error executing query: {e}", file=sys.stderr)
561
+ print(f"Error executing query: {format_error_for_cli(e)}", file=sys.stderr)
504
562
  return EXIT_ERROR
505
563
 
506
564
 
@@ -535,6 +593,10 @@ Examples:
535
593
  atquery -f query.sql
536
594
  echo "SELECT * FROM users" | atquery
537
595
 
596
+ # Override only the schema/database segment of ATQUERY_DATASOURCE for this run
597
+ atquery -s another_db -f query.sql
598
+ atquery -s another_db tables
599
+
538
600
  # Pass parameters
539
601
  atquery -f query.sql -p name=John -p age=30
540
602
 
@@ -640,6 +702,13 @@ Examples:
640
702
  help="Database connection string (or set ATQUERY_DATASOURCE env var)",
641
703
  )
642
704
 
705
+ parser.add_argument(
706
+ "-s",
707
+ "--schema",
708
+ required=False,
709
+ help="Override the schema/database segment of the resolved connection URI (applies to the root command and all subcommands)",
710
+ )
711
+
643
712
  sql_source_group = parser.add_mutually_exclusive_group()
644
713
  sql_source_group.add_argument(
645
714
  "-f", "--file", required=False, help="SQL file path (use '-' or omit for stdin)"
@@ -745,8 +814,8 @@ Examples:
745
814
  from atquery.cli.ecd import execute_ecd
746
815
  return execute_ecd(args)
747
816
 
748
- # データベース接続文字列の取得(優先順位: 引数 > 環境変数)
749
- database_uri = args.datasource or os.environ.get("ATQUERY_DATASOURCE")
817
+ # データベース接続文字列の取得(優先順位: 引数 > 環境変数)、-s/--schemaがあればschema部分を上書き
818
+ database_uri = resolve_datasource_uri(args.datasource, args.schema)
750
819
 
751
820
  # --print-query でない場合は database_uri が必須
752
821
  if not args.print_query and not database_uri:
@@ -836,13 +905,13 @@ Examples:
836
905
  )
837
906
 
838
907
  except FileNotFoundError as e:
839
- print(f"Error: {e}", file=sys.stderr)
908
+ print(f"Error: {format_error_for_cli(e)}", file=sys.stderr)
840
909
  return EXIT_ERROR
841
910
  except ValueError as e:
842
- print(f"Error: {e}", file=sys.stderr)
911
+ print(f"Error: {format_error_for_cli(e)}", file=sys.stderr)
843
912
  return EXIT_ERROR
844
913
  except Exception as e:
845
- print(f"Error: {e}", file=sys.stderr)
914
+ print(f"Error: {format_error_for_cli(e)}", file=sys.stderr)
846
915
  return EXIT_ERROR
847
916
 
848
917
 
@@ -5,7 +5,7 @@ import os
5
5
  import sys
6
6
  from typing import Any
7
7
 
8
- from atquery.cli.main import EXIT_ERROR, EXIT_SUCCESS
8
+ from atquery.cli.main import EXIT_ERROR, EXIT_SUCCESS, resolve_datasource_uri
9
9
  from atquery.dialect import create_datasource
10
10
 
11
11
 
@@ -45,19 +45,19 @@ def _resolve_migration(args: argparse.Namespace) -> Any | None:
45
45
  return cls()
46
46
 
47
47
  if args.dir:
48
- database_uri = getattr(args, "datasource", None) or os.environ.get("ATQUERY_DATASOURCE", "")
49
- if database_uri.startswith("mysql"):
48
+ database_uri = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
49
+ if database_uri and database_uri.startswith("mysql"):
50
50
  return StandardMySQLMigration(
51
51
  migrations_dir=args.dir,
52
52
  name=args.name,
53
- table_prefix=args.table_prefix,
53
+ table_prefix=args.migration_table_prefix,
54
54
  baseline_revision=args.baseline_revision,
55
- schema=args.schema,
55
+ schema=args.migration_schema,
56
56
  )
57
57
  return StandardMigration(
58
58
  migrations_dir=args.dir,
59
59
  name=args.name,
60
- table_prefix=args.table_prefix,
60
+ table_prefix=args.migration_table_prefix,
61
61
  baseline_revision=args.baseline_revision,
62
62
  )
63
63
 
@@ -77,6 +77,12 @@ def _add_common_args(parser: argparse.ArgumentParser) -> None:
77
77
  default=argparse.SUPPRESS,
78
78
  help="Database connection string (env: ATQUERY_DATASOURCE)",
79
79
  )
80
+ parser.add_argument(
81
+ "-s",
82
+ "--schema",
83
+ default=argparse.SUPPRESS,
84
+ help="Override the schema/database segment of the resolved connection URI (applies to this command only)",
85
+ )
80
86
  parser.add_argument(
81
87
  "--dir",
82
88
  default=os.environ.get("ATQUERY_MIGRATION_DIR"),
@@ -95,9 +101,9 @@ def _add_common_args(parser: argparse.ArgumentParser) -> None:
95
101
  help="Migration name key in the management table (env: ATQUERY_MIGRATION_NAME, default: default)",
96
102
  )
97
103
  parser.add_argument(
98
- "--table-prefix",
104
+ "--migration-table-prefix",
99
105
  default=os.environ.get("ATQUERY_MIGRATION_TABLE_PREFIX", "atquery"),
100
- dest="table_prefix",
106
+ dest="migration_table_prefix",
101
107
  help="Prefix for management table names (env: ATQUERY_MIGRATION_TABLE_PREFIX, default: atquery)",
102
108
  )
103
109
  parser.add_argument(
@@ -109,8 +115,9 @@ def _add_common_args(parser: argparse.ArgumentParser) -> None:
109
115
  help="Initial revision when no record exists; scripts up to N are skipped (env: ATQUERY_MIGRATION_BASELINE_REVISION, default: 0)",
110
116
  )
111
117
  parser.add_argument(
112
- "--schema",
118
+ "--migration-schema",
113
119
  default=os.environ.get("ATQUERY_MIGRATION_SCHEMA"),
120
+ dest="migration_schema",
114
121
  metavar="SCHEMA",
115
122
  help="Schema for management tables, MySQL only (env: ATQUERY_MIGRATION_SCHEMA)",
116
123
  )
@@ -142,11 +149,14 @@ Examples:
142
149
  atquery migrate run --dir ddl/migrate --refresh-routines
143
150
 
144
151
  # Multi-schema: isolate management tables per schema
145
- atquery migrate run --dir ddl/app --name app --schema infra
146
- atquery migrate run --dir ddl/log --name log --schema infra
152
+ atquery migrate run --dir ddl/app --name app --migration-schema infra
153
+ atquery migrate run --dir ddl/log --name log --migration-schema infra
147
154
 
148
155
  # Change management table prefix
149
- atquery migrate run --dir ddl/migrate --table-prefix _mig
156
+ atquery migrate run --dir ddl/migrate --migration-table-prefix _mig
157
+
158
+ # Apply migrations against a different schema than ATQUERY_DATASOURCE points to
159
+ atquery migrate run --dir ddl/migrate -s another_db
150
160
 
151
161
  # First-time adoption on existing DB (skip scripts up to revision 15)
152
162
  atquery migrate run --dir ddl/migrate --baseline-revision 15
@@ -202,7 +212,7 @@ def execute_migrate(args: argparse.Namespace) -> int:
202
212
 
203
213
 
204
214
  def _execute_status(args: argparse.Namespace) -> int:
205
- args.datasource = getattr(args, "datasource", None) or os.environ.get("ATQUERY_DATASOURCE")
215
+ args.datasource = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
206
216
  if not args.datasource:
207
217
  print(
208
218
  "Error: -d/--datasource または ATQUERY_DATASOURCE 環境変数を指定してください",
@@ -240,7 +250,7 @@ def _execute_status(args: argparse.Namespace) -> int:
240
250
 
241
251
 
242
252
  def _execute_run(args: argparse.Namespace) -> int:
243
- args.datasource = getattr(args, "datasource", None) or os.environ.get("ATQUERY_DATASOURCE")
253
+ args.datasource = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
244
254
  if not args.datasource:
245
255
  print(
246
256
  "Error: -d/--datasource または ATQUERY_DATASOURCE 環境変数を指定してください",
@@ -9,6 +9,8 @@ from atquery.cli.main import (
9
9
  EXIT_SUCCESS,
10
10
  OutputWriter,
11
11
  add_output_format_arguments,
12
+ parse_qualified_name,
13
+ resolve_datasource_uri,
12
14
  )
13
15
  from atquery.dialect import create_datasource
14
16
 
@@ -41,6 +43,12 @@ Examples:
41
43
  # Pattern matching for routines
42
44
  atquery routines -d mysql://user:pass@localhost/mydb -n "calc_%"
43
45
 
46
+ # Pattern matching across schemas (schema.routine notation)
47
+ atquery routines -d mysql://user:pass@localhost/ -n "tenant_%.calc_%"
48
+
49
+ # Override the connection schema for this command only
50
+ atquery routines -d mysql://user:pass@localhost/ -s mydb
51
+
44
52
  # Output as JSON
45
53
  atquery routines -d mysql://user:pass@localhost/mydb --json
46
54
  """
@@ -56,11 +64,13 @@ Examples:
56
64
  parser.add_argument(
57
65
  "-s",
58
66
  "--schema",
59
- help="Schema name or pattern (%%, _ wildcards supported). If not specified, uses default schema.",
67
+ required=False,
68
+ default=argparse.SUPPRESS,
69
+ help="Override the schema/database segment of the resolved connection URI (applies to this command only)",
60
70
  )
61
71
 
62
72
  parser.add_argument(
63
- "-n", "--name", help="Routine name or pattern (%%, _ wildcards supported). If not specified, returns all routines."
73
+ "-n", "--name", help="Routine name or pattern (%%, _ wildcards supported). Use 'schema.routine' notation (e.g. 'tenant_%%.calc_%%') to also filter by schema. If not specified, returns all routines in the connected schema."
64
74
  )
65
75
 
66
76
  add_output_format_arguments(parser)
@@ -76,8 +86,8 @@ def execute_routines(args: argparse.Namespace) -> int:
76
86
  int: 終了コード
77
87
  """
78
88
 
79
- # データベース接続文字列の取得(優先順位: 引数 > 環境変数)
80
- database_uri = args.datasource or os.environ.get("ATQUERY_DATASOURCE")
89
+ # データベース接続文字列の取得(優先順位: 引数 > 環境変数)、-sがあればschema部分を上書き
90
+ database_uri = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
81
91
 
82
92
  if not database_uri:
83
93
  print(
@@ -90,9 +100,10 @@ def execute_routines(args: argparse.Namespace) -> int:
90
100
  # データソースの作成
91
101
  datasource = create_datasource(database_uri)
92
102
 
93
- # ルーチン構造の取得
103
+ # ルーチン構造の取得(-nは 'schema.routine' 形式ならschema/routineに分割)
94
104
  with datasource.connect() as conn:
95
- result = conn.meta.routines(schema=args.schema, routine=args.name)
105
+ schema_filter, name_filter = parse_qualified_name(args.name)
106
+ result = conn.meta.routines(schema=schema_filter, routine=name_filter)
96
107
 
97
108
  # 出力処理
98
109
  json_indent = None if args.compact else 2
@@ -27,6 +27,8 @@ import argparse
27
27
  import sys
28
28
  from pathlib import Path
29
29
 
30
+ from atquery.cli.main import resolve_datasource_uri
31
+
30
32
 
31
33
  def setup_parser(parser: argparse.ArgumentParser) -> None:
32
34
  """scenario サブコマンドのパーサー設定"""
@@ -97,9 +99,7 @@ def execute_scenario(args) -> int:
97
99
 
98
100
  import atquery
99
101
 
100
- database_uri = getattr(args, "datasource", None)
101
- import os
102
- database_uri = database_uri or os.environ.get("ATQUERY_DATASOURCE")
102
+ database_uri = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
103
103
 
104
104
  if not database_uri:
105
105
  print(
@@ -9,6 +9,7 @@ from atquery.cli.main import (
9
9
  EXIT_SUCCESS,
10
10
  OutputWriter,
11
11
  add_output_format_arguments,
12
+ resolve_datasource_uri,
12
13
  )
13
14
  from atquery.dialect import create_datasource
14
15
 
@@ -53,6 +54,14 @@ Examples:
53
54
  help="Database connection string (e.g., sqlite:///path/to/db.sqlite3, mysql://user:pass@host:port/db). Falls back to ATQUERY_DATASOURCE environment variable if not specified.",
54
55
  )
55
56
 
57
+ parser.add_argument(
58
+ "-s",
59
+ "--schema",
60
+ required=False,
61
+ default=argparse.SUPPRESS,
62
+ help="Override the schema/database segment of the resolved connection URI (applies to this command only)",
63
+ )
64
+
56
65
  parser.add_argument(
57
66
  "-n",
58
67
  "--name",
@@ -72,8 +81,8 @@ def execute_schemas(args: argparse.Namespace) -> int:
72
81
  int: 終了コード
73
82
  """
74
83
 
75
- # データベース接続文字列の取得(優先順位: 引数 > 環境変数)
76
- database_uri = args.datasource or os.environ.get("ATQUERY_DATASOURCE")
84
+ # データベース接続文字列の取得(優先順位: 引数 > 環境変数)、-sがあればschema部分を上書き
85
+ database_uri = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
77
86
 
78
87
  if not database_uri:
79
88
  print(
@@ -9,6 +9,8 @@ from atquery.cli.main import (
9
9
  EXIT_SUCCESS,
10
10
  OutputWriter,
11
11
  add_output_format_arguments,
12
+ parse_qualified_name,
13
+ resolve_datasource_uri,
12
14
  )
13
15
  from atquery.dialect import create_datasource
14
16
 
@@ -61,8 +63,11 @@ Examples:
61
63
  # Pattern matching for tables
62
64
  atquery tables -d mysql://user:pass@localhost/mydb -n "user%"
63
65
 
64
- # Pattern matching for schemas
65
- atquery tables -d mysql://user:pass@localhost/ -s "mydb%" -n "user%"
66
+ # Pattern matching across schemas (schema.table notation)
67
+ atquery tables -d mysql://user:pass@localhost/ -n "tenant_%.user%"
68
+
69
+ # Override the connection schema for this command only
70
+ atquery tables -d mysql://user:pass@localhost/ -s mydb
66
71
 
67
72
  # Output as JSON
68
73
  atquery tables -d mysql://user:pass@localhost/mydb --json
@@ -79,11 +84,13 @@ Examples:
79
84
  parser.add_argument(
80
85
  "-s",
81
86
  "--schema",
82
- help="Schema name or pattern (%%, _ wildcards supported). If not specified, uses default schema.",
87
+ required=False,
88
+ default=argparse.SUPPRESS,
89
+ help="Override the schema/database segment of the resolved connection URI (applies to this command only)",
83
90
  )
84
91
 
85
92
  parser.add_argument(
86
- "-n", "--name", help="Table/view name or pattern (%%, _ wildcards supported). If not specified, returns all tables and views."
93
+ "-n", "--name", help="Table/view name or pattern (%%, _ wildcards supported). Use 'schema.table' notation (e.g. 'tenant_%%.orders') to also filter by schema. If not specified, returns all tables and views in the connected schema."
87
94
  )
88
95
 
89
96
  add_output_format_arguments(parser)
@@ -99,8 +106,8 @@ def execute_tables(args: argparse.Namespace) -> int:
99
106
  int: 終了コード
100
107
  """
101
108
 
102
- # データベース接続文字列の取得(優先順位: 引数 > 環境変数)
103
- database_uri = args.datasource or os.environ.get("ATQUERY_DATASOURCE")
109
+ # データベース接続文字列の取得(優先順位: 引数 > 環境変数)、-sがあればschema部分を上書き
110
+ database_uri = resolve_datasource_uri(getattr(args, "datasource", None), getattr(args, "schema", None))
104
111
 
105
112
  if not database_uri:
106
113
  print(
@@ -113,9 +120,10 @@ def execute_tables(args: argparse.Namespace) -> int:
113
120
  # データソースの作成
114
121
  datasource = create_datasource(database_uri)
115
122
 
116
- # テーブル一覧の取得
123
+ # テーブル一覧の取得(-nは 'schema.table' 形式ならschema/tableに分割)
117
124
  with datasource.connect() as conn:
118
- result = conn.meta.tables(schema=args.schema, table=args.name)
125
+ schema_filter, name_filter = parse_qualified_name(args.name)
126
+ result = conn.meta.tables(schema=schema_filter, table=name_filter)
119
127
 
120
128
  # 出力処理
121
129
  json_indent = None if args.compact else 2
@@ -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
  ]
@@ -28,6 +28,8 @@
28
28
  - `ecd = "columns"`のみで構成されるファイル(columns glossary、テーブル/VIEWを持たない)も
29
29
  `all_source_files`経由でファイル参照リンク・`## Summary`・`## [label]`見出しに登場させる
30
30
  (中身はソースファイルへのリンクのみで、Mermaid図・見出しリンク一覧・詳細セクションは出さない)
31
+ - frontmatterの`schema`は`schema_by_file`経由で受け取り、`## [label]`見出し直下に
32
+ `* **Schema:** <schema>`として出力する(未指定のファイルは出力しない)
31
33
  """
32
34
 
33
35
  import os
@@ -55,6 +57,7 @@ def generate_catalog_markdown(
55
57
  no_diagram: bool = False,
56
58
  diagram_theme: str | None = None,
57
59
  all_source_files: Sequence[str] = (),
60
+ schema_by_file: dict[str, str | None] | None = None,
58
61
  ) -> str:
59
62
  """Markdownカタログ文字列を生成する。
60
63
 
@@ -65,7 +68,10 @@ def generate_catalog_markdown(
65
68
  `all_source_files`は読み込んだ全ECDファイルのパス(読み込み順)。`ecd = "columns"`のみで
66
69
  テーブル/VIEWを持たないファイル(columns glossary)も、ソースファイルへのリンクのみのセクション
67
70
  として登場させるために使う(テーブル/VIEWを持つファイルのみを渡した場合と結果は変わらない)。
71
+ `schema_by_file`はECDファイルパス->frontmatterの`schema`。`## [label]`見出し直下に
72
+ `* **Schema:**`として表示するために使う(省略時・値がNoneのファイルは表示しない)。
68
73
  """
74
+ schema_by_file = schema_by_file or {}
69
75
  base_dir = os.path.dirname(os.path.abspath(output_path)) if output_path else os.getcwd()
70
76
 
71
77
  source_files: list[str] = []
@@ -103,6 +109,9 @@ def generate_catalog_markdown(
103
109
  lines.append("")
104
110
  lines.append(f"## [{labels[source_file]}](#{_slugify(labels[source_file])})")
105
111
  lines.append(f"[Source File↗][{labels[source_file]}]")
112
+ file_schema = schema_by_file.get(source_file)
113
+ if file_schema:
114
+ lines.append(f"* **Schema:** {file_schema}")
106
115
 
107
116
  if not no_diagram:
108
117
  diagram_lines = _mermaid_diagram_lines(file_tables, tables_by_name, theme=diagram_theme)
@@ -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