| 365 | } |
| 366 | |
| 367 | static bool gm_build(cbm_graph_mem_t *g, sqlite3 *db, int64_t max_node, int64_t max_edge) { |
| 368 | gm_scan_t sc = {.prev_src = 0, .last_type = -1, .max_id = (uint32_t)max_node}; |
| 369 | sc.edge_cap = (size_t)max_edge; |
| 370 | g->out_nbr = gm_alloc(sc.edge_cap * sizeof(uint32_t)); |
| 371 | g->out_type = gm_alloc(sc.edge_cap); |
| 372 | if (!g->out_nbr || !g->out_type || |
| 373 | !gm_grow_u32(&g->out_off, &sc.off_cap, (size_t)max_node + GM_GROWTH)) { |
| 374 | return false; |
| 375 | } |
| 376 | /* ORDER BY the covering UNIQUE index's leading columns: a sequential walk |
| 377 | * of sqlite_autoindex_edges_1, no sort and no table access. */ |
| 378 | sqlite3_stmt *st = NULL; |
| 379 | if (sqlite3_prepare_v2(db, |
| 380 | "SELECT source_id, target_id, type FROM edges " |
| 381 | "ORDER BY source_id, target_id, type;", |
| 382 | -1, &st, NULL) != SQLITE_OK) { |
| 383 | sqlite3_finalize(st); |
| 384 | return false; |
| 385 | } |
| 386 | int rc; |
| 387 | bool ok = true; |
| 388 | while ((rc = sqlite3_step(st)) == SQLITE_ROW) { |
| 389 | if (!gm_scan_row(g, &sc, st)) { |
| 390 | ok = false; |
| 391 | break; |
| 392 | } |
| 393 | } |
| 394 | sqlite3_finalize(st); |
| 395 | if (!ok || rc != SQLITE_DONE) { |
| 396 | return false; |
| 397 | } |
| 398 | g->n_ids = sc.max_id + 1; |
| 399 | if (!gm_grow_u32(&g->out_off, &sc.off_cap, (size_t)g->n_ids + 1)) { |
| 400 | return false; |
| 401 | } |
| 402 | while (sc.next_start <= g->n_ids) { |
| 403 | g->out_off[sc.next_start++] = g->n_edges; |
| 404 | } |
| 405 | /* max(edges.id) over-counts after deletions; give the slack back. */ |
| 406 | if (g->n_edges < sc.edge_cap) { |
| 407 | size_t keep = g->n_edges ? g->n_edges : 1; |
| 408 | uint32_t *nbr = cbm_realloc(CBM_MEM_CLASS_GRAPH_CACHE, g->out_nbr, keep * sizeof(uint32_t)); |
| 409 | uint8_t *types = nbr ? cbm_realloc(CBM_MEM_CLASS_GRAPH_CACHE, g->out_type, keep) : NULL; |
| 410 | if (nbr) { |
| 411 | g->out_nbr = nbr; |
| 412 | } |
| 413 | if (types) { |
| 414 | g->out_type = types; |
| 415 | } |
| 416 | } |
| 417 | return gm_build_inbound(g); |
| 418 | } |
| 419 | |
| 420 | static size_t gm_actual_bytes(const cbm_graph_mem_t *g) { |
| 421 | size_t offsets = ((size_t)g->n_ids + 1) * sizeof(uint32_t); |
no test coverage detected