// SPDX-FileCopyrightText: 2026 Stefan Majewsky // SPDX-License-Identifier: Apache-2.0 package oblast import ( "context" "database/sql" "errors" "fmt" "reflect" ) // Select executes the provided SQL query and fills an instance of the record type R for each row in the result set, // according to the column names reported by the database as part of the result set. // // An error is returned if any column name in the result set does not correspond to an addressable field in R. func (s Store[R]) Select(ctx context.Context, db Handle, query string, args ...any) ([]R, error) { // NOTE: This function body should be as short as possible to reduce the binary size after monomorphization. // Any expression that does not depend on type R should be factored out into a reusable function. rows, indexes, err := startSelectQuery(ctx, db, s.plan, query, args...) if err != nil { return nil, err } var result []R slots := make([]any, len(indexes)) for rows.Next() { var target R err = collectRow(rows, s.plan, reflect.ValueOf(&target).Elem(), slots, indexes) if err != nil { return nil, err } result = append(result, target) } return result, newIOError(err, "Rows.Err", rows.Err()) } // SelectWhere is like [Store.Select], but you only provide the part of the SELECT query that comes after the WHERE. // The initial part ("SELECT ... FROM ... WHERE") is autogenerated and prepended to partialQuery. // This has two benefits: // - It is more efficient because the strategy for loading result rows into the record type R has already been precomputed during [NewStore], // whereas a regular [Store.Select] must inspect the column names in the result set for each [Store.Select] call. // - For record types that contain only some of the columns of the corresponding database table, // the autogenerated SELECT query will only load exactly the necessary fields and nothing else. // // partialQuery is implied to start right after the WHERE keyword, which is added automatically. // To select all records unconditionally, provide a partialQuery of "TRUE", leading to a full query of "SELECT ... FROM ... WHERE TRUE". // Besides a condition for the WHERE clause, it may contain additional clauses, such as ORDER BY or LIMIT. // // Returns an error if [NewStore] was called without the [TableNameIs] option, which is required to generate a query for this method. func (s Store[R]) SelectWhere(ctx context.Context, db Handle, partialQuery string, args ...any) ([]R, error) { // NOTE: This function body should be as short as possible to reduce the binary size after monomorphization. // Any expression that does not depend on type R should be factored out into a reusable function. rows, indexes, err := startSelectWhereQuery(ctx, db, s.plan, partialQuery, args...) if err != nil { return nil, err } var result []R slots := make([]any, len(indexes)) for rows.Next() { var target R err = collectRow(rows, s.plan, reflect.ValueOf(&target).Elem(), slots, indexes) if err != nil { return nil, err } result = append(result, target) } return result, newIOError(err, "Rows.Err", rows.Err()) } func startSelectQuery(ctx context.Context, db Handle, plan plan, query string, args ...any) (*sql.Rows, [][]int, error) { rows, err := db.QueryContext(ctx, query, args...) if err != nil { return nil, nil, fmt.Errorf("during Query(): %w", err) } columnNames, err := rows.Columns() if err != nil { err = fmt.Errorf("during rows.Columns(): %w", err) return nil, nil, newIOError(err, "Rows.Close", rows.Close()) } indexes := make([][]int, len(columnNames)) for idx, columnName := range columnNames { var ok bool indexes[idx], ok = plan.IndexByColumnName[columnName] if !ok { err := fmt.Errorf( "result has column %q in position %d, but no field in type %s has `db:%[1]q`", columnName, idx, plan.TypeName, ) return nil, nil, newIOError(err, "Rows.Close", rows.Close()) } } return rows, indexes, nil } func startSelectWhereQuery(ctx context.Context, db Handle, plan plan, partialQuery string, args ...any) (rows *sql.Rows, indexes [][]int, err error) { if plan.Select.Query == "" { return nil, nil, errors.New("cannot execute SelectWhere() because query could not be autogenerated") } query := plan.Select.Query + partialQuery rows, err = db.QueryContext(ctx, query, args...) if err != nil { err = fmt.Errorf("during Query(): %w", err) } return rows, plan.Select.ScanIndexes, err } func collectRow(rows *sql.Rows, plan plan, v reflect.Value, slots []any, indexes [][]int) error { for _, index := range plan.IndexesOfTransparentPointerStructs { f := v.FieldByIndex(index) f.Set(reflect.New(f.Type().Elem())) } for idx, index := range indexes { slots[idx] = v.FieldByIndex(index).Addr().Interface() } err := rows.Scan(slots...) if err != nil { return newIOError(err, "Rows.Close", rows.Close()) } return nil } // SelectOne executes the provided SQL query and fills an instance of the record type R if there is exactly one row in the result set, // according to the column names reported by the database as part of the result set. // // If there are no rows in the result set, [sql.ErrNoRows] is returned. // // Warning: Because of limitations in the interface of database/sql, this function is built on [Store.Select] and cannot be any faster than it. // For maximum performance, use [Store.SelectOneWhere] which avoids the overhead of potentially having to read multiple rows. func (s Store[R]) SelectOne(ctx context.Context, db Handle, query string, args ...any) (result R, err error) { // NOTE: This function body should be as short as possible to reduce the binary size after monomorphization. // Any expression that does not depend on type R should be factored out into a reusable function. var results []R results, err = s.Select(ctx, db, query, args...) if err == nil { if len(results) == 0 { err = sql.ErrNoRows } else { result = results[0] } } return } // SelectOneWhere is like [Store.SelectOne], but you only provide the part of the SELECT query that comes after the WHERE. // See [Store.SelectWhere] for an explanation of how the full query is constructed from this partial query. // // This method is more efficient than [Store.SelectOne] on CPU runtime, but has a slight memory allocation overhead per call from query preparation. // This can be avoided by using [Store.PrepareSelectQueryWhere] instead. func (s Store[R]) SelectOneWhere(ctx context.Context, db Handle, partialQuery string, args ...any) (result R, err error) { // NOTE: This function body should be as short as possible to reduce the binary size after monomorphization. // Any expression that does not depend on type R should be factored out into a reusable function. err = selectOneWhere(ctx, db, s.plan, reflect.ValueOf(&result).Elem(), partialQuery, args) return } func selectOneWhere(ctx context.Context, db Handle, plan plan, v reflect.Value, partialQuery string, args []any) error { if plan.Select.Query == "" { return errors.New("cannot execute SelectOneWhere() because query could not be autogenerated") } query := plan.Select.Query + partialQuery return selectOne(ctx, db, plan, v, query, args) } func selectOne(ctx context.Context, db Handle, plan plan, v reflect.Value, query string, args []any) error { for _, index := range plan.IndexesOfTransparentPointerStructs { f := v.FieldByIndex(index) f.Set(reflect.New(f.Type().Elem())) } slots := make([]any, len(plan.Select.ScanIndexes)) for idx, index := range plan.Select.ScanIndexes { slots[idx] = v.FieldByIndex(index).Addr().Interface() } return db.QueryRowContext(ctx, query, args...).Scan(slots...) } // PrepareSelectQueryWhere performs the same query string preparation as [Store.SelectWhere] or [Store.SelectOneWhere]. // The resulting query can then be executed multiple times without incurring repeated memory allocation overhead from this preparation step. func (s Store[R]) PrepareSelectQueryWhere(partialQuery string) (PreparedSelectQuery[R], error) { // NOTE: This function body should be as short as possible to reduce the binary size after monomorphization. // Any expression that does not depend on type R should be factored out into a reusable function. query, err := prepareSelectQueryWhere(s.plan, partialQuery) return PreparedSelectQuery[R]{s, query}, err } // MustPrepareSelectQueryWhere is like [Store.PrepareSelectQueryWhere], but panics on error. func (s Store[R]) MustPrepareSelectQueryWhere(partialQuery string) PreparedSelectQuery[R] { q, err := s.PrepareSelectQueryWhere(partialQuery) if err != nil { panic(err.Error()) } return q } func prepareSelectQueryWhere(plan plan, partialQuery string) (string, error) { if plan.Select.Query == "" { return "", errors.New("cannot execute PrepareSelectQueryWhere() because query could not be autogenerated") } return plan.Select.Query + partialQuery, nil } // PreparedSelectQuery holds a pre-computed SELECT query that was customized by the user. // This type is an optimization to avoid performing the same query string manipulations over and over again in hot paths. // // It is returned by [Store.PrepareSelectQueryWhere]. type PreparedSelectQuery[R any] struct { store Store[R] query string } // Select behaves the same as [Store.SelectWhere], but uses the query that was precomputed when q was constructed. func (q PreparedSelectQuery[R]) Select(ctx context.Context, db Handle, args ...any) ([]R, error) { // NOTE: This function body should be as short as possible to reduce the binary size after monomorphization. // Any expression that does not depend on type R should be factored out into a reusable function. rows, indexes, err := startSelectQuery(ctx, db, q.store.plan, q.query, args...) if err != nil { return nil, err } var result []R slots := make([]any, len(indexes)) for rows.Next() { var target R err = collectRow(rows, q.store.plan, reflect.ValueOf(&target).Elem(), slots, indexes) if err != nil { return nil, err } result = append(result, target) } return result, newIOError(err, "Rows.Err", rows.Err()) } // SelectOne behaves the same as [Store.SelectOneWhere], but uses the query that was precomputed when q was constructed. func (q PreparedSelectQuery[R]) SelectOne(ctx context.Context, db Handle, args ...any) (result R, err error) { // NOTE: This function body should be as short as possible to reduce the binary size after monomorphization. // Any expression that does not depend on type R should be factored out into a reusable function. err = selectOne(ctx, db, q.store.plan, reflect.ValueOf(&result).Elem(), q.query, args) return }