Repository navigation
Expand file tree
/
Copy path07_stackoverflow_tables_oltp.py
More file actions
2428 lines (2088 loc) · 80.7 KB
/
Copy path07_stackoverflow_tables_oltp.py
File metadata and controls
2428 lines (2088 loc) · 80.7 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
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Example 07: Stack Overflow Tables (OLTP)
Loads Stack Overflow XML tables and runs a mixed OLTP workload (CRUD).
CRUD operations are point-oriented and randomly target one table per operation.
Threading note:
- Databases can exhibit different scaling behavior as thread count increases.
- For cross-database comparability, it is recommended to run with --threads 1.
"""
import argparse
import concurrent.futures
import csv
import json
import os
import random
import re
import shutil
import sqlite3
import subprocess
import sys
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
try:
from lxml import etree
except ImportError:
print("Missing dependency: lxml")
print("Install with: uv add lxml")
sys.exit(1)
# The uv release the containers download: the version the repo's CI pins (.github/workflows/test-native.yml UV_VERSION),
# fetched straight from its release URL instead of asking the GitHub API for "latest" (unpinned, and rate-limited for anonymous use).
UV_VERSION = "0.12.0"
def uv_bootstrap_commands(python_cmd: str) -> List[str]:
return [
(
f'{python_cmd} -c "import json, pathlib, platform, shutil, tarfile, urllib.request; '
"arch={'x86_64':'x86_64-unknown-linux-gnu','amd64':'x86_64-unknown-linux-gnu','aarch64':'aarch64-unknown-linux-gnu','arm64':'aarch64-unknown-linux-gnu'}[platform.machine().lower()]; "
f"version='{UV_VERSION}'; "
"archive=pathlib.Path('/tmp/uv.tar.gz'); "
"archive.write_bytes(urllib.request.urlopen(f'https://github.com/astral-sh/uv/releases/download/{version}/uv-{arch}.tar.gz', timeout=30).read()); "
"target=pathlib.Path('/tmp/uv-extract'); target.mkdir(parents=True, exist_ok=True); "
"tarfile.open(archive, 'r:gz').extractall(target); "
"uv_bin=next(p for p in target.rglob('uv') if p.is_file()); "
"pathlib.Path('/tmp/uv-bin').mkdir(parents=True, exist_ok=True); "
"shutil.copy2(uv_bin, '/tmp/uv-bin/uv')\""
),
'export PATH="/tmp/uv-bin:$PATH"',
]
def parse_int(value: Optional[str]) -> Optional[int]:
if value is None or value == "":
return None
try:
return int(value)
except ValueError:
return None
def parse_bool(value: Optional[str]) -> Optional[bool]:
if value is None or value == "":
return None
return value.lower() == "true"
def parse_datetime(value: Optional[str]) -> Optional[datetime]:
if not value:
return None
try:
return datetime.fromisoformat(value.replace("Z", ""))
except ValueError:
return None
def serialize_datetime(value: Optional[datetime]) -> Optional[str]:
if value is None:
return None
if value.tzinfo is None:
return value.isoformat()
return value.astimezone(timezone.utc).isoformat()
def to_arcadedb_sql_value(value: Any) -> Any:
if isinstance(value, datetime):
return serialize_datetime(value)
return value
FieldDef = Tuple[str, str, Callable[[Optional[str]], Any]]
TABLE_DEFS: List[Dict[str, Any]] = [
{
"name": "User",
"xml": "Users.xml",
"fields": [
("Id", "INTEGER", parse_int),
("Reputation", "INTEGER", parse_int),
("CreationDate", "DATETIME", parse_datetime),
("DisplayName", "STRING", lambda v: v),
("LastAccessDate", "DATETIME", parse_datetime),
("WebsiteUrl", "STRING", lambda v: v),
("Location", "STRING", lambda v: v),
("AboutMe", "STRING", lambda v: v),
("Views", "INTEGER", parse_int),
("UpVotes", "INTEGER", parse_int),
("DownVotes", "INTEGER", parse_int),
("AccountId", "INTEGER", parse_int),
],
},
{
"name": "Post",
"xml": "Posts.xml",
"fields": [
("Id", "INTEGER", parse_int),
("PostTypeId", "INTEGER", parse_int),
("ParentId", "INTEGER", parse_int),
("AcceptedAnswerId", "INTEGER", parse_int),
("CreationDate", "DATETIME", parse_datetime),
("Score", "INTEGER", parse_int),
("ViewCount", "INTEGER", parse_int),
("Body", "STRING", lambda v: v),
("OwnerUserId", "INTEGER", parse_int),
("LastEditorUserId", "INTEGER", parse_int),
("LastEditorDisplayName", "STRING", lambda v: v),
("LastEditDate", "DATETIME", parse_datetime),
("LastActivityDate", "DATETIME", parse_datetime),
("Title", "STRING", lambda v: v),
("Tags", "STRING", lambda v: v),
("AnswerCount", "INTEGER", parse_int),
("CommentCount", "INTEGER", parse_int),
("FavoriteCount", "INTEGER", parse_int),
("ClosedDate", "DATETIME", parse_datetime),
("CommunityOwnedDate", "DATETIME", parse_datetime),
],
},
{
"name": "Comment",
"xml": "Comments.xml",
"fields": [
("Id", "INTEGER", parse_int),
("PostId", "INTEGER", parse_int),
("Score", "INTEGER", parse_int),
("Text", "STRING", lambda v: v),
("CreationDate", "DATETIME", parse_datetime),
("UserId", "INTEGER", parse_int),
],
},
{
"name": "Badge",
"xml": "Badges.xml",
"fields": [
("Id", "INTEGER", parse_int),
("UserId", "INTEGER", parse_int),
("Name", "STRING", lambda v: v),
("Date", "DATETIME", parse_datetime),
("Class", "INTEGER", parse_int),
("TagBased", "BOOLEAN", parse_bool),
],
},
{
"name": "Vote",
"xml": "Votes.xml",
"fields": [
("Id", "INTEGER", parse_int),
("PostId", "INTEGER", parse_int),
("VoteTypeId", "INTEGER", parse_int),
("CreationDate", "DATETIME", parse_datetime),
("UserId", "INTEGER", parse_int),
("BountyAmount", "INTEGER", parse_int),
],
},
{
"name": "PostLink",
"xml": "PostLinks.xml",
"fields": [
("Id", "INTEGER", parse_int),
("CreationDate", "DATETIME", parse_datetime),
("PostId", "INTEGER", parse_int),
("RelatedPostId", "INTEGER", parse_int),
("LinkTypeId", "INTEGER", parse_int),
],
},
{
"name": "Tag",
"xml": "Tags.xml",
"fields": [
("Id", "INTEGER", parse_int),
("TagName", "STRING", lambda v: v),
("Count", "INTEGER", parse_int),
("ExcerptPostId", "INTEGER", parse_int),
("WikiPostId", "INTEGER", parse_int),
],
},
{
"name": "PostHistory",
"xml": "PostHistory.xml",
"fields": [
("Id", "INTEGER", parse_int),
("PostHistoryTypeId", "INTEGER", parse_int),
("PostId", "INTEGER", parse_int),
("RevisionGUID", "STRING", lambda v: v),
("CreationDate", "DATETIME", parse_datetime),
("UserId", "INTEGER", parse_int),
("UserDisplayName", "STRING", lambda v: v),
("Comment", "STRING", lambda v: v),
("Text", "STRING", lambda v: v),
("CloseReasonId", "INTEGER", parse_int),
],
},
]
EXPECTED_DATASETS = {
"stackoverflow-tiny",
"stackoverflow-small",
"stackoverflow-medium",
"stackoverflow-large",
"stackoverflow-xlarge",
"stackoverflow-full",
}
DEFAULT_OLTP_MIX = {"read": 0.60, "update": 0.20, "insert": 0.10, "delete": 0.10}
SQLITE_PROFILE_CHOICES = ["fair", "perf", "olap"]
def mem_limit_tag(mem_limit: str) -> str:
normalized = re.sub(r"[^0-9a-z]+", "", mem_limit.lower())
return f"mem{normalized}" if normalized else "memdefault"
def build_benchmark_db_name(
dataset: str,
db: str,
run_label: Optional[str],
mem_limit: Optional[str] = None,
) -> str:
db_name = f"{dataset.replace('-', '_')}_tables_oltp_{db}"
if mem_limit:
db_name = f"{db_name}_{mem_limit_tag(mem_limit)}"
if run_label:
db_name = f"{db_name}_{run_label}"
return db_name
def build_table_schema() -> Dict[str, dict]:
return {
table["name"]: {
"columns": [field[0] for field in table["fields"]],
"column_count": len(table["fields"]),
}
for table in TABLE_DEFS
}
def get_table_def(name: str) -> Dict[str, Any]:
for table in TABLE_DEFS:
if table["name"] == name:
return table
raise KeyError(name)
def get_numeric_update_column(table: Dict[str, Any]) -> Optional[str]:
for field_name, field_type, _ in table["fields"]:
if field_name == "Id":
continue
if field_type in ("INTEGER", "BOOLEAN"):
return field_name
return None
def count_table_rows_arcadedb(db) -> Dict[str, int]:
counts: Dict[str, int] = {}
for table in TABLE_DEFS:
rows = db.query(
"sql", f"SELECT count(*) AS count FROM {table['name']}"
).to_list()
counts[table["name"]] = int(rows[0].get("count", 0)) if rows else 0
return counts
def count_table_rows_sql(conn) -> Dict[str, int]:
counts: Dict[str, int] = {}
for table in TABLE_DEFS:
row = conn.execute(f'SELECT count(*) FROM "{table["name"]}"').fetchone()
counts[table["name"]] = int(row[0]) if row else 0
return counts
def quote_ident_pg(name: str) -> str:
return '"' + name.replace('"', '""') + '"'
def count_table_rows_postgres(conn) -> Dict[str, int]:
counts: Dict[str, int] = {}
with conn.cursor() as cur:
for table in TABLE_DEFS:
cur.execute(f"SELECT count(*) FROM {quote_ident_pg(table['name'])}")
row = cur.fetchone()
counts[table["name"]] = int(row[0]) if row else 0
return counts
def get_duckdb_module():
try:
import duckdb
except ImportError:
return None
return duckdb
def get_arcadedb_module():
try:
import arcadedb
from arcadedb.exceptions import ArcadeDBError
except ImportError:
return None, None
return arcadedb, ArcadeDBError
def get_psycopg_module():
try:
import psycopg
except ImportError:
return None
return psycopg
def get_rss_kb() -> int:
try:
with open("/proc/self/status", "r", encoding="utf-8") as handle:
for line in handle:
if line.startswith("VmRSS:"):
parts = line.split()
if len(parts) >= 2:
return int(parts[1])
except FileNotFoundError:
return 0
return 0
def read_proc_rss_kb(pid: int) -> int:
try:
with open(f"/proc/{pid}/status", "r", encoding="utf-8") as handle:
for line in handle:
if line.startswith("VmRSS:"):
parts = line.split()
if len(parts) >= 2:
return int(parts[1])
except (FileNotFoundError, PermissionError, ProcessLookupError):
return 0
return 0
def read_postmaster_pid(pgdata: Path) -> Optional[int]:
try:
content = (pgdata / "postmaster.pid").read_text(encoding="utf-8").splitlines()
except FileNotFoundError:
return None
if not content:
return None
try:
return int(content[0].strip())
except ValueError:
return None
def list_postgres_pids(pgdata: Path) -> List[int]:
main_pid = read_postmaster_pid(pgdata)
if not main_pid:
return []
pids = [main_pid]
proc_dir = Path("/proc")
for entry in proc_dir.iterdir():
if not entry.name.isdigit():
continue
pid = int(entry.name)
if pid == main_pid:
continue
try:
stat_parts = (entry / "stat").read_text(encoding="utf-8").split()
except FileNotFoundError:
continue
if len(stat_parts) >= 4:
try:
ppid = int(stat_parts[3])
except ValueError:
continue
if ppid == main_pid:
pids.append(pid)
return pids
def get_dir_size_bytes(path: Path) -> int:
total = 0
if not path.exists():
return 0
for root, _, files in os.walk(path):
for name in files:
file_path = Path(root) / name
try:
total += file_path.stat().st_size
except FileNotFoundError:
continue
return total
def find_postgres_bin_dir() -> Optional[Path]:
candidates = []
base = Path("/usr/lib/postgresql")
if base.exists():
for path in base.glob("*/bin/pg_ctl"):
candidates.append(path.parent)
if not candidates:
return None
return sorted(candidates, reverse=True)[0]
def format_bytes(value: int) -> str:
for unit in ["B", "KB", "MB", "GB", "TB"]:
if value < 1024:
return f"{value:.1f}{unit}"
value /= 1024
return f"{value:.1f}PB"
def format_bytes_binary(value: int) -> str:
for unit in ["B", "KiB", "MiB", "GiB", "TiB"]:
if value < 1024:
return f"{value:.1f}{unit}"
value /= 1024
return f"{value:.1f}PiB"
def percentiles(values: List[float], points: List[float]) -> Dict[float, float]:
if not values:
return {p: 0.0 for p in points}
values_sorted = sorted(values)
results = {}
for p in points:
k = int(round((p / 100.0) * (len(values_sorted) - 1)))
results[p] = values_sorted[k]
return results
def start_rss_sampler(
interval_sec: float = 0.2,
) -> Tuple[threading.Event, dict, threading.Thread]:
stop_event = threading.Event()
state = {"max_kb": 0}
def run():
while not stop_event.is_set():
rss_kb = get_rss_kb()
if rss_kb > state["max_kb"]:
state["max_kb"] = rss_kb
time.sleep(interval_sec)
thread = threading.Thread(target=run, daemon=True)
thread.start()
return stop_event, state, thread
def start_combined_rss_sampler(
pid_provider,
interval_sec: float = 0.2,
) -> Tuple[threading.Event, dict, threading.Thread]:
stop_event = threading.Event()
state = {"max_kb": 0, "client_max_kb": 0, "server_max_kb": 0}
def run():
while not stop_event.is_set():
client_kb = get_rss_kb()
server_kb = 0
for pid in pid_provider():
server_kb += read_proc_rss_kb(pid)
if client_kb > state["client_max_kb"]:
state["client_max_kb"] = client_kb
if server_kb > state["server_max_kb"]:
state["server_max_kb"] = server_kb
total_kb = client_kb + server_kb
if total_kb > state["max_kb"]:
state["max_kb"] = total_kb
time.sleep(interval_sec)
thread = threading.Thread(target=run, daemon=True)
thread.start()
return stop_event, state, thread
def ensure_dataset(data_dir: Path):
if not data_dir.exists():
raise FileNotFoundError(
f"Dataset not found: {data_dir}. Run download_data.py first."
)
def iter_xml_rows(
xml_path: Path, limit: Optional[int] = None
) -> Iterable[Dict[str, str]]:
context = etree.iterparse(str(xml_path), events=("end",), tag="row")
seen = 0
for _, elem in context:
yield elem.attrib
seen += 1
elem.clear()
while elem.getprevious() is not None:
del elem.getparent()[0]
if limit is not None and seen >= limit:
break
def parse_row(attrs: Dict[str, str], table: Dict[str, Any]) -> Optional[Dict[str, Any]]:
row: Dict[str, Any] = {}
for field_name, _, parser in table["fields"]:
row[field_name] = parser(attrs.get(field_name))
if row.get("Id") is None:
return None
return row
def sqlite_type(field_type: str) -> str:
if field_type == "INTEGER":
return "INTEGER"
if field_type == "BOOLEAN":
return "INTEGER"
return "TEXT"
def duckdb_type(field_type: str) -> str:
if field_type == "INTEGER":
return "INTEGER"
if field_type == "BOOLEAN":
return "BOOLEAN"
if field_type == "DATETIME":
return "TIMESTAMP"
return "VARCHAR"
def postgres_type(field_type: str) -> str:
if field_type == "INTEGER":
return "INTEGER"
if field_type == "BOOLEAN":
return "BOOLEAN"
if field_type == "DATETIME":
return "TIMESTAMP"
return "TEXT"
def create_schema_arcadedb(db):
for table in TABLE_DEFS:
db.command("sql", f"CREATE DOCUMENT TYPE {table['name']}")
for field_name, field_type, _ in table["fields"]:
arc_type = "STRING" if field_type == "BOOLEAN" else field_type
db.command(
"sql", f"CREATE PROPERTY {table['name']}.{field_name} {arc_type}"
)
def create_arcadedb_id_indexes(db):
for table in TABLE_DEFS:
db.command("sql", f"CREATE INDEX ON {table['name']} (Id) UNIQUE_HASH")
def create_schema_sqlite(conn: sqlite3.Connection):
for table in TABLE_DEFS:
cols = []
for field_name, field_type, _ in table["fields"]:
col_type = sqlite_type(field_type)
cols.append(f'"{field_name}" {col_type}')
conn.execute(
f'CREATE TABLE IF NOT EXISTS "{table["name"]}" ({", ".join(cols)})'
)
def create_sqlite_id_indexes(conn: sqlite3.Connection):
for table in TABLE_DEFS:
conn.execute(
f'CREATE UNIQUE INDEX IF NOT EXISTS idx_{table["name"].lower()}_id ON "{table["name"]}"("Id")'
)
def create_schema_duckdb(conn):
for table in TABLE_DEFS:
cols = []
for field_name, field_type, _ in table["fields"]:
col_type = duckdb_type(field_type)
cols.append(f'"{field_name}" {col_type}')
conn.execute(
f'CREATE TABLE IF NOT EXISTS "{table["name"]}" ({", ".join(cols)})'
)
def create_duckdb_id_indexes(conn):
print("Skipping manual DuckDB secondary indexes for this benchmark.")
return 0.0
def create_schema_postgresql(conn):
for table in TABLE_DEFS:
cols = []
for field_name, field_type, _ in table["fields"]:
col_type = postgres_type(field_type)
cols.append(f"{quote_ident_pg(field_name)} {col_type}")
conn.execute(
f"CREATE TABLE IF NOT EXISTS {quote_ident_pg(table['name'])} ({', '.join(cols)})"
)
def create_postgresql_id_indexes(conn):
for table in TABLE_DEFS:
conn.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS "
f"idx_{table['name'].lower()}_id ON {quote_ident_pg(table['name'])} ({quote_ident_pg('Id')})"
)
def sanitize_value(field_type: str, value: Any) -> Any:
if value is None:
return None
if field_type == "DATETIME":
return serialize_datetime(value) if isinstance(value, datetime) else value
if field_type == "BOOLEAN":
return 1 if value else 0
return value
def insert_batch_arcadedb(db, table: Dict[str, Any], rows: List[Dict[str, Any]]):
if not rows:
return
columns = [f[0] for f in table["fields"]]
placeholders = ", ".join([f"{col} = ?" for col in columns])
sql = f"INSERT INTO {table['name']} SET {placeholders}"
with db.transaction():
for row in rows:
args = []
for field_name, field_type, _ in table["fields"]:
value = sanitize_value(field_type, row.get(field_name))
args.append(to_arcadedb_sql_value(value))
db.command("sql", sql, args)
def configure_arcadedb_bulk_loader(db):
"""Put the database into bulk-load mode for the preload phase.
This preload used to submit one INSERT per row through
`async_executor().command(...)`. That path silently discarded records above
parallel level 1 before 26.10.1 (ArcadeData/arcadedb#7615, fixed in #7625),
so the rows now go through
`db.insert_many(...)`, which loops Java-side inside one transaction per
batch and returns the number written.
"""
db.set_read_your_writes(False)
def reset_arcadedb_bulk_loader(db):
db.set_read_your_writes(True)
def insert_batch_sqlite(conn, table: Dict[str, Any], rows: List[Dict[str, Any]]):
if not rows:
return
columns = [f[0] for f in table["fields"]]
placeholders = ", ".join(["?"] * len(columns))
quoted_cols = ", ".join([f'"{c}"' for c in columns])
stmt = f'INSERT INTO "{table["name"]}" ({quoted_cols}) VALUES ({placeholders})'
payload = []
for row in rows:
payload.append(
tuple(
sanitize_value(field_type, row.get(field_name))
for field_name, field_type, _ in table["fields"]
)
)
conn.executemany(stmt, payload)
def insert_batch_duckdb(conn, table: Dict[str, Any], rows: List[Dict[str, Any]]):
if not rows:
return
columns = [f[0] for f in table["fields"]]
placeholders = ", ".join(["?"] * len(columns))
quoted_cols = ", ".join([f'"{c}"' for c in columns])
stmt = f'INSERT INTO "{table["name"]}" ({quoted_cols}) VALUES ({placeholders})'
payload = []
for row in rows:
payload.append(
tuple(
sanitize_value(field_type, row.get(field_name))
for field_name, field_type, _ in table["fields"]
)
)
conn.executemany(stmt, payload)
def insert_batch_postgresql(conn, table: Dict[str, Any], rows: List[Dict[str, Any]]):
if not rows:
return
columns = [f[0] for f in table["fields"]]
placeholders = ", ".join(["%s"] * len(columns))
quoted_cols = ", ".join([quote_ident_pg(c) for c in columns])
stmt = f"INSERT INTO {quote_ident_pg(table['name'])} ({quoted_cols}) VALUES ({placeholders})"
payload = []
for row in rows:
converted = []
for field_name, field_type, _ in table["fields"]:
value = sanitize_value(field_type, row.get(field_name))
if field_type == "BOOLEAN" and value is not None:
value = bool(value)
converted.append(value)
payload.append(tuple(converted))
with conn.cursor() as cur:
cur.executemany(stmt, payload)
def to_duckdb_csv_value(field_type: str, value: Any) -> Any:
if value is None:
return None
if field_type == "DATETIME":
return serialize_datetime(value) if isinstance(value, datetime) else value
if field_type == "BOOLEAN":
return "true" if bool(value) else "false"
return value
def to_arcadedb_csv_value(field_type: str, value: Any) -> Any:
if value is None:
return None
if field_type == "DATETIME":
return serialize_datetime(value) if isinstance(value, datetime) else value
if field_type == "BOOLEAN":
return "1" if bool(value) else "0"
return value
def load_tables_arcadedb_bulk(
db,
data_dir: Path,
batch_size: int,
) -> Tuple[Dict[str, List[int]], Dict[str, int], float]:
id_pools: Dict[str, List[int]] = {table["name"]: [] for table in TABLE_DEFS}
next_ids: Dict[str, int] = {table["name"]: 1 for table in TABLE_DEFS}
configure_arcadedb_bulk_loader(db)
start = time.time()
try:
for table in TABLE_DEFS:
table_name = table["name"]
xml_path = data_dir / table["xml"]
if not xml_path.exists():
raise FileNotFoundError(f"Missing XML file: {xml_path}")
max_id = 0
submitted = 0
written = 0
pending: List[Dict[str, Any]] = []
def flush(rows: List[Dict[str, Any]], name: str = table_name) -> int:
if not rows:
return 0
n = db.insert_many(name, rows, commit_every=batch_size)
if n != len(rows):
raise RuntimeError(
f"insert_many wrote {n} of {len(rows)} rows for {name}"
)
return n
for attrs in iter_xml_rows(xml_path):
row = parse_row(attrs, table)
if row is None:
continue
row_id = int(row["Id"])
id_pools[table_name].append(row_id)
if row_id > max_id:
max_id = row_id
record: Dict[str, Any] = {}
for field_name, field_type, _ in table["fields"]:
value = sanitize_value(field_type, row.get(field_name))
record[field_name] = to_arcadedb_sql_value(value)
pending.append(record)
submitted += 1
if len(pending) >= batch_size:
written += flush(pending)
pending = []
written += flush(pending)
if written != submitted:
raise RuntimeError(
f"Preload wrote {written} of {submitted} rows " f"for {table_name}"
)
next_ids[table_name] = max_id + 1
return id_pools, next_ids, time.time() - start
finally:
reset_arcadedb_bulk_loader(db)
def load_tables(
insert_batch_fn,
db_obj,
data_dir: Path,
batch_size: int,
) -> Tuple[Dict[str, List[int]], Dict[str, int], float]:
id_pools: Dict[str, List[int]] = {table["name"]: [] for table in TABLE_DEFS}
next_ids: Dict[str, int] = {table["name"]: 1 for table in TABLE_DEFS}
start = time.time()
for table in TABLE_DEFS:
table_name = table["name"]
xml_path = data_dir / table["xml"]
if not xml_path.exists():
raise FileNotFoundError(f"Missing XML file: {xml_path}")
batch: List[Dict[str, Any]] = []
max_id = 0
for attrs in iter_xml_rows(xml_path):
row = parse_row(attrs, table)
if row is None:
continue
row_id = int(row["Id"])
id_pools[table_name].append(row_id)
if row_id > max_id:
max_id = row_id
batch.append(row)
if len(batch) >= batch_size:
insert_batch_fn(db_obj, table, batch)
batch = []
if batch:
insert_batch_fn(db_obj, table, batch)
next_ids[table_name] = max_id + 1
return id_pools, next_ids, time.time() - start
def load_tables_duckdb_copy(
conn,
data_dir: Path,
db_dir: Path,
) -> Tuple[Dict[str, List[int]], Dict[str, int], float]:
id_pools: Dict[str, List[int]] = {table["name"]: [] for table in TABLE_DEFS}
next_ids: Dict[str, int] = {table["name"]: 1 for table in TABLE_DEFS}
csv_dir = db_dir / "duckdb_csv_bulk"
if csv_dir.exists():
shutil.rmtree(csv_dir)
csv_dir.mkdir(parents=True, exist_ok=True)
start = time.time()
for table in TABLE_DEFS:
table_name = table["name"]
xml_path = data_dir / table["xml"]
if not xml_path.exists():
raise FileNotFoundError(f"Missing XML file: {xml_path}")
csv_path = csv_dir / f"{table_name}.csv"
field_names = [field[0] for field in table["fields"]]
max_id = 0
row_count = 0
with csv_path.open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=field_names)
writer.writeheader()
for attrs in iter_xml_rows(xml_path):
row = parse_row(attrs, table)
if row is None:
continue
row_id = int(row["Id"])
id_pools[table_name].append(row_id)
if row_id > max_id:
max_id = row_id
payload = {}
for field_name, field_type, _ in table["fields"]:
payload[field_name] = to_duckdb_csv_value(
field_type,
row.get(field_name),
)
writer.writerow(payload)
row_count += 1
csv_path_sql = csv_path.as_posix().replace("'", "''")
print(f" COPY {table_name}: {row_count:,} rows")
conn.execute(
f"COPY \"{table_name}\" FROM '{csv_path_sql}' (AUTO_DETECT TRUE, HEADER TRUE)"
)
next_ids[table_name] = max_id + 1
return id_pools, next_ids, time.time() - start
def to_postgres_csv_value(field_type: str, value: Any) -> Any:
if value is None:
return None
if field_type == "DATETIME":
return serialize_datetime(value) if isinstance(value, datetime) else value
if field_type == "BOOLEAN":
return "true" if bool(value) else "false"
return value
def load_tables_postgresql_copy(
conn,
data_dir: Path,
db_dir: Path,
) -> Tuple[Dict[str, List[int]], Dict[str, int], float]:
id_pools: Dict[str, List[int]] = {table["name"]: [] for table in TABLE_DEFS}
next_ids: Dict[str, int] = {table["name"]: 1 for table in TABLE_DEFS}
csv_dir = db_dir / "postgres_csv_bulk"
if csv_dir.exists():
shutil.rmtree(csv_dir)
csv_dir.mkdir(parents=True, exist_ok=True)
start = time.time()
for table in TABLE_DEFS:
table_name = table["name"]
xml_path = data_dir / table["xml"]
if not xml_path.exists():
raise FileNotFoundError(f"Missing XML file: {xml_path}")
csv_path = csv_dir / f"{table_name}.csv"
field_names = [field[0] for field in table["fields"]]
max_id = 0
row_count = 0
with csv_path.open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=field_names)
writer.writeheader()
for attrs in iter_xml_rows(xml_path):
row = parse_row(attrs, table)
if row is None:
continue
row_id = int(row["Id"])
id_pools[table_name].append(row_id)
if row_id > max_id:
max_id = row_id
payload = {}
for field_name, field_type, _ in table["fields"]:
payload[field_name] = to_postgres_csv_value(
field_type,
row.get(field_name),
)
writer.writerow(payload)
row_count += 1
columns_sql = ", ".join(quote_ident_pg(name) for name in field_names)
copy_sql = (
f"COPY {quote_ident_pg(table_name)} ({columns_sql}) "
"FROM STDIN WITH (FORMAT CSV, HEADER TRUE)"
)
print(f" COPY {table_name}: {row_count:,} rows")
with conn.cursor() as cur:
with cur.copy(copy_sql) as copy:
with csv_path.open("r", encoding="utf-8") as source:
while True:
chunk = source.read(1024 * 1024)
if not chunk:
break
copy.write(chunk)
next_ids[table_name] = max_id + 1
return id_pools, next_ids, time.time() - start
def build_operation_plan(
count: int,
mix: Dict[str, float],
seed: int,
table_names: List[str],
) -> List[Tuple[str, str]]:
rng = random.Random(seed)
ops = rng.choices(
population=["read", "update", "insert", "delete"],
weights=[mix["read"], mix["update"], mix["insert"], mix["delete"]],
k=count,
)
return [(op, rng.choice(table_names)) for op in ops]
def simulate_expected_counts_single_thread(