mvd001/cyberset / scripts /code /load_cvefixes_meta.py
mvd001's picture
download
raw
3.47 kB
#!/usr/bin/env python3
"""Rebuild the small CVEfixes metadata DB used by ingest_fixdb_stream.py, streaming CVEfixes_v1.0.8.sql.gz out of the Zenodo zip.
Kept: fixes, commits, cve, cwe_classification (as dumped) and file_change *without* code blobs (stored as file_change_slim via an
INSTEAD OF trigger on a view named file_change). Skipped: method_change (streamed separately), cwe, repository.
Statement boundaries are found with a streaming single-quote parity scan (SQLite escapes ' as ''), so skipped statements
are never held in memory. Usage: load_cvefixes_meta.py <zip> <member> <out.db>"""
import sys, zipfile, gzip, io, re, sqlite3, os
zp, member, out = sys.argv[1:4]
if os.path.exists(out): os.remove(out)
con = sqlite3.connect(out); con.execute("PRAGMA journal_mode=OFF"); con.execute("PRAGMA synchronous=OFF"); cur = con.cursor()
FC_KEEP = ["file_change_id", "hash", "filename", "old_path", "new_path", "change_type", "num_lines_added", "num_lines_deleted",
"programming_language", "nloc", "complexity", "token_count"]
DROP_TABLES = {"method_change", "cwe", "repository"}
TABLE_RX = re.compile(r'\s*(?:CREATE TABLE(?: IF NOT EXISTS)?|INSERT INTO)\s+[`"\[]?(\w+)', re.I)
def table_of(head):
m = TABLE_RX.match(head); return m.group(1).lower() if m else None
def handle(stmt):
s = stmt.lstrip(); up = s[:20].upper()
if up.startswith(("BEGIN", "COMMIT", "PRAGMA")): return
if up.startswith("CREATE TABLE") and table_of(s) == "file_change":
body = s[s.index("(") + 1:s.rindex(")")]; parts, depth, cur_ = [], 0, ""
for ch in body: # split column defs on top-level commas
depth += (ch == "(") - (ch == ")")
if ch == "," and depth == 0: parts.append(cur_); cur_ = ""
else: cur_ += ch
parts.append(cur_)
cols = [re.match(r'\s*[`"\[]?(\w+)', x).group(1) for x in parts if x.strip()]
cols = [c for c in cols if c.upper() not in ("PRIMARY", "FOREIGN", "UNIQUE", "CONSTRAINT", "CHECK")]
keep = [c for c in cols if c in FC_KEEP]
cur.execute(f"CREATE TABLE file_change_slim ({', '.join(keep)})")
cur.execute(f"CREATE VIEW file_change AS SELECT {', '.join('NULL AS ' + c for c in cols)}")
cur.execute(f"CREATE TRIGGER fc_ins INSTEAD OF INSERT ON file_change BEGIN INSERT INTO file_change_slim VALUES ({', '.join('NEW.' + c for c in keep)}); END")
return
try: cur.execute(stmt)
except sqlite3.Error as e:
if not up.startswith("CREATE INDEX"): print("ERR", e, s[:120], flush=True)
f = io.TextIOWrapper(gzip.GzipFile(fileobj=zipfile.ZipFile(zp).open(member)), encoding="utf-8", errors="replace")
buf, in_q, skip, n = [], False, None, 0
for line in f:
if skip is None: # start of a new statement: decide keep / skip from its head
skip = table_of(line) in DROP_TABLES
if not skip: buf.append(line)
if line.count("'") % 2: in_q = not in_q
if not in_q and line.rstrip().endswith(";"):
if not skip:
stmt = "".join(buf)
if sqlite3.complete_statement(stmt): handle(stmt); buf = []; n += 1
else: continue # ';' inside an identifier etc. -> keep accumulating
skip = None
if n % 100000 == 0: con.commit()
con.commit()
for (t,) in con.execute("select name from sqlite_master where type='table'").fetchall():
print(t, con.execute(f"select count(*) from {t}").fetchone()[0], flush=True)

Xet Storage Details

Size:
3.47 kB
·
Xet hash:
14088aed5128f8387e3c60e7280672782aada1505a527bacd536b9b7c03beb47

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.