Skip to content

Commit 949d90b

Browse files
committed
Use a transaction when reading graph.
1 parent 59b84a2 commit 949d90b

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

internal/database/mariadb.go

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -434,9 +434,14 @@ func (m *MariaDB) ReadGraph(sourceName string, graph *knowledge.Graph) error {
434434

435435
now := time.Now()
436436

437+
tx, err := m.db.Begin()
438+
if err != nil {
439+
return fmt.Errorf("Unable to create transaction: %v", err)
440+
}
441+
437442
{
438443
// Select all relations produced by this source
439-
rows, err := m.db.QueryContext(context.Background(), `
444+
rows, err := tx.QueryContext(context.Background(), `
440445
SELECT a.type, a.value, b.type, b.value, r.type FROM relations_by_source rbs
441446
INNER JOIN relations r ON rbs.relation_id = r.id
442447
INNER JOIN assets a ON a.id=r.from_id
@@ -445,6 +450,7 @@ WHERE rbs.source_id = ?
445450
`, sourceID)
446451

447452
if err != nil {
453+
tx.Rollback()
448454
return fmt.Errorf("Unable to retrieve relations: %v", err)
449455
}
450456

@@ -472,13 +478,15 @@ WHERE rbs.source_id = ?
472478

473479
{
474480
// Select all assets produced by this source. This is useful in case there are some standalone nodes in the graph of the source.
475-
rows, err := m.db.QueryContext(context.Background(), `
481+
// TODO(c.michaud): optimization could be done by only selecting assets without any relation since the others have already have been retrieved in the previous query.
482+
rows, err := tx.QueryContext(context.Background(), `
476483
SELECT a.type, a.value FROM assets_by_source abs
477484
INNER JOIN assets a ON a.id=abs.asset_id
478485
WHERE abs.source_id = ?
479486
`, sourceID)
480487

481488
if err != nil {
489+
tx.Rollback()
482490
return fmt.Errorf("Unable to retrieve assets: %v", err)
483491
}
484492

@@ -487,12 +495,17 @@ WHERE abs.source_id = ?
487495
for rows.Next() {
488496
var Key, Type string
489497
if err := rows.Scan(&Type, &Key); err != nil {
490-
return err
498+
tx.Rollback()
499+
return fmt.Errorf("Unable to read standalone asset: %v", err)
491500
}
492501
graph.AddAsset(schema.AssetType(Type), Key)
493502
}
494503
}
495504

505+
if err = tx.Commit(); err != nil {
506+
return fmt.Errorf("Unable to commit transaction: %v", err)
507+
}
508+
496509
elapsed := time.Since(now)
497510
fmt.Printf("Read graph of data source with name %s in %fs\n", sourceName, elapsed.Seconds())
498511
return nil

0 commit comments

Comments
 (0)