QueryConn queries a SQL statement in a given connection.
(ctx context.Context, conn *sql.Conn, statement string, queryContext db.QueryContext)
| 328 | |
| 329 | // QueryConn queries a SQL statement in a given connection. |
| 330 | func (*Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string, queryContext db.QueryContext) ([]*v1pb.QueryResult, error) { |
| 331 | singleSQLs, err := base.SplitMultiSQL(storepb.Engine_SNOWFLAKE, statement) |
| 332 | if err != nil { |
| 333 | return nil, err |
| 334 | } |
| 335 | |
| 336 | var results []*v1pb.QueryResult |
| 337 | for _, singleSQL := range singleSQLs { |
| 338 | statement := singleSQL.Text |
| 339 | if queryContext.Explain { |
| 340 | statement = fmt.Sprintf("EXPLAIN %s", statement) |
| 341 | } else if queryContext.Limit > 0 { |
| 342 | statement = getStatementWithResultLimit(statement, queryContext.Limit) |
| 343 | } |
| 344 | |
| 345 | _, allQuery, err := base.ValidateSQLForEditor(storepb.Engine_SNOWFLAKE, statement) |
| 346 | if err != nil { |
| 347 | slog.Error("failed to validate sql", slog.String("statement", statement), log.BBError(err)) |
| 348 | allQuery = true |
| 349 | } |
| 350 | |
| 351 | // Sanitize the schema name by escaping any quotes. |
| 352 | safeSchemeName := strings.ReplaceAll(queryContext.Schema, "\"", "\"\"") |
| 353 | |
| 354 | // If the queryContext.Schema is not empty, set the current schema to the given schema. |
| 355 | // Reference: https://docs.snowflake.com/en/sql-reference/sql/use-schema |
| 356 | if queryContext.Schema != "" { |
| 357 | if _, err := conn.ExecContext(ctx, fmt.Sprintf(`USE SCHEMA "%s";`, safeSchemeName)); err != nil { // NOSONAR(go:S2077) safeSchemeName is sanitized by escaping double quotes above |
| 358 | return nil, err |
| 359 | } |
| 360 | } else { |
| 361 | // If the queryContext.Schema is empty, we try to set the current schema to "PUBLIC" and ignore the error because |
| 362 | // the schema may not exist. |
| 363 | if _, err := conn.ExecContext(ctx, "USE SCHEMA PUBLIC;"); err != nil { |
| 364 | slog.Debug("failed to set schema to PUBLIC", log.BBError(err)) |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | startTime := time.Now() |
| 369 | queryResult, err := func() (*v1pb.QueryResult, error) { |
| 370 | if allQuery { |
| 371 | rows, err := conn.QueryContext(ctx, statement) |
| 372 | if err != nil { |
| 373 | return nil, err |
| 374 | } |
| 375 | defer rows.Close() |
| 376 | r, err := util.RowsToQueryResult(rows, util.MakeCommonValueByTypeName, util.ConvertCommonValue, queryContext.MaximumSQLResultSize) |
| 377 | if err != nil { |
| 378 | return nil, err |
| 379 | } |
| 380 | if err := rows.Err(); err != nil { |
| 381 | return nil, err |
| 382 | } |
| 383 | return r, nil |
| 384 | } |
| 385 | |
| 386 | sqlResult, err := conn.ExecContext(ctx, statement) |
| 387 | if err != nil { |
nothing calls this directly
no test coverage detected