masked files and script
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
"account_id","user_id","account_number","account_name","account_type","created_at","updated_at"
|
||||
1,3,"79967586SCHW",Contributory IRA,,2026-03-06 08:15:28.167 -0500,2026-03-06 08:15:28.167 -0500
|
||||
2,3,"70445085SCHW",Individual,,2026-03-06 08:15:28.167 -0500,2026-03-06 08:15:28.167 -0500
|
||||
3,1,"1102517",,,2026-03-26 22:24:13.119 -0400,2026-03-26 22:24:13.119 -0400
|
||||
4,3,"1102517",,,2026-05-05 07:08:33.683 -0400,2026-05-05 07:08:33.683 -0400
|
||||
5,3,DEMO1507475,,,2026-10-17 08:45:32.501 -0400,2026-10-17 08:45:32.501 -0400
|
||||
1,3,"AcctA",Contributory IRA,,2026-03-06 08:15:28.167 -0500,2026-03-06 08:15:28.167 -0500
|
||||
2,3,"AcctB",Individual,,2026-03-06 08:15:28.167 -0500,2026-03-06 08:15:28.167 -0500
|
||||
3,1,"AcctC",,,2026-03-26 22:24:13.119 -0400,2026-03-26 22:24:13.119 -0400
|
||||
4,3,"AcctD",,,2026-05-05 07:08:33.683 -0400,2026-05-05 07:08:33.683 -0400
|
||||
5,3,"AcctE",,,2026-10-17 08:45:32.501 -0400,2026-10-17 08:45:32.501 -0400
|
||||
|
||||
|
@@ -1,8 +1,8 @@
|
||||
"source_id","user_id","source_name","is_active","created_at","updated_at"
|
||||
1,2,Trade Ideas,true,2026-03-08 15:20:20.853 -0400,2026-03-08 15:20:20.853 -0400
|
||||
2,2,Mike Edwards,true,2026-03-08 15:20:30.892 -0400,2026-03-08 15:20:30.892 -0400
|
||||
2,2,Mike,true,2026-03-08 15:20:30.892 -0400,2026-03-08 15:20:30.892 -0400
|
||||
3,3,Trade Ideas,true,2026-03-08 19:40:50.021 -0400,2026-03-08 19:40:50.021 -0400
|
||||
4,3,Mike Edwards,true,2026-03-08 19:40:52.988 -0400,2026-03-08 19:40:52.988 -0400
|
||||
4,3,Mike,true,2026-03-08 19:40:52.988 -0400,2026-03-08 19:40:52.988 -0400
|
||||
5,3,MARI,true,2026-03-11 21:50:04.110 -0400,2026-03-11 21:50:04.110 -0400
|
||||
6,3,Adam,true,2026-03-12 12:53:21.940 -0400,2026-03-12 12:53:21.940 -0400
|
||||
7,3,Cha Martin,true,2026-08-13 13:41:03.179 -0400,2026-08-13 13:41:03.179 -0400
|
||||
7,3,Cha,true,2026-08-13 13:41:03.179 -0400,2026-08-13 13:41:03.179 -0400
|
||||
|
||||
|
202
sources/database/tests/test_changed_files.py
Normal file
202
sources/database/tests/test_changed_files.py
Normal file
@@ -0,0 +1,202 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Report which database-dump files changed relative to a git baseline.
|
||||
|
||||
The dump folder (schema.sql, data.sql, one CSV per table) is committed, so git
|
||||
is the change detector: the baseline is `git show <base>:<path>` and the new
|
||||
state is the working tree (staged, unstaged and untracked all count).
|
||||
|
||||
Exit status: 0 = no completeness problems, 1 = completeness warnings,
|
||||
2 = could not run (not a git repo, bad ref, ...).
|
||||
|
||||
Usage: python3 tests/test_changed_files.py [--base REF] [--json]
|
||||
Also collectable by pytest (test_* functions at the bottom).
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
DB_DIR = Path(__file__).resolve().parent.parent
|
||||
TESTS_DIR = Path(__file__).resolve().parent
|
||||
SCHEMA = "schema.sql"
|
||||
DATA = "data.sql"
|
||||
|
||||
STATUS_NAMES = {"A": "added", "M": "modified", "D": "deleted", "R": "renamed",
|
||||
"C": "copied", "T": "type-changed", "U": "unmerged", "?": "untracked"}
|
||||
|
||||
|
||||
class GitError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def git(*args, check=True):
|
||||
p = subprocess.run(["git", *args], cwd=DB_DIR, capture_output=True)
|
||||
if check and p.returncode != 0:
|
||||
raise GitError(f"git {' '.join(args)}: {p.stderr.decode(errors='replace').strip()}")
|
||||
return p.stdout
|
||||
|
||||
|
||||
def git_text(*args):
|
||||
return git(*args).decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def under_tests(rel):
|
||||
return (DB_DIR / rel).resolve().is_relative_to(TESTS_DIR)
|
||||
|
||||
|
||||
def changed_files(base):
|
||||
"""Return {path: {"status", "old_path"?, "stat"}} for files in this folder.
|
||||
|
||||
Paths are relative to the database folder. The tests/ folder is excluded.
|
||||
"""
|
||||
git("rev-parse", "--verify", "--quiet", f"{base}^{{commit}}")
|
||||
out = git("diff", "--name-status", "-z", "-M", "--relative", base, "--", ".")
|
||||
parts = out.decode("utf-8", errors="replace").split("\0")
|
||||
files, i = {}, 0
|
||||
while i < len(parts) and parts[i]:
|
||||
code = parts[i][0]
|
||||
if code in "RC":
|
||||
old, new = parts[i + 1], parts[i + 2]
|
||||
i += 3
|
||||
files[new] = {"status": STATUS_NAMES[code], "old_path": old}
|
||||
else:
|
||||
files[parts[i + 1]] = {"status": STATUS_NAMES.get(code, code)}
|
||||
i += 2
|
||||
untracked = git("ls-files", "--others", "--exclude-standard", "-z", "--", ".")
|
||||
for p in untracked.decode("utf-8", errors="replace").split("\0"):
|
||||
if p:
|
||||
files.setdefault(p, {"status": "untracked"})
|
||||
files = {p: v for p, v in files.items() if not under_tests(p)}
|
||||
|
||||
# size of each change; binary/untracked files report no stat
|
||||
stat = git_text("diff", "--numstat", "-M", "--relative", base, "--", ".")
|
||||
for line in stat.splitlines():
|
||||
add, dele, path = line.split("\t", 2)
|
||||
if " => " in path or path not in files:
|
||||
continue
|
||||
files[path]["stat"] = {"added": add, "removed": dele}
|
||||
return files
|
||||
|
||||
|
||||
def tables_in_schema(text):
|
||||
return set(re.findall(r"^CREATE TABLE public\.(\w+) \(", text, re.M))
|
||||
|
||||
|
||||
def csv_header(text):
|
||||
try:
|
||||
return next(csv.reader(io.StringIO(text)))
|
||||
except StopIteration:
|
||||
return []
|
||||
|
||||
|
||||
def base_text(base, path):
|
||||
p = git("show", f"{base}:./{path}", check=False)
|
||||
return p.decode("utf-8", errors="replace") if p else None
|
||||
|
||||
|
||||
def analyze(base="HEAD"):
|
||||
files = changed_files(base)
|
||||
csv_files = {p: v for p, v in files.items() if p.endswith(".csv")}
|
||||
other = {p: v for p, v in files.items() if not p.endswith(".csv")}
|
||||
|
||||
schema_tables = tables_in_schema((DB_DIR / SCHEMA).read_text(encoding="utf-8"))
|
||||
csv_tables_now = {p.stem for p in DB_DIR.glob("*.csv")}
|
||||
|
||||
# CSV <-> table name for changed CSVs; header changes read from git + disk
|
||||
header_changes = {}
|
||||
for path, info in csv_files.items():
|
||||
old_path = info.get("old_path", path)
|
||||
old = base_text(base, old_path) if info["status"] not in ("added", "untracked") else None
|
||||
new_file = DB_DIR / path
|
||||
new = new_file.read_text(encoding="utf-8") if new_file.exists() else None
|
||||
old_h = csv_header(old) if old is not None else None
|
||||
new_h = csv_header(new) if new is not None else None
|
||||
if old_h is not None and new_h is not None and old_h != new_h:
|
||||
header_changes[path] = {"removed": [c for c in old_h if c not in new_h],
|
||||
"added": [c for c in new_h if c not in old_h],
|
||||
"reordered": sorted(old_h) == sorted(new_h)}
|
||||
|
||||
changed_csv_tables = {Path(p).stem for p in csv_files}
|
||||
schema_changed = SCHEMA in other
|
||||
data_changed = DATA in other
|
||||
|
||||
warnings = []
|
||||
if changed_csv_tables and not data_changed:
|
||||
warnings.append(f"CSV changed ({', '.join(sorted(changed_csv_tables))}) but {DATA} did not")
|
||||
if data_changed and not changed_csv_tables:
|
||||
warnings.append(f"{DATA} changed but no CSV did")
|
||||
if header_changes and not schema_changed:
|
||||
warnings.append(f"CSV header changed ({', '.join(sorted(header_changes))}) but {SCHEMA} did not")
|
||||
if schema_changed and not (data_changed or changed_csv_tables):
|
||||
warnings.append(f"{SCHEMA} changed but neither {DATA} nor any CSV did")
|
||||
for t in sorted(schema_tables - csv_tables_now):
|
||||
warnings.append(f"table '{t}' in {SCHEMA} has no {t}.csv")
|
||||
for t in sorted(csv_tables_now - schema_tables):
|
||||
warnings.append(f"{t}.csv has no table '{t}' in {SCHEMA}")
|
||||
for p in sorted(other):
|
||||
if p not in (SCHEMA, DATA):
|
||||
warnings.append(f"unexpected changed file: {p}")
|
||||
|
||||
return {"base": base, "files": files, "header_changes": header_changes,
|
||||
"changed_tables": sorted(changed_csv_tables), "warnings": warnings}
|
||||
|
||||
|
||||
def render(report):
|
||||
files = report["files"]
|
||||
lines = [f"Baseline: {report['base']} (working tree vs baseline)", ""]
|
||||
if not files:
|
||||
lines.append("No changed files.")
|
||||
for group, pick in (("schema", lambda p: p == SCHEMA), ("data", lambda p: p == DATA),
|
||||
("csv", lambda p: p.endswith(".csv")),
|
||||
("other", lambda p: p not in (SCHEMA, DATA) and not p.endswith(".csv"))):
|
||||
rows = sorted(p for p in files if pick(p))
|
||||
if not rows:
|
||||
continue
|
||||
lines.append(f"[{group}]")
|
||||
for p in rows:
|
||||
v = files[p]
|
||||
size = f" +{v['stat']['added']} -{v['stat']['removed']}" if "stat" in v else ""
|
||||
ren = f" (from {v['old_path']})" if "old_path" in v else ""
|
||||
lines.append(f" {v['status']:<12} {p}{ren}{size}")
|
||||
h = report["header_changes"].get(p)
|
||||
if h:
|
||||
if h["reordered"]:
|
||||
lines.append(" header: columns reordered")
|
||||
else:
|
||||
lines.append(f" header: +{h['added']} -{h['removed']}")
|
||||
lines.append("")
|
||||
if report["warnings"]:
|
||||
lines.append("Completeness warnings:")
|
||||
lines += [f" ! {w}" for w in report["warnings"]]
|
||||
else:
|
||||
lines.append("Completeness: OK")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ---- pytest entry points -------------------------------------------------
|
||||
|
||||
def test_dump_files_are_consistent():
|
||||
report = analyze()
|
||||
assert not report["warnings"], "\n" + render(report)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
ap.add_argument("--base", default="HEAD", help="git ref to compare against (default HEAD)")
|
||||
ap.add_argument("--json", action="store_true", help="emit JSON instead of text")
|
||||
args = ap.parse_args()
|
||||
try:
|
||||
report = analyze(args.base)
|
||||
except GitError as e:
|
||||
print(f"error: {e}", file=sys.stderr)
|
||||
return 2
|
||||
print(json.dumps(report, indent=2) if args.json else render(report))
|
||||
return 1 if report["warnings"] else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,4 +1,4 @@
|
||||
"user_id","username","email","password_hash","auth_method","is_active","is_admin","api_key_hash","api_key_created_at","created_at","updated_at","last_login_at","timezone"
|
||||
1,system,system@trading-journal.local,,api_key,true,true,,,2025-11-27 13:56:11.561 -0500,2025-11-27 13:56:11.561 -0500,,US/Eastern
|
||||
3,Eric,eric@polymorph.co,scrypt:32768:8:1$VHGit0KzIgbNEYQf$abd5dff97fd44bd56a9a7848ab3519cbe3d94bf3c86cb7484719164e44e46a6102a1ce01af6a694547be02d4f50e210f42a83b9525ceb2829449020716e48d9e,api_key,true,true,a3033f7208a6dd7053a302c3f61c9b8512fb6ff2ae479b17c2804078992caf39,2025-11-28 15:48:36.807 -0500,2025-11-28 15:48:35.525 -0500,2026-03-28 15:15:33.251 -0400,2026-03-03 20:37:21.303 -0500,US/Eastern
|
||||
3,Eric,eric@example.com,scrypt:32768:8:1$VHGit0KzIgbNEYQf$abd5dff97fd44bd56a9a7848ab3519cbe3d94bf3c86cb7484719164e44e46a6102a1ce01af6a694547be02d4f50e210f42a83b9525ceb2829449020716e48d9e,api_key,true,true,a3033f7208a6dd7053a302c3f61c9b8512fb6ff2ae479b17c2804078992caf39,2025-11-28 15:48:36.807 -0500,2025-11-28 15:48:35.525 -0500,2026-03-28 15:15:33.251 -0400,2026-03-03 20:37:21.303 -0500,US/Eastern
|
||||
2,default_user,user@example.com,scrypt:32768:8:1$DvgQUisnUPYN7AQc$9d08418db69c75dc6df6d6db5a288d3c7b4875a16b176b91d5b7b64ea7fb4e0946dc7da01cb9bde51919efe38febe9a6d9bad91f09e22e9e1de609d9527eb713,api_key,true,false,"2bfcd22bdeb3625d6e1729698adc2420aa2b32c2281af14eca2f21fbc01519da",,2025-11-27 13:56:20.250 -0500,2026-08-21 16:17:15.098 -0400,2025-11-27 13:56:59.869 -0500,US/Eastern
|
||||
|
||||
|
Reference in New Issue
Block a user