-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.py
More file actions
93 lines (80 loc) · 2.31 KB
/
Copy pathcli.py
File metadata and controls
93 lines (80 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""CLI interface for json2sql using Typer."""
import sys
from pathlib import Path
from typing import Optional
import typer
from .converter import JSONToSQLConverter
from .dialects import Dialect
app = typer.Typer(
name="json2sql",
help="Convert JSON files/datasets to SQL INSERT statements.",
no_args_is_help=True,
)
@app.command()
def convert(
input_file: Optional[Path] = typer.Argument(
None,
help="Path to JSON file. Reads from stdin if not provided.",
exists=True,
),
dialect: Dialect = typer.Option(
Dialect.POSTGRES,
"--dialect",
"-d",
help="SQL dialect: postgres, mysql, sqlite",
),
table: str = typer.Option(
"data",
"--table",
"-t",
help="Table name for INSERT statements.",
),
output: Optional[Path] = typer.Option(
None,
"--output",
"-o",
help="Output SQL file. Prints to stdout if not provided.",
),
flatten: bool = typer.Option(
False,
"--flatten",
"-f",
help="Flatten nested JSON into relational tables.",
),
schema_only: bool = typer.Option(
False,
"--schema-only",
help="Generate CREATE TABLE statements only (no INSERT).",
),
):
"""Convert a JSON file to SQL INSERT statements."""
# Read input
if input_file:
json_text = input_file.read_text(encoding="utf-8")
elif not sys.stdin.isatty():
json_text = sys.stdin.read()
else:
typer.echo("Error: Provide a JSON file or pipe JSON to stdin.", err=True)
raise typer.Exit(code=1)
converter = JSONToSQLConverter(dialect=dialect, flatten=flatten)
try:
if schema_only:
result = converter.generate_schema(json_text, table_name=table)
else:
result = converter.convert(json_text, table_name=table)
except Exception as e:
typer.echo(f"Error converting JSON: {e}", err=True)
raise typer.Exit(code=1)
# Write output
if output:
output.write_text(result, encoding="utf-8")
typer.echo(f"SQL written to {output}", err=True)
else:
typer.echo(result)
@app.command()
def version():
"""Show version."""
from . import __version__
typer.echo(f"json2sql {__version__}")
if __name__ == "__main__":
app()