|
| 1 | +/* |
| 2 | +Copyright 2025 eatmoreapple |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package juice |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "database/sql" |
| 22 | +) |
| 23 | + |
| 24 | +// This file provides context-based database helper shortcuts. |
| 25 | + |
| 26 | +// QueryContext executes a query with the provided context and scans a single result into T. |
| 27 | +// (ctx must contain a Manager via ManagerFromContext) |
| 28 | +func QueryContext[T any](ctx context.Context, statement, param any) (result T, err error) { |
| 29 | + manager := ManagerFromContext(ctx) |
| 30 | + executor := NewGenericManager[T](manager).Object(statement) |
| 31 | + return executor.QueryContext(ctx, param) |
| 32 | +} |
| 33 | + |
| 34 | +// ExecContext executes a statement that does not return rows and returns a sql.Result. |
| 35 | +// (ctx must contain a Manager via ManagerFromContext) |
| 36 | +func ExecContext(ctx context.Context, statement, param any) (result sql.Result, err error) { |
| 37 | + manager := ManagerFromContext(ctx) |
| 38 | + executor := NewGenericManager[any](manager).Object(statement) |
| 39 | + return executor.ExecContext(ctx, param) |
| 40 | +} |
| 41 | + |
| 42 | +// QueryListContext executes a query and returns a slice of T. Rows are closed after reading. |
| 43 | +// (ctx must contain a Manager via ManagerFromContext) |
| 44 | +func QueryListContext[T any](ctx context.Context, statement, param any) (result []T, err error) { |
| 45 | + manager := ManagerFromContext(ctx) |
| 46 | + rows, err := manager.Object(statement).QueryContext(ctx, param) |
| 47 | + if err != nil { |
| 48 | + return nil, err |
| 49 | + } |
| 50 | + defer func() { _ = rows.Close() }() |
| 51 | + return List[T](rows) |
| 52 | +} |
| 53 | + |
| 54 | +// QueryList2Context executes a query and returns a slice of pointers to T. Rows are closed after reading. |
| 55 | +// (ctx must contain a Manager via ManagerFromContext) |
| 56 | +func QueryList2Context[T any](ctx context.Context, statement, param any) (result []*T, err error) { |
| 57 | + manager := ManagerFromContext(ctx) |
| 58 | + rows, err := manager.Object(statement).QueryContext(ctx, param) |
| 59 | + if err != nil { |
| 60 | + return nil, err |
| 61 | + } |
| 62 | + defer func() { _ = rows.Close() }() |
| 63 | + return List2[T](rows) |
| 64 | +} |
0 commit comments