-
Notifications
You must be signed in to change notification settings - Fork 245
/
stats.go
94 lines (78 loc) · 2.54 KB
/
stats.go
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
package mysql
import (
"context"
"fmt"
"github.com/Masterminds/squirrel"
"github.com/authzed/spicedb/internal/datastore/common"
"github.com/authzed/spicedb/pkg/datastore"
)
const (
informationSchemaTableRowsColumn = "table_rows"
informationSchemaTablesTable = "INFORMATION_SCHEMA.TABLES"
informationSchemaTableNameColumn = "table_name"
metadataIDColumn = "id"
metadataUniqueIDColumn = "unique_id"
)
func (mds *Datastore) Statistics(ctx context.Context) (datastore.Stats, error) {
if mds.analyzeBeforeStats {
_, err := mds.db.ExecContext(ctx, "ANALYZE TABLE "+mds.driver.RelationTuple())
if err != nil {
return datastore.Stats{}, fmt.Errorf("unable to run ANALYZE TABLE: %w", err)
}
}
uniqueID, err := mds.getUniqueID(ctx)
if err != nil {
return datastore.Stats{}, err
}
query, args, err := sb.
Select(informationSchemaTableRowsColumn).
From(informationSchemaTablesTable).
Where(squirrel.Eq{informationSchemaTableNameColumn: mds.driver.RelationTuple()}).
ToSql()
if err != nil {
return datastore.Stats{}, err
}
var count uint64
err = mds.db.QueryRowContext(ctx, query, args...).Scan(&count)
if err != nil {
return datastore.Stats{}, err
}
if count == 0 {
// If we get a count of zero, its possible the information schema table has not yet
// been updated, so we use a slower count(*) call.
query, args, err := mds.QueryBuilder.CountTupleQuery.ToSql()
if err != nil {
return datastore.Stats{}, err
}
err = mds.db.QueryRowContext(ctx, query, args...).Scan(&count)
if err != nil {
return datastore.Stats{}, err
}
}
nsQuery := mds.ReadNamespaceQuery.Where(squirrel.Eq{colDeletedTxn: liveDeletedTxnID})
tx, err := mds.db.BeginTx(ctx, nil)
if err != nil {
return datastore.Stats{}, err
}
defer common.LogOnError(ctx, tx.Rollback)
nsDefs, err := loadAllNamespaces(ctx, tx, nsQuery)
if err != nil {
return datastore.Stats{}, fmt.Errorf("unable to load namespaces: %w", err)
}
return datastore.Stats{
UniqueID: uniqueID,
ObjectTypeStatistics: datastore.ComputeObjectTypeStats(nsDefs),
EstimatedRelationshipCount: count,
}, nil
}
func (mds *Datastore) getUniqueID(ctx context.Context) (string, error) {
sql, args, err := sb.Select(metadataUniqueIDColumn).From(mds.driver.Metadata()).ToSql()
if err != nil {
return "", fmt.Errorf("unable to generate query sql: %w", err)
}
var uniqueID string
if err := mds.db.QueryRowContext(ctx, sql, args...).Scan(&uniqueID); err != nil {
return "", fmt.Errorf("unable to query unique ID: %w", err)
}
return uniqueID, nil
}