Skip to content

Commit

Permalink
Make bob.Cache() require an Executor to run any query hooks.
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenafamo committed Nov 9, 2024
1 parent 1d6c532 commit f546682
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
The same functionality can be achieved by using `modelSlice.Delete()` or creating an `Delete` query using `table.Delete()`.
- `BeforeInsertHooks` now only takes a single `ModelSetter` at a time.
This is because it is not possible to know before executing the queries exactly how many setters are being used since additional rows can be inserted by applying another setter as a mod.
- `bob.Cache()` now requires an `Executor`. This is used to run any query hooks.

### Removed

Expand Down
31 changes: 26 additions & 5 deletions cached.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,43 @@ import (
"io"
)

func Cache(ctx context.Context, q Query) (BaseQuery[*cached], error) {
return CacheN(ctx, q, 1)
func Cache(ctx context.Context, exec Executor, q Query) (BaseQuery[*cached], error) {
return CacheN(ctx, exec, q, 1)
}

func CacheN(ctx context.Context, q Query, start int) (BaseQuery[*cached], error) {
func CacheN(ctx context.Context, exec Executor, q Query, start int) (BaseQuery[*cached], error) {
var err error

if h, ok := q.(HookableQuery); ok {
ctx, err = h.RunHooks(ctx, exec)
if err != nil {
return BaseQuery[*cached]{}, err
}
}

query, args, err := BuildN(ctx, q, start)
if err != nil {
return BaseQuery[*cached]{}, err
}

return BaseQuery[*cached]{
cached := BaseQuery[*cached]{
QueryType: q.Type(),
Expression: &cached{
query: []byte(query),
args: args,
start: start,
},
}, nil
}

if l, ok := q.(Loadable); ok {
cached.Expression.SetLoaders(l.GetLoaders()...)
}

if m, ok := q.(MapperModder); ok {
cached.Expression.SetMapperMods(m.GetMapperMods()...)
}

return cached, nil
}

type WrongStartError struct {
Expand All @@ -38,6 +58,7 @@ type cached struct {
query []byte
args []any
start int
Load
}

// WriteSQL implements Expression.
Expand Down
4 changes: 4 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,8 @@ var (
_ Loadable = BaseQuery[Expression]{}
_ MapperModder = BaseQuery[Expression]{}
_ HookableQuery = BaseQuery[Expression]{}

_ Expression = &cached{}
_ Loadable = &cached{}
_ MapperModder = &cached{}
)

0 comments on commit f546682

Please sign in to comment.