codegraphcontext-rust 0.9.24__cp314-cp314-win_amd64.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.
- codegraphcontext/__init__.py +2 -0
- codegraphcontext/__main__.py +5 -0
- codegraphcontext/_cgc_rust.cp314-win_amd64.pyd +4 -0
- codegraphcontext/cli/__init__.py +1 -0
- codegraphcontext/cli/cli_helpers.py +774 -0
- codegraphcontext/cli/config_manager.py +1051 -0
- codegraphcontext/cli/entry.py +21 -0
- codegraphcontext/cli/main.py +2386 -0
- codegraphcontext/cli/registry_commands.py +404 -0
- codegraphcontext/cli/setup_macos.py +93 -0
- codegraphcontext/cli/setup_wizard.py +991 -0
- codegraphcontext/cli/visualizer.py +50 -0
- codegraphcontext/core/__init__.py +165 -0
- codegraphcontext/core/bundle_registry.py +181 -0
- codegraphcontext/core/cgc_bundle.py +858 -0
- codegraphcontext/core/cgcignore.py +118 -0
- codegraphcontext/core/database.py +273 -0
- codegraphcontext/core/database_falkordb.py +480 -0
- codegraphcontext/core/database_falkordb_remote.py +199 -0
- codegraphcontext/core/database_kuzu.py +636 -0
- codegraphcontext/core/falkor_worker.py +132 -0
- codegraphcontext/core/jobs.py +132 -0
- codegraphcontext/core/watcher.py +260 -0
- codegraphcontext/prompts.py +125 -0
- codegraphcontext/server.py +471 -0
- codegraphcontext/tool_definitions.py +220 -0
- codegraphcontext/tools/__init__.py +0 -0
- codegraphcontext/tools/advanced_language_query_tool.py +103 -0
- codegraphcontext/tools/code_finder.py +1160 -0
- codegraphcontext/tools/graph_builder.py +337 -0
- codegraphcontext/tools/handlers/analysis_handlers.py +114 -0
- codegraphcontext/tools/handlers/indexing_handlers.py +116 -0
- codegraphcontext/tools/handlers/management_handlers.py +339 -0
- codegraphcontext/tools/handlers/query_handlers.py +83 -0
- codegraphcontext/tools/handlers/watcher_handlers.py +83 -0
- codegraphcontext/tools/indexing/__init__.py +1 -0
- codegraphcontext/tools/indexing/angular_routes.py +396 -0
- codegraphcontext/tools/indexing/cgc_wiki_cli.py +1334 -0
- codegraphcontext/tools/indexing/constants.py +70 -0
- codegraphcontext/tools/indexing/context_generator.py +461 -0
- codegraphcontext/tools/indexing/discovery.py +64 -0
- codegraphcontext/tools/indexing/engine.py +114 -0
- codegraphcontext/tools/indexing/execution_flows.py +355 -0
- codegraphcontext/tools/indexing/module_grouping.py +551 -0
- codegraphcontext/tools/indexing/noise_filter.py +131 -0
- codegraphcontext/tools/indexing/op_param_extraction.py +287 -0
- codegraphcontext/tools/indexing/persistence/__init__.py +3 -0
- codegraphcontext/tools/indexing/persistence/duckdb_writer.py +1116 -0
- codegraphcontext/tools/indexing/persistence/parquet_loader.py +643 -0
- codegraphcontext/tools/indexing/persistence/writer.py +1562 -0
- codegraphcontext/tools/indexing/pipeline.py +171 -0
- codegraphcontext/tools/indexing/pre_scan.py +105 -0
- codegraphcontext/tools/indexing/rationale_extraction.py +154 -0
- codegraphcontext/tools/indexing/resolution/__init__.py +8 -0
- codegraphcontext/tools/indexing/resolution/calls.py +253 -0
- codegraphcontext/tools/indexing/resolution/inheritance.py +91 -0
- codegraphcontext/tools/indexing/route_extraction.py +659 -0
- codegraphcontext/tools/indexing/sanitize.py +41 -0
- codegraphcontext/tools/indexing/schema.py +79 -0
- codegraphcontext/tools/indexing/schema_contract.py +44 -0
- codegraphcontext/tools/indexing/scip_pipeline.py +140 -0
- codegraphcontext/tools/languages/c.py +563 -0
- codegraphcontext/tools/languages/cpp.py +616 -0
- codegraphcontext/tools/languages/csharp.py +551 -0
- codegraphcontext/tools/languages/dart.py +378 -0
- codegraphcontext/tools/languages/elixir.py +460 -0
- codegraphcontext/tools/languages/go.py +499 -0
- codegraphcontext/tools/languages/haskell.py +426 -0
- codegraphcontext/tools/languages/java.py +500 -0
- codegraphcontext/tools/languages/javascript.py +589 -0
- codegraphcontext/tools/languages/kotlin.py +640 -0
- codegraphcontext/tools/languages/perl.py +260 -0
- codegraphcontext/tools/languages/php.py +519 -0
- codegraphcontext/tools/languages/python.py +578 -0
- codegraphcontext/tools/languages/ruby.py +537 -0
- codegraphcontext/tools/languages/rust.py +295 -0
- codegraphcontext/tools/languages/scala.py +519 -0
- codegraphcontext/tools/languages/swift.py +491 -0
- codegraphcontext/tools/languages/typescript.py +606 -0
- codegraphcontext/tools/languages/typescriptjsx.py +151 -0
- codegraphcontext/tools/package_resolver.py +472 -0
- codegraphcontext/tools/query_tool_languages/c_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/cpp_toolkit.py +87 -0
- codegraphcontext/tools/query_tool_languages/csharp_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/dart_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/go_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/haskell_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/java_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/javascript_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/perl_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/python_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/ruby_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/rust_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/scala_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/swift_toolkit.py +5 -0
- codegraphcontext/tools/query_tool_languages/typescript_toolkit.py +5 -0
- codegraphcontext/tools/scip_indexer.py +467 -0
- codegraphcontext/tools/scip_pb2.py +2455 -0
- codegraphcontext/tools/system.py +133 -0
- codegraphcontext/tools/tree_sitter_parser.py +103 -0
- codegraphcontext/utils/debug_log.py +90 -0
- codegraphcontext/utils/path_ignore.py +55 -0
- codegraphcontext/utils/repo_path.py +27 -0
- codegraphcontext/utils/tree_sitter_manager.py +285 -0
- codegraphcontext/utils/visualize_graph.py +0 -0
- codegraphcontext/viz/server.py +282 -0
- codegraphcontext_rust-0.9.24.dist-info/METADATA +543 -0
- codegraphcontext_rust-0.9.24.dist-info/RECORD +112 -0
- codegraphcontext_rust-0.9.24.dist-info/WHEEL +4 -0
- codegraphcontext_rust-0.9.24.dist-info/entry_points.txt +4 -0
- codegraphcontext_rust-0.9.24.dist-info/licenses/LICENSE +21 -0
- codegraphcontext_rust-0.9.24.dist-info/sboms/cgc-python.cyclonedx.json +2302 -0
|
@@ -0,0 +1,1116 @@
|
|
|
1
|
+
"""DuckDB graph writer using Parquet COPY FROM for ~45x faster DB writes.
|
|
2
|
+
|
|
3
|
+
Architecture:
|
|
4
|
+
Rust parse → Python collect → PyArrow Parquet → DuckDB CREATE AS SELECT
|
|
5
|
+
|
|
6
|
+
Usage:
|
|
7
|
+
from codegraphcontext.tools.indexing.persistence.duckdb_writer import DuckDBGraphWriter
|
|
8
|
+
|
|
9
|
+
writer = DuckDBGraphWriter(db_path)
|
|
10
|
+
writer.write_all(parsed_results, repo_path, call_groups, inheritance)
|
|
11
|
+
# Query:
|
|
12
|
+
top = writer.get_top_connected(limit=20)
|
|
13
|
+
edges = writer.get_call_graph(file_paths)
|
|
14
|
+
writer.close()
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
import os
|
|
21
|
+
import tempfile
|
|
22
|
+
import time
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _safe_str(v: Any) -> str:
|
|
30
|
+
if v is None:
|
|
31
|
+
return ""
|
|
32
|
+
if isinstance(v, list):
|
|
33
|
+
import json
|
|
34
|
+
return json.dumps(v)
|
|
35
|
+
return str(v)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class DuckDBGraphWriter:
|
|
39
|
+
"""High-performance graph writer backed by DuckDB + Parquet bulk load."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, db_path: str):
|
|
42
|
+
self._conn = None # set before connect to prevent __del__ crash
|
|
43
|
+
self._schema_created = False
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
import duckdb
|
|
47
|
+
except ImportError:
|
|
48
|
+
raise ImportError("duckdb not installed. Run: pip install duckdb")
|
|
49
|
+
|
|
50
|
+
self.db_path = db_path
|
|
51
|
+
os.makedirs(os.path.dirname(db_path) or ".", exist_ok=True)
|
|
52
|
+
self._conn = duckdb.connect(db_path)
|
|
53
|
+
|
|
54
|
+
def close(self):
|
|
55
|
+
if hasattr(self, "_conn") and self._conn:
|
|
56
|
+
self._conn.close()
|
|
57
|
+
self._conn = None
|
|
58
|
+
|
|
59
|
+
def __del__(self):
|
|
60
|
+
self.close()
|
|
61
|
+
|
|
62
|
+
# ── Schema ───────────────────────────────────────────────────────
|
|
63
|
+
|
|
64
|
+
def _create_schema(self):
|
|
65
|
+
if self._schema_created:
|
|
66
|
+
return
|
|
67
|
+
c = self._conn
|
|
68
|
+
c.execute("""CREATE TABLE IF NOT EXISTS repository (
|
|
69
|
+
path VARCHAR PRIMARY KEY, name VARCHAR)""")
|
|
70
|
+
c.execute("""CREATE TABLE IF NOT EXISTS files (
|
|
71
|
+
path VARCHAR PRIMARY KEY, name VARCHAR,
|
|
72
|
+
relative_path VARCHAR, is_dependency BOOLEAN DEFAULT FALSE)""")
|
|
73
|
+
c.execute("""CREATE TABLE IF NOT EXISTS directories (
|
|
74
|
+
path VARCHAR PRIMARY KEY, name VARCHAR, parent_path VARCHAR)""")
|
|
75
|
+
c.execute("""CREATE TABLE IF NOT EXISTS functions (
|
|
76
|
+
uid VARCHAR PRIMARY KEY, name VARCHAR, path VARCHAR,
|
|
77
|
+
line_number INTEGER, complexity INTEGER DEFAULT 0,
|
|
78
|
+
return_type VARCHAR DEFAULT '', docstring VARCHAR DEFAULT '',
|
|
79
|
+
class_context VARCHAR DEFAULT '', is_async BOOLEAN DEFAULT FALSE,
|
|
80
|
+
body_start_line INTEGER DEFAULT 0, body_end_line INTEGER DEFAULT 0,
|
|
81
|
+
decorators VARCHAR DEFAULT '')""")
|
|
82
|
+
c.execute("""CREATE TABLE IF NOT EXISTS classes (
|
|
83
|
+
uid VARCHAR PRIMARY KEY, name VARCHAR, path VARCHAR,
|
|
84
|
+
line_number INTEGER, docstring VARCHAR DEFAULT '',
|
|
85
|
+
bases VARCHAR DEFAULT '', decorators VARCHAR DEFAULT '',
|
|
86
|
+
kind VARCHAR DEFAULT 'class')""")
|
|
87
|
+
# Dependency injection: injector class -> injected bean type
|
|
88
|
+
# (Spring @Autowired/@Inject fields, Lombok final fields, constructors)
|
|
89
|
+
c.execute("""CREATE TABLE IF NOT EXISTS injections (
|
|
90
|
+
injector_class VARCHAR, injector_path VARCHAR,
|
|
91
|
+
injected_type VARCHAR, injected_path VARCHAR DEFAULT '',
|
|
92
|
+
field_name VARCHAR DEFAULT '', line_number INTEGER DEFAULT 0,
|
|
93
|
+
kind VARCHAR DEFAULT '', stereotype VARCHAR DEFAULT '')""")
|
|
94
|
+
c.execute("""CREATE TABLE IF NOT EXISTS variables (
|
|
95
|
+
uid VARCHAR PRIMARY KEY, name VARCHAR, path VARCHAR,
|
|
96
|
+
line_number INTEGER, type VARCHAR DEFAULT '')""")
|
|
97
|
+
c.execute("""CREATE TABLE IF NOT EXISTS parameters (
|
|
98
|
+
uid VARCHAR PRIMARY KEY, name VARCHAR, path VARCHAR,
|
|
99
|
+
function_uid VARCHAR, function_line_number INTEGER)""")
|
|
100
|
+
c.execute("""CREATE TABLE IF NOT EXISTS modules (
|
|
101
|
+
name VARCHAR PRIMARY KEY)""")
|
|
102
|
+
c.execute("""CREATE TABLE IF NOT EXISTS imports (
|
|
103
|
+
file_path VARCHAR, module_name VARCHAR,
|
|
104
|
+
imported_name VARCHAR DEFAULT '', alias VARCHAR DEFAULT '',
|
|
105
|
+
full_import_name VARCHAR DEFAULT '', line_number INTEGER DEFAULT 0)""")
|
|
106
|
+
c.execute("""CREATE TABLE IF NOT EXISTS calls (
|
|
107
|
+
caller_uid VARCHAR, called_uid VARCHAR,
|
|
108
|
+
caller_type VARCHAR, called_type VARCHAR,
|
|
109
|
+
caller_name VARCHAR DEFAULT '', called_name VARCHAR DEFAULT '',
|
|
110
|
+
caller_path VARCHAR DEFAULT '', called_path VARCHAR DEFAULT '',
|
|
111
|
+
line_number INTEGER DEFAULT 0, full_call_name VARCHAR DEFAULT '',
|
|
112
|
+
confidence VARCHAR DEFAULT 'EXTRACTED',
|
|
113
|
+
resolution_tier INTEGER DEFAULT 0,
|
|
114
|
+
receiver_type VARCHAR DEFAULT '')""")
|
|
115
|
+
# ORM: entity -> table, repository -> entity, code -> table access
|
|
116
|
+
c.execute("""CREATE TABLE IF NOT EXISTS orm_entities (
|
|
117
|
+
entity_class VARCHAR, entity_path VARCHAR, table_name VARCHAR,
|
|
118
|
+
schema VARCHAR DEFAULT '', datastore VARCHAR DEFAULT '',
|
|
119
|
+
line_number INTEGER DEFAULT 0)""")
|
|
120
|
+
c.execute("""CREATE TABLE IF NOT EXISTS orm_repositories (
|
|
121
|
+
repository VARCHAR, repository_path VARCHAR, entity_class VARCHAR,
|
|
122
|
+
entity_path VARCHAR DEFAULT '', table_name VARCHAR DEFAULT '',
|
|
123
|
+
schema VARCHAR DEFAULT '')""")
|
|
124
|
+
c.execute("""CREATE TABLE IF NOT EXISTS db_access (
|
|
125
|
+
caller_class VARCHAR DEFAULT '', caller_name VARCHAR DEFAULT '',
|
|
126
|
+
caller_path VARCHAR, line_number INTEGER DEFAULT 0,
|
|
127
|
+
table_name VARCHAR, schema VARCHAR DEFAULT '',
|
|
128
|
+
operation VARCHAR, via VARCHAR, repository VARCHAR DEFAULT '',
|
|
129
|
+
method VARCHAR DEFAULT '')""")
|
|
130
|
+
c.execute("""CREATE TABLE IF NOT EXISTS inheritance (
|
|
131
|
+
child_uid VARCHAR, parent_uid VARCHAR,
|
|
132
|
+
child_name VARCHAR DEFAULT '', parent_name VARCHAR DEFAULT '',
|
|
133
|
+
child_path VARCHAR DEFAULT '', parent_path VARCHAR DEFAULT '')""")
|
|
134
|
+
c.execute("""CREATE TABLE IF NOT EXISTS file_contains (
|
|
135
|
+
file_path VARCHAR, symbol_uid VARCHAR, symbol_type VARCHAR)""")
|
|
136
|
+
c.execute("""CREATE TABLE IF NOT EXISTS execution_flows (
|
|
137
|
+
name VARCHAR, entry_file VARCHAR, entry_line INTEGER DEFAULT 0,
|
|
138
|
+
entry_class VARCHAR DEFAULT '', step_count INTEGER DEFAULT 0,
|
|
139
|
+
depth INTEGER DEFAULT 0, score INTEGER DEFAULT 0,
|
|
140
|
+
steps_json VARCHAR DEFAULT '[]')""")
|
|
141
|
+
c.execute("""CREATE TABLE IF NOT EXISTS rationales (
|
|
142
|
+
tag VARCHAR, text VARCHAR, file VARCHAR,
|
|
143
|
+
line INTEGER DEFAULT 0, context VARCHAR DEFAULT '')""")
|
|
144
|
+
c.execute("""CREATE TABLE IF NOT EXISTS routes (
|
|
145
|
+
method VARCHAR, path VARCHAR, handler VARCHAR,
|
|
146
|
+
file VARCHAR, line INTEGER DEFAULT 0,
|
|
147
|
+
framework VARCHAR DEFAULT '')""")
|
|
148
|
+
# Calls the resolver dropped, with the reason (diagnostics)
|
|
149
|
+
c.execute("""CREATE TABLE IF NOT EXISTS unresolved_calls (
|
|
150
|
+
caller_name VARCHAR DEFAULT '', caller_path VARCHAR,
|
|
151
|
+
line_number INTEGER DEFAULT 0, called_name VARCHAR,
|
|
152
|
+
full_call_name VARCHAR DEFAULT '', receiver_type VARCHAR DEFAULT '',
|
|
153
|
+
reason VARCHAR)""")
|
|
154
|
+
# Frontend navigations: router.navigate(...) -> matched route
|
|
155
|
+
c.execute("""CREATE TABLE IF NOT EXISTS navigations (
|
|
156
|
+
caller_name VARCHAR DEFAULT '', caller_path VARCHAR,
|
|
157
|
+
line_number INTEGER DEFAULT 0, target VARCHAR,
|
|
158
|
+
route_path VARCHAR DEFAULT '', route_handler VARCHAR DEFAULT '',
|
|
159
|
+
route_file VARCHAR DEFAULT '')""")
|
|
160
|
+
c.execute("""CREATE TABLE IF NOT EXISTS operational_params (
|
|
161
|
+
name VARCHAR, value VARCHAR, path VARCHAR,
|
|
162
|
+
line_number INTEGER DEFAULT 0, category VARCHAR DEFAULT '')""")
|
|
163
|
+
self._schema_created = True
|
|
164
|
+
|
|
165
|
+
# ── Main write method ────────────────────────────────────────────
|
|
166
|
+
|
|
167
|
+
def write_all(
|
|
168
|
+
self,
|
|
169
|
+
parsed_results: List[Dict[str, Any]],
|
|
170
|
+
repo_path: str,
|
|
171
|
+
call_groups: Tuple,
|
|
172
|
+
inheritance: List[Dict] = None,
|
|
173
|
+
on_progress: Optional[Callable] = None,
|
|
174
|
+
unresolved: Optional[List[Dict]] = None,
|
|
175
|
+
) -> Dict[str, int]:
|
|
176
|
+
"""Write entire graph via Parquet bulk load.
|
|
177
|
+
|
|
178
|
+
Returns dict of counts: {files, functions, classes, variables, calls, ...}
|
|
179
|
+
"""
|
|
180
|
+
|
|
181
|
+
repo_path_obj = Path(repo_path).resolve()
|
|
182
|
+
total = len(parsed_results)
|
|
183
|
+
t_start = time.perf_counter()
|
|
184
|
+
|
|
185
|
+
if on_progress:
|
|
186
|
+
on_progress(0, total, "Collecting graph data...")
|
|
187
|
+
|
|
188
|
+
# ── Collect into columnar lists ──────────────────────────────
|
|
189
|
+
# Files
|
|
190
|
+
f_path = []; f_name = []; f_rel = []; f_dep = []
|
|
191
|
+
# Directories
|
|
192
|
+
dir_set: Dict[str, Tuple[str, str]] = {} # path → (name, parent)
|
|
193
|
+
# Functions
|
|
194
|
+
fn_uid = []; fn_name = []; fn_path = []; fn_line = []
|
|
195
|
+
fn_cx = []; fn_rt = []; fn_doc = []; fn_cc = []; fn_async = []
|
|
196
|
+
fn_bstart = []; fn_bend = []; fn_dec = []
|
|
197
|
+
# Classes
|
|
198
|
+
cl_uid = []; cl_name = []; cl_path = []; cl_line = []; cl_doc = []; cl_bases = []; cl_dec = []; cl_kind = []
|
|
199
|
+
# Injections (target path resolved after all classes are known)
|
|
200
|
+
inj_rows = [] # (injector_class, injector_rel, injected_type, field, line, kind, stereotype, imports)
|
|
201
|
+
orm_rows = [] # (rel path, orm mapping dict)
|
|
202
|
+
# Variables
|
|
203
|
+
v_uid = []; v_name = []; v_path = []; v_line = []; v_type = []
|
|
204
|
+
# Parameters
|
|
205
|
+
p_uid = []; p_name = []; p_path = []; p_func_uid = []; p_func_line = []
|
|
206
|
+
# Imports
|
|
207
|
+
im_fp = []; im_mod = []; im_name = []; im_alias = []; im_full = []; im_line = []
|
|
208
|
+
# File-contains
|
|
209
|
+
fc_fp = []; fc_uid = []; fc_type = []
|
|
210
|
+
# Modules
|
|
211
|
+
mod_set = set()
|
|
212
|
+
|
|
213
|
+
func_set = set(); class_set = set(); var_set = set(); param_set = set()
|
|
214
|
+
|
|
215
|
+
for r in parsed_results:
|
|
216
|
+
fp = str(Path(r["path"]).resolve())
|
|
217
|
+
fname = Path(fp).name
|
|
218
|
+
try:
|
|
219
|
+
rel = str(Path(fp).relative_to(repo_path_obj))
|
|
220
|
+
except ValueError:
|
|
221
|
+
rel = fname
|
|
222
|
+
is_dep = r.get("is_dependency", False)
|
|
223
|
+
f_path.append(fp); f_name.append(fname); f_rel.append(rel); f_dep.append(is_dep)
|
|
224
|
+
|
|
225
|
+
# Directories
|
|
226
|
+
try:
|
|
227
|
+
rel_parts = Path(fp).relative_to(repo_path_obj).parts[:-1]
|
|
228
|
+
except ValueError:
|
|
229
|
+
rel_parts = ()
|
|
230
|
+
parent = str(repo_path_obj)
|
|
231
|
+
for part in rel_parts:
|
|
232
|
+
dp = str(Path(parent) / part)
|
|
233
|
+
if dp not in dir_set:
|
|
234
|
+
dir_set[dp] = (part, parent)
|
|
235
|
+
parent = dp
|
|
236
|
+
|
|
237
|
+
lang = r.get("lang", "")
|
|
238
|
+
|
|
239
|
+
# Functions — store relative path for consistency with routes/rationales
|
|
240
|
+
for fn in r.get("functions", []):
|
|
241
|
+
uid = f"{fn.get('name', '')}|{fp}|{fn.get('line_number', 0)}"
|
|
242
|
+
if uid not in func_set:
|
|
243
|
+
func_set.add(uid)
|
|
244
|
+
fn_uid.append(uid); fn_name.append(fn.get("name", "")); fn_path.append(rel)
|
|
245
|
+
fn_line.append(fn.get("line_number", 0))
|
|
246
|
+
fn_cx.append(fn.get("complexity", 0) or 0)
|
|
247
|
+
fn_rt.append(fn.get("return_type", "") or "")
|
|
248
|
+
fn_doc.append(fn.get("docstring", "") or "")
|
|
249
|
+
fn_cc.append(fn.get("class_context", "") or "")
|
|
250
|
+
fn_async.append(fn.get("is_async", False) or False)
|
|
251
|
+
fn_bstart.append(fn.get("body_start_line", 0) or 0)
|
|
252
|
+
fn_bend.append(fn.get("body_end_line", 0) or 0)
|
|
253
|
+
fn_dec.append("\n".join(fn.get("decorators", []) or []))
|
|
254
|
+
fc_fp.append(rel); fc_uid.append(uid); fc_type.append("Function")
|
|
255
|
+
|
|
256
|
+
# Parameters
|
|
257
|
+
for arg in fn.get("args", []) or []:
|
|
258
|
+
arg_name = arg if isinstance(arg, str) else str(arg)
|
|
259
|
+
if arg_name:
|
|
260
|
+
puid = f"{arg_name}|{fp}|{fn.get('line_number', 0)}"
|
|
261
|
+
if puid not in param_set:
|
|
262
|
+
param_set.add(puid)
|
|
263
|
+
p_uid.append(puid); p_name.append(arg_name)
|
|
264
|
+
p_path.append(rel); p_func_uid.append(uid)
|
|
265
|
+
p_func_line.append(fn.get("line_number", 0))
|
|
266
|
+
|
|
267
|
+
# Classes
|
|
268
|
+
for cls in r.get("classes", []):
|
|
269
|
+
uid = f"{cls.get('name', '')}|{fp}|{cls.get('line_number', 0)}"
|
|
270
|
+
if uid not in class_set:
|
|
271
|
+
class_set.add(uid)
|
|
272
|
+
cl_uid.append(uid); cl_name.append(cls.get("name", ""))
|
|
273
|
+
cl_path.append(rel); cl_line.append(cls.get("line_number", 0))
|
|
274
|
+
cl_doc.append(cls.get("docstring", "") or "")
|
|
275
|
+
bases = cls.get("bases", [])
|
|
276
|
+
cl_bases.append(",".join(str(b) for b in bases) if bases else "")
|
|
277
|
+
cl_dec.append("\n".join(cls.get("decorators", []) or []))
|
|
278
|
+
cl_kind.append(cls.get("kind") or "class")
|
|
279
|
+
fc_fp.append(rel); fc_uid.append(uid); fc_type.append("Class")
|
|
280
|
+
|
|
281
|
+
for m in r.get("orm_mappings") or []:
|
|
282
|
+
orm_rows.append((rel, m))
|
|
283
|
+
|
|
284
|
+
# Injections
|
|
285
|
+
if r.get("injections"):
|
|
286
|
+
file_imports = [i.get("name", "") for i in r.get("imports", []) or []]
|
|
287
|
+
for inj in r["injections"]:
|
|
288
|
+
inj_rows.append((
|
|
289
|
+
inj.get("injector_class", ""), rel, inj.get("injected_type", ""),
|
|
290
|
+
inj.get("field_name", ""), inj.get("line_number", 0),
|
|
291
|
+
inj.get("kind", ""), inj.get("stereotype") or "", file_imports,
|
|
292
|
+
))
|
|
293
|
+
|
|
294
|
+
# Variables
|
|
295
|
+
for var in r.get("variables", []):
|
|
296
|
+
uid = f"{var.get('name', '')}|{fp}|{var.get('line_number', 0)}"
|
|
297
|
+
if uid not in var_set:
|
|
298
|
+
var_set.add(uid)
|
|
299
|
+
v_uid.append(uid); v_name.append(var.get("name", ""))
|
|
300
|
+
v_path.append(rel); v_line.append(var.get("line_number", 0))
|
|
301
|
+
v_type.append(var.get("type", "") or "")
|
|
302
|
+
fc_fp.append(rel); fc_uid.append(uid); fc_type.append("Variable")
|
|
303
|
+
|
|
304
|
+
# Imports
|
|
305
|
+
for imp in r.get("imports", []):
|
|
306
|
+
source = imp.get("source", "") or imp.get("name", "")
|
|
307
|
+
name = imp.get("name", "")
|
|
308
|
+
alias = imp.get("alias", "") or ""
|
|
309
|
+
full = imp.get("full_import_name", "") or source or name
|
|
310
|
+
ln = imp.get("line_number", 0)
|
|
311
|
+
mod_name = source or name
|
|
312
|
+
if mod_name:
|
|
313
|
+
mod_set.add(mod_name)
|
|
314
|
+
im_fp.append(fp); im_mod.append(mod_name); im_name.append(name)
|
|
315
|
+
im_alias.append(alias); im_full.append(full); im_line.append(ln)
|
|
316
|
+
|
|
317
|
+
if on_progress:
|
|
318
|
+
on_progress(total // 3, total, "Writing Parquet files...")
|
|
319
|
+
|
|
320
|
+
# ── CALLS edges ──────────────────────────────────────────────
|
|
321
|
+
c_caller = []; c_called = []; c_ct = []; c_cdt = []
|
|
322
|
+
c_cn = []; c_dn = []; c_cp = []; c_dp = []
|
|
323
|
+
c_ln = []; c_fcn = []; c_conf = []; c_tier = []; c_recv = []
|
|
324
|
+
edge_labels = [
|
|
325
|
+
("Function", "Function"), ("Function", "Class"),
|
|
326
|
+
("Class", "Function"), ("Class", "Class"),
|
|
327
|
+
("File", "Function"), ("File", "Class"),
|
|
328
|
+
]
|
|
329
|
+
for (ct, cdt), group in zip(edge_labels, call_groups):
|
|
330
|
+
for e in group:
|
|
331
|
+
if ct == "File":
|
|
332
|
+
cuid = e.get("caller_file_path", "")
|
|
333
|
+
else:
|
|
334
|
+
cuid = f"{e.get('caller_name', '')}|{e.get('caller_file_path', '')}|{e.get('caller_line_number', 0)}"
|
|
335
|
+
duid = f"{e.get('called_name', '')}|{e.get('called_file_path', '')}|0"
|
|
336
|
+
c_caller.append(cuid); c_called.append(duid); c_ct.append(ct); c_cdt.append(cdt)
|
|
337
|
+
c_cn.append(e.get("caller_name", "")); c_dn.append(e.get("called_name", ""))
|
|
338
|
+
caller_path = e.get("caller_file_path", "")
|
|
339
|
+
called_path = e.get("called_file_path", "")
|
|
340
|
+
# Normalize to relative paths
|
|
341
|
+
try:
|
|
342
|
+
caller_path = str(Path(caller_path).relative_to(repo_path_obj)) if caller_path else ""
|
|
343
|
+
except ValueError:
|
|
344
|
+
pass
|
|
345
|
+
try:
|
|
346
|
+
called_path = str(Path(called_path).relative_to(repo_path_obj)) if called_path else ""
|
|
347
|
+
except ValueError:
|
|
348
|
+
pass
|
|
349
|
+
c_cp.append(caller_path); c_dp.append(called_path)
|
|
350
|
+
c_ln.append(e.get("line_number", 0)); c_fcn.append(e.get("full_call_name", ""))
|
|
351
|
+
# Confidence comes from the resolver's tier (upstream scheme):
|
|
352
|
+
# EXTRACTED / INFERRED / AMBIGUOUS. Older resolvers without a
|
|
353
|
+
# tier fall back to the same-file heuristic.
|
|
354
|
+
tier = e.get("resolution_tier", 0)
|
|
355
|
+
c_tier.append(tier)
|
|
356
|
+
c_recv.append(e.get("receiver_type") or "")
|
|
357
|
+
c_conf.append(e.get("confidence") or (
|
|
358
|
+
"EXTRACTED" if caller_path == called_path else "INFERRED"))
|
|
359
|
+
|
|
360
|
+
# ── Inheritance ──────────────────────────────────────────────
|
|
361
|
+
inh_child = []; inh_parent = []; inh_cn = []; inh_pn = []; inh_cp = []; inh_pp = []
|
|
362
|
+
for edge in (inheritance or []):
|
|
363
|
+
child_name = edge.get("child_name", "")
|
|
364
|
+
parent_name = edge.get("parent_name", "")
|
|
365
|
+
# Rust resolver emits `path` / `resolved_parent_file_path` (same
|
|
366
|
+
# contract as the graph writer); keep the old keys as fallback.
|
|
367
|
+
child_path = edge.get("path") or edge.get("child_file_path", "")
|
|
368
|
+
parent_path = edge.get("resolved_parent_file_path") or edge.get("parent_file_path", "")
|
|
369
|
+
# Normalize to relative paths
|
|
370
|
+
try:
|
|
371
|
+
child_path = str(Path(child_path).relative_to(repo_path_obj)) if child_path else ""
|
|
372
|
+
except ValueError:
|
|
373
|
+
pass
|
|
374
|
+
try:
|
|
375
|
+
parent_path = str(Path(parent_path).relative_to(repo_path_obj)) if parent_path else ""
|
|
376
|
+
except ValueError:
|
|
377
|
+
pass
|
|
378
|
+
inh_child.append(f"{child_name}|{child_path}|0")
|
|
379
|
+
inh_parent.append(f"{parent_name}|{parent_path}|0")
|
|
380
|
+
inh_cn.append(child_name); inh_pn.append(parent_name)
|
|
381
|
+
inh_cp.append(child_path); inh_pp.append(parent_path)
|
|
382
|
+
|
|
383
|
+
# ── Stage tables for bulk load (Parquet via pyarrow if installed, else CSV)
|
|
384
|
+
_t_pq = time.perf_counter()
|
|
385
|
+
pq_dir = tempfile.mkdtemp(prefix="cgc_pq_")
|
|
386
|
+
|
|
387
|
+
_stage({
|
|
388
|
+
"path": f_path, "name": f_name, "relative_path": f_rel, "is_dependency": f_dep,
|
|
389
|
+
}, f"{pq_dir}/files")
|
|
390
|
+
|
|
391
|
+
if dir_set:
|
|
392
|
+
d_paths = list(dir_set.keys())
|
|
393
|
+
d_names = [dir_set[p][0] for p in d_paths]
|
|
394
|
+
d_parents = [dir_set[p][1] for p in d_paths]
|
|
395
|
+
_stage({
|
|
396
|
+
"path": d_paths, "name": d_names, "parent_path": d_parents,
|
|
397
|
+
}, f"{pq_dir}/directories")
|
|
398
|
+
|
|
399
|
+
_stage({
|
|
400
|
+
"uid": fn_uid, "name": fn_name, "path": fn_path, "line_number": fn_line,
|
|
401
|
+
"complexity": fn_cx, "return_type": fn_rt, "docstring": fn_doc,
|
|
402
|
+
"class_context": fn_cc, "is_async": fn_async,
|
|
403
|
+
"body_start_line": fn_bstart, "body_end_line": fn_bend,
|
|
404
|
+
"decorators": fn_dec,
|
|
405
|
+
}, f"{pq_dir}/functions")
|
|
406
|
+
|
|
407
|
+
_stage({
|
|
408
|
+
"uid": cl_uid, "name": cl_name, "path": cl_path,
|
|
409
|
+
"line_number": cl_line, "docstring": cl_doc, "bases": cl_bases,
|
|
410
|
+
"decorators": cl_dec, "kind": cl_kind,
|
|
411
|
+
}, f"{pq_dir}/classes")
|
|
412
|
+
|
|
413
|
+
_stage({
|
|
414
|
+
"uid": v_uid, "name": v_name, "path": v_path,
|
|
415
|
+
"line_number": v_line, "type": v_type,
|
|
416
|
+
}, f"{pq_dir}/variables")
|
|
417
|
+
|
|
418
|
+
if p_uid:
|
|
419
|
+
_stage({
|
|
420
|
+
"uid": p_uid, "name": p_name, "path": p_path,
|
|
421
|
+
"function_uid": p_func_uid, "function_line_number": p_func_line,
|
|
422
|
+
}, f"{pq_dir}/parameters")
|
|
423
|
+
|
|
424
|
+
_stage({
|
|
425
|
+
"file_path": im_fp, "module_name": im_mod, "imported_name": im_name,
|
|
426
|
+
"alias": im_alias, "full_import_name": im_full, "line_number": im_line,
|
|
427
|
+
}, f"{pq_dir}/imports")
|
|
428
|
+
|
|
429
|
+
_stage({
|
|
430
|
+
"file_path": fc_fp, "symbol_uid": fc_uid, "symbol_type": fc_type,
|
|
431
|
+
}, f"{pq_dir}/file_contains")
|
|
432
|
+
|
|
433
|
+
_stage({
|
|
434
|
+
"caller_uid": c_caller, "called_uid": c_called,
|
|
435
|
+
"caller_type": c_ct, "called_type": c_cdt,
|
|
436
|
+
"caller_name": c_cn, "called_name": c_dn,
|
|
437
|
+
"caller_path": c_cp, "called_path": c_dp,
|
|
438
|
+
"line_number": c_ln, "full_call_name": c_fcn,
|
|
439
|
+
"confidence": c_conf,
|
|
440
|
+
"resolution_tier": c_tier,
|
|
441
|
+
"receiver_type": c_recv,
|
|
442
|
+
}, f"{pq_dir}/calls")
|
|
443
|
+
|
|
444
|
+
if inh_child:
|
|
445
|
+
_stage({
|
|
446
|
+
"child_uid": inh_child, "parent_uid": inh_parent,
|
|
447
|
+
"child_name": inh_cn, "parent_name": inh_pn,
|
|
448
|
+
"child_path": inh_cp, "parent_path": inh_pp,
|
|
449
|
+
}, f"{pq_dir}/inheritance")
|
|
450
|
+
|
|
451
|
+
if on_progress:
|
|
452
|
+
on_progress(total * 2 // 3, total, "Loading into DuckDB...")
|
|
453
|
+
|
|
454
|
+
logger.info(" [timing] stage_write: %.1fs", time.perf_counter() - _t_pq)
|
|
455
|
+
|
|
456
|
+
# ── DROP + COPY FROM ─────────────────────────────────────────
|
|
457
|
+
_t_db = time.perf_counter()
|
|
458
|
+
c = self._conn
|
|
459
|
+
|
|
460
|
+
# Drop existing data
|
|
461
|
+
for tbl in ["operational_params", "rationales", "routes", "execution_flows", "calls", "inheritance", "injections", "orm_entities", "orm_repositories", "db_access", "navigations", "unresolved_calls", "file_contains",
|
|
462
|
+
"imports", "parameters", "variables", "classes", "functions",
|
|
463
|
+
"directories", "files", "modules", "repository"]:
|
|
464
|
+
c.execute(f"DROP TABLE IF EXISTS {tbl}")
|
|
465
|
+
self._schema_created = False
|
|
466
|
+
self._create_schema()
|
|
467
|
+
|
|
468
|
+
# Repository
|
|
469
|
+
c.execute("INSERT INTO repository VALUES (?, ?)",
|
|
470
|
+
[str(repo_path_obj), repo_path_obj.name])
|
|
471
|
+
|
|
472
|
+
# Bulk load from Parquet
|
|
473
|
+
_load(c, "files", f"{pq_dir}/files")
|
|
474
|
+
|
|
475
|
+
if _staged(f"{pq_dir}/directories"):
|
|
476
|
+
_load(c, "directories", f"{pq_dir}/directories")
|
|
477
|
+
|
|
478
|
+
_load(c, "functions", f"{pq_dir}/functions")
|
|
479
|
+
_load(c, "classes", f"{pq_dir}/classes")
|
|
480
|
+
_load(c, "variables", f"{pq_dir}/variables")
|
|
481
|
+
|
|
482
|
+
if _staged(f"{pq_dir}/parameters"):
|
|
483
|
+
_load(c, "parameters", f"{pq_dir}/parameters")
|
|
484
|
+
|
|
485
|
+
# Modules (deduplicated)
|
|
486
|
+
if mod_set:
|
|
487
|
+
_insert_rows(c, "modules", [(m,) for m in mod_set])
|
|
488
|
+
|
|
489
|
+
_load(c, "imports", f"{pq_dir}/imports")
|
|
490
|
+
_load(c, "file_contains", f"{pq_dir}/file_contains")
|
|
491
|
+
_load(c, "calls", f"{pq_dir}/calls")
|
|
492
|
+
|
|
493
|
+
if _staged(f"{pq_dir}/inheritance"):
|
|
494
|
+
_load(c, "inheritance", f"{pq_dir}/inheritance")
|
|
495
|
+
|
|
496
|
+
if inj_rows:
|
|
497
|
+
_insert_rows(c, "injections", _resolve_injection_targets(inj_rows, cl_name, cl_path),
|
|
498
|
+
)
|
|
499
|
+
|
|
500
|
+
if orm_rows:
|
|
501
|
+
_write_orm(c, orm_rows)
|
|
502
|
+
|
|
503
|
+
if unresolved:
|
|
504
|
+
def _rel_path(p):
|
|
505
|
+
try:
|
|
506
|
+
return str(Path(p).relative_to(repo_path_obj)) if p else ""
|
|
507
|
+
except ValueError:
|
|
508
|
+
return p
|
|
509
|
+
_insert_rows(c, "unresolved_calls", [
|
|
510
|
+
(u.get("caller_name") or "", _rel_path(u.get("caller_file_path", "")),
|
|
511
|
+
u.get("line_number", 0), u.get("called_name", ""),
|
|
512
|
+
(u.get("full_call_name") or "")[:300], u.get("receiver_type") or "", u.get("reason", ""))
|
|
513
|
+
for u in unresolved
|
|
514
|
+
])
|
|
515
|
+
|
|
516
|
+
# Indexes for query performance
|
|
517
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_fn_name ON functions(name)")
|
|
518
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_fn_path ON functions(path)")
|
|
519
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_fn_uid ON functions(uid)")
|
|
520
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_cls_name ON classes(name)")
|
|
521
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_cls_path ON classes(path)")
|
|
522
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_var_path ON variables(path)")
|
|
523
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_calls_caller ON calls(caller_uid)")
|
|
524
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_calls_called ON calls(called_uid)")
|
|
525
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_calls_types ON calls(caller_type, called_type)")
|
|
526
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_fc_file ON file_contains(file_path)")
|
|
527
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_fc_uid ON file_contains(symbol_uid)")
|
|
528
|
+
c.execute("CREATE INDEX IF NOT EXISTS idx_imp_file ON imports(file_path)")
|
|
529
|
+
|
|
530
|
+
logger.info(" [timing] duckdb_load: %.1fs", time.perf_counter() - _t_db)
|
|
531
|
+
|
|
532
|
+
# ── Detect execution flows ────────────────────────────────
|
|
533
|
+
_t = time.perf_counter()
|
|
534
|
+
try:
|
|
535
|
+
from ..execution_flows import detect_execution_flows
|
|
536
|
+
import json as _json
|
|
537
|
+
flows = detect_execution_flows(parsed_results, call_groups, repo_path=str(repo_path_obj))
|
|
538
|
+
if flows:
|
|
539
|
+
flow_rows = [
|
|
540
|
+
(f["name"], f["entry_file"], f["entry_line"],
|
|
541
|
+
f.get("entry_class", ""), f["step_count"],
|
|
542
|
+
f["depth"], f["score"], _json.dumps(f["steps"]))
|
|
543
|
+
for f in flows
|
|
544
|
+
]
|
|
545
|
+
_insert_rows(c, "execution_flows", flow_rows,
|
|
546
|
+
)
|
|
547
|
+
except Exception as exc:
|
|
548
|
+
logger.debug("Execution flow detection failed: %s", exc)
|
|
549
|
+
flows = []
|
|
550
|
+
|
|
551
|
+
logger.info(" [timing] execution_flows: %.1fs", time.perf_counter() - _t)
|
|
552
|
+
|
|
553
|
+
# ── Detect API routes ────────────────────────────────────
|
|
554
|
+
_t = time.perf_counter()
|
|
555
|
+
detected_routes = []
|
|
556
|
+
try:
|
|
557
|
+
from ..route_extraction import extract_routes
|
|
558
|
+
detected_routes = extract_routes(parsed_results, repo_path)
|
|
559
|
+
if detected_routes:
|
|
560
|
+
_insert_rows(c, "routes", [(r["method"], r["path"], r["handler"],
|
|
561
|
+
r["file"], r["line"], r["framework"])
|
|
562
|
+
for r in detected_routes],
|
|
563
|
+
)
|
|
564
|
+
except Exception as exc:
|
|
565
|
+
logger.debug("Route extraction failed: %s", exc)
|
|
566
|
+
|
|
567
|
+
try:
|
|
568
|
+
from ..angular_routes import extract_navigations
|
|
569
|
+
ng_routes = [r for r in detected_routes if r.get("framework") == "angular"]
|
|
570
|
+
navs = extract_navigations(parsed_results, repo_path, ng_routes)
|
|
571
|
+
if navs:
|
|
572
|
+
_insert_rows(c, "navigations", [(n["caller_name"], n["caller_path"], n["line"], n["target"],
|
|
573
|
+
n["route_path"], n["route_handler"], n["route_file"]) for n in navs],
|
|
574
|
+
)
|
|
575
|
+
except Exception as exc:
|
|
576
|
+
logger.debug("Navigation extraction failed: %s", exc)
|
|
577
|
+
|
|
578
|
+
logger.info(" [timing] route_extraction: %.1fs", time.perf_counter() - _t)
|
|
579
|
+
|
|
580
|
+
# ── Extract design rationale comments ─────────────────────
|
|
581
|
+
_t = time.perf_counter()
|
|
582
|
+
detected_rationales = []
|
|
583
|
+
try:
|
|
584
|
+
from ..rationale_extraction import extract_rationales
|
|
585
|
+
detected_rationales = extract_rationales(parsed_results, repo_path)
|
|
586
|
+
if detected_rationales:
|
|
587
|
+
_insert_rows(c, "rationales", [(r["tag"], r["text"], r["file"], r["line"], r["context"])
|
|
588
|
+
for r in detected_rationales],
|
|
589
|
+
)
|
|
590
|
+
except Exception as exc:
|
|
591
|
+
logger.debug("Rationale extraction failed: %s", exc)
|
|
592
|
+
|
|
593
|
+
logger.info(" [timing] rationale_extraction: %.1fs", time.perf_counter() - _t)
|
|
594
|
+
|
|
595
|
+
# ── Extract operational parameters ──────────────────────────
|
|
596
|
+
_t = time.perf_counter()
|
|
597
|
+
detected_op_params = []
|
|
598
|
+
try:
|
|
599
|
+
from ..op_param_extraction import extract_operational_params
|
|
600
|
+
detected_op_params = extract_operational_params(parsed_results, repo_path)
|
|
601
|
+
if detected_op_params:
|
|
602
|
+
_insert_rows(c, "operational_params", [(p["name"], p["value"], p["path"],
|
|
603
|
+
p["line_number"], p["category"])
|
|
604
|
+
for p in detected_op_params],
|
|
605
|
+
)
|
|
606
|
+
except Exception as exc:
|
|
607
|
+
logger.debug("Operational param extraction failed: %s", exc)
|
|
608
|
+
|
|
609
|
+
logger.info(" [timing] op_param_extraction: %.1fs", time.perf_counter() - _t)
|
|
610
|
+
|
|
611
|
+
# ── Post-process: fill inheritance from classes.bases ──────
|
|
612
|
+
try:
|
|
613
|
+
# Build class name → uid map
|
|
614
|
+
class_map = {}
|
|
615
|
+
for row in c.execute("SELECT uid, name, path FROM classes").fetchall():
|
|
616
|
+
class_map[row[1]] = (row[0], row[2])
|
|
617
|
+
|
|
618
|
+
# Check existing inheritance count
|
|
619
|
+
existing = c.execute("SELECT count(*) FROM inheritance").fetchone()[0]
|
|
620
|
+
|
|
621
|
+
# For each class with bases, create inheritance edges if not exists
|
|
622
|
+
import re as _re
|
|
623
|
+
added = 0
|
|
624
|
+
for row in c.execute("SELECT uid, name, path, bases FROM classes WHERE bases != ''").fetchall():
|
|
625
|
+
child_uid, child_name, child_path, bases_str = row
|
|
626
|
+
# Normalize: remove newlines, strip "extends"/"implements" keywords
|
|
627
|
+
cleaned = bases_str.replace("\n", " ").replace("\r", "")
|
|
628
|
+
cleaned = _re.sub(r"\b(extends|implements)\b", ",", cleaned)
|
|
629
|
+
# Strip ALL generic type params: BaseCrudService<A, B, C> → BaseCrudService
|
|
630
|
+
stripped = _re.sub(r"<[^<>]*>", "", cleaned)
|
|
631
|
+
while "<" in stripped:
|
|
632
|
+
stripped = _re.sub(r"<[^<>]*>", "", stripped)
|
|
633
|
+
# Split by comma, clean whitespace
|
|
634
|
+
base_names = [b.strip() for b in stripped.split(",") if b.strip()]
|
|
635
|
+
for base_name in base_names:
|
|
636
|
+
if base_name in class_map:
|
|
637
|
+
parent_uid, parent_path = class_map[base_name]
|
|
638
|
+
# Skip if the resolver already linked this child to a
|
|
639
|
+
# parent of that name (possibly in another file).
|
|
640
|
+
exists = c.execute(
|
|
641
|
+
"SELECT 1 FROM inheritance WHERE child_name=? AND child_path=? AND parent_name=?",
|
|
642
|
+
[child_name, child_path, base_name],
|
|
643
|
+
).fetchone()
|
|
644
|
+
if not exists:
|
|
645
|
+
c.execute(
|
|
646
|
+
"INSERT INTO inheritance VALUES (?,?,?,?,?,?)",
|
|
647
|
+
[child_uid, parent_uid, child_name, base_name,
|
|
648
|
+
child_path, parent_path],
|
|
649
|
+
)
|
|
650
|
+
added += 1
|
|
651
|
+
if added:
|
|
652
|
+
logger.info("Post-process: added %d inheritance edges (was %d)", added, existing)
|
|
653
|
+
except Exception as exc:
|
|
654
|
+
logger.debug("Inheritance post-process failed: %s", exc)
|
|
655
|
+
|
|
656
|
+
# Cleanup staged files
|
|
657
|
+
import shutil
|
|
658
|
+
shutil.rmtree(pq_dir, ignore_errors=True)
|
|
659
|
+
|
|
660
|
+
elapsed = time.perf_counter() - t_start
|
|
661
|
+
|
|
662
|
+
if on_progress:
|
|
663
|
+
on_progress(total, total, f"DuckDB write complete ({elapsed:.1f}s)")
|
|
664
|
+
|
|
665
|
+
counts = {
|
|
666
|
+
"files": len(f_path),
|
|
667
|
+
"functions": len(fn_uid),
|
|
668
|
+
"classes": len(cl_uid),
|
|
669
|
+
"variables": len(v_uid),
|
|
670
|
+
"parameters": len(p_uid),
|
|
671
|
+
"calls": len(c_caller),
|
|
672
|
+
"imports": len(im_fp),
|
|
673
|
+
"modules": len(mod_set),
|
|
674
|
+
"inheritance": len(inh_child),
|
|
675
|
+
"execution_flows": len(flows),
|
|
676
|
+
"routes": len(detected_routes),
|
|
677
|
+
"rationales": len(detected_rationales),
|
|
678
|
+
"operational_params": len(detected_op_params),
|
|
679
|
+
"elapsed_s": round(elapsed, 2),
|
|
680
|
+
}
|
|
681
|
+
logger.info(f"DuckDB write complete: {counts}")
|
|
682
|
+
return counts
|
|
683
|
+
|
|
684
|
+
# ── Query methods (for CGCBridge) ────────────────────────────────
|
|
685
|
+
|
|
686
|
+
def get_stats(self) -> Dict[str, int]:
|
|
687
|
+
c = self._conn
|
|
688
|
+
stats = {}
|
|
689
|
+
for tbl in ["files", "functions", "classes", "variables", "calls", "modules", "imports"]:
|
|
690
|
+
try:
|
|
691
|
+
stats[tbl] = c.execute(f"SELECT count(*) FROM {tbl}").fetchone()[0]
|
|
692
|
+
except Exception:
|
|
693
|
+
stats[tbl] = 0
|
|
694
|
+
return stats
|
|
695
|
+
|
|
696
|
+
def get_operational_params(self, file_paths: List[str] = None) -> List[Dict]:
|
|
697
|
+
"""Get operational parameters, optionally filtered by file paths."""
|
|
698
|
+
try:
|
|
699
|
+
if file_paths:
|
|
700
|
+
placeholders = ",".join(["?"] * len(file_paths))
|
|
701
|
+
rows = self._conn.execute(f"""
|
|
702
|
+
SELECT name, value, path, line_number, category
|
|
703
|
+
FROM operational_params
|
|
704
|
+
WHERE path IN ({placeholders})
|
|
705
|
+
ORDER BY path, line_number
|
|
706
|
+
""", file_paths).fetchall()
|
|
707
|
+
else:
|
|
708
|
+
rows = self._conn.execute("""
|
|
709
|
+
SELECT name, value, path, line_number, category
|
|
710
|
+
FROM operational_params
|
|
711
|
+
ORDER BY path, line_number
|
|
712
|
+
""").fetchall()
|
|
713
|
+
return [
|
|
714
|
+
{"name": r[0], "value": r[1], "path": r[2],
|
|
715
|
+
"line_number": r[3], "category": r[4]}
|
|
716
|
+
for r in rows
|
|
717
|
+
]
|
|
718
|
+
except Exception:
|
|
719
|
+
return []
|
|
720
|
+
|
|
721
|
+
def get_top_connected(self, limit: int = 30) -> List[Dict]:
|
|
722
|
+
"""Get top connected functions/classes by call count."""
|
|
723
|
+
rows = self._conn.execute("""
|
|
724
|
+
SELECT
|
|
725
|
+
called_name AS name,
|
|
726
|
+
called_path AS path,
|
|
727
|
+
called_type AS type,
|
|
728
|
+
count(*) AS call_count
|
|
729
|
+
FROM calls
|
|
730
|
+
WHERE called_type IN ('Function', 'Class')
|
|
731
|
+
GROUP BY called_name, called_path, called_type
|
|
732
|
+
ORDER BY call_count DESC
|
|
733
|
+
LIMIT ?
|
|
734
|
+
""", [limit]).fetchall()
|
|
735
|
+
return [
|
|
736
|
+
{"name": r[0], "path": r[1], "type": r[2], "call_count": r[3]}
|
|
737
|
+
for r in rows
|
|
738
|
+
]
|
|
739
|
+
|
|
740
|
+
def get_call_graph_for_files(
|
|
741
|
+
self, file_paths: List[str]
|
|
742
|
+
) -> Dict[str, List[Dict]]:
|
|
743
|
+
"""Get intra/outgoing/incoming call edges for given files."""
|
|
744
|
+
if not file_paths:
|
|
745
|
+
return {"intra": [], "outgoing": [], "incoming": []}
|
|
746
|
+
|
|
747
|
+
placeholders = ",".join(["?"] * len(file_paths))
|
|
748
|
+
|
|
749
|
+
# All edges where caller OR called is in our files
|
|
750
|
+
rows = self._conn.execute(f"""
|
|
751
|
+
SELECT caller_name, caller_path, caller_type,
|
|
752
|
+
called_name, called_path, called_type,
|
|
753
|
+
line_number, full_call_name
|
|
754
|
+
FROM calls
|
|
755
|
+
WHERE caller_path IN ({placeholders})
|
|
756
|
+
OR called_path IN ({placeholders})
|
|
757
|
+
""", file_paths + file_paths).fetchall()
|
|
758
|
+
|
|
759
|
+
fp_set = set(file_paths)
|
|
760
|
+
intra = []; outgoing = []; incoming = []
|
|
761
|
+
|
|
762
|
+
for r in rows:
|
|
763
|
+
edge = {
|
|
764
|
+
"caller_name": r[0], "caller_path": r[1], "caller_type": r[2],
|
|
765
|
+
"called_name": r[3], "called_path": r[4], "called_type": r[5],
|
|
766
|
+
"line_number": r[6], "full_call_name": r[7],
|
|
767
|
+
}
|
|
768
|
+
caller_in = r[1] in fp_set
|
|
769
|
+
called_in = r[4] in fp_set
|
|
770
|
+
|
|
771
|
+
if caller_in and called_in:
|
|
772
|
+
intra.append(edge)
|
|
773
|
+
elif caller_in:
|
|
774
|
+
outgoing.append(edge)
|
|
775
|
+
elif called_in:
|
|
776
|
+
incoming.append(edge)
|
|
777
|
+
|
|
778
|
+
return {"intra": intra, "outgoing": outgoing, "incoming": incoming}
|
|
779
|
+
|
|
780
|
+
def get_functions_in_file(self, file_path: str) -> List[Dict]:
|
|
781
|
+
rows = self._conn.execute("""
|
|
782
|
+
SELECT name, line_number, complexity, return_type, docstring, class_context, is_async
|
|
783
|
+
FROM functions WHERE path = ?
|
|
784
|
+
ORDER BY line_number
|
|
785
|
+
""", [file_path]).fetchall()
|
|
786
|
+
return [
|
|
787
|
+
{"name": r[0], "line_number": r[1], "complexity": r[2],
|
|
788
|
+
"return_type": r[3], "docstring": r[4], "class_context": r[5], "is_async": r[6]}
|
|
789
|
+
for r in rows
|
|
790
|
+
]
|
|
791
|
+
|
|
792
|
+
def get_classes_in_file(self, file_path: str) -> List[Dict]:
|
|
793
|
+
rows = self._conn.execute("""
|
|
794
|
+
SELECT name, line_number, docstring, bases
|
|
795
|
+
FROM classes WHERE path = ?
|
|
796
|
+
ORDER BY line_number
|
|
797
|
+
""", [file_path]).fetchall()
|
|
798
|
+
return [
|
|
799
|
+
{"name": r[0], "line_number": r[1], "docstring": r[2], "bases": r[3]}
|
|
800
|
+
for r in rows
|
|
801
|
+
]
|
|
802
|
+
|
|
803
|
+
def get_imports_for_file(self, file_path: str) -> List[Dict]:
|
|
804
|
+
rows = self._conn.execute("""
|
|
805
|
+
SELECT module_name, imported_name, alias, line_number
|
|
806
|
+
FROM imports WHERE file_path = ?
|
|
807
|
+
""", [file_path]).fetchall()
|
|
808
|
+
return [
|
|
809
|
+
{"module_name": r[0], "imported_name": r[1], "alias": r[2], "line_number": r[3]}
|
|
810
|
+
for r in rows
|
|
811
|
+
]
|
|
812
|
+
|
|
813
|
+
def search_symbols(self, query: str, limit: int = 20) -> List[Dict]:
|
|
814
|
+
"""Search functions and classes by name pattern."""
|
|
815
|
+
pattern = f"%{query}%"
|
|
816
|
+
rows = self._conn.execute("""
|
|
817
|
+
SELECT 'Function' AS type, name, path, line_number FROM functions WHERE name ILIKE ?
|
|
818
|
+
UNION ALL
|
|
819
|
+
SELECT 'Class' AS type, name, path, line_number FROM classes WHERE name ILIKE ?
|
|
820
|
+
ORDER BY name LIMIT ?
|
|
821
|
+
""", [pattern, pattern, limit]).fetchall()
|
|
822
|
+
return [
|
|
823
|
+
{"type": r[0], "name": r[1], "path": r[2], "line_number": r[3]}
|
|
824
|
+
for r in rows
|
|
825
|
+
]
|
|
826
|
+
|
|
827
|
+
def get_routes(self, limit: int = 100) -> List[Dict]:
|
|
828
|
+
"""Get detected API routes."""
|
|
829
|
+
try:
|
|
830
|
+
rows = self._conn.execute("""
|
|
831
|
+
SELECT method, path, handler, file, line, framework
|
|
832
|
+
FROM routes ORDER BY path, method LIMIT ?
|
|
833
|
+
""", [limit]).fetchall()
|
|
834
|
+
return [
|
|
835
|
+
{"method": r[0], "path": r[1], "handler": r[2],
|
|
836
|
+
"file": r[3], "line": r[4], "framework": r[5]}
|
|
837
|
+
for r in rows
|
|
838
|
+
]
|
|
839
|
+
except Exception:
|
|
840
|
+
return []
|
|
841
|
+
|
|
842
|
+
def get_execution_flows(self, limit: int = 50) -> List[Dict]:
|
|
843
|
+
"""Get top execution flows by score."""
|
|
844
|
+
import json
|
|
845
|
+
try:
|
|
846
|
+
rows = self._conn.execute("""
|
|
847
|
+
SELECT name, entry_file, entry_line, entry_class,
|
|
848
|
+
step_count, depth, score, steps_json
|
|
849
|
+
FROM execution_flows
|
|
850
|
+
ORDER BY score DESC, step_count DESC
|
|
851
|
+
LIMIT ?
|
|
852
|
+
""", [limit]).fetchall()
|
|
853
|
+
return [
|
|
854
|
+
{
|
|
855
|
+
"name": r[0], "entry_file": r[1], "entry_line": r[2],
|
|
856
|
+
"entry_class": r[3], "step_count": r[4], "depth": r[5],
|
|
857
|
+
"score": r[6], "steps": json.loads(r[7]),
|
|
858
|
+
}
|
|
859
|
+
for r in rows
|
|
860
|
+
]
|
|
861
|
+
except Exception:
|
|
862
|
+
return []
|
|
863
|
+
|
|
864
|
+
def get_rationales(self, limit: int = 200) -> List[Dict]:
|
|
865
|
+
"""Get design rationale comments."""
|
|
866
|
+
try:
|
|
867
|
+
rows = self._conn.execute("""
|
|
868
|
+
SELECT tag, text, file, line, context
|
|
869
|
+
FROM rationales ORDER BY file, line LIMIT ?
|
|
870
|
+
""", [limit]).fetchall()
|
|
871
|
+
return [
|
|
872
|
+
{"tag": r[0], "text": r[1], "file": r[2],
|
|
873
|
+
"line": r[3], "context": r[4]}
|
|
874
|
+
for r in rows
|
|
875
|
+
]
|
|
876
|
+
except Exception:
|
|
877
|
+
return []
|
|
878
|
+
|
|
879
|
+
def execute(self, query: str, params=None):
|
|
880
|
+
"""Raw query execution for advanced use."""
|
|
881
|
+
if params:
|
|
882
|
+
return self._conn.execute(query, params)
|
|
883
|
+
return self._conn.execute(query)
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def _resolve_injection_targets(inj_rows, class_names, class_paths):
|
|
887
|
+
"""Attach the repo file declaring each injected type.
|
|
888
|
+
|
|
889
|
+
Unique type name → that file; otherwise the candidate matching one of the
|
|
890
|
+
injector file's imports; otherwise one in the injector's own package
|
|
891
|
+
directory (Java same-package types need no import). Unresolvable or
|
|
892
|
+
external types (e.g. a framework bean) keep an empty path.
|
|
893
|
+
"""
|
|
894
|
+
by_name: Dict[str, List[str]] = {}
|
|
895
|
+
for name, path in zip(class_names, class_paths):
|
|
896
|
+
if name and path not in by_name.setdefault(name, []):
|
|
897
|
+
by_name[name].append(path)
|
|
898
|
+
out = []
|
|
899
|
+
for injector, rel, typ, field, line, kind, stereotype, imports in inj_rows:
|
|
900
|
+
cands = by_name.get(typ, [])
|
|
901
|
+
target = ""
|
|
902
|
+
if len(cands) == 1:
|
|
903
|
+
target = cands[0]
|
|
904
|
+
elif cands:
|
|
905
|
+
for imp in imports:
|
|
906
|
+
if imp.rsplit(".", 1)[-1] == typ:
|
|
907
|
+
imp_path = imp.replace(".", "/")
|
|
908
|
+
target = next((p for p in cands if imp_path in p), "")
|
|
909
|
+
if target:
|
|
910
|
+
break
|
|
911
|
+
if not target:
|
|
912
|
+
pkg_dir = os.path.dirname(rel)
|
|
913
|
+
target = next((p for p in cands if os.path.dirname(p) == pkg_dir), "")
|
|
914
|
+
out.append((injector, rel, typ, target, field, line, kind, stereotype))
|
|
915
|
+
return out
|
|
916
|
+
|
|
917
|
+
|
|
918
|
+
# Spring Data CRUD / derived-query method prefixes (lower-case). Writes first:
|
|
919
|
+
# "saveAndFlush" must not match a read prefix.
|
|
920
|
+
_REPO_WRITE_PREFIXES = (
|
|
921
|
+
"save", "insert", "update", "delete", "remove", "flush", "create", "upsert",
|
|
922
|
+
)
|
|
923
|
+
_REPO_READ_PREFIXES = (
|
|
924
|
+
"find", "read", "get", "query", "search", "count", "exists", "stream", "fetch", "load",
|
|
925
|
+
)
|
|
926
|
+
_SPRING_DATA_BASES = {
|
|
927
|
+
"JpaRepository", "CrudRepository", "PagingAndSortingRepository", "ListCrudRepository",
|
|
928
|
+
"ListPagingAndSortingRepository", "Repository", "MongoRepository", "ReactiveMongoRepository",
|
|
929
|
+
"CassandraRepository", "ReactiveCassandraRepository", "R2dbcRepository",
|
|
930
|
+
"JpaSpecificationExecutor", "QuerydslPredicateExecutor", "CoroutineCrudRepository",
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
def _split_table(name: str) -> Tuple[str, str]:
|
|
935
|
+
"""`schema.table` -> (table, schema)."""
|
|
936
|
+
schema, _, table = name.rpartition(".")
|
|
937
|
+
return table, schema
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
def _write_orm(c, orm_rows) -> None:
|
|
941
|
+
"""Fill orm_entities, orm_repositories and db_access.
|
|
942
|
+
|
|
943
|
+
db_access combines two sources:
|
|
944
|
+
- query: tables named in a repository method's @Query / MyBatis SQL
|
|
945
|
+
(JPQL entity names mapped to their tables);
|
|
946
|
+
- repository: resolved calls whose receiver is a repository, e.g.
|
|
947
|
+
petRepository.save(...) / findByOwner(...) -> the entity's table, with
|
|
948
|
+
READ/WRITE from the Spring Data method name (or the method's @Query).
|
|
949
|
+
"""
|
|
950
|
+
entities = {} # class -> (path, table, schema, datastore, line)
|
|
951
|
+
repos_raw = []
|
|
952
|
+
queries = []
|
|
953
|
+
for rel, m in orm_rows:
|
|
954
|
+
kind = m.get("kind")
|
|
955
|
+
if kind == "entity" and m.get("tables"):
|
|
956
|
+
entities.setdefault(m["class_name"], (
|
|
957
|
+
rel, m["tables"][0], m.get("schema") or "", m.get("datastore") or "", m.get("line_number", 0)))
|
|
958
|
+
elif kind == "repository":
|
|
959
|
+
repos_raw.append((rel, m))
|
|
960
|
+
elif kind == "query":
|
|
961
|
+
queries.append((rel, m))
|
|
962
|
+
|
|
963
|
+
_insert_rows(c, "orm_entities", [
|
|
964
|
+
(cls, p, table, schema, store, line) for cls, (p, table, schema, store, line) in entities.items()
|
|
965
|
+
])
|
|
966
|
+
|
|
967
|
+
repos = {} # repository -> (path, entity, table, schema)
|
|
968
|
+
for rel, m in repos_raw:
|
|
969
|
+
repo, base, ent = m["class_name"], m.get("base") or "", m.get("entity") or ""
|
|
970
|
+
if ent not in entities or repo in repos:
|
|
971
|
+
continue
|
|
972
|
+
if base in _SPRING_DATA_BASES or base.endswith("Repository") or repo.endswith("Repository"):
|
|
973
|
+
_, table, schema, _, _ = entities[ent]
|
|
974
|
+
repos[repo] = (rel, ent, table, schema)
|
|
975
|
+
_insert_rows(c, "orm_repositories", [
|
|
976
|
+
(repo, p, ent, entities[ent][0], table, schema) for repo, (p, ent, table, schema) in repos.items()
|
|
977
|
+
])
|
|
978
|
+
|
|
979
|
+
def query_tables(m, repo_entity=None):
|
|
980
|
+
out = []
|
|
981
|
+
for t in m.get("tables") or []:
|
|
982
|
+
if m.get("native"):
|
|
983
|
+
table, schema = _split_table(t)
|
|
984
|
+
out.append((table, schema))
|
|
985
|
+
elif t in entities: # JPQL entity name
|
|
986
|
+
out.append((entities[t][1], entities[t][2]))
|
|
987
|
+
elif t == "entityName" and repo_entity in entities: # SpEL #{#entityName}
|
|
988
|
+
out.append((entities[repo_entity][1], entities[repo_entity][2]))
|
|
989
|
+
return out
|
|
990
|
+
|
|
991
|
+
# Repository -> its generic base interface (for queries declared on a
|
|
992
|
+
# shared base such as TenantAwareRepository<E>)
|
|
993
|
+
repo_base = {m["class_name"]: m.get("base") or "" for _, m in repos_raw}
|
|
994
|
+
queries_by_key = {(m["class_name"], m.get("method_name") or ""): m for _, m in queries}
|
|
995
|
+
|
|
996
|
+
access = []
|
|
997
|
+
repo_queries = {} # (repository, method) -> [(table, schema, op)]
|
|
998
|
+
for rel, m in queries:
|
|
999
|
+
op = m.get("operation") or "READ"
|
|
1000
|
+
tables = query_tables(m)
|
|
1001
|
+
repo_queries[(m["class_name"], m.get("method_name") or "")] = [(t, s, op) for t, s in tables]
|
|
1002
|
+
for table, schema in tables:
|
|
1003
|
+
access.append((m["class_name"], m.get("method_name") or "", rel, m.get("line_number", 0),
|
|
1004
|
+
table, schema, op, "query", m["class_name"], m.get("method_name") or ""))
|
|
1005
|
+
|
|
1006
|
+
if repos:
|
|
1007
|
+
names = list(repos)
|
|
1008
|
+
rows = c.execute(
|
|
1009
|
+
"SELECT caller_name, caller_path, line_number, called_name, receiver_type FROM calls "
|
|
1010
|
+
"WHERE confidence <> 'AMBIGUOUS' AND receiver_type IN (SELECT unnest(?))", [names]
|
|
1011
|
+
).fetchall()
|
|
1012
|
+
for caller, caller_path, line, method, repo in rows:
|
|
1013
|
+
declared = repo_queries.get((repo, method))
|
|
1014
|
+
base_query = queries_by_key.get((repo_base.get(repo, ""), method))
|
|
1015
|
+
if not declared and base_query:
|
|
1016
|
+
op = base_query.get("operation") or "READ"
|
|
1017
|
+
declared = [(t, s, op) for t, s in query_tables(base_query, repos[repo][1])]
|
|
1018
|
+
if declared:
|
|
1019
|
+
for table, schema, op in declared:
|
|
1020
|
+
access.append(("", caller or "", caller_path, line, table, schema, op, "repository", repo, method))
|
|
1021
|
+
continue
|
|
1022
|
+
low = (method or "").lower()
|
|
1023
|
+
if low.startswith(_REPO_WRITE_PREFIXES):
|
|
1024
|
+
op = "WRITE"
|
|
1025
|
+
elif low.startswith(_REPO_READ_PREFIXES):
|
|
1026
|
+
op = "READ"
|
|
1027
|
+
else:
|
|
1028
|
+
continue
|
|
1029
|
+
_, _, table, schema = repos[repo]
|
|
1030
|
+
access.append(("", caller or "", caller_path, line, table, schema, op, "repository", repo, method))
|
|
1031
|
+
|
|
1032
|
+
if access:
|
|
1033
|
+
_insert_rows(c, "db_access", list(dict.fromkeys(access)))
|
|
1034
|
+
|
|
1035
|
+
|
|
1036
|
+
# Bulk-load staging. pyarrow is optional:
|
|
1037
|
+
# - installed (wiki-forge declares it; extra `fast`): Parquet + read_parquet
|
|
1038
|
+
# / registered Arrow tables, the fastest path (C++ conversion);
|
|
1039
|
+
# - not installed (core install, e.g. slim Docker images): quoted CSV +
|
|
1040
|
+
# COPY into the declared column types. Identical table contents, ~3-4x
|
|
1041
|
+
# slower staging (≈0.3 s on a 1.5k-file repo).
|
|
1042
|
+
# Every CSV field is quoted, NULL is a sentinel no real value uses, and COPY
|
|
1043
|
+
# doesn't sniff types, so values round-trip exactly ('' stays '', "007"
|
|
1044
|
+
# stays a string, newlines/quotes survive).
|
|
1045
|
+
try:
|
|
1046
|
+
import pyarrow as _pa
|
|
1047
|
+
import pyarrow.parquet as _pq
|
|
1048
|
+
except ImportError: # core install without the `fast` extra
|
|
1049
|
+
_pa = _pq = None
|
|
1050
|
+
|
|
1051
|
+
_CSV_NULL = "__CGC_NULL__"
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
def _write_csv(columns: Dict[str, list], path: str) -> None:
|
|
1055
|
+
"""Write column lists (in table column order) as a quoted CSV."""
|
|
1056
|
+
import csv
|
|
1057
|
+
|
|
1058
|
+
cols = list(columns.values())
|
|
1059
|
+
with open(path, "w", newline="", encoding="utf-8") as fh:
|
|
1060
|
+
w = csv.writer(fh, quoting=csv.QUOTE_ALL, lineterminator="\n")
|
|
1061
|
+
w.writerows([_CSV_NULL if v is None else v for v in row] for row in zip(*cols))
|
|
1062
|
+
|
|
1063
|
+
|
|
1064
|
+
def _copy_csv(c, table: str, path: str, columns: Optional[List[str]] = None) -> None:
|
|
1065
|
+
target = f"{table} ({', '.join(columns)})" if columns else table
|
|
1066
|
+
c.execute(
|
|
1067
|
+
f"COPY {target} FROM '{path}' (FORMAT csv, HEADER false, DELIMITER ',', "
|
|
1068
|
+
f"QUOTE '\"', ESCAPE '\"', NULLSTR '{_CSV_NULL}', AUTO_DETECT false)"
|
|
1069
|
+
)
|
|
1070
|
+
|
|
1071
|
+
|
|
1072
|
+
def _stage(columns: Dict[str, list], base: str) -> None:
|
|
1073
|
+
"""Stage one table (column lists in table order) at `base` (+ extension)."""
|
|
1074
|
+
if _pa is not None:
|
|
1075
|
+
_pq.write_table(_pa.table(columns), base + ".parquet")
|
|
1076
|
+
else:
|
|
1077
|
+
_write_csv(columns, base + ".csv")
|
|
1078
|
+
|
|
1079
|
+
|
|
1080
|
+
def _staged(base: str) -> bool:
|
|
1081
|
+
return os.path.exists(base + ".parquet") or os.path.exists(base + ".csv")
|
|
1082
|
+
|
|
1083
|
+
|
|
1084
|
+
def _load(c, table: str, base: str) -> None:
|
|
1085
|
+
"""Bulk-load a table staged by _stage()."""
|
|
1086
|
+
if os.path.exists(base + ".parquet"):
|
|
1087
|
+
c.execute(f"INSERT INTO {table} SELECT * FROM read_parquet('{base}.parquet')")
|
|
1088
|
+
else:
|
|
1089
|
+
_copy_csv(c, table, base + ".csv")
|
|
1090
|
+
|
|
1091
|
+
|
|
1092
|
+
def _insert_rows(c, table: str, rows) -> None:
|
|
1093
|
+
"""Bulk-insert row tuples (in table column order) via a staged CSV + COPY.
|
|
1094
|
+
|
|
1095
|
+
DuckDB's executemany runs one INSERT per row (~0.5 ms each, worse with a
|
|
1096
|
+
large Python heap); COPY is a single columnar load.
|
|
1097
|
+
"""
|
|
1098
|
+
rows = list(rows)
|
|
1099
|
+
if not rows:
|
|
1100
|
+
return
|
|
1101
|
+
cols = [r[1] for r in c.execute(f"PRAGMA table_info('{table}')").fetchall()][: len(rows[0])]
|
|
1102
|
+
if _pa is not None:
|
|
1103
|
+
tbl = _pa.table({name: [row[i] for row in rows] for i, name in enumerate(cols)})
|
|
1104
|
+
c.register("_bulk_rows", tbl)
|
|
1105
|
+
try:
|
|
1106
|
+
c.execute(f"INSERT INTO {table} ({', '.join(cols)}) SELECT * FROM _bulk_rows")
|
|
1107
|
+
finally:
|
|
1108
|
+
c.unregister("_bulk_rows")
|
|
1109
|
+
return
|
|
1110
|
+
fd, path = tempfile.mkstemp(prefix=f"cgc_{table}_", suffix=".csv")
|
|
1111
|
+
os.close(fd)
|
|
1112
|
+
try:
|
|
1113
|
+
_write_csv({name: [row[i] for row in rows] for i, name in enumerate(cols)}, path)
|
|
1114
|
+
_copy_csv(c, table, path, cols)
|
|
1115
|
+
finally:
|
|
1116
|
+
os.remove(path)
|