Add sqlboiler to benchmarks

add-transactionCtx-method
Vinícius Garcia 2022-07-26 23:20:23 -03:00
parent ed1e5ec27d
commit 3d34bae47e
17 changed files with 2823 additions and 21 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
.make.setup
**/*coverage.txt
go.work
go.work.sum

View File

@ -15,14 +15,14 @@ test: setup go-mod-tidy
@( cd adapters/ksqlite3 ; $(GOBIN)/richgo test $(path) $(args) )
bench: go-mod-tidy
cd benchmarks && make bench TIME=$(TIME)
@make --no-print-directory -C benchmarks TIME=$(TIME)
@echo "Benchmark executed at: $$(date --iso)"
@echo "Benchmark executed on commit: $$(git rev-parse HEAD)"
lint: setup go-mod-tidy
@$(GOBIN)/staticcheck $(path) $(args)
@go vet $(path) $(args)
@make --no-print-directory -C benchmarks
@make --no-print-directory -C benchmarks lint
@echo "StaticCheck & Go Vet found no problems on your code!"
# Run go mod tidy for all submodules:

View File

@ -14,6 +14,12 @@ gen: sqlcfiles
sqlcfiles: $(GOBIN)/sqlc sqlc.yaml schema.sql sqlcgen/queries.sql
sqlc generate
# This recipe requires the ksql database to be setup
# exactly as described in the `sqlboiler.toml` file, that's
# why it is not running automatically before each benchmark.
sqlboilerfiles: $(GOBIN)/sqlboiler
sqlboiler psql -c sqlboiler.toml --wipe --no-tests
$(GOBIN)/sqlc:
go install github.com/kyleconroy/sqlc/cmd/sqlc@latest

View File

@ -7,12 +7,17 @@ import (
"strconv"
"testing"
_ "embed"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/vingarcia/ksql"
"github.com/vingarcia/ksql/adapters/kpgx"
"github.com/vingarcia/ksql/benchmarks/sqlboilergen"
"github.com/vingarcia/ksql/benchmarks/sqlcgen"
"github.com/volatiletech/sqlboiler/v4/boil"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
@ -332,6 +337,32 @@ func BenchmarkInsert(b *testing.B) {
}
})
})
b.Run("sqlboiler", func(b *testing.B) {
sqlDB, err := sql.Open(driver, connStr)
if err != nil {
b.Fatalf("error creating sql client: %s", err)
}
sqlDB.SetMaxOpenConns(1)
err = recreateTable(connStr)
if err != nil {
b.Fatalf("error creating table: %s", err.Error())
}
b.Run("insert-one", func(b *testing.B) {
for i := 0; i < b.N; i++ {
user := sqlboilergen.User{
Name: strconv.Itoa(i),
Age: i,
}
err := user.Insert(ctx, sqlDB, boil.Infer())
if err != nil {
b.Fatalf("insert error: %s", err.Error())
}
}
})
})
}
func BenchmarkQuery(b *testing.B) {
@ -832,8 +863,47 @@ func BenchmarkQuery(b *testing.B) {
}
})
})
b.Run("sqlboiler", func(b *testing.B) {
sqlDB, err := sql.Open(driver, connStr)
if err != nil {
b.Fatalf("error creating sql client: %s", err)
}
sqlDB.SetMaxOpenConns(1)
err = recreateTable(connStr)
if err != nil {
b.Fatalf("error creating table: %s", err.Error())
}
err = insertUsers(connStr, 100)
if err != nil {
b.Fatalf("error inserting users: %s", err.Error())
}
b.Run("single-row", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_, err := sqlboilergen.Users(qm.Select("id", "name", "age"), qm.Offset(i%100), qm.Limit(1)).One(ctx, sqlDB)
if err != nil {
b.Fatalf("query error: %s", err.Error())
}
}
})
b.Run("multiple-rows", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_, err := sqlboilergen.Users(qm.Select("id", "name", "age"), qm.Offset(i%90), qm.Limit(10)).One(ctx, sqlDB)
if err != nil {
b.Fatalf("query error: %s", err.Error())
}
}
})
})
}
//go:embed schema.sql
var createTablesSQL string
func recreateTable(connStr string) error {
db, err := sql.Open("postgres", connStr)
if err != nil {
@ -843,11 +913,7 @@ func recreateTable(connStr string) error {
db.Exec(`DROP TABLE users`)
_, err = db.Exec(`CREATE TABLE users (
id serial PRIMARY KEY,
age INT,
name VARCHAR(50)
)`)
_, err = db.Exec(createTablesSQL)
if err != nil {
return fmt.Errorf("failed to create new users table: %s", err.Error())
}

View File

@ -1,13 +1,16 @@
module github.com/vingarcia/ksql/benchmarks
go 1.14
go 1.16
require (
github.com/friendsofgo/errors v0.9.2
github.com/jackc/pgx/v4 v4.13.0
github.com/jmoiron/sqlx v1.3.4
github.com/lib/pq v1.10.4
github.com/vingarcia/ksql v1.4.7
github.com/vingarcia/ksql/adapters/kpgx v0.0.0-00010101000000-000000000000
github.com/volatiletech/sqlboiler/v4 v4.12.0
github.com/volatiletech/strmangle v0.0.4
gorm.io/driver/postgres v1.2.2
gorm.io/gorm v1.22.3
)

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
name text NOT NULL,
age integer NOT NULL
id serial PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT NOT NULL
);

14
benchmarks/sqlboiler.toml Normal file
View File

@ -0,0 +1,14 @@
output = "sqlboilergen"
pkgname = "sqlboilergen"
wipe = true
no-tests = true
add-enum-types = true
[psql]
dbname = "ksql"
host = "localhost"
port = 5432
user = "postgres"
pass = "postgres"
blacklist = ["migrations", "other"]
sslmode = "disable"

View File

@ -0,0 +1,33 @@
// Code generated by SQLBoiler 4.12.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package sqlboilergen
import (
"github.com/volatiletech/sqlboiler/v4/drivers"
"github.com/volatiletech/sqlboiler/v4/queries"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
)
var dialect = drivers.Dialect{
LQ: 0x22,
RQ: 0x22,
UseIndexPlaceholders: true,
UseLastInsertID: false,
UseSchema: false,
UseDefaultKeyword: true,
UseAutoColumns: false,
UseTopClause: false,
UseOutputClause: false,
UseCaseWhenExistsClause: false,
}
// NewQuery initializes a new Query using the passed in QueryMods
func NewQuery(mods ...qm.QueryMod) *queries.Query {
q := &queries.Query{}
queries.SetDialect(q, &dialect)
qm.Apply(q, mods...)
return q
}

View File

@ -0,0 +1,12 @@
// Code generated by SQLBoiler 4.12.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package sqlboilergen
var TableNames = struct {
Users string
UsersPermissions string
}{
Users: "users",
UsersPermissions: "users_permissions",
}

View File

@ -0,0 +1,52 @@
// Code generated by SQLBoiler 4.12.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package sqlboilergen
import (
"strconv"
"github.com/friendsofgo/errors"
"github.com/volatiletech/sqlboiler/v4/boil"
"github.com/volatiletech/strmangle"
)
// M type is for providing columns and column values to UpdateAll.
type M map[string]interface{}
// ErrSyncFail occurs during insert when the record could not be retrieved in
// order to populate default value information. This usually happens when LastInsertId
// fails or there was a primary key configuration that was not resolvable.
var ErrSyncFail = errors.New("sqlboilergen: failed to synchronize data after insert")
type insertCache struct {
query string
retQuery string
valueMapping []uint64
retMapping []uint64
}
type updateCache struct {
query string
valueMapping []uint64
}
func makeCacheKey(cols boil.Columns, nzDefaults []string) string {
buf := strmangle.GetBuffer()
buf.WriteString(strconv.Itoa(cols.Kind))
for _, w := range cols.Cols {
buf.WriteString(w)
}
if len(nzDefaults) != 0 {
buf.WriteByte('.')
}
for _, nz := range nzDefaults {
buf.WriteString(nz)
}
str := buf.String()
strmangle.PutBuffer(buf)
return str
}

View File

@ -0,0 +1,7 @@
// Code generated by SQLBoiler 4.12.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package sqlboilergen
var ViewNames = struct {
}{}

View File

@ -0,0 +1,61 @@
// Code generated by SQLBoiler 4.12.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package sqlboilergen
import (
"fmt"
"strings"
"github.com/volatiletech/sqlboiler/v4/drivers"
"github.com/volatiletech/strmangle"
)
// buildUpsertQueryPostgres builds a SQL statement string using the upsertData provided.
func buildUpsertQueryPostgres(dia drivers.Dialect, tableName string, updateOnConflict bool, ret, update, conflict, whitelist []string) string {
conflict = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, conflict)
whitelist = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, whitelist)
ret = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, ret)
buf := strmangle.GetBuffer()
defer strmangle.PutBuffer(buf)
columns := "DEFAULT VALUES"
if len(whitelist) != 0 {
columns = fmt.Sprintf("(%s) VALUES (%s)",
strings.Join(whitelist, ", "),
strmangle.Placeholders(dia.UseIndexPlaceholders, len(whitelist), 1, 1))
}
fmt.Fprintf(
buf,
"INSERT INTO %s %s ON CONFLICT ",
tableName,
columns,
)
if !updateOnConflict || len(update) == 0 {
buf.WriteString("DO NOTHING")
} else {
buf.WriteByte('(')
buf.WriteString(strings.Join(conflict, ", "))
buf.WriteString(") DO UPDATE SET ")
for i, v := range update {
if i != 0 {
buf.WriteByte(',')
}
quoted := strmangle.IdentQuote(dia.LQ, dia.RQ, v)
buf.WriteString(quoted)
buf.WriteString(" = EXCLUDED.")
buf.WriteString(quoted)
}
}
if len(ret) != 0 {
buf.WriteString(" RETURNING ")
buf.WriteString(strings.Join(ret, ", "))
}
return buf.String()
}

View File

@ -0,0 +1,943 @@
// Code generated by SQLBoiler 4.12.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package sqlboilergen
import (
"context"
"database/sql"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/friendsofgo/errors"
"github.com/volatiletech/sqlboiler/v4/boil"
"github.com/volatiletech/sqlboiler/v4/queries"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
"github.com/volatiletech/sqlboiler/v4/queries/qmhelper"
"github.com/volatiletech/strmangle"
)
// User is an object representing the database table.
type User struct {
ID int `boil:"id" json:"id" toml:"id" yaml:"id"`
Age int `boil:"age" json:"age" toml:"age" yaml:"age"`
Name string `boil:"name" json:"name" toml:"name" yaml:"name"`
R *userR `boil:"-" json:"-" toml:"-" yaml:"-"`
L userL `boil:"-" json:"-" toml:"-" yaml:"-"`
}
var UserColumns = struct {
ID string
Age string
Name string
}{
ID: "id",
Age: "age",
Name: "name",
}
var UserTableColumns = struct {
ID string
Age string
Name string
}{
ID: "users.id",
Age: "users.age",
Name: "users.name",
}
// Generated where
type whereHelperint struct{ field string }
func (w whereHelperint) EQ(x int) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) }
func (w whereHelperint) NEQ(x int) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) }
func (w whereHelperint) LT(x int) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) }
func (w whereHelperint) LTE(x int) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) }
func (w whereHelperint) GT(x int) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) }
func (w whereHelperint) GTE(x int) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) }
func (w whereHelperint) IN(slice []int) qm.QueryMod {
values := make([]interface{}, 0, len(slice))
for _, value := range slice {
values = append(values, value)
}
return qm.WhereIn(fmt.Sprintf("%s IN ?", w.field), values...)
}
func (w whereHelperint) NIN(slice []int) qm.QueryMod {
values := make([]interface{}, 0, len(slice))
for _, value := range slice {
values = append(values, value)
}
return qm.WhereNotIn(fmt.Sprintf("%s NOT IN ?", w.field), values...)
}
type whereHelperstring struct{ field string }
func (w whereHelperstring) EQ(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) }
func (w whereHelperstring) NEQ(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) }
func (w whereHelperstring) LT(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) }
func (w whereHelperstring) LTE(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) }
func (w whereHelperstring) GT(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) }
func (w whereHelperstring) GTE(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) }
func (w whereHelperstring) IN(slice []string) qm.QueryMod {
values := make([]interface{}, 0, len(slice))
for _, value := range slice {
values = append(values, value)
}
return qm.WhereIn(fmt.Sprintf("%s IN ?", w.field), values...)
}
func (w whereHelperstring) NIN(slice []string) qm.QueryMod {
values := make([]interface{}, 0, len(slice))
for _, value := range slice {
values = append(values, value)
}
return qm.WhereNotIn(fmt.Sprintf("%s NOT IN ?", w.field), values...)
}
var UserWhere = struct {
ID whereHelperint
Age whereHelperint
Name whereHelperstring
}{
ID: whereHelperint{field: "\"users\".\"id\""},
Age: whereHelperint{field: "\"users\".\"age\""},
Name: whereHelperstring{field: "\"users\".\"name\""},
}
// UserRels is where relationship names are stored.
var UserRels = struct {
}{}
// userR is where relationships are stored.
type userR struct {
}
// NewStruct creates a new relationship struct
func (*userR) NewStruct() *userR {
return &userR{}
}
// userL is where Load methods for each relationship are stored.
type userL struct{}
var (
userAllColumns = []string{"id", "age", "name"}
userColumnsWithoutDefault = []string{"age", "name"}
userColumnsWithDefault = []string{"id"}
userPrimaryKeyColumns = []string{"id"}
userGeneratedColumns = []string{}
)
type (
// UserSlice is an alias for a slice of pointers to User.
// This should almost always be used instead of []User.
UserSlice []*User
// UserHook is the signature for custom User hook methods
UserHook func(context.Context, boil.ContextExecutor, *User) error
userQuery struct {
*queries.Query
}
)
// Cache for insert, update and upsert
var (
userType = reflect.TypeOf(&User{})
userMapping = queries.MakeStructMapping(userType)
userPrimaryKeyMapping, _ = queries.BindMapping(userType, userMapping, userPrimaryKeyColumns)
userInsertCacheMut sync.RWMutex
userInsertCache = make(map[string]insertCache)
userUpdateCacheMut sync.RWMutex
userUpdateCache = make(map[string]updateCache)
userUpsertCacheMut sync.RWMutex
userUpsertCache = make(map[string]insertCache)
)
var (
// Force time package dependency for automated UpdatedAt/CreatedAt.
_ = time.Second
// Force qmhelper dependency for where clause generation (which doesn't
// always happen)
_ = qmhelper.Where
)
var userAfterSelectHooks []UserHook
var userBeforeInsertHooks []UserHook
var userAfterInsertHooks []UserHook
var userBeforeUpdateHooks []UserHook
var userAfterUpdateHooks []UserHook
var userBeforeDeleteHooks []UserHook
var userAfterDeleteHooks []UserHook
var userBeforeUpsertHooks []UserHook
var userAfterUpsertHooks []UserHook
// doAfterSelectHooks executes all "after Select" hooks.
func (o *User) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range userAfterSelectHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeInsertHooks executes all "before insert" hooks.
func (o *User) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range userBeforeInsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterInsertHooks executes all "after Insert" hooks.
func (o *User) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range userAfterInsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeUpdateHooks executes all "before Update" hooks.
func (o *User) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range userBeforeUpdateHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterUpdateHooks executes all "after Update" hooks.
func (o *User) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range userAfterUpdateHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeDeleteHooks executes all "before Delete" hooks.
func (o *User) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range userBeforeDeleteHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterDeleteHooks executes all "after Delete" hooks.
func (o *User) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range userAfterDeleteHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeUpsertHooks executes all "before Upsert" hooks.
func (o *User) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range userBeforeUpsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterUpsertHooks executes all "after Upsert" hooks.
func (o *User) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range userAfterUpsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// AddUserHook registers your hook function for all future operations.
func AddUserHook(hookPoint boil.HookPoint, userHook UserHook) {
switch hookPoint {
case boil.AfterSelectHook:
userAfterSelectHooks = append(userAfterSelectHooks, userHook)
case boil.BeforeInsertHook:
userBeforeInsertHooks = append(userBeforeInsertHooks, userHook)
case boil.AfterInsertHook:
userAfterInsertHooks = append(userAfterInsertHooks, userHook)
case boil.BeforeUpdateHook:
userBeforeUpdateHooks = append(userBeforeUpdateHooks, userHook)
case boil.AfterUpdateHook:
userAfterUpdateHooks = append(userAfterUpdateHooks, userHook)
case boil.BeforeDeleteHook:
userBeforeDeleteHooks = append(userBeforeDeleteHooks, userHook)
case boil.AfterDeleteHook:
userAfterDeleteHooks = append(userAfterDeleteHooks, userHook)
case boil.BeforeUpsertHook:
userBeforeUpsertHooks = append(userBeforeUpsertHooks, userHook)
case boil.AfterUpsertHook:
userAfterUpsertHooks = append(userAfterUpsertHooks, userHook)
}
}
// One returns a single user record from the query.
func (q userQuery) One(ctx context.Context, exec boil.ContextExecutor) (*User, error) {
o := &User{}
queries.SetLimit(q.Query, 1)
err := q.Bind(ctx, exec, o)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, sql.ErrNoRows
}
return nil, errors.Wrap(err, "sqlboilergen: failed to execute a one query for users")
}
if err := o.doAfterSelectHooks(ctx, exec); err != nil {
return o, err
}
return o, nil
}
// All returns all User records from the query.
func (q userQuery) All(ctx context.Context, exec boil.ContextExecutor) (UserSlice, error) {
var o []*User
err := q.Bind(ctx, exec, &o)
if err != nil {
return nil, errors.Wrap(err, "sqlboilergen: failed to assign all query results to User slice")
}
if len(userAfterSelectHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterSelectHooks(ctx, exec); err != nil {
return o, err
}
}
}
return o, nil
}
// Count returns the count of all User records in the query.
func (q userQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
var count int64
queries.SetSelect(q.Query, nil)
queries.SetCount(q.Query)
err := q.Query.QueryRowContext(ctx, exec).Scan(&count)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: failed to count users rows")
}
return count, nil
}
// Exists checks if the row exists in the table.
func (q userQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {
var count int64
queries.SetSelect(q.Query, nil)
queries.SetCount(q.Query)
queries.SetLimit(q.Query, 1)
err := q.Query.QueryRowContext(ctx, exec).Scan(&count)
if err != nil {
return false, errors.Wrap(err, "sqlboilergen: failed to check if users exists")
}
return count > 0, nil
}
// Users retrieves all the records using an executor.
func Users(mods ...qm.QueryMod) userQuery {
mods = append(mods, qm.From("\"users\""))
q := NewQuery(mods...)
if len(queries.GetSelect(q)) == 0 {
queries.SetSelect(q, []string{"\"users\".*"})
}
return userQuery{q}
}
// FindUser retrieves a single record by ID with an executor.
// If selectCols is empty Find will return all columns.
func FindUser(ctx context.Context, exec boil.ContextExecutor, iD int, selectCols ...string) (*User, error) {
userObj := &User{}
sel := "*"
if len(selectCols) > 0 {
sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",")
}
query := fmt.Sprintf(
"select %s from \"users\" where \"id\"=$1", sel,
)
q := queries.Raw(query, iD)
err := q.Bind(ctx, exec, userObj)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, sql.ErrNoRows
}
return nil, errors.Wrap(err, "sqlboilergen: unable to select from users")
}
if err = userObj.doAfterSelectHooks(ctx, exec); err != nil {
return userObj, err
}
return userObj, nil
}
// Insert a single record using an executor.
// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts.
func (o *User) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {
if o == nil {
return errors.New("sqlboilergen: no users provided for insertion")
}
var err error
if err := o.doBeforeInsertHooks(ctx, exec); err != nil {
return err
}
nzDefaults := queries.NonZeroDefaultSet(userColumnsWithDefault, o)
key := makeCacheKey(columns, nzDefaults)
userInsertCacheMut.RLock()
cache, cached := userInsertCache[key]
userInsertCacheMut.RUnlock()
if !cached {
wl, returnColumns := columns.InsertColumnSet(
userAllColumns,
userColumnsWithDefault,
userColumnsWithoutDefault,
nzDefaults,
)
cache.valueMapping, err = queries.BindMapping(userType, userMapping, wl)
if err != nil {
return err
}
cache.retMapping, err = queries.BindMapping(userType, userMapping, returnColumns)
if err != nil {
return err
}
if len(wl) != 0 {
cache.query = fmt.Sprintf("INSERT INTO \"users\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))
} else {
cache.query = "INSERT INTO \"users\" %sDEFAULT VALUES%s"
}
var queryOutput, queryReturning string
if len(cache.retMapping) != 0 {
queryReturning = fmt.Sprintf(" RETURNING \"%s\"", strings.Join(returnColumns, "\",\""))
}
cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)
}
value := reflect.Indirect(reflect.ValueOf(o))
vals := queries.ValuesFromMapping(value, cache.valueMapping)
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, cache.query)
fmt.Fprintln(writer, vals)
}
if len(cache.retMapping) != 0 {
err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)
} else {
_, err = exec.ExecContext(ctx, cache.query, vals...)
}
if err != nil {
return errors.Wrap(err, "sqlboilergen: unable to insert into users")
}
if !cached {
userInsertCacheMut.Lock()
userInsertCache[key] = cache
userInsertCacheMut.Unlock()
}
return o.doAfterInsertHooks(ctx, exec)
}
// Update uses an executor to update the User.
// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates.
// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records.
func (o *User) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {
var err error
if err = o.doBeforeUpdateHooks(ctx, exec); err != nil {
return 0, err
}
key := makeCacheKey(columns, nil)
userUpdateCacheMut.RLock()
cache, cached := userUpdateCache[key]
userUpdateCacheMut.RUnlock()
if !cached {
wl := columns.UpdateColumnSet(
userAllColumns,
userPrimaryKeyColumns,
)
if !columns.IsWhitelist() {
wl = strmangle.SetComplement(wl, []string{"created_at"})
}
if len(wl) == 0 {
return 0, errors.New("sqlboilergen: unable to update users, could not build whitelist")
}
cache.query = fmt.Sprintf("UPDATE \"users\" SET %s WHERE %s",
strmangle.SetParamNames("\"", "\"", 1, wl),
strmangle.WhereClause("\"", "\"", len(wl)+1, userPrimaryKeyColumns),
)
cache.valueMapping, err = queries.BindMapping(userType, userMapping, append(wl, userPrimaryKeyColumns...))
if err != nil {
return 0, err
}
}
values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, cache.query)
fmt.Fprintln(writer, values)
}
var result sql.Result
result, err = exec.ExecContext(ctx, cache.query, values...)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to update users row")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: failed to get rows affected by update for users")
}
if !cached {
userUpdateCacheMut.Lock()
userUpdateCache[key] = cache
userUpdateCacheMut.Unlock()
}
return rowsAff, o.doAfterUpdateHooks(ctx, exec)
}
// UpdateAll updates all rows with the specified column values.
func (q userQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) {
queries.SetUpdate(q.Query, cols)
result, err := q.Query.ExecContext(ctx, exec)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to update all for users")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to retrieve rows affected for users")
}
return rowsAff, nil
}
// UpdateAll updates all rows with the specified column values, using an executor.
func (o UserSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) {
ln := int64(len(o))
if ln == 0 {
return 0, nil
}
if len(cols) == 0 {
return 0, errors.New("sqlboilergen: update all requires at least one column argument")
}
colNames := make([]string, len(cols))
args := make([]interface{}, len(cols))
i := 0
for name, value := range cols {
colNames[i] = name
args[i] = value
i++
}
// Append all of the primary key values for each column
for _, obj := range o {
pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), userPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := fmt.Sprintf("UPDATE \"users\" SET %s WHERE %s",
strmangle.SetParamNames("\"", "\"", 1, colNames),
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, userPrimaryKeyColumns, len(o)))
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, args...)
}
result, err := exec.ExecContext(ctx, sql, args...)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to update all in user slice")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to retrieve rows affected all in update all user")
}
return rowsAff, nil
}
// Upsert attempts an insert using an executor, and does an update or ignore on conflict.
// See boil.Columns documentation for how to properly use updateColumns and insertColumns.
func (o *User) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns) error {
if o == nil {
return errors.New("sqlboilergen: no users provided for upsert")
}
if err := o.doBeforeUpsertHooks(ctx, exec); err != nil {
return err
}
nzDefaults := queries.NonZeroDefaultSet(userColumnsWithDefault, o)
// Build cache key in-line uglily - mysql vs psql problems
buf := strmangle.GetBuffer()
if updateOnConflict {
buf.WriteByte('t')
} else {
buf.WriteByte('f')
}
buf.WriteByte('.')
for _, c := range conflictColumns {
buf.WriteString(c)
}
buf.WriteByte('.')
buf.WriteString(strconv.Itoa(updateColumns.Kind))
for _, c := range updateColumns.Cols {
buf.WriteString(c)
}
buf.WriteByte('.')
buf.WriteString(strconv.Itoa(insertColumns.Kind))
for _, c := range insertColumns.Cols {
buf.WriteString(c)
}
buf.WriteByte('.')
for _, c := range nzDefaults {
buf.WriteString(c)
}
key := buf.String()
strmangle.PutBuffer(buf)
userUpsertCacheMut.RLock()
cache, cached := userUpsertCache[key]
userUpsertCacheMut.RUnlock()
var err error
if !cached {
insert, ret := insertColumns.InsertColumnSet(
userAllColumns,
userColumnsWithDefault,
userColumnsWithoutDefault,
nzDefaults,
)
update := updateColumns.UpdateColumnSet(
userAllColumns,
userPrimaryKeyColumns,
)
if updateOnConflict && len(update) == 0 {
return errors.New("sqlboilergen: unable to upsert users, could not build update column list")
}
conflict := conflictColumns
if len(conflict) == 0 {
conflict = make([]string, len(userPrimaryKeyColumns))
copy(conflict, userPrimaryKeyColumns)
}
cache.query = buildUpsertQueryPostgres(dialect, "\"users\"", updateOnConflict, ret, update, conflict, insert)
cache.valueMapping, err = queries.BindMapping(userType, userMapping, insert)
if err != nil {
return err
}
if len(ret) != 0 {
cache.retMapping, err = queries.BindMapping(userType, userMapping, ret)
if err != nil {
return err
}
}
}
value := reflect.Indirect(reflect.ValueOf(o))
vals := queries.ValuesFromMapping(value, cache.valueMapping)
var returns []interface{}
if len(cache.retMapping) != 0 {
returns = queries.PtrsFromMapping(value, cache.retMapping)
}
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, cache.query)
fmt.Fprintln(writer, vals)
}
if len(cache.retMapping) != 0 {
err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(returns...)
if errors.Is(err, sql.ErrNoRows) {
err = nil // Postgres doesn't return anything when there's no update
}
} else {
_, err = exec.ExecContext(ctx, cache.query, vals...)
}
if err != nil {
return errors.Wrap(err, "sqlboilergen: unable to upsert users")
}
if !cached {
userUpsertCacheMut.Lock()
userUpsertCache[key] = cache
userUpsertCacheMut.Unlock()
}
return o.doAfterUpsertHooks(ctx, exec)
}
// Delete deletes a single User record with an executor.
// Delete will match against the primary key column to find the record to delete.
func (o *User) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
if o == nil {
return 0, errors.New("sqlboilergen: no User provided for delete")
}
if err := o.doBeforeDeleteHooks(ctx, exec); err != nil {
return 0, err
}
args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), userPrimaryKeyMapping)
sql := "DELETE FROM \"users\" WHERE \"id\"=$1"
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, args...)
}
result, err := exec.ExecContext(ctx, sql, args...)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to delete from users")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: failed to get rows affected by delete for users")
}
if err := o.doAfterDeleteHooks(ctx, exec); err != nil {
return 0, err
}
return rowsAff, nil
}
// DeleteAll deletes all matching rows.
func (q userQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
if q.Query == nil {
return 0, errors.New("sqlboilergen: no userQuery provided for delete all")
}
queries.SetDelete(q.Query)
result, err := q.Query.ExecContext(ctx, exec)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to delete all from users")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: failed to get rows affected by deleteall for users")
}
return rowsAff, nil
}
// DeleteAll deletes all rows in the slice, using an executor.
func (o UserSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
if len(o) == 0 {
return 0, nil
}
if len(userBeforeDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil {
return 0, err
}
}
}
var args []interface{}
for _, obj := range o {
pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), userPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := "DELETE FROM \"users\" WHERE " +
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, userPrimaryKeyColumns, len(o))
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, args)
}
result, err := exec.ExecContext(ctx, sql, args...)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to delete all from user slice")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: failed to get rows affected by deleteall for users")
}
if len(userAfterDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterDeleteHooks(ctx, exec); err != nil {
return 0, err
}
}
}
return rowsAff, nil
}
// Reload refetches the object from the database
// using the primary keys with an executor.
func (o *User) Reload(ctx context.Context, exec boil.ContextExecutor) error {
ret, err := FindUser(ctx, exec, o.ID)
if err != nil {
return err
}
*o = *ret
return nil
}
// ReloadAll refetches every row with matching primary key column values
// and overwrites the original object slice with the newly updated slice.
func (o *UserSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error {
if o == nil || len(*o) == 0 {
return nil
}
slice := UserSlice{}
var args []interface{}
for _, obj := range *o {
pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), userPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := "SELECT \"users\".* FROM \"users\" WHERE " +
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, userPrimaryKeyColumns, len(*o))
q := queries.Raw(sql, args...)
err := q.Bind(ctx, exec, &slice)
if err != nil {
return errors.Wrap(err, "sqlboilergen: unable to reload all in UserSlice")
}
*o = slice
return nil
}
// UserExists checks if the User row exists.
func UserExists(ctx context.Context, exec boil.ContextExecutor, iD int) (bool, error) {
var exists bool
sql := "select exists(select 1 from \"users\" where \"id\"=$1 limit 1)"
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, iD)
}
row := exec.QueryRowContext(ctx, sql, iD)
err := row.Scan(&exists)
if err != nil {
return false, errors.Wrap(err, "sqlboilergen: unable to check if users exists")
}
return exists, nil
}

View File

@ -0,0 +1,890 @@
// Code generated by SQLBoiler 4.12.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package sqlboilergen
import (
"context"
"database/sql"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/friendsofgo/errors"
"github.com/volatiletech/sqlboiler/v4/boil"
"github.com/volatiletech/sqlboiler/v4/queries"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
"github.com/volatiletech/sqlboiler/v4/queries/qmhelper"
"github.com/volatiletech/strmangle"
)
// UsersPermission is an object representing the database table.
type UsersPermission struct {
UserID int `boil:"user_id" json:"user_id" toml:"user_id" yaml:"user_id"`
PostID int `boil:"post_id" json:"post_id" toml:"post_id" yaml:"post_id"`
R *usersPermissionR `boil:"-" json:"-" toml:"-" yaml:"-"`
L usersPermissionL `boil:"-" json:"-" toml:"-" yaml:"-"`
}
var UsersPermissionColumns = struct {
UserID string
PostID string
}{
UserID: "user_id",
PostID: "post_id",
}
var UsersPermissionTableColumns = struct {
UserID string
PostID string
}{
UserID: "users_permissions.user_id",
PostID: "users_permissions.post_id",
}
// Generated where
var UsersPermissionWhere = struct {
UserID whereHelperint
PostID whereHelperint
}{
UserID: whereHelperint{field: "\"users_permissions\".\"user_id\""},
PostID: whereHelperint{field: "\"users_permissions\".\"post_id\""},
}
// UsersPermissionRels is where relationship names are stored.
var UsersPermissionRels = struct {
}{}
// usersPermissionR is where relationships are stored.
type usersPermissionR struct {
}
// NewStruct creates a new relationship struct
func (*usersPermissionR) NewStruct() *usersPermissionR {
return &usersPermissionR{}
}
// usersPermissionL is where Load methods for each relationship are stored.
type usersPermissionL struct{}
var (
usersPermissionAllColumns = []string{"user_id", "post_id"}
usersPermissionColumnsWithoutDefault = []string{"user_id", "post_id"}
usersPermissionColumnsWithDefault = []string{}
usersPermissionPrimaryKeyColumns = []string{"user_id", "post_id"}
usersPermissionGeneratedColumns = []string{}
)
type (
// UsersPermissionSlice is an alias for a slice of pointers to UsersPermission.
// This should almost always be used instead of []UsersPermission.
UsersPermissionSlice []*UsersPermission
// UsersPermissionHook is the signature for custom UsersPermission hook methods
UsersPermissionHook func(context.Context, boil.ContextExecutor, *UsersPermission) error
usersPermissionQuery struct {
*queries.Query
}
)
// Cache for insert, update and upsert
var (
usersPermissionType = reflect.TypeOf(&UsersPermission{})
usersPermissionMapping = queries.MakeStructMapping(usersPermissionType)
usersPermissionPrimaryKeyMapping, _ = queries.BindMapping(usersPermissionType, usersPermissionMapping, usersPermissionPrimaryKeyColumns)
usersPermissionInsertCacheMut sync.RWMutex
usersPermissionInsertCache = make(map[string]insertCache)
usersPermissionUpdateCacheMut sync.RWMutex
usersPermissionUpdateCache = make(map[string]updateCache)
usersPermissionUpsertCacheMut sync.RWMutex
usersPermissionUpsertCache = make(map[string]insertCache)
)
var (
// Force time package dependency for automated UpdatedAt/CreatedAt.
_ = time.Second
// Force qmhelper dependency for where clause generation (which doesn't
// always happen)
_ = qmhelper.Where
)
var usersPermissionAfterSelectHooks []UsersPermissionHook
var usersPermissionBeforeInsertHooks []UsersPermissionHook
var usersPermissionAfterInsertHooks []UsersPermissionHook
var usersPermissionBeforeUpdateHooks []UsersPermissionHook
var usersPermissionAfterUpdateHooks []UsersPermissionHook
var usersPermissionBeforeDeleteHooks []UsersPermissionHook
var usersPermissionAfterDeleteHooks []UsersPermissionHook
var usersPermissionBeforeUpsertHooks []UsersPermissionHook
var usersPermissionAfterUpsertHooks []UsersPermissionHook
// doAfterSelectHooks executes all "after Select" hooks.
func (o *UsersPermission) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range usersPermissionAfterSelectHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeInsertHooks executes all "before insert" hooks.
func (o *UsersPermission) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range usersPermissionBeforeInsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterInsertHooks executes all "after Insert" hooks.
func (o *UsersPermission) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range usersPermissionAfterInsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeUpdateHooks executes all "before Update" hooks.
func (o *UsersPermission) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range usersPermissionBeforeUpdateHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterUpdateHooks executes all "after Update" hooks.
func (o *UsersPermission) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range usersPermissionAfterUpdateHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeDeleteHooks executes all "before Delete" hooks.
func (o *UsersPermission) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range usersPermissionBeforeDeleteHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterDeleteHooks executes all "after Delete" hooks.
func (o *UsersPermission) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range usersPermissionAfterDeleteHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeUpsertHooks executes all "before Upsert" hooks.
func (o *UsersPermission) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range usersPermissionBeforeUpsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterUpsertHooks executes all "after Upsert" hooks.
func (o *UsersPermission) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range usersPermissionAfterUpsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// AddUsersPermissionHook registers your hook function for all future operations.
func AddUsersPermissionHook(hookPoint boil.HookPoint, usersPermissionHook UsersPermissionHook) {
switch hookPoint {
case boil.AfterSelectHook:
usersPermissionAfterSelectHooks = append(usersPermissionAfterSelectHooks, usersPermissionHook)
case boil.BeforeInsertHook:
usersPermissionBeforeInsertHooks = append(usersPermissionBeforeInsertHooks, usersPermissionHook)
case boil.AfterInsertHook:
usersPermissionAfterInsertHooks = append(usersPermissionAfterInsertHooks, usersPermissionHook)
case boil.BeforeUpdateHook:
usersPermissionBeforeUpdateHooks = append(usersPermissionBeforeUpdateHooks, usersPermissionHook)
case boil.AfterUpdateHook:
usersPermissionAfterUpdateHooks = append(usersPermissionAfterUpdateHooks, usersPermissionHook)
case boil.BeforeDeleteHook:
usersPermissionBeforeDeleteHooks = append(usersPermissionBeforeDeleteHooks, usersPermissionHook)
case boil.AfterDeleteHook:
usersPermissionAfterDeleteHooks = append(usersPermissionAfterDeleteHooks, usersPermissionHook)
case boil.BeforeUpsertHook:
usersPermissionBeforeUpsertHooks = append(usersPermissionBeforeUpsertHooks, usersPermissionHook)
case boil.AfterUpsertHook:
usersPermissionAfterUpsertHooks = append(usersPermissionAfterUpsertHooks, usersPermissionHook)
}
}
// One returns a single usersPermission record from the query.
func (q usersPermissionQuery) One(ctx context.Context, exec boil.ContextExecutor) (*UsersPermission, error) {
o := &UsersPermission{}
queries.SetLimit(q.Query, 1)
err := q.Bind(ctx, exec, o)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, sql.ErrNoRows
}
return nil, errors.Wrap(err, "sqlboilergen: failed to execute a one query for users_permissions")
}
if err := o.doAfterSelectHooks(ctx, exec); err != nil {
return o, err
}
return o, nil
}
// All returns all UsersPermission records from the query.
func (q usersPermissionQuery) All(ctx context.Context, exec boil.ContextExecutor) (UsersPermissionSlice, error) {
var o []*UsersPermission
err := q.Bind(ctx, exec, &o)
if err != nil {
return nil, errors.Wrap(err, "sqlboilergen: failed to assign all query results to UsersPermission slice")
}
if len(usersPermissionAfterSelectHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterSelectHooks(ctx, exec); err != nil {
return o, err
}
}
}
return o, nil
}
// Count returns the count of all UsersPermission records in the query.
func (q usersPermissionQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
var count int64
queries.SetSelect(q.Query, nil)
queries.SetCount(q.Query)
err := q.Query.QueryRowContext(ctx, exec).Scan(&count)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: failed to count users_permissions rows")
}
return count, nil
}
// Exists checks if the row exists in the table.
func (q usersPermissionQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {
var count int64
queries.SetSelect(q.Query, nil)
queries.SetCount(q.Query)
queries.SetLimit(q.Query, 1)
err := q.Query.QueryRowContext(ctx, exec).Scan(&count)
if err != nil {
return false, errors.Wrap(err, "sqlboilergen: failed to check if users_permissions exists")
}
return count > 0, nil
}
// UsersPermissions retrieves all the records using an executor.
func UsersPermissions(mods ...qm.QueryMod) usersPermissionQuery {
mods = append(mods, qm.From("\"users_permissions\""))
q := NewQuery(mods...)
if len(queries.GetSelect(q)) == 0 {
queries.SetSelect(q, []string{"\"users_permissions\".*"})
}
return usersPermissionQuery{q}
}
// FindUsersPermission retrieves a single record by ID with an executor.
// If selectCols is empty Find will return all columns.
func FindUsersPermission(ctx context.Context, exec boil.ContextExecutor, userID int, postID int, selectCols ...string) (*UsersPermission, error) {
usersPermissionObj := &UsersPermission{}
sel := "*"
if len(selectCols) > 0 {
sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",")
}
query := fmt.Sprintf(
"select %s from \"users_permissions\" where \"user_id\"=$1 AND \"post_id\"=$2", sel,
)
q := queries.Raw(query, userID, postID)
err := q.Bind(ctx, exec, usersPermissionObj)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, sql.ErrNoRows
}
return nil, errors.Wrap(err, "sqlboilergen: unable to select from users_permissions")
}
if err = usersPermissionObj.doAfterSelectHooks(ctx, exec); err != nil {
return usersPermissionObj, err
}
return usersPermissionObj, nil
}
// Insert a single record using an executor.
// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts.
func (o *UsersPermission) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {
if o == nil {
return errors.New("sqlboilergen: no users_permissions provided for insertion")
}
var err error
if err := o.doBeforeInsertHooks(ctx, exec); err != nil {
return err
}
nzDefaults := queries.NonZeroDefaultSet(usersPermissionColumnsWithDefault, o)
key := makeCacheKey(columns, nzDefaults)
usersPermissionInsertCacheMut.RLock()
cache, cached := usersPermissionInsertCache[key]
usersPermissionInsertCacheMut.RUnlock()
if !cached {
wl, returnColumns := columns.InsertColumnSet(
usersPermissionAllColumns,
usersPermissionColumnsWithDefault,
usersPermissionColumnsWithoutDefault,
nzDefaults,
)
cache.valueMapping, err = queries.BindMapping(usersPermissionType, usersPermissionMapping, wl)
if err != nil {
return err
}
cache.retMapping, err = queries.BindMapping(usersPermissionType, usersPermissionMapping, returnColumns)
if err != nil {
return err
}
if len(wl) != 0 {
cache.query = fmt.Sprintf("INSERT INTO \"users_permissions\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))
} else {
cache.query = "INSERT INTO \"users_permissions\" %sDEFAULT VALUES%s"
}
var queryOutput, queryReturning string
if len(cache.retMapping) != 0 {
queryReturning = fmt.Sprintf(" RETURNING \"%s\"", strings.Join(returnColumns, "\",\""))
}
cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)
}
value := reflect.Indirect(reflect.ValueOf(o))
vals := queries.ValuesFromMapping(value, cache.valueMapping)
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, cache.query)
fmt.Fprintln(writer, vals)
}
if len(cache.retMapping) != 0 {
err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)
} else {
_, err = exec.ExecContext(ctx, cache.query, vals...)
}
if err != nil {
return errors.Wrap(err, "sqlboilergen: unable to insert into users_permissions")
}
if !cached {
usersPermissionInsertCacheMut.Lock()
usersPermissionInsertCache[key] = cache
usersPermissionInsertCacheMut.Unlock()
}
return o.doAfterInsertHooks(ctx, exec)
}
// Update uses an executor to update the UsersPermission.
// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates.
// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records.
func (o *UsersPermission) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {
var err error
if err = o.doBeforeUpdateHooks(ctx, exec); err != nil {
return 0, err
}
key := makeCacheKey(columns, nil)
usersPermissionUpdateCacheMut.RLock()
cache, cached := usersPermissionUpdateCache[key]
usersPermissionUpdateCacheMut.RUnlock()
if !cached {
wl := columns.UpdateColumnSet(
usersPermissionAllColumns,
usersPermissionPrimaryKeyColumns,
)
if !columns.IsWhitelist() {
wl = strmangle.SetComplement(wl, []string{"created_at"})
}
if len(wl) == 0 {
return 0, errors.New("sqlboilergen: unable to update users_permissions, could not build whitelist")
}
cache.query = fmt.Sprintf("UPDATE \"users_permissions\" SET %s WHERE %s",
strmangle.SetParamNames("\"", "\"", 1, wl),
strmangle.WhereClause("\"", "\"", len(wl)+1, usersPermissionPrimaryKeyColumns),
)
cache.valueMapping, err = queries.BindMapping(usersPermissionType, usersPermissionMapping, append(wl, usersPermissionPrimaryKeyColumns...))
if err != nil {
return 0, err
}
}
values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, cache.query)
fmt.Fprintln(writer, values)
}
var result sql.Result
result, err = exec.ExecContext(ctx, cache.query, values...)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to update users_permissions row")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: failed to get rows affected by update for users_permissions")
}
if !cached {
usersPermissionUpdateCacheMut.Lock()
usersPermissionUpdateCache[key] = cache
usersPermissionUpdateCacheMut.Unlock()
}
return rowsAff, o.doAfterUpdateHooks(ctx, exec)
}
// UpdateAll updates all rows with the specified column values.
func (q usersPermissionQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) {
queries.SetUpdate(q.Query, cols)
result, err := q.Query.ExecContext(ctx, exec)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to update all for users_permissions")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to retrieve rows affected for users_permissions")
}
return rowsAff, nil
}
// UpdateAll updates all rows with the specified column values, using an executor.
func (o UsersPermissionSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) {
ln := int64(len(o))
if ln == 0 {
return 0, nil
}
if len(cols) == 0 {
return 0, errors.New("sqlboilergen: update all requires at least one column argument")
}
colNames := make([]string, len(cols))
args := make([]interface{}, len(cols))
i := 0
for name, value := range cols {
colNames[i] = name
args[i] = value
i++
}
// Append all of the primary key values for each column
for _, obj := range o {
pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), usersPermissionPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := fmt.Sprintf("UPDATE \"users_permissions\" SET %s WHERE %s",
strmangle.SetParamNames("\"", "\"", 1, colNames),
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, usersPermissionPrimaryKeyColumns, len(o)))
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, args...)
}
result, err := exec.ExecContext(ctx, sql, args...)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to update all in usersPermission slice")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to retrieve rows affected all in update all usersPermission")
}
return rowsAff, nil
}
// Upsert attempts an insert using an executor, and does an update or ignore on conflict.
// See boil.Columns documentation for how to properly use updateColumns and insertColumns.
func (o *UsersPermission) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns) error {
if o == nil {
return errors.New("sqlboilergen: no users_permissions provided for upsert")
}
if err := o.doBeforeUpsertHooks(ctx, exec); err != nil {
return err
}
nzDefaults := queries.NonZeroDefaultSet(usersPermissionColumnsWithDefault, o)
// Build cache key in-line uglily - mysql vs psql problems
buf := strmangle.GetBuffer()
if updateOnConflict {
buf.WriteByte('t')
} else {
buf.WriteByte('f')
}
buf.WriteByte('.')
for _, c := range conflictColumns {
buf.WriteString(c)
}
buf.WriteByte('.')
buf.WriteString(strconv.Itoa(updateColumns.Kind))
for _, c := range updateColumns.Cols {
buf.WriteString(c)
}
buf.WriteByte('.')
buf.WriteString(strconv.Itoa(insertColumns.Kind))
for _, c := range insertColumns.Cols {
buf.WriteString(c)
}
buf.WriteByte('.')
for _, c := range nzDefaults {
buf.WriteString(c)
}
key := buf.String()
strmangle.PutBuffer(buf)
usersPermissionUpsertCacheMut.RLock()
cache, cached := usersPermissionUpsertCache[key]
usersPermissionUpsertCacheMut.RUnlock()
var err error
if !cached {
insert, ret := insertColumns.InsertColumnSet(
usersPermissionAllColumns,
usersPermissionColumnsWithDefault,
usersPermissionColumnsWithoutDefault,
nzDefaults,
)
update := updateColumns.UpdateColumnSet(
usersPermissionAllColumns,
usersPermissionPrimaryKeyColumns,
)
if updateOnConflict && len(update) == 0 {
return errors.New("sqlboilergen: unable to upsert users_permissions, could not build update column list")
}
conflict := conflictColumns
if len(conflict) == 0 {
conflict = make([]string, len(usersPermissionPrimaryKeyColumns))
copy(conflict, usersPermissionPrimaryKeyColumns)
}
cache.query = buildUpsertQueryPostgres(dialect, "\"users_permissions\"", updateOnConflict, ret, update, conflict, insert)
cache.valueMapping, err = queries.BindMapping(usersPermissionType, usersPermissionMapping, insert)
if err != nil {
return err
}
if len(ret) != 0 {
cache.retMapping, err = queries.BindMapping(usersPermissionType, usersPermissionMapping, ret)
if err != nil {
return err
}
}
}
value := reflect.Indirect(reflect.ValueOf(o))
vals := queries.ValuesFromMapping(value, cache.valueMapping)
var returns []interface{}
if len(cache.retMapping) != 0 {
returns = queries.PtrsFromMapping(value, cache.retMapping)
}
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, cache.query)
fmt.Fprintln(writer, vals)
}
if len(cache.retMapping) != 0 {
err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(returns...)
if errors.Is(err, sql.ErrNoRows) {
err = nil // Postgres doesn't return anything when there's no update
}
} else {
_, err = exec.ExecContext(ctx, cache.query, vals...)
}
if err != nil {
return errors.Wrap(err, "sqlboilergen: unable to upsert users_permissions")
}
if !cached {
usersPermissionUpsertCacheMut.Lock()
usersPermissionUpsertCache[key] = cache
usersPermissionUpsertCacheMut.Unlock()
}
return o.doAfterUpsertHooks(ctx, exec)
}
// Delete deletes a single UsersPermission record with an executor.
// Delete will match against the primary key column to find the record to delete.
func (o *UsersPermission) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
if o == nil {
return 0, errors.New("sqlboilergen: no UsersPermission provided for delete")
}
if err := o.doBeforeDeleteHooks(ctx, exec); err != nil {
return 0, err
}
args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), usersPermissionPrimaryKeyMapping)
sql := "DELETE FROM \"users_permissions\" WHERE \"user_id\"=$1 AND \"post_id\"=$2"
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, args...)
}
result, err := exec.ExecContext(ctx, sql, args...)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to delete from users_permissions")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: failed to get rows affected by delete for users_permissions")
}
if err := o.doAfterDeleteHooks(ctx, exec); err != nil {
return 0, err
}
return rowsAff, nil
}
// DeleteAll deletes all matching rows.
func (q usersPermissionQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
if q.Query == nil {
return 0, errors.New("sqlboilergen: no usersPermissionQuery provided for delete all")
}
queries.SetDelete(q.Query)
result, err := q.Query.ExecContext(ctx, exec)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to delete all from users_permissions")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: failed to get rows affected by deleteall for users_permissions")
}
return rowsAff, nil
}
// DeleteAll deletes all rows in the slice, using an executor.
func (o UsersPermissionSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
if len(o) == 0 {
return 0, nil
}
if len(usersPermissionBeforeDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil {
return 0, err
}
}
}
var args []interface{}
for _, obj := range o {
pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), usersPermissionPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := "DELETE FROM \"users_permissions\" WHERE " +
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, usersPermissionPrimaryKeyColumns, len(o))
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, args)
}
result, err := exec.ExecContext(ctx, sql, args...)
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: unable to delete all from usersPermission slice")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "sqlboilergen: failed to get rows affected by deleteall for users_permissions")
}
if len(usersPermissionAfterDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterDeleteHooks(ctx, exec); err != nil {
return 0, err
}
}
}
return rowsAff, nil
}
// Reload refetches the object from the database
// using the primary keys with an executor.
func (o *UsersPermission) Reload(ctx context.Context, exec boil.ContextExecutor) error {
ret, err := FindUsersPermission(ctx, exec, o.UserID, o.PostID)
if err != nil {
return err
}
*o = *ret
return nil
}
// ReloadAll refetches every row with matching primary key column values
// and overwrites the original object slice with the newly updated slice.
func (o *UsersPermissionSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error {
if o == nil || len(*o) == 0 {
return nil
}
slice := UsersPermissionSlice{}
var args []interface{}
for _, obj := range *o {
pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), usersPermissionPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := "SELECT \"users_permissions\".* FROM \"users_permissions\" WHERE " +
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, usersPermissionPrimaryKeyColumns, len(*o))
q := queries.Raw(sql, args...)
err := q.Bind(ctx, exec, &slice)
if err != nil {
return errors.Wrap(err, "sqlboilergen: unable to reload all in UsersPermissionSlice")
}
*o = slice
return nil
}
// UsersPermissionExists checks if the UsersPermission row exists.
func UsersPermissionExists(ctx context.Context, exec boil.ContextExecutor, userID int, postID int) (bool, error) {
var exists bool
sql := "select exists(select 1 from \"users_permissions\" where \"user_id\"=$1 AND \"post_id\"=$2 limit 1)"
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, userID, postID)
}
row := exec.QueryRowContext(ctx, sql, userID, postID)
err := row.Scan(&exists)
if err != nil {
return false, errors.Wrap(err, "sqlboilergen: unable to check if users_permissions exists")
}
return exists, nil
}

View File

@ -7,7 +7,7 @@ package sqlcgen
import ()
type User struct {
ID int64
ID int32
Name string
Age int32
}

View File

@ -31,9 +31,9 @@ type InsertUserParams struct {
Age int32
}
func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) (int64, error) {
func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) (int32, error) {
row := q.queryRow(ctx, q.insertUserStmt, insertUser, arg.Name, arg.Age)
var id int64
var id int32
err := row.Scan(&id)
return id, err
}