xplain-import-pilot 0.1.0__py3-none-any.whl
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.
- xplain_import_pilot/__init__.py +54 -0
- xplain_import_pilot/__main__.py +3 -0
- xplain_import_pilot/autopilot_cli.py +393 -0
- xplain_import_pilot/cli.py +196 -0
- xplain_import_pilot/config.py +288 -0
- xplain_import_pilot/csv_autopilot_cli.py +389 -0
- xplain_import_pilot/csv_cli.py +145 -0
- xplain_import_pilot/csv_config.py +90 -0
- xplain_import_pilot/csv_enricher.py +194 -0
- xplain_import_pilot/csv_explorer.py +71 -0
- xplain_import_pilot/csv_importer.py +391 -0
- xplain_import_pilot/explorer.py +182 -0
- xplain_import_pilot/importer.py +381 -0
- xplain_import_pilot/notebook.py +348 -0
- xplain_import_pilot/py.typed +0 -0
- xplain_import_pilot/skills.md +253 -0
- xplain_import_pilot/suggester.py +192 -0
- xplain_import_pilot/utils.py +380 -0
- xplain_import_pilot-0.1.0.dist-info/METADATA +813 -0
- xplain_import_pilot-0.1.0.dist-info/RECORD +23 -0
- xplain_import_pilot-0.1.0.dist-info/WHEEL +4 -0
- xplain_import_pilot-0.1.0.dist-info/entry_points.txt +5 -0
- xplain_import_pilot-0.1.0.dist-info/licenses/LICENSE +9 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""
|
|
2
|
+
xplain-import-pilot - YAML-driven batch import tool for Xplain analytics platform.
|
|
3
|
+
|
|
4
|
+
This package provides a declarative approach to importing database tables
|
|
5
|
+
into XOE (Xplain Object Explorer) sessions. Define your data model in YAML
|
|
6
|
+
and import entire table hierarchies with a single command.
|
|
7
|
+
|
|
8
|
+
Features:
|
|
9
|
+
- Declarative YAML configuration
|
|
10
|
+
- Multi-level parent-child relationships
|
|
11
|
+
- Smart sampling with database-specific random functions
|
|
12
|
+
- SQL-computed dimensions
|
|
13
|
+
- Comprehensive validation before network calls
|
|
14
|
+
- Dry-run mode for previewing import plans
|
|
15
|
+
|
|
16
|
+
Example:
|
|
17
|
+
>>> from xplain_import_pilot import run_import, ImportConfig
|
|
18
|
+
>>>
|
|
19
|
+
>>> config = ImportConfig.model_validate(yaml_data)
|
|
20
|
+
>>> result = run_import(config, session_id="...", url="http://localhost:8080")
|
|
21
|
+
|
|
22
|
+
CLI Usage:
|
|
23
|
+
$ xplain-import --config my-import.yaml --session-id <JSESSIONID>
|
|
24
|
+
$ xplain-import --config my-import.yaml --dry-run # Preview only
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
__version__ = "0.1.0"
|
|
28
|
+
__author__ = "Xplain Data"
|
|
29
|
+
|
|
30
|
+
from xplain_import_pilot.config import (
|
|
31
|
+
DatabaseConfig,
|
|
32
|
+
DatabaseType,
|
|
33
|
+
DimensionType,
|
|
34
|
+
ImportConfig,
|
|
35
|
+
ObjectConfig,
|
|
36
|
+
SqlDimension,
|
|
37
|
+
)
|
|
38
|
+
from xplain_import_pilot.importer import print_plan, run_import
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
# Version
|
|
42
|
+
"__version__",
|
|
43
|
+
# Config classes
|
|
44
|
+
"ImportConfig",
|
|
45
|
+
"DatabaseConfig",
|
|
46
|
+
"ObjectConfig",
|
|
47
|
+
"SqlDimension",
|
|
48
|
+
# Enums
|
|
49
|
+
"DatabaseType",
|
|
50
|
+
"DimensionType",
|
|
51
|
+
# Functions
|
|
52
|
+
"run_import",
|
|
53
|
+
"print_plan",
|
|
54
|
+
]
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
"""CLI entry point for the autopilot feature.
|
|
2
|
+
|
|
3
|
+
Connects to a live XOE session, introspects a database, infers a
|
|
4
|
+
root/parent/child hierarchy, writes a suggested YAML config, and — after
|
|
5
|
+
a single user confirmation — executes the import.
|
|
6
|
+
|
|
7
|
+
Usage::
|
|
8
|
+
|
|
9
|
+
xplain-import-autopilot --db-config conn.yaml \\
|
|
10
|
+
--session-id $XPLAIN_SESSION_ID
|
|
11
|
+
|
|
12
|
+
xplain-import-autopilot \\
|
|
13
|
+
--db-type POSTGRESQL --db-host localhost --db-port 5432 \\
|
|
14
|
+
--db-user admin --db-password secret --db-name mydb \\
|
|
15
|
+
--schema public \\
|
|
16
|
+
--session-id $XPLAIN_SESSION_ID \\
|
|
17
|
+
--output-yaml suggested.yaml --yes
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import logging
|
|
24
|
+
import os
|
|
25
|
+
import sys
|
|
26
|
+
from typing import Optional
|
|
27
|
+
|
|
28
|
+
import yaml
|
|
29
|
+
from rich.console import Console
|
|
30
|
+
from rich.table import Table as RichTable
|
|
31
|
+
from rich.tree import Tree
|
|
32
|
+
|
|
33
|
+
import xplain
|
|
34
|
+
from xplain.tools.importer import Importer
|
|
35
|
+
|
|
36
|
+
from xplain_import_pilot.config import DatabaseConfig, ImportConfig
|
|
37
|
+
from xplain_import_pilot.explorer import DatabaseSchema, SchemaExplorer
|
|
38
|
+
from xplain_import_pilot.importer import run_import
|
|
39
|
+
from xplain_import_pilot.suggester import (
|
|
40
|
+
HierarchySuggester,
|
|
41
|
+
ObjectSuggestion,
|
|
42
|
+
to_yaml_dict,
|
|
43
|
+
to_yaml_str,
|
|
44
|
+
)
|
|
45
|
+
from xplain_import_pilot.utils import resolve_session_id
|
|
46
|
+
|
|
47
|
+
logger = logging.getLogger(__name__)
|
|
48
|
+
console = Console()
|
|
49
|
+
|
|
50
|
+
_DB_TYPES = ["POSTGRESQL", "MYSQL", "ORACLE", "DB2", "MARIADB", "DATABRICKS"]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ── Helpers ───────────────────────────────────────────────────────────────────
|
|
54
|
+
|
|
55
|
+
def _load_db_dict(args: argparse.Namespace) -> dict:
|
|
56
|
+
"""Build a database config dict from --db-config file or individual flags."""
|
|
57
|
+
if args.db_config:
|
|
58
|
+
with open(args.db_config) as fh:
|
|
59
|
+
raw = yaml.safe_load(fh)
|
|
60
|
+
if "database" not in raw:
|
|
61
|
+
raise ValueError("--db-config YAML must contain a 'database:' section")
|
|
62
|
+
return raw["database"]
|
|
63
|
+
|
|
64
|
+
missing = [
|
|
65
|
+
flag
|
|
66
|
+
for flag, val in [
|
|
67
|
+
("--db-type", args.db_type),
|
|
68
|
+
("--db-host", args.db_host),
|
|
69
|
+
("--db-port", args.db_port),
|
|
70
|
+
("--db-user", args.db_user),
|
|
71
|
+
("--db-password", args.db_password),
|
|
72
|
+
("--db-name", args.db_name),
|
|
73
|
+
]
|
|
74
|
+
if not val
|
|
75
|
+
]
|
|
76
|
+
if missing:
|
|
77
|
+
raise ValueError(
|
|
78
|
+
f"Missing required flags: {', '.join(missing)}. "
|
|
79
|
+
"Provide either --db-config YAML or all individual --db-* flags."
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
cfg: dict = {
|
|
83
|
+
"type": args.db_type,
|
|
84
|
+
"host": args.db_host,
|
|
85
|
+
"port": args.db_port,
|
|
86
|
+
"user": args.db_user,
|
|
87
|
+
"password": args.db_password,
|
|
88
|
+
"database": args.db_name,
|
|
89
|
+
}
|
|
90
|
+
if args.db_schema:
|
|
91
|
+
cfg["schema"] = args.db_schema
|
|
92
|
+
return cfg
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _display_results(schema: DatabaseSchema, suggestions: list[ObjectSuggestion]) -> None:
|
|
96
|
+
"""Print exploration results and the suggested hierarchy via rich."""
|
|
97
|
+
# ── Tables + columns ──────────────────────────────────────────────────────
|
|
98
|
+
console.print("\n[bold cyan]── Database Schema ──[/bold cyan]")
|
|
99
|
+
tbl = RichTable(show_header=True, header_style="bold", expand=False)
|
|
100
|
+
tbl.add_column("Table", style="cyan", no_wrap=True)
|
|
101
|
+
tbl.add_column("Columns", overflow="fold")
|
|
102
|
+
tbl.add_column("Rows sampled", justify="right")
|
|
103
|
+
for t in schema.tables:
|
|
104
|
+
cols = ", ".join(c.name for c in t.columns) or "(no columns)"
|
|
105
|
+
tbl.add_row(t.name, cols, str(t.row_sample_count))
|
|
106
|
+
console.print(tbl)
|
|
107
|
+
|
|
108
|
+
# ── Inferred FKs ──────────────────────────────────────────────────────────
|
|
109
|
+
if schema.inferred_fks:
|
|
110
|
+
console.print("\n[bold cyan]── Inferred Relationships ──[/bold cyan]")
|
|
111
|
+
fk_tbl = RichTable(show_header=True, header_style="bold")
|
|
112
|
+
fk_tbl.add_column("Child table")
|
|
113
|
+
fk_tbl.add_column("FK column")
|
|
114
|
+
fk_tbl.add_column("→ Parent table")
|
|
115
|
+
fk_tbl.add_column("Confidence", justify="right")
|
|
116
|
+
for fk in schema.inferred_fks:
|
|
117
|
+
conf_color = "green" if fk.confidence >= 0.85 else "yellow"
|
|
118
|
+
fk_tbl.add_row(
|
|
119
|
+
fk.from_table, fk.from_column, fk.to_table,
|
|
120
|
+
f"[{conf_color}]{fk.confidence:.0%}[/{conf_color}]",
|
|
121
|
+
)
|
|
122
|
+
console.print(fk_tbl)
|
|
123
|
+
else:
|
|
124
|
+
console.print(
|
|
125
|
+
"\n[yellow]No FK relationships inferred — "
|
|
126
|
+
"all tables will be imported as roots.[/yellow]"
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
# ── Hierarchy tree ────────────────────────────────────────────────────────
|
|
130
|
+
console.print("\n[bold cyan]── Suggested Hierarchy ──[/bold cyan]")
|
|
131
|
+
|
|
132
|
+
node_map: dict[str, Tree] = {}
|
|
133
|
+
roots: list[Tree] = []
|
|
134
|
+
|
|
135
|
+
for s in suggestions: # already in topological order
|
|
136
|
+
pk_label = f", pk={s.primary_key}" if s.primary_key else ", pk=?"
|
|
137
|
+
pk_color = "green" if s.pk_confidence >= 0.7 else "red"
|
|
138
|
+
if s.role == "root":
|
|
139
|
+
label = f"[bold green]{s.name}[/bold green] (root[{pk_color}]{pk_label}[/{pk_color}])"
|
|
140
|
+
node = Tree(label)
|
|
141
|
+
roots.append(node)
|
|
142
|
+
node_map[s.name] = node
|
|
143
|
+
else:
|
|
144
|
+
fk_color = "green" if s.fk_confidence >= 0.8 else "yellow"
|
|
145
|
+
conf_label = f"[{fk_color}]{s.fk_confidence:.0%}[/{fk_color}]"
|
|
146
|
+
label = (
|
|
147
|
+
f"[yellow]{s.name}[/yellow] "
|
|
148
|
+
f"(fk={s.foreign_keys}, conf={conf_label}[{pk_color}]{pk_label})"
|
|
149
|
+
)
|
|
150
|
+
child_node = Tree(label)
|
|
151
|
+
parent_node = node_map.get(s.parent or "")
|
|
152
|
+
if parent_node is not None:
|
|
153
|
+
parent_node.add(child_node)
|
|
154
|
+
else:
|
|
155
|
+
roots.append(child_node)
|
|
156
|
+
node_map[s.name] = child_node
|
|
157
|
+
|
|
158
|
+
for root_tree in roots:
|
|
159
|
+
console.print(root_tree)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
# ── Main ──────────────────────────────────────────────────────────────────────
|
|
163
|
+
|
|
164
|
+
def main() -> None:
|
|
165
|
+
parser = argparse.ArgumentParser(
|
|
166
|
+
description=(
|
|
167
|
+
"Auto-discover a database schema and import it into Xplain XOE. "
|
|
168
|
+
"Explores the database, infers root/parent/child relationships, "
|
|
169
|
+
"writes a YAML config, and executes the import after confirmation."
|
|
170
|
+
),
|
|
171
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
172
|
+
epilog="""
|
|
173
|
+
examples:
|
|
174
|
+
# Using a partial YAML for DB credentials
|
|
175
|
+
xplain-import-autopilot --db-config conn.yaml
|
|
176
|
+
|
|
177
|
+
# Using inline flags
|
|
178
|
+
xplain-import-autopilot --db-type POSTGRESQL --db-host localhost \\
|
|
179
|
+
--db-port 5432 --db-user admin --db-password secret --db-name mydb
|
|
180
|
+
|
|
181
|
+
# Skip confirmation, persist configs to XOE
|
|
182
|
+
xplain-import-autopilot --db-config conn.yaml --yes --persist
|
|
183
|
+
""",
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
# ── DB connection ─────────────────────────────────────────────────────────
|
|
187
|
+
db_grp = parser.add_argument_group(
|
|
188
|
+
"database connection",
|
|
189
|
+
"Either --db-config (YAML file with 'database:' section) "
|
|
190
|
+
"or all individual --db-* flags are required.",
|
|
191
|
+
)
|
|
192
|
+
db_grp.add_argument(
|
|
193
|
+
"--db-config", metavar="YAML",
|
|
194
|
+
help="YAML file containing only the 'database:' section",
|
|
195
|
+
)
|
|
196
|
+
db_grp.add_argument("--db-type", choices=_DB_TYPES, metavar="TYPE")
|
|
197
|
+
db_grp.add_argument("--db-host", metavar="HOST")
|
|
198
|
+
db_grp.add_argument("--db-port", type=int, metavar="PORT")
|
|
199
|
+
db_grp.add_argument("--db-user", metavar="USER")
|
|
200
|
+
db_grp.add_argument("--db-password", metavar="PASSWORD")
|
|
201
|
+
db_grp.add_argument("--db-name", metavar="DBNAME")
|
|
202
|
+
db_grp.add_argument("--db-schema", metavar="SCHEMA",
|
|
203
|
+
help="Restrict table discovery to this schema")
|
|
204
|
+
|
|
205
|
+
# ── XOE session ───────────────────────────────────────────────────────────
|
|
206
|
+
xoe_grp = parser.add_argument_group("XOE session")
|
|
207
|
+
xoe_grp.add_argument(
|
|
208
|
+
"--session-id",
|
|
209
|
+
help="XOE JSESSIONID (or set XPLAIN_SESSION_ID env var)",
|
|
210
|
+
)
|
|
211
|
+
xoe_grp.add_argument(
|
|
212
|
+
"--url", default=os.environ.get("XPLAIN_SERVER_URL", "http://localhost:8080"),
|
|
213
|
+
help="XOE server URL (default: http://localhost:8080, or XPLAIN_SERVER_URL env var)",
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
# ── Autopilot options ─────────────────────────────────────────────────────
|
|
217
|
+
parser.add_argument(
|
|
218
|
+
"--output-yaml", metavar="PATH",
|
|
219
|
+
help="Write suggested config to this file (default: <db-name>_autopilot.yaml)",
|
|
220
|
+
)
|
|
221
|
+
parser.add_argument(
|
|
222
|
+
"--max-tables", type=int, default=50,
|
|
223
|
+
help="Limit exploration to this many tables (default: 50)",
|
|
224
|
+
)
|
|
225
|
+
parser.add_argument(
|
|
226
|
+
"--sample-rows", type=int, default=5,
|
|
227
|
+
help="Rows to fetch per table for type inference (default: 5)",
|
|
228
|
+
)
|
|
229
|
+
parser.add_argument(
|
|
230
|
+
"--yes", action="store_true",
|
|
231
|
+
help="Skip the confirmation prompt and run import immediately",
|
|
232
|
+
)
|
|
233
|
+
parser.add_argument(
|
|
234
|
+
"--dry-run", action="store_true",
|
|
235
|
+
help="Explore and print suggestion only — do not import",
|
|
236
|
+
)
|
|
237
|
+
parser.add_argument(
|
|
238
|
+
"--persist", action="store_true",
|
|
239
|
+
help="Persist xtable configs and xview to XOE after import",
|
|
240
|
+
)
|
|
241
|
+
parser.add_argument(
|
|
242
|
+
"--persist-prefix", metavar="PREFIX",
|
|
243
|
+
help="Prefix for persisted config names (default: <db-name>)",
|
|
244
|
+
)
|
|
245
|
+
parser.add_argument(
|
|
246
|
+
"--log-level", default="INFO",
|
|
247
|
+
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
args = parser.parse_args()
|
|
251
|
+
|
|
252
|
+
logging.basicConfig(
|
|
253
|
+
level=getattr(logging, args.log_level),
|
|
254
|
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
# ── Session ID ────────────────────────────────────────────────────────────
|
|
258
|
+
try:
|
|
259
|
+
session_id = resolve_session_id(args.session_id)
|
|
260
|
+
except ValueError as exc:
|
|
261
|
+
logger.error(str(exc))
|
|
262
|
+
sys.exit(1)
|
|
263
|
+
|
|
264
|
+
# ── DB config ─────────────────────────────────────────────────────────────
|
|
265
|
+
try:
|
|
266
|
+
db_dict = _load_db_dict(args)
|
|
267
|
+
db_config = DatabaseConfig.model_validate(db_dict)
|
|
268
|
+
except (ValueError, FileNotFoundError) as exc:
|
|
269
|
+
logger.error("Database config error: %s", exc)
|
|
270
|
+
sys.exit(1)
|
|
271
|
+
|
|
272
|
+
# ── Connect to XOE ────────────────────────────────────────────────────────
|
|
273
|
+
console.print(f"\n[bold]Connecting to XOE at [cyan]{args.url}[/cyan]...[/bold]")
|
|
274
|
+
session = xplain.Xsession(url=args.url, http_session_id=session_id)
|
|
275
|
+
importer: Importer = session.get_importer()
|
|
276
|
+
|
|
277
|
+
# ── DB connection ─────────────────────────────────────────────────────────
|
|
278
|
+
console.print(
|
|
279
|
+
f"[bold]Connecting to [cyan]{db_config.type.value}[/cyan] "
|
|
280
|
+
f"@ {db_config.host}:{db_config.port}/{db_config.database}...[/bold]"
|
|
281
|
+
)
|
|
282
|
+
driver_props = db_config.driver_properties or {}
|
|
283
|
+
if db_config.type.value == "POSTGRESQL" and db_config.db_schema:
|
|
284
|
+
driver_props = {**driver_props, "currentSchema": db_config.db_schema}
|
|
285
|
+
|
|
286
|
+
connection = importer.create_connection(
|
|
287
|
+
databaseType=db_config.type.value,
|
|
288
|
+
url=db_config.host,
|
|
289
|
+
portNumber=db_config.port,
|
|
290
|
+
user=db_config.user,
|
|
291
|
+
password=db_config.password,
|
|
292
|
+
databaseName=db_config.database,
|
|
293
|
+
schema=None if db_config.type.value == "POSTGRESQL" else db_config.db_schema,
|
|
294
|
+
driverProperties=driver_props if driver_props else None,
|
|
295
|
+
)
|
|
296
|
+
test = connection.test_connection()
|
|
297
|
+
if test.get("status") != "success":
|
|
298
|
+
logger.error("DB connection test failed: %s", test.get("result"))
|
|
299
|
+
sys.exit(1)
|
|
300
|
+
console.print("[green]Connection OK.[/green]")
|
|
301
|
+
|
|
302
|
+
# ── Explore ───────────────────────────────────────────────────────────────
|
|
303
|
+
console.print("\n[bold]Exploring database schema...[/bold]")
|
|
304
|
+
explorer = SchemaExplorer(
|
|
305
|
+
connection=connection,
|
|
306
|
+
schema=db_config.db_schema,
|
|
307
|
+
sample_limit=args.sample_rows,
|
|
308
|
+
)
|
|
309
|
+
schema = explorer.explore()
|
|
310
|
+
|
|
311
|
+
if not schema.tables:
|
|
312
|
+
logger.error("No tables found in schema '%s'.", db_config.db_schema or "*")
|
|
313
|
+
sys.exit(1)
|
|
314
|
+
|
|
315
|
+
if len(schema.tables) > args.max_tables:
|
|
316
|
+
console.print(
|
|
317
|
+
f"[yellow]Found {len(schema.tables)} tables; limiting to first "
|
|
318
|
+
f"{args.max_tables} (use --max-tables to raise the limit).[/yellow]"
|
|
319
|
+
)
|
|
320
|
+
schema.tables = schema.tables[: args.max_tables]
|
|
321
|
+
kept = {t.name for t in schema.tables}
|
|
322
|
+
schema.inferred_fks = [
|
|
323
|
+
fk for fk in schema.inferred_fks
|
|
324
|
+
if fk.from_table in kept and fk.to_table in kept
|
|
325
|
+
]
|
|
326
|
+
|
|
327
|
+
# ── Suggest hierarchy ─────────────────────────────────────────────────────
|
|
328
|
+
suggester = HierarchySuggester()
|
|
329
|
+
suggestions = suggester.suggest(schema)
|
|
330
|
+
|
|
331
|
+
# ── Display ───────────────────────────────────────────────────────────────
|
|
332
|
+
_display_results(schema, suggestions)
|
|
333
|
+
|
|
334
|
+
# ── Dry-run path ──────────────────────────────────────────────────────────
|
|
335
|
+
if args.dry_run:
|
|
336
|
+
console.print("\n[bold]Suggested YAML config (dry-run, no import):[/bold]\n")
|
|
337
|
+
console.print(to_yaml_str(suggestions, db_dict))
|
|
338
|
+
return
|
|
339
|
+
|
|
340
|
+
# ── Write YAML ────────────────────────────────────────────────────────────
|
|
341
|
+
output_path = args.output_yaml or f"{db_config.database}_autopilot.yaml"
|
|
342
|
+
yaml_content = to_yaml_str(suggestions, db_dict)
|
|
343
|
+
with open(output_path, "w") as fh:
|
|
344
|
+
fh.write(yaml_content)
|
|
345
|
+
console.print(f"\n[green]Suggested config written to:[/green] [bold]{output_path}[/bold]")
|
|
346
|
+
|
|
347
|
+
# ── Confirm ───────────────────────────────────────────────────────────────
|
|
348
|
+
if not args.yes:
|
|
349
|
+
console.print(
|
|
350
|
+
f"\nReview [cyan]{output_path}[/cyan] and edit if needed, "
|
|
351
|
+
"then confirm to proceed."
|
|
352
|
+
)
|
|
353
|
+
answer = console.input("Proceed with import? [y/N] ").strip().lower()
|
|
354
|
+
if answer not in ("y", "yes"):
|
|
355
|
+
console.print("[yellow]Import cancelled. Edit the YAML and re-run:[/yellow]")
|
|
356
|
+
console.print(f" xplain-import --config {output_path}")
|
|
357
|
+
sys.exit(0)
|
|
358
|
+
|
|
359
|
+
# ── Validate generated config ─────────────────────────────────────────────
|
|
360
|
+
try:
|
|
361
|
+
import_config = ImportConfig.model_validate(to_yaml_dict(suggestions, db_dict))
|
|
362
|
+
except Exception as exc:
|
|
363
|
+
logger.error(
|
|
364
|
+
"Generated config has validation errors:\n%s\n\n"
|
|
365
|
+
"Edit %s to fix the issues, then run:\n"
|
|
366
|
+
" xplain-import --config %s",
|
|
367
|
+
exc, output_path, output_path,
|
|
368
|
+
)
|
|
369
|
+
sys.exit(1)
|
|
370
|
+
|
|
371
|
+
# ── Import ────────────────────────────────────────────────────────────────
|
|
372
|
+
persist_prefix = (
|
|
373
|
+
args.persist_prefix or db_config.database if args.persist else None
|
|
374
|
+
)
|
|
375
|
+
try:
|
|
376
|
+
run_import(
|
|
377
|
+
import_config,
|
|
378
|
+
session_id=session_id,
|
|
379
|
+
url=args.url,
|
|
380
|
+
persist=args.persist,
|
|
381
|
+
persist_prefix=persist_prefix,
|
|
382
|
+
)
|
|
383
|
+
console.print("\n[bold green]Import complete![/bold green]")
|
|
384
|
+
if args.persist:
|
|
385
|
+
console.print(f" Configs persisted with prefix '[cyan]{persist_prefix}[/cyan]'.")
|
|
386
|
+
except Exception as exc:
|
|
387
|
+
logger.error(
|
|
388
|
+
"Import failed: %s\n\n"
|
|
389
|
+
"Hint: Edit %s and re-run manually:\n"
|
|
390
|
+
" xplain-import --config %s",
|
|
391
|
+
exc, output_path, output_path,
|
|
392
|
+
)
|
|
393
|
+
sys.exit(1)
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""CLI entry point. Parses arguments, loads + validates the YAML config,
|
|
2
|
+
then delegates to the importer."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
|
|
11
|
+
from xplain_import_pilot import __version__
|
|
12
|
+
from xplain_import_pilot.config import ImportConfig
|
|
13
|
+
from xplain_import_pilot.importer import print_plan, run_import
|
|
14
|
+
from xplain_import_pilot.notebook import export_notebook
|
|
15
|
+
from xplain_import_pilot.utils import resolve_session_id
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main() -> None:
|
|
21
|
+
parser = argparse.ArgumentParser(
|
|
22
|
+
description="Import database tables into xplain via a YAML config",
|
|
23
|
+
)
|
|
24
|
+
parser.add_argument(
|
|
25
|
+
"--version",
|
|
26
|
+
action="version",
|
|
27
|
+
version=f"xplain-import-pilot {__version__}",
|
|
28
|
+
)
|
|
29
|
+
parser.add_argument(
|
|
30
|
+
"--session-id",
|
|
31
|
+
required=False,
|
|
32
|
+
help="XOE JSESSIONID (browser -> DevTools -> Application -> Cookies). "
|
|
33
|
+
"Can also be set via XPLAIN_SESSION_ID environment variable.",
|
|
34
|
+
)
|
|
35
|
+
parser.add_argument(
|
|
36
|
+
"--config",
|
|
37
|
+
required=True,
|
|
38
|
+
help="Path to the YAML import config file",
|
|
39
|
+
)
|
|
40
|
+
parser.add_argument(
|
|
41
|
+
"--url",
|
|
42
|
+
default=os.environ.get("XPLAIN_SERVER_URL", "http://localhost:8080"),
|
|
43
|
+
help="XOE server URL (default: http://localhost:8080, or XPLAIN_SERVER_URL env var)",
|
|
44
|
+
)
|
|
45
|
+
parser.add_argument(
|
|
46
|
+
"--dry-run",
|
|
47
|
+
action="store_true",
|
|
48
|
+
help="Validate the config and print the import plan without connecting",
|
|
49
|
+
)
|
|
50
|
+
parser.add_argument(
|
|
51
|
+
"--log-level",
|
|
52
|
+
default="INFO",
|
|
53
|
+
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
|
|
54
|
+
help="Logging level (default: INFO)",
|
|
55
|
+
)
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
"--sampling-rate",
|
|
58
|
+
type=float,
|
|
59
|
+
metavar="RATE",
|
|
60
|
+
help="Override sampling rate for all objects (float in (0.0, 1.0], "
|
|
61
|
+
"adds RANDOM() < rate to WHERE clause). "
|
|
62
|
+
"Overrides any sampling_rate specified in YAML config.",
|
|
63
|
+
)
|
|
64
|
+
parser.add_argument(
|
|
65
|
+
"--persist",
|
|
66
|
+
action="store_true",
|
|
67
|
+
help="Persist configurations to XOE: saves xtable configs, "
|
|
68
|
+
"database connection, and xview for reuse",
|
|
69
|
+
)
|
|
70
|
+
parser.add_argument(
|
|
71
|
+
"--persist-prefix",
|
|
72
|
+
metavar="PREFIX",
|
|
73
|
+
help="Prefix for persisted config names (default: derived from YAML filename)",
|
|
74
|
+
)
|
|
75
|
+
parser.add_argument(
|
|
76
|
+
"--persist-ownership",
|
|
77
|
+
choices=["PUBLIC", "PRIVATE"],
|
|
78
|
+
default="PUBLIC",
|
|
79
|
+
help="Ownership level for persisted configs (default: PUBLIC)",
|
|
80
|
+
)
|
|
81
|
+
parser.add_argument(
|
|
82
|
+
"--export-notebook",
|
|
83
|
+
action="store_true",
|
|
84
|
+
help="Export a Jupyter notebook with the xplain method sequence",
|
|
85
|
+
)
|
|
86
|
+
parser.add_argument(
|
|
87
|
+
"--notebook-output",
|
|
88
|
+
metavar="PATH",
|
|
89
|
+
help="Output path for notebook (default: <config-name>_import.ipynb)",
|
|
90
|
+
)
|
|
91
|
+
args = parser.parse_args()
|
|
92
|
+
|
|
93
|
+
# validate sampling rate if provided ---------------------------------------
|
|
94
|
+
if args.sampling_rate is not None:
|
|
95
|
+
if args.sampling_rate <= 0.0 or args.sampling_rate > 1.0:
|
|
96
|
+
logger.error(
|
|
97
|
+
"Invalid sampling rate: %s (must be in (0.0, 1.0])",
|
|
98
|
+
args.sampling_rate,
|
|
99
|
+
)
|
|
100
|
+
sys.exit(1)
|
|
101
|
+
|
|
102
|
+
# configure logging --------------------------------------------------------
|
|
103
|
+
logging.basicConfig(
|
|
104
|
+
level=getattr(logging, args.log_level),
|
|
105
|
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
# --- load YAML -----------------------------------------------------------
|
|
109
|
+
try:
|
|
110
|
+
with open(args.config) as fh:
|
|
111
|
+
raw = yaml.safe_load(fh)
|
|
112
|
+
except FileNotFoundError:
|
|
113
|
+
logger.error(
|
|
114
|
+
"Config file not found: %s\n"
|
|
115
|
+
"Hint: Ensure the file path is correct and the file exists.",
|
|
116
|
+
args.config,
|
|
117
|
+
)
|
|
118
|
+
sys.exit(1)
|
|
119
|
+
except yaml.YAMLError as exc:
|
|
120
|
+
logger.error("Failed to parse YAML config: %s", exc)
|
|
121
|
+
sys.exit(1)
|
|
122
|
+
|
|
123
|
+
# --- validate ------------------------------------------------------------
|
|
124
|
+
try:
|
|
125
|
+
config = ImportConfig.model_validate(raw)
|
|
126
|
+
except Exception as exc:
|
|
127
|
+
logger.error(
|
|
128
|
+
"Config validation failed:\n%s\n\n"
|
|
129
|
+
"Hint: Check the example.yaml file for reference configuration.",
|
|
130
|
+
exc,
|
|
131
|
+
)
|
|
132
|
+
sys.exit(1)
|
|
133
|
+
|
|
134
|
+
# apply global sampling rate override if provided -------------------------
|
|
135
|
+
if args.sampling_rate is not None:
|
|
136
|
+
logger.info(
|
|
137
|
+
"Applying global sampling rate override: %.2f", args.sampling_rate
|
|
138
|
+
)
|
|
139
|
+
for obj in config.objects:
|
|
140
|
+
obj.sampling_rate = args.sampling_rate
|
|
141
|
+
|
|
142
|
+
# Derive persist prefix from config filename if not specified
|
|
143
|
+
persist_prefix = args.persist_prefix
|
|
144
|
+
if (args.persist or args.export_notebook) and not persist_prefix:
|
|
145
|
+
persist_prefix = os.path.splitext(os.path.basename(args.config))[0]
|
|
146
|
+
|
|
147
|
+
# --- export notebook if requested ----------------------------------------
|
|
148
|
+
if args.export_notebook:
|
|
149
|
+
notebook_path = args.notebook_output
|
|
150
|
+
if not notebook_path:
|
|
151
|
+
notebook_path = os.path.splitext(args.config)[0] + "_import.ipynb"
|
|
152
|
+
|
|
153
|
+
export_notebook(
|
|
154
|
+
config=config,
|
|
155
|
+
output_path=notebook_path,
|
|
156
|
+
url=args.url,
|
|
157
|
+
persist=args.persist,
|
|
158
|
+
persist_prefix=persist_prefix,
|
|
159
|
+
persist_ownership=args.persist_ownership,
|
|
160
|
+
)
|
|
161
|
+
logger.info("Notebook exported to %s", notebook_path)
|
|
162
|
+
|
|
163
|
+
# If only exporting notebook (with dry-run), exit here
|
|
164
|
+
if args.dry_run:
|
|
165
|
+
print_plan(config)
|
|
166
|
+
return
|
|
167
|
+
|
|
168
|
+
# --- dry-run or execute --------------------------------------------------
|
|
169
|
+
if args.dry_run:
|
|
170
|
+
print_plan(config)
|
|
171
|
+
return
|
|
172
|
+
|
|
173
|
+
# --- resolve session ID (only needed once we actually connect) -----------
|
|
174
|
+
try:
|
|
175
|
+
session_id = resolve_session_id(args.session_id)
|
|
176
|
+
except ValueError as exc:
|
|
177
|
+
logger.error(str(exc))
|
|
178
|
+
sys.exit(1)
|
|
179
|
+
|
|
180
|
+
try:
|
|
181
|
+
run_import(
|
|
182
|
+
config,
|
|
183
|
+
session_id=session_id,
|
|
184
|
+
url=args.url,
|
|
185
|
+
persist=args.persist,
|
|
186
|
+
persist_prefix=persist_prefix,
|
|
187
|
+
persist_ownership=args.persist_ownership,
|
|
188
|
+
)
|
|
189
|
+
except Exception as exc:
|
|
190
|
+
logger.error(
|
|
191
|
+
"Import failed: %s\n\n"
|
|
192
|
+
"Hint: Check database credentials, XOE session validity, "
|
|
193
|
+
"and network connectivity.",
|
|
194
|
+
exc,
|
|
195
|
+
)
|
|
196
|
+
sys.exit(1)
|