-
Notifications
You must be signed in to change notification settings - Fork 111
/
table_cardinality.go
92 lines (76 loc) · 1.96 KB
/
table_cardinality.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
package queries
import (
"context"
"fmt"
"io"
"reflect"
runtimev1 "github.com/rilldata/rill/proto/gen/rill/runtime/v1"
"github.com/rilldata/rill/runtime"
"github.com/rilldata/rill/runtime/drivers"
)
type TableCardinality struct {
TableName string
Result int64
}
var _ runtime.Query = &TableCardinality{}
func (q *TableCardinality) Key() string {
return fmt.Sprintf("TableCardinality:%s", q.TableName)
}
func (q *TableCardinality) Deps() []*runtimev1.ResourceName {
return []*runtimev1.ResourceName{
{Kind: runtime.ResourceKindSource, Name: q.TableName},
{Kind: runtime.ResourceKindModel, Name: q.TableName},
}
}
func (q *TableCardinality) MarshalResult() *runtime.QueryResult {
return &runtime.QueryResult{
Value: q.Result,
Bytes: int64(reflect.TypeOf(q.Result).Size()),
}
}
func (q *TableCardinality) UnmarshalResult(v any) error {
res, ok := v.(int64)
if !ok {
return fmt.Errorf("TableCardinality: mismatched unmarshal input")
}
q.Result = res
return nil
}
func (q *TableCardinality) Resolve(ctx context.Context, rt *runtime.Runtime, instanceID string, priority int) error {
countSQL := fmt.Sprintf("SELECT count(*) AS count FROM %s",
safeName(q.TableName),
)
olap, release, err := rt.OLAP(ctx, instanceID)
if err != nil {
return err
}
defer release()
if olap.Dialect() != drivers.DialectDuckDB {
return fmt.Errorf("not available for dialect '%s'", olap.Dialect())
}
rows, err := olap.Execute(ctx, &drivers.Statement{
Query: countSQL,
Priority: priority,
ExecutionTimeout: defaultExecutionTimeout,
})
if err != nil {
return err
}
defer rows.Close()
var count int64
for rows.Next() {
err = rows.Scan(&count)
if err != nil {
return err
}
}
err = rows.Err()
if err != nil {
return err
}
q.Result = count
return nil
}
func (q *TableCardinality) Export(ctx context.Context, rt *runtime.Runtime, instanceID string, w io.Writer, opts *runtime.ExportOptions) error {
return ErrExportNotSupported
}