lakefreight 0.2.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.
- lakefreight/__init__.py +0 -0
- lakefreight/__main__.py +5 -0
- lakefreight/chunk_planner.py +107 -0
- lakefreight/cli.py +82 -0
- lakefreight/config.py +85 -0
- lakefreight/defaults.toml +45 -0
- lakefreight/generate.py +311 -0
- lakefreight/handlers.py +210 -0
- lakefreight/models.py +60 -0
- lakefreight/planning.py +81 -0
- lakefreight/py.typed +0 -0
- lakefreight/reconcile.py +78 -0
- lakefreight/register.py +309 -0
- lakefreight/renderer.py +125 -0
- lakefreight/store.py +78 -0
- lakefreight/templates/copy_unload.sql.j2 +19 -0
- lakefreight-0.2.0.dist-info/METADATA +188 -0
- lakefreight-0.2.0.dist-info/RECORD +22 -0
- lakefreight-0.2.0.dist-info/WHEEL +5 -0
- lakefreight-0.2.0.dist-info/entry_points.txt +2 -0
- lakefreight-0.2.0.dist-info/licenses/LICENSE +21 -0
- lakefreight-0.2.0.dist-info/top_level.txt +1 -0
lakefreight/__init__.py
ADDED
|
File without changes
|
lakefreight/__main__.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Split a large table into date-range chunks of roughly equal size.
|
|
2
|
+
|
|
3
|
+
Input is one profile query per table (row count by month). Months are packed
|
|
4
|
+
in order into chunks close to the target size. The resulting predicates cover
|
|
5
|
+
every possible value of the chunk column:
|
|
6
|
+
|
|
7
|
+
first chunk col < end (no lower bound)
|
|
8
|
+
middle col >= start AND col < end
|
|
9
|
+
last chunk col >= start (no upper bound)
|
|
10
|
+
null chunk col IS NULL (always emitted)
|
|
11
|
+
|
|
12
|
+
so rows outside the profiled range cannot be missed.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from datetime import date
|
|
18
|
+
|
|
19
|
+
from .models import Chunk, quote_ident
|
|
20
|
+
|
|
21
|
+
FULL_CHUNK_ID = "full"
|
|
22
|
+
NULL_CHUNK_ID = "null"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def profile_sql(source_fqn: str, column: str) -> str:
|
|
26
|
+
col = quote_ident(column)
|
|
27
|
+
return (
|
|
28
|
+
f"SELECT DATE_TRUNC('MONTH', {col})::DATE AS MONTH_START, COUNT(*) AS ROW_COUNT "
|
|
29
|
+
f"FROM {source_fqn} GROUP BY 1"
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def full_chunk(table_bytes: int = 0) -> Chunk:
|
|
34
|
+
return Chunk(chunk_id=FULL_CHUNK_ID, predicate=None, est_bytes=table_bytes)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def plan_chunks(
|
|
38
|
+
column: str,
|
|
39
|
+
month_counts: list[tuple[date | None, int]],
|
|
40
|
+
table_bytes: int,
|
|
41
|
+
target_bytes: int,
|
|
42
|
+
) -> list[Chunk]:
|
|
43
|
+
"""Return chunks for one table. `month_counts` is the profile query result."""
|
|
44
|
+
if target_bytes <= 0:
|
|
45
|
+
raise ValueError("target_bytes must be positive")
|
|
46
|
+
|
|
47
|
+
col = f"t.{quote_ident(column)}" # every rendered statement aliases the source as t
|
|
48
|
+
null_rows = sum(n for m, n in month_counts if m is None)
|
|
49
|
+
months = sorted((m, n) for m, n in month_counts if m is not None)
|
|
50
|
+
total_rows = null_rows + sum(n for _, n in months)
|
|
51
|
+
bytes_per_row = table_bytes / total_rows if total_rows else 0.0
|
|
52
|
+
|
|
53
|
+
# Greedy packing of consecutive months.
|
|
54
|
+
groups: list[list[tuple[date, int]]] = []
|
|
55
|
+
current: list[tuple[date, int]] = []
|
|
56
|
+
current_bytes = 0.0
|
|
57
|
+
for month, rows in months:
|
|
58
|
+
month_bytes = rows * bytes_per_row
|
|
59
|
+
if current and current_bytes + month_bytes > target_bytes:
|
|
60
|
+
groups.append(current)
|
|
61
|
+
current, current_bytes = [], 0.0
|
|
62
|
+
current.append((month, rows))
|
|
63
|
+
current_bytes += month_bytes
|
|
64
|
+
if current:
|
|
65
|
+
groups.append(current)
|
|
66
|
+
|
|
67
|
+
chunks: list[Chunk] = []
|
|
68
|
+
for i, group in enumerate(groups):
|
|
69
|
+
start = group[0][0]
|
|
70
|
+
is_first, is_last = i == 0, i == len(groups) - 1
|
|
71
|
+
end = None if is_last else groups[i + 1][0][0]
|
|
72
|
+
parts = []
|
|
73
|
+
if not is_first:
|
|
74
|
+
parts.append(f"{col} >= '{start.isoformat()}'")
|
|
75
|
+
if not is_last:
|
|
76
|
+
parts.append(f"{col} < '{end.isoformat()}'")
|
|
77
|
+
# A single group has no bounds at all, so match every non-null value.
|
|
78
|
+
predicate = " AND ".join(parts) if parts else f"{col} IS NOT NULL"
|
|
79
|
+
rows = sum(n for _, n in group)
|
|
80
|
+
chunks.append(
|
|
81
|
+
Chunk(
|
|
82
|
+
chunk_id=f"{i + 1:04d}_{start:%Y%m}_{group[-1][0]:%Y%m}",
|
|
83
|
+
predicate=predicate,
|
|
84
|
+
est_rows=rows,
|
|
85
|
+
est_bytes=int(rows * bytes_per_row),
|
|
86
|
+
months=tuple(m for m, _ in group),
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
if not chunks:
|
|
91
|
+
chunks.append(Chunk(chunk_id="0001_all", predicate=f"{col} IS NOT NULL"))
|
|
92
|
+
|
|
93
|
+
chunks.append(
|
|
94
|
+
Chunk(
|
|
95
|
+
chunk_id=NULL_CHUNK_ID,
|
|
96
|
+
predicate=f"{col} IS NULL",
|
|
97
|
+
est_rows=null_rows,
|
|
98
|
+
est_bytes=int(null_rows * bytes_per_row),
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
return chunks
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def oversized(chunks: list[Chunk], target_bytes: int, factor: float = 2.0) -> list[Chunk]:
|
|
105
|
+
"""Chunks far above target: a single month too big to pack. Review these;
|
|
106
|
+
they may need a finer (weekly or daily) split."""
|
|
107
|
+
return [c for c in chunks if c.est_bytes > target_bytes * factor]
|
lakefreight/cli.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""lakefreight command line.
|
|
2
|
+
|
|
3
|
+
lakefreight plan --metadata tables.csv [--profiles months.csv] [--out generated]
|
|
4
|
+
lakefreight register --format delta|iceberg --table-root s3://bucket/zone/DB/SCHEMA/TABLE
|
|
5
|
+
lakefreight config [--write lakefreight.toml]
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import sys
|
|
12
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from . import generate, register
|
|
16
|
+
from .config import LOCAL_NAME, config_source, default_config_text
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def config_command(argv: list[str], prog: str | None = None) -> int:
|
|
20
|
+
parser = argparse.ArgumentParser(
|
|
21
|
+
prog=prog, description="Show which settings file is used, or write a copy to edit"
|
|
22
|
+
)
|
|
23
|
+
parser.add_argument(
|
|
24
|
+
"--write",
|
|
25
|
+
nargs="?",
|
|
26
|
+
const=LOCAL_NAME,
|
|
27
|
+
metavar="PATH",
|
|
28
|
+
help=f"write the default settings to PATH (default: {LOCAL_NAME})",
|
|
29
|
+
)
|
|
30
|
+
args = parser.parse_args(argv)
|
|
31
|
+
if args.write:
|
|
32
|
+
target = Path(args.write)
|
|
33
|
+
if target.exists():
|
|
34
|
+
print(f"lakefreight config: {target} already exists", file=sys.stderr)
|
|
35
|
+
return 1
|
|
36
|
+
target.write_text(default_config_text(), encoding="utf-8")
|
|
37
|
+
print(f"wrote {target}; edit the CHANGE-ME values")
|
|
38
|
+
return 0
|
|
39
|
+
source = config_source()
|
|
40
|
+
print(f"# settings in use: {source or 'built-in defaults'}")
|
|
41
|
+
print(source.read_text(encoding="utf-8") if source else default_config_text(), end="")
|
|
42
|
+
return 0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
COMMANDS = {
|
|
46
|
+
"plan": (generate.main, "Generate extract SQL and a work-item list from a metadata CSV"),
|
|
47
|
+
"register": (register.main, "Register unloaded Parquet files as a Delta or Iceberg table"),
|
|
48
|
+
"config": (config_command, "Show the settings in use, or write a copy to edit"),
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _version() -> str:
|
|
53
|
+
try:
|
|
54
|
+
return version("lakefreight")
|
|
55
|
+
except PackageNotFoundError:
|
|
56
|
+
return "unknown"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _usage() -> str:
|
|
60
|
+
lines = ["usage: lakefreight <command> [options]", "", "commands:"]
|
|
61
|
+
lines += [f" {name:<10}{desc}" for name, (_, desc) in COMMANDS.items()]
|
|
62
|
+
lines += ["", "Run 'lakefreight <command> --help' for a command's options."]
|
|
63
|
+
return "\n".join(lines)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def main(argv: list[str] | None = None) -> int:
|
|
67
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
68
|
+
if not argv or argv[0] in ("-h", "--help"):
|
|
69
|
+
print(_usage())
|
|
70
|
+
return 0
|
|
71
|
+
if argv[0] in ("-V", "--version"):
|
|
72
|
+
print(f"lakefreight {_version()}")
|
|
73
|
+
return 0
|
|
74
|
+
command = COMMANDS.get(argv[0])
|
|
75
|
+
if command is None:
|
|
76
|
+
print(f"lakefreight: unknown command '{argv[0]}'\n\n{_usage()}", file=sys.stderr)
|
|
77
|
+
return 2
|
|
78
|
+
return command[0](argv[1:], prog=f"lakefreight {argv[0]}")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
if __name__ == "__main__":
|
|
82
|
+
sys.exit(main())
|
lakefreight/config.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Load settings into typed values.
|
|
2
|
+
|
|
3
|
+
Settings are read from the first of these that exists:
|
|
4
|
+
|
|
5
|
+
1. the path passed in (the --config option)
|
|
6
|
+
2. the file named by the LAKEFREIGHT_CONFIG environment variable
|
|
7
|
+
3. lakefreight.toml in the current directory
|
|
8
|
+
4. the defaults shipped with the package (write a copy with `lakefreight config --write`)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import tomllib
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from importlib.resources import files
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
LOCAL_NAME = "lakefreight.toml"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def default_config_text() -> str:
|
|
23
|
+
"""The packaged defaults, as TOML text."""
|
|
24
|
+
return files("lakefreight").joinpath("defaults.toml").read_text(encoding="utf-8")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Zone:
|
|
29
|
+
stage: str
|
|
30
|
+
bucket: str
|
|
31
|
+
prefix: str
|
|
32
|
+
role: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Lane:
|
|
37
|
+
warehouse: str
|
|
38
|
+
max_concurrency: int
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class Settings:
|
|
43
|
+
control_schema: str
|
|
44
|
+
full_threshold_bytes: int
|
|
45
|
+
target_chunk_bytes: int
|
|
46
|
+
max_file_size_bytes: int
|
|
47
|
+
unmatched_token_threshold: int
|
|
48
|
+
xref_table: str
|
|
49
|
+
xref_token_column: str
|
|
50
|
+
xref_clear_column: str
|
|
51
|
+
zones: dict[str, Zone]
|
|
52
|
+
lanes: dict[str, Lane]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def config_source(path: str | Path | None = None) -> Path | None:
|
|
56
|
+
"""The settings file that will be used, or None for the packaged defaults."""
|
|
57
|
+
if path:
|
|
58
|
+
return Path(path)
|
|
59
|
+
if os.environ.get("LAKEFREIGHT_CONFIG"):
|
|
60
|
+
return Path(os.environ["LAKEFREIGHT_CONFIG"])
|
|
61
|
+
if Path(LOCAL_NAME).is_file():
|
|
62
|
+
return Path(LOCAL_NAME)
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def load_settings(path: str | Path | None = None) -> Settings:
|
|
67
|
+
source = config_source(path)
|
|
68
|
+
if source is None:
|
|
69
|
+
raw = tomllib.loads(default_config_text())
|
|
70
|
+
else:
|
|
71
|
+
with open(source, "rb") as f:
|
|
72
|
+
raw = tomllib.load(f)
|
|
73
|
+
ex, xref = raw["extract"], raw["xref"]
|
|
74
|
+
return Settings(
|
|
75
|
+
control_schema=ex["control_schema"],
|
|
76
|
+
full_threshold_bytes=int(ex["full_threshold_bytes"]),
|
|
77
|
+
target_chunk_bytes=int(ex["target_chunk_bytes"]),
|
|
78
|
+
max_file_size_bytes=int(ex["max_file_size_bytes"]),
|
|
79
|
+
unmatched_token_threshold=int(ex["unmatched_token_threshold"]),
|
|
80
|
+
xref_table=xref["table"],
|
|
81
|
+
xref_token_column=xref["token_column"],
|
|
82
|
+
xref_clear_column=xref["clear_column"],
|
|
83
|
+
zones={k: Zone(**v) for k, v in raw["zones"].items()},
|
|
84
|
+
lanes={k: Lane(**v) for k, v in raw["lanes"].items()},
|
|
85
|
+
)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Defaults for the migration. Every value marked CHANGE-ME is a placeholder.
|
|
2
|
+
|
|
3
|
+
[extract]
|
|
4
|
+
control_schema = "MIGRATION.CONTROL" # CHANGE-ME: database.schema holding the control tables
|
|
5
|
+
full_threshold_bytes = 107374182400 # 100 GiB: at or below this, one COPY for the whole table
|
|
6
|
+
target_chunk_bytes = 80530636800 # 75 GiB: target size of one chunk for larger tables
|
|
7
|
+
max_file_size_bytes = 1073741824 # 1 GiB Parquet part files
|
|
8
|
+
unmatched_token_threshold = 0 # restricted zone: max non-null tokens with no xref match per chunk
|
|
9
|
+
|
|
10
|
+
[xref]
|
|
11
|
+
table = "SECURE.PUBLIC.TOKEN_XREF" # CHANGE-ME: fully qualified name
|
|
12
|
+
token_column = "TOKEN_VALUE" # CHANGE-ME
|
|
13
|
+
clear_column = "CLEAR_VALUE" # CHANGE-ME
|
|
14
|
+
|
|
15
|
+
# One zone per sensitivity class. The stage URL must be s3://<bucket>/<prefix>/.
|
|
16
|
+
[zones.INTERNAL]
|
|
17
|
+
stage = "MIGRATION.CONTROL.EGRESS_INTERNAL_STAGE"
|
|
18
|
+
bucket = "CHANGE-ME-egress"
|
|
19
|
+
prefix = "internal"
|
|
20
|
+
role = "MIG_INTERNAL_EXTRACT"
|
|
21
|
+
|
|
22
|
+
[zones.PII]
|
|
23
|
+
stage = "MIGRATION.CONTROL.EGRESS_PII_STAGE"
|
|
24
|
+
bucket = "CHANGE-ME-egress"
|
|
25
|
+
prefix = "pii"
|
|
26
|
+
role = "MIG_PII_EXTRACT"
|
|
27
|
+
|
|
28
|
+
[zones.RESTRICTED]
|
|
29
|
+
stage = "MIGRATION.CONTROL.EGRESS_RESTRICTED_STAGE"
|
|
30
|
+
bucket = "CHANGE-ME-egress-restricted"
|
|
31
|
+
prefix = "restricted"
|
|
32
|
+
role = "MIG_RESTRICTED_EXTRACT" # the only role with SELECT on the xref
|
|
33
|
+
|
|
34
|
+
# One lane per Step Functions execution, each with its own warehouse.
|
|
35
|
+
[lanes.LARGE]
|
|
36
|
+
warehouse = "MIG_LARGE_WH"
|
|
37
|
+
max_concurrency = 8
|
|
38
|
+
|
|
39
|
+
[lanes.SMALL]
|
|
40
|
+
warehouse = "MIG_SMALL_WH"
|
|
41
|
+
max_concurrency = 32
|
|
42
|
+
|
|
43
|
+
[lanes.RESTRICTED]
|
|
44
|
+
warehouse = "MIG_RESTRICTED_WH"
|
|
45
|
+
max_concurrency = 4
|
lakefreight/generate.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"""Generate extract SQL offline from a metadata CSV. No Snowflake access needed.
|
|
2
|
+
|
|
3
|
+
lakefreight plan --metadata examples/metadata_sample.csv \
|
|
4
|
+
--profiles examples/profiles_sample.csv --out generated
|
|
5
|
+
|
|
6
|
+
Writes one .sql file per work item under <out>/<ZONE>/<db>.<schema>.<table>/
|
|
7
|
+
and a work_items.csv summary. Large tables with no month profile get a
|
|
8
|
+
profile.sql to run first; rerun with --profiles once you have the results.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import csv
|
|
15
|
+
import sys
|
|
16
|
+
from collections import Counter
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from datetime import date
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from . import chunk_planner, renderer
|
|
22
|
+
from .config import Settings, load_settings
|
|
23
|
+
from .models import ColumnSpec, TableSpec, resolve_zone
|
|
24
|
+
|
|
25
|
+
REQUIRED = {
|
|
26
|
+
"table_database",
|
|
27
|
+
"table_schema",
|
|
28
|
+
"table_name",
|
|
29
|
+
"table_size_bytes",
|
|
30
|
+
"table_pii_flag",
|
|
31
|
+
"table_restricted_flag",
|
|
32
|
+
"column_name",
|
|
33
|
+
"column_datatype",
|
|
34
|
+
"column_pii_flag",
|
|
35
|
+
"column_restricted_flag",
|
|
36
|
+
}
|
|
37
|
+
OPTIONAL = {"column_ordinal", "column_length", "column_description", "chunk_column"}
|
|
38
|
+
SUMMARY_FIELDS = [
|
|
39
|
+
"database",
|
|
40
|
+
"schema",
|
|
41
|
+
"table",
|
|
42
|
+
"zone",
|
|
43
|
+
"lane",
|
|
44
|
+
"strategy",
|
|
45
|
+
"chunk_id",
|
|
46
|
+
"est_bytes",
|
|
47
|
+
"status",
|
|
48
|
+
"file",
|
|
49
|
+
"notes",
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class TableMeta:
|
|
55
|
+
spec: TableSpec
|
|
56
|
+
table_bytes: int
|
|
57
|
+
chunk_column: str | None
|
|
58
|
+
notes: list[str] = field(default_factory=list)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _flag(value: str | None) -> str | None:
|
|
62
|
+
value = (value or "").strip().upper()
|
|
63
|
+
return value if value in ("Y", "N") else None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _read_rows(path: Path, required: set[str]) -> list[dict[str, str]]:
|
|
67
|
+
with open(path, newline="", encoding="utf-8-sig") as f:
|
|
68
|
+
reader = csv.DictReader(f)
|
|
69
|
+
headers = {(h or "").strip().lower() for h in reader.fieldnames or []}
|
|
70
|
+
missing = required - headers
|
|
71
|
+
if missing:
|
|
72
|
+
raise ValueError(f"{path}: missing columns {sorted(missing)}")
|
|
73
|
+
rows = []
|
|
74
|
+
for line, row in enumerate(reader, start=2):
|
|
75
|
+
if None in row: # more values than headers, usually an unquoted comma
|
|
76
|
+
raise ValueError(
|
|
77
|
+
f"{path} line {line}: too many values; quote fields that contain "
|
|
78
|
+
'commas, such as "NUMBER(38,0)"'
|
|
79
|
+
)
|
|
80
|
+
rows.append({(k or "").strip().lower(): (v or "").strip() for k, v in row.items()})
|
|
81
|
+
return rows
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def pick_chunk_column(columns: tuple[ColumnSpec, ...]) -> str | None:
|
|
85
|
+
"""First guess at a date column to chunk on. Load dates first, because
|
|
86
|
+
tables are usually clustered in load order; update dates last."""
|
|
87
|
+
|
|
88
|
+
def rank(name: str) -> int:
|
|
89
|
+
name = name.upper()
|
|
90
|
+
if any(k in name for k in ("LOAD", "INSERT", "CREAT")):
|
|
91
|
+
return 1
|
|
92
|
+
if any(k in name for k in ("TXN", "TRANS", "EVENT", "POST")):
|
|
93
|
+
return 2
|
|
94
|
+
if any(k in name for k in ("UPDAT", "MODIF")):
|
|
95
|
+
return 4
|
|
96
|
+
return 3
|
|
97
|
+
|
|
98
|
+
dated = [c for c in columns if c.data_type.upper().startswith(("DATE", "TIMESTAMP"))]
|
|
99
|
+
return min(dated, key=lambda c: (rank(c.name), c.name)).name if dated else None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def read_metadata(path: str | Path) -> list[TableMeta]:
|
|
103
|
+
"""One row per column in the CSV; returns one TableMeta per table."""
|
|
104
|
+
grouped: dict[tuple[str, str, str], list[dict[str, str]]] = {}
|
|
105
|
+
for row in _read_rows(Path(path), REQUIRED):
|
|
106
|
+
key = (row["table_database"], row["table_schema"], row["table_name"])
|
|
107
|
+
grouped.setdefault(key, []).append(row)
|
|
108
|
+
|
|
109
|
+
tables = []
|
|
110
|
+
for (db, schema, table), rows in grouped.items():
|
|
111
|
+
notes: list[str] = []
|
|
112
|
+
if all(r.get("column_ordinal") for r in rows):
|
|
113
|
+
rows = sorted(rows, key=lambda r: int(float(r["column_ordinal"])))
|
|
114
|
+
columns = tuple(
|
|
115
|
+
ColumnSpec(
|
|
116
|
+
name=r["column_name"],
|
|
117
|
+
data_type=r["column_datatype"].upper(),
|
|
118
|
+
use_xref=_flag(r["column_restricted_flag"]) == "Y",
|
|
119
|
+
length=int(float(r["column_length"])) if r.get("column_length") else None,
|
|
120
|
+
description=r.get("column_description") or None,
|
|
121
|
+
pii_flag=_flag(r["column_pii_flag"]),
|
|
122
|
+
restricted_flag=_flag(r["column_restricted_flag"]),
|
|
123
|
+
)
|
|
124
|
+
for r in rows
|
|
125
|
+
)
|
|
126
|
+
restricted, pii = _flag(rows[0]["table_restricted_flag"]), _flag(rows[0]["table_pii_flag"])
|
|
127
|
+
# A flagged column outranks the table flag: route to the stricter zone.
|
|
128
|
+
if any(c.restricted_flag == "Y" for c in columns) and restricted != "Y":
|
|
129
|
+
notes.append("column flagged restricted but table flag is not Y; routed to RESTRICTED")
|
|
130
|
+
restricted = "Y"
|
|
131
|
+
if any(c.pii_flag == "Y" for c in columns) and pii != "Y":
|
|
132
|
+
notes.append("column flagged PII but table flag is not Y; treated as PII")
|
|
133
|
+
pii = "Y"
|
|
134
|
+
if restricted is None or pii is None:
|
|
135
|
+
notes.append("table PII/RESTRICTED flag missing; treated as sensitive")
|
|
136
|
+
zone = resolve_zone(restricted, pii)
|
|
137
|
+
if zone == "RESTRICTED" and not any(c.use_xref for c in columns):
|
|
138
|
+
notes.append("RESTRICTED table with no restricted column; nothing will be detokenized")
|
|
139
|
+
try:
|
|
140
|
+
table_bytes = int(float(rows[0]["table_size_bytes"] or 0))
|
|
141
|
+
except ValueError:
|
|
142
|
+
table_bytes = 0
|
|
143
|
+
notes.append("table size is not a number; treated as 0")
|
|
144
|
+
tables.append(
|
|
145
|
+
TableMeta(
|
|
146
|
+
spec=TableSpec(db, schema, table, zone, columns),
|
|
147
|
+
table_bytes=table_bytes,
|
|
148
|
+
chunk_column=rows[0].get("chunk_column") or pick_chunk_column(columns),
|
|
149
|
+
notes=notes,
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
return tables
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def read_profiles(path: str | Path) -> dict[tuple[str, str, str], list[tuple[date | None, int]]]:
|
|
156
|
+
"""Month profile results: table_database, table_schema, table_name,
|
|
157
|
+
month_start (blank for NULL dates), row_count."""
|
|
158
|
+
required = {"table_database", "table_schema", "table_name", "month_start", "row_count"}
|
|
159
|
+
profiles: dict[tuple[str, str, str], list[tuple[date | None, int]]] = {}
|
|
160
|
+
for row in _read_rows(Path(path), required):
|
|
161
|
+
key = (row["table_database"], row["table_schema"], row["table_name"])
|
|
162
|
+
month = date.fromisoformat(row["month_start"][:10]) if row["month_start"] else None
|
|
163
|
+
profiles.setdefault(key, []).append((month, int(float(row["row_count"]))))
|
|
164
|
+
return profiles
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _statements(meta: TableMeta, chunk, run_id: str, settings: Settings) -> str:
|
|
168
|
+
spec = meta.spec
|
|
169
|
+
parts = [
|
|
170
|
+
f"-- {spec.path} chunk {chunk.chunk_id} ({spec.zone})",
|
|
171
|
+
"-- 1. Unload",
|
|
172
|
+
renderer.unload_sql(spec, chunk.predicate, chunk.chunk_id, run_id, settings) + ";",
|
|
173
|
+
"-- 2. Source row count: must equal the rows unloaded",
|
|
174
|
+
renderer.source_count_sql(spec, chunk.predicate) + ";",
|
|
175
|
+
]
|
|
176
|
+
unmatched = renderer.unmatched_sql(spec, chunk.predicate, settings)
|
|
177
|
+
if unmatched:
|
|
178
|
+
parts += ["-- 3. Tokens with no xref match: must be within the threshold", unmatched + ";"]
|
|
179
|
+
return "\n\n".join(parts) + "\n"
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def generate(
|
|
183
|
+
tables: list[TableMeta],
|
|
184
|
+
profiles: dict,
|
|
185
|
+
settings: Settings,
|
|
186
|
+
out_dir: str | Path,
|
|
187
|
+
run_id: str = "manual",
|
|
188
|
+
) -> list[dict]:
|
|
189
|
+
"""Write the SQL files and return the summary rows."""
|
|
190
|
+
out_dir = Path(out_dir)
|
|
191
|
+
summary: list[dict] = []
|
|
192
|
+
for meta in tables:
|
|
193
|
+
spec = meta.spec
|
|
194
|
+
key = (spec.database, spec.schema, spec.table)
|
|
195
|
+
notes = list(meta.notes)
|
|
196
|
+
chunked = meta.table_bytes > settings.full_threshold_bytes
|
|
197
|
+
lane = "RESTRICTED" if spec.zone == "RESTRICTED" else ("LARGE" if chunked else "SMALL")
|
|
198
|
+
base = dict(
|
|
199
|
+
database=spec.database,
|
|
200
|
+
schema=spec.schema,
|
|
201
|
+
table=spec.table,
|
|
202
|
+
zone=spec.zone,
|
|
203
|
+
lane=lane,
|
|
204
|
+
strategy="CHUNKED" if chunked else "FULL",
|
|
205
|
+
)
|
|
206
|
+
rel_dir = Path(spec.zone) / ".".join(key)
|
|
207
|
+
|
|
208
|
+
def row(chunk_id, est_bytes, status, file, extra=(), base=base, notes=notes):
|
|
209
|
+
summary.append(
|
|
210
|
+
{
|
|
211
|
+
**base,
|
|
212
|
+
"chunk_id": chunk_id,
|
|
213
|
+
"est_bytes": est_bytes,
|
|
214
|
+
"status": status,
|
|
215
|
+
"file": str(file),
|
|
216
|
+
"notes": "; ".join([*notes, *extra]),
|
|
217
|
+
}
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
try:
|
|
221
|
+
if chunked and meta.chunk_column and key not in profiles:
|
|
222
|
+
target = out_dir / rel_dir / "profile.sql"
|
|
223
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
224
|
+
target.write_text(
|
|
225
|
+
f"-- Run this, save the result, and pass it with --profiles.\n"
|
|
226
|
+
f"{chunk_planner.profile_sql(spec.source_fqn, meta.chunk_column)};\n"
|
|
227
|
+
)
|
|
228
|
+
row(
|
|
229
|
+
"",
|
|
230
|
+
meta.table_bytes,
|
|
231
|
+
"NEEDS_PROFILE",
|
|
232
|
+
rel_dir / "profile.sql",
|
|
233
|
+
[f"chunk column {meta.chunk_column}: confirm it prunes before using it"],
|
|
234
|
+
)
|
|
235
|
+
continue
|
|
236
|
+
|
|
237
|
+
if chunked and meta.chunk_column:
|
|
238
|
+
chunks = chunk_planner.plan_chunks(
|
|
239
|
+
meta.chunk_column, profiles[key], meta.table_bytes, settings.target_chunk_bytes
|
|
240
|
+
)
|
|
241
|
+
big = {
|
|
242
|
+
c.chunk_id for c in chunk_planner.oversized(chunks, settings.target_chunk_bytes)
|
|
243
|
+
}
|
|
244
|
+
else:
|
|
245
|
+
chunks, big = [chunk_planner.full_chunk(meta.table_bytes)], set()
|
|
246
|
+
if chunked:
|
|
247
|
+
notes.append("over the size threshold with no date column; single pass")
|
|
248
|
+
|
|
249
|
+
for chunk in chunks:
|
|
250
|
+
target = out_dir / rel_dir / f"{chunk.chunk_id}.sql"
|
|
251
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
252
|
+
target.write_text(_statements(meta, chunk, run_id, settings))
|
|
253
|
+
extra = (
|
|
254
|
+
["far above target size; consider a finer split"]
|
|
255
|
+
if chunk.chunk_id in big
|
|
256
|
+
else []
|
|
257
|
+
)
|
|
258
|
+
row(
|
|
259
|
+
chunk.chunk_id,
|
|
260
|
+
chunk.est_bytes,
|
|
261
|
+
"READY",
|
|
262
|
+
rel_dir / f"{chunk.chunk_id}.sql",
|
|
263
|
+
extra,
|
|
264
|
+
)
|
|
265
|
+
except ValueError as exc:
|
|
266
|
+
row("", meta.table_bytes, "ERROR", "", [str(exc)])
|
|
267
|
+
|
|
268
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
269
|
+
with open(out_dir / "work_items.csv", "w", newline="") as f:
|
|
270
|
+
writer = csv.DictWriter(f, fieldnames=SUMMARY_FIELDS)
|
|
271
|
+
writer.writeheader()
|
|
272
|
+
writer.writerows(summary)
|
|
273
|
+
return summary
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def main(argv: list[str] | None = None, prog: str | None = None) -> int:
|
|
277
|
+
parser = argparse.ArgumentParser(prog=prog, description=__doc__.splitlines()[0])
|
|
278
|
+
parser.add_argument("--metadata", required=True, help="metadata CSV, one row per column")
|
|
279
|
+
parser.add_argument("--profiles", help="month profile CSV for large tables")
|
|
280
|
+
parser.add_argument("--out", default="generated", help="output directory")
|
|
281
|
+
parser.add_argument(
|
|
282
|
+
"--config",
|
|
283
|
+
help="settings TOML (default: $LAKEFREIGHT_CONFIG, ./lakefreight.toml, or built-in defaults)",
|
|
284
|
+
)
|
|
285
|
+
parser.add_argument("--run-id", default="manual", help="run id used in the unload path")
|
|
286
|
+
args = parser.parse_args(argv)
|
|
287
|
+
|
|
288
|
+
settings = load_settings(args.config)
|
|
289
|
+
tables = read_metadata(args.metadata)
|
|
290
|
+
profiles = read_profiles(args.profiles) if args.profiles else {}
|
|
291
|
+
summary = generate(tables, profiles, settings, args.out, args.run_id)
|
|
292
|
+
|
|
293
|
+
by_status = Counter(r["status"] for r in summary)
|
|
294
|
+
by_zone = Counter(r["zone"] for r in summary if r["status"] == "READY")
|
|
295
|
+
print(f"{len(tables)} tables -> {len(summary)} work items in {args.out}/")
|
|
296
|
+
print(" status: " + ", ".join(f"{k} {v}" for k, v in sorted(by_status.items())))
|
|
297
|
+
print(
|
|
298
|
+
" ready by zone: " + (", ".join(f"{k} {v}" for k, v in sorted(by_zone.items())) or "none")
|
|
299
|
+
)
|
|
300
|
+
flagged = [r for r in summary if r["notes"]]
|
|
301
|
+
seen = set()
|
|
302
|
+
for r in flagged:
|
|
303
|
+
label = f"{r['database']}.{r['schema']}.{r['table']}"
|
|
304
|
+
if (label, r["notes"]) not in seen:
|
|
305
|
+
seen.add((label, r["notes"]))
|
|
306
|
+
print(f" note: {label}: {r['notes']}")
|
|
307
|
+
return 1 if by_status.get("ERROR") else 0
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
if __name__ == "__main__":
|
|
311
|
+
sys.exit(main())
|