File size: 4,201 Bytes
3bfd464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import sys
import os
import sqlite3
import subprocess
from urllib.parse import urlparse

BATCH_SIZE = 100000  # Insert in chunks of 100k to save RAM

# Embedded schema to make the script standalone[span_1](start_span)[span_1](end_span)
SCHEMA_SQL = """
-- 1. The Payload Table (Standard ROWID table)
-- 'id' becomes a direct alias for the SQLite rowid.
CREATE TABLE payload_data (
    id INTEGER PRIMARY KEY,
    json_record TEXT
);

-- 2. The Lookup Table (WITHOUT ROWID)
-- Clustered directly by SURT for extremely fast prefix/exact lookups.
CREATE TABLE surt_lookup (
    surt TEXT,
    capture_time INTEGER,
    payload_id INTEGER,
    PRIMARY KEY (surt, capture_time)
) WITHOUT ROWID;
"""

if len(sys.argv) < 2:
    print("Usage: uv run import_cdx.py <file-or-url>")
    sys.exit(1)

source = sys.argv[1]

# --- 1. Parse File Info and Compression ---
parsed_url = urlparse(source)
original_file_name = os.path.basename(parsed_url.path)

# Determine compression based strictly on the parsed path
is_zst = original_file_name.endswith('.zst')

# --- 2. Determine Database Name ---
if is_zst:
    base_name = original_file_name[:-4]
else:
    base_name = original_file_name

db_name = f"{base_name}.db"
print(f"Input source: {source}")
print(f"Target database: {db_name}")

# --- 3. Initialize Database and Schema ---
if not os.path.exists(db_name):
    print(f"Initializing {db_name} with embedded schema...")
    init_conn = sqlite3.connect(db_name)
    init_conn.executescript(SCHEMA_SQL)
    init_conn.close()

# --- 4. Setup Streaming Pipeline (curl/cat -> zstdcat) ---
is_url = source.startswith("http://") or source.startswith("https://")

fetch_process = None
decompress_process = None

if is_url:
    fetch_process = subprocess.Popen(["curl", "-sL", source], stdout=subprocess.PIPE)
    raw_stream = fetch_process.stdout
else:
    raw_stream = open(source, "rb")

if is_zst:
    decompress_process = subprocess.Popen(["zstdcat"], stdin=raw_stream, stdout=subprocess.PIPE)
    stream = decompress_process.stdout
else:
    stream = raw_stream

# --- 5. Process and Insert Data ---
connection = sqlite3.connect(db_name)
cursor = connection.cursor()

cursor.execute("PRAGMA journal_mode = WAL;")
cursor.execute("PRAGMA synchronous = NORMAL;")

cursor.execute("SELECT IFNULL(MAX(id), 0) FROM payload_data")
current_id = cursor.fetchone()[0]

payload_batch = []
lookup_batch = []

# Variables to track the last seen record for deduplication
last_surt = None
last_capture_time = None

cursor.execute("BEGIN TRANSACTION;")

print("Importing data (with duplicate filtering)...")
for line_bytes in stream:
    line = line_bytes.decode('utf-8', errors='replace').strip()
    if not line:
        continue

    parts = line.split(' ', 2)
    if len(parts) != 3:
        continue

    surt = parts[0]
    try:
        capture_time = int(parts[1])
    except ValueError:
        continue
    json_record = parts[2]

    # Deduplication check: skip if it matches the previous row's keys
    if surt == last_surt and capture_time == last_capture_time:
        continue

    # Update trackers for the next iteration
    last_surt = surt
    last_capture_time = capture_time

    current_id += 1

    payload_batch.append((current_id, json_record))
    lookup_batch.append((surt, capture_time, current_id))

    if len(payload_batch) >= BATCH_SIZE:
        cursor.executemany("INSERT INTO payload_data (id, json_record) VALUES (?, ?)", payload_batch)
        cursor.executemany("INSERT INTO surt_lookup (surt, capture_time, payload_id) VALUES (?, ?, ?)", lookup_batch)

        payload_batch.clear()
        lookup_batch.clear()
        print(f"Inserted up to ID {current_id} in {db_name}...")

# Cleanup leftover batch
if payload_batch:
    cursor.executemany("INSERT INTO payload_data (id, json_record) VALUES (?, ?)", payload_batch)
    cursor.executemany("INSERT INTO surt_lookup (surt, capture_time, payload_id) VALUES (?, ?, ?)", lookup_batch)

connection.commit()
connection.close()

# Close processes and files safely
if decompress_process:
    decompress_process.wait()
if fetch_process:
    fetch_process.wait()
elif not is_url:
    raw_stream.close()

print(f"Import fully complete for {db_name}!")