MCPcopy Create free account
hub / github.com/rilldata/rill / newSQL

Function newSQL

runtime/resolvers/sql.go:50–140  ·  view source on GitHub ↗

newSQL creates a resolver that executes a SQL query. It supports the use of templating in the SQL string to inject user attributes and args into the SQL query.

(ctx context.Context, opts *runtime.ResolverOptions)

Source from the content-addressed store, hash-verified

48// newSQL creates a resolver that executes a SQL query.
49// It supports the use of templating in the SQL string to inject user attributes and args into the SQL query.
50func newSQL(ctx context.Context, opts *runtime.ResolverOptions) (runtime.Resolver, error) {
51 props := &sqlProps{}
52 if err := mapstructureutil.WeakDecode(opts.Properties, props); err != nil {
53 return nil, err
54 }
55
56 span := trace.SpanFromContext(ctx)
57 if span.SpanContext().IsValid() {
58 span.SetAttributes(attribute.String("sql", props.SQL))
59 }
60
61 // trim semicolon
62 props.SQL = strings.TrimSuffix(strings.TrimSpace(props.SQL), ";")
63
64 args := &sqlArgs{}
65 if err := mapstructureutil.WeakDecode(opts.Args, args); err != nil {
66 return nil, err
67 }
68
69 inst, err := opts.Runtime.Instance(ctx, opts.InstanceID)
70 if err != nil {
71 return nil, err
72 }
73
74 olap, release, err := opts.Runtime.OLAP(ctx, opts.InstanceID, props.Connector)
75 if err != nil {
76 return nil, err
77 }
78
79 // Resolve the SQL template
80 sql, refs, err := resolveTemplate(props.SQL, opts.Args, inst, opts.Claims.UserAttributes, opts.ForExport)
81 if err != nil {
82 return nil, err
83 }
84
85 // For DuckDB, we can do ref inference using the SQL AST (similar to the parser).
86 if olap.Dialect().String() == drivers.DialectNameDuckDB {
87 ast, err := duckdbsql.Parse(sql)
88 if err != nil {
89 return nil, err
90 }
91 for _, t := range ast.GetTableRefs() {
92 if !t.LocalAlias && t.Name != "" && t.Function == "" && len(t.Paths) == 0 {
93 // We don't know if it's a model, but add it anyway. Refs are just approximate.
94 refs = append(refs, &runtimev1.ResourceName{Kind: runtime.ResourceKindModel, Name: t.Name})
95 }
96 }
97 }
98
99 // Normalize the refs
100 refs = normalizeRefs(refs)
101
102 // Compute row cap (limit after which we return an error in interactive queries).
103 var rowCap int64
104 if !opts.ForExport {
105 cfg, err := inst.Config()
106 if err != nil {
107 return nil, err

Callers 1

newBuiltinSQLFunction · 0.85

Calls 11

WeakDecodeFunction · 0.92
ParseFunction · 0.92
resolveTemplateFunction · 0.85
normalizeRefsFunction · 0.85
InstanceMethod · 0.80
OLAPMethod · 0.80
GetTableRefsMethod · 0.80
StringMethod · 0.65
DialectMethod · 0.65
ConfigMethod · 0.65
ErrorfMethod · 0.65

Tested by

no test coverage detected