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)
| 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. |
| 50 | func 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 |
no test coverage detected