From 0dd414b2059ad307b1c24a12d491da16e39c97d3 Mon Sep 17 00:00:00 2001 From: mackee Date: Tue, 9 Apr 2024 16:58:01 +0900 Subject: [PATCH 01/11] feature in-working: supports sql.Null[T] but not completed --- .gitignore | 1 + _example/group.gen.go | 1206 +++++++++++++++++++++++++++++ _example/group.go | 24 + _example/sqlite3.sql | 47 -- _example/tools.go | 5 + _example/user.gen.go | 1271 ------------------------------- _example/user.go | 2 +- _example/user_external.gen.go | 1076 -------------------------- _example/user_item.gen.go | 1166 ---------------------------- _example/user_sns.gen.go | 985 ------------------------ _example/user_withmysql_test.go | 3 +- column.go | 5 +- expr.go | 61 ++ generator.go | 8 + main.go | 34 +- table.go | 72 +- template/select_column.tmpl | 16 +- 17 files changed, 1400 insertions(+), 4582 deletions(-) create mode 100644 _example/group.gen.go create mode 100644 _example/group.go create mode 100644 _example/tools.go diff --git a/.gitignore b/.gitignore index 6c43eb5..6ed7fce 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,4 @@ _bin vendor/ _artifacts _gobin +go.work diff --git a/_example/group.gen.go b/_example/group.gen.go new file mode 100644 index 0000000..287efa6 --- /dev/null +++ b/_example/group.gen.go @@ -0,0 +1,1206 @@ +// Code generated by github.com/mackee/go-sqlla/v2/cmd/sqlla - DO NOT EDIT. +package example + +import ( + "context" + "fmt" + "strconv" + "strings" + + "database/sql" + "github.com/go-sql-driver/mysql" + "time" + + "github.com/mackee/go-sqlla/v2" +) + +type groupSQL struct { + where sqlla.Where +} + +func NewGroupSQL() groupSQL { + q := groupSQL{} + return q +} + +var groupAllColumns = []string{ + "`id`", "`name`", "`leader_user_id`", "`sub_leader_user_id`", "`created_at`", "`updated_at`", +} + +type groupSelectSQL struct { + groupSQL + Columns []string + order string + limit *uint64 + offset *uint64 + tableAlias string + joinClauses []string + + additionalWhereClause string + additionalWhereClauseArgs []interface{} + + groupByColumns []string + + isForUpdate bool +} + +func (q groupSQL) Select() groupSelectSQL { + return groupSelectSQL{ + q, + groupAllColumns, + "", + nil, + nil, + "", + nil, + "", + nil, + nil, + false, + } +} + +func (q groupSelectSQL) Or(qs ...groupSelectSQL) groupSelectSQL { + ws := make([]sqlla.Where, 0, len(qs)) + for _, q := range qs { + ws = append(ws, q.where) + } + q.where = append(q.where, sqlla.ExprOr(ws)) + return q +} + +func (q groupSelectSQL) Limit(l uint64) groupSelectSQL { + q.limit = &l + return q +} + +func (q groupSelectSQL) Offset(o uint64) groupSelectSQL { + q.offset = &o + return q +} + +func (q groupSelectSQL) ForUpdate() groupSelectSQL { + q.isForUpdate = true + return q +} + +func (q groupSelectSQL) TableAlias(alias string) groupSelectSQL { + q.tableAlias = "`" + alias + "`" + return q +} + +func (q groupSelectSQL) SetColumns(columns ...string) groupSelectSQL { + q.Columns = make([]string, 0, len(columns)) + for _, column := range columns { + if strings.ContainsAny(column, "(.`") { + q.Columns = append(q.Columns, column) + } else { + q.Columns = append(q.Columns, "`"+column+"`") + } + } + return q +} + +func (q groupSelectSQL) JoinClause(clause string) groupSelectSQL { + q.joinClauses = append(q.joinClauses, clause) + return q +} + +func (q groupSelectSQL) AdditionalWhereClause(clause string, args ...interface{}) groupSelectSQL { + q.additionalWhereClause = clause + q.additionalWhereClauseArgs = args + return q +} + +func (q groupSelectSQL) appendColumnPrefix(column string) string { + if q.tableAlias == "" || strings.ContainsAny(column, "(.") { + return column + } + return q.tableAlias + "." + column +} + +func (q groupSelectSQL) GroupBy(columns ...string) groupSelectSQL { + q.groupByColumns = make([]string, 0, len(columns)) + for _, column := range columns { + if strings.ContainsAny(column, "(.`") { + q.groupByColumns = append(q.groupByColumns, column) + } else { + q.groupByColumns = append(q.groupByColumns, "`"+column+"`") + } + } + return q +} + +func (q groupSelectSQL) ID(v GroupID, exprs ...sqlla.Operator) groupSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + + where := sqlla.Expruint64{Value: uint64(v), Op: op, Column: q.appendColumnPrefix("`id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) IDIn(vs ...GroupID) groupSelectSQL { + _vs := make([]uint64, 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, uint64(v)) + } + where := sqlla.ExprMultiuint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) PkColumn(pk int64, exprs ...sqlla.Operator) groupSelectSQL { + v := GroupID(pk) + return q.ID(v, exprs...) +} + +func (q groupSelectSQL) OrderByID(order sqlla.Order) groupSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`id`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q groupSelectSQL) Name(v string, exprs ...sqlla.Operator) groupSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + + where := sqlla.Exprstring{Value: v, Op: op, Column: q.appendColumnPrefix("`name`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) NameIn(vs ...string) groupSelectSQL { + where := sqlla.ExprMultistring{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`name`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) OrderByName(order sqlla.Order) groupSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`name`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q groupSelectSQL) LeaderUserID(v UserId, exprs ...sqlla.Operator) groupSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + + where := sqlla.Expruint64{Value: uint64(v), Op: op, Column: q.appendColumnPrefix("`leader_user_id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) LeaderUserIDIn(vs ...UserId) groupSelectSQL { + _vs := make([]uint64, 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, uint64(v)) + } + where := sqlla.ExprMultiuint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`leader_user_id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) OrderByLeaderUserID(order sqlla.Order) groupSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`leader_user_id`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q groupSelectSQL) SubLeaderUserID(v sql.Null[T], exprs ...sqlla.Operator) groupSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + + where := sqlla.Exprsql.Null[T]{Value: v, Op: op, Column: q.appendColumnPrefix("`sub_leader_user_id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) SubLeaderUserIDIn(vs ...sql.Null[T]) groupSelectSQL { + where := sqlla.ExprMultisql.Null[T]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`sub_leader_user_id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) OrderBySubLeaderUserID(order sqlla.Order) groupSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`sub_leader_user_id`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q groupSelectSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) groupSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + + where := sqlla.Exprtime.Time{Value: v, Op: op, Column: q.appendColumnPrefix("`created_at`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) CreatedAtIn(vs ...time.Time) groupSelectSQL { + where := sqlla.ExprMultitime.Time{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`created_at`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) OrderByCreatedAt(order sqlla.Order) groupSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`created_at`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q groupSelectSQL) UpdatedAt(v MysqlNullTime, exprs ...sqlla.Operator) groupSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + + where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: q.appendColumnPrefix("`updated_at`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) UpdatedAtIn(vs ...MysqlNullTime) groupSelectSQL { + where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`updated_at`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) OrderByUpdatedAt(order sqlla.Order) groupSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`updated_at`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q groupSelectSQL) ToSql() (string, []interface{}, error) { + columns := strings.Join(q.Columns, ", ") + wheres, vs, err := q.where.ToSql() + if err != nil { + return "", nil, err + } + + tableName := "`group`" + if q.tableAlias != "" { + tableName = tableName + " AS " + q.tableAlias + pcs := make([]string, 0, len(q.Columns)) + for _, column := range q.Columns { + pcs = append(pcs, q.appendColumnPrefix(column)) + } + columns = strings.Join(pcs, ", ") + } + query := "SELECT " + columns + " FROM " + tableName + if len(q.joinClauses) > 0 { + jc := strings.Join(q.joinClauses, " ") + query += " " + jc + } + if wheres != "" { + query += " WHERE" + wheres + } + if q.additionalWhereClause != "" { + query += " " + q.additionalWhereClause + if len(q.additionalWhereClauseArgs) > 0 { + vs = append(vs, q.additionalWhereClauseArgs...) + } + } + if len(q.groupByColumns) > 0 { + query += " GROUP BY " + gbcs := make([]string, 0, len(q.groupByColumns)) + for _, column := range q.groupByColumns { + gbcs = append(gbcs, q.appendColumnPrefix(column)) + } + query += strings.Join(gbcs, ", ") + } + query += q.order + if q.limit != nil { + query += " LIMIT " + strconv.FormatUint(*q.limit, 10) + } + if q.offset != nil { + query += " OFFSET " + strconv.FormatUint(*q.offset, 10) + } + + if q.isForUpdate { + query += " FOR UPDATE" + } + + return query + ";", vs, nil +} + +func (s Group) Select() groupSelectSQL { + return NewGroupSQL().Select().ID(s.ID) +} +func (q groupSelectSQL) Single(db sqlla.DB) (Group, error) { + q.Columns = groupAllColumns + query, args, err := q.ToSql() + if err != nil { + return Group{}, err + } + + row := db.QueryRow(query, args...) + return q.Scan(row) +} + +func (q groupSelectSQL) SingleContext(ctx context.Context, db sqlla.DB) (Group, error) { + q.Columns = groupAllColumns + query, args, err := q.ToSql() + if err != nil { + return Group{}, err + } + + row := db.QueryRowContext(ctx, query, args...) + return q.Scan(row) +} + +func (q groupSelectSQL) All(db sqlla.DB) ([]Group, error) { + rs := make([]Group, 0, 10) + q.Columns = groupAllColumns + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := db.Query(query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + r, err := q.Scan(rows) + if err != nil { + return nil, err + } + rs = append(rs, r) + } + return rs, nil +} + +func (q groupSelectSQL) AllContext(ctx context.Context, db sqlla.DB) ([]Group, error) { + rs := make([]Group, 0, 10) + q.Columns = groupAllColumns + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + r, err := q.Scan(rows) + if err != nil { + return nil, err + } + rs = append(rs, r) + } + return rs, nil +} + +func (q groupSelectSQL) Scan(s sqlla.Scanner) (Group, error) { + var row Group + err := s.Scan( + &row.ID, + &row.Name, + &row.LeaderUserID, + &row.SubLeaderUserID, + &row.CreatedAt, + &row.UpdatedAt, + ) + return row, err +} + +type groupUpdateSQL struct { + groupSQL + setMap sqlla.SetMap + Columns []string +} + +func (q groupSQL) Update() groupUpdateSQL { + return groupUpdateSQL{ + groupSQL: q, + setMap: sqlla.SetMap{}, + } +} + +func (q groupUpdateSQL) SetID(v GroupID) groupUpdateSQL { + q.setMap["`id`"] = v + return q +} + +func (q groupUpdateSQL) WhereID(v GroupID, exprs ...sqlla.Operator) groupUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereIDIn(vs ...GroupID) groupUpdateSQL { + _vs := make([]uint64, 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, uint64(v)) + } + where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) SetName(v string) groupUpdateSQL { + q.setMap["`name`"] = v + return q +} + +func (q groupUpdateSQL) WhereName(v string, exprs ...sqlla.Operator) groupUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprString{Value: v, Op: op, Column: "`name`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereNameIn(vs ...string) groupUpdateSQL { + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`name`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) SetLeaderUserID(v UserId) groupUpdateSQL { + q.setMap["`leader_user_id`"] = v + return q +} + +func (q groupUpdateSQL) WhereLeaderUserID(v UserId, exprs ...sqlla.Operator) groupUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: "`leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereLeaderUserIDIn(vs ...UserId) groupUpdateSQL { + _vs := make([]uint64, 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, uint64(v)) + } + where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) SetSubLeaderUserID(v sql.Null[T]) groupUpdateSQL { + q.setMap["`sub_leader_user_id`"] = v + return q +} + +func (q groupUpdateSQL) WhereSubLeaderUserID(v sql.Null[T], exprs ...sqlla.Operator) groupUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNull[T]{Value: v, Op: op, Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereSubLeaderUserIDIn(vs ...sql.Null[T]) groupUpdateSQL { + where := sqlla.ExprMultiNull[T]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) SetCreatedAt(v time.Time) groupUpdateSQL { + q.setMap["`created_at`"] = v + return q +} + +func (q groupUpdateSQL) WhereCreatedAt(v time.Time, exprs ...sqlla.Operator) groupUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereCreatedAtIn(vs ...time.Time) groupUpdateSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) SetUpdatedAt(v MysqlNullTime) groupUpdateSQL { + q.setMap["`updated_at`"] = v + return q +} + +func (q groupUpdateSQL) WhereUpdatedAt(v MysqlNullTime, exprs ...sqlla.Operator) groupUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNullTime{Value: mysql.NullTime(v), Op: op, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereUpdatedAtIn(vs ...MysqlNullTime) groupUpdateSQL { + _vs := make([]mysql.NullTime, 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, mysql.NullTime(v)) + } + where := sqlla.ExprMultiNullTime{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) ToSql() (string, []interface{}, error) { + var err error + var s interface{} = Group{} + if t, ok := s.(groupDefaultUpdateHooker); ok { + q, err = t.DefaultUpdateHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + setColumns, svs, err := q.setMap.ToUpdateSql() + if err != nil { + return "", []interface{}{}, err + } + wheres, wvs, err := q.where.ToSql() + if err != nil { + return "", []interface{}{}, err + } + + query := "UPDATE `group` SET" + setColumns + if wheres != "" { + query += " WHERE" + wheres + } + + return query + ";", append(svs, wvs...), nil +} +func (s Group) Update() groupUpdateSQL { + return NewGroupSQL().Update().WhereID(s.ID) +} + +func (q groupUpdateSQL) Exec(db sqlla.DB) ([]Group, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + _, err = db.Exec(query, args...) + if err != nil { + return nil, err + } + qq := q.groupSQL + + return qq.Select().All(db) +} + +func (q groupUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) ([]Group, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + _, err = db.ExecContext(ctx, query, args...) + if err != nil { + return nil, err + } + qq := q.groupSQL + + return qq.Select().AllContext(ctx, db) +} + +type groupDefaultUpdateHooker interface { + DefaultUpdateHook(groupUpdateSQL) (groupUpdateSQL, error) +} + +type groupInsertSQL struct { + groupSQL + setMap sqlla.SetMap + Columns []string +} + +func (q groupSQL) Insert() groupInsertSQL { + return groupInsertSQL{ + groupSQL: q, + setMap: sqlla.SetMap{}, + } +} + +func (q groupInsertSQL) ValueID(v GroupID) groupInsertSQL { + q.setMap["`id`"] = v + return q +} + +func (q groupInsertSQL) ValueName(v string) groupInsertSQL { + q.setMap["`name`"] = v + return q +} + +func (q groupInsertSQL) ValueLeaderUserID(v UserId) groupInsertSQL { + q.setMap["`leader_user_id`"] = v + return q +} + +func (q groupInsertSQL) ValueSubLeaderUserID(v sql.Null[T]) groupInsertSQL { + q.setMap["`sub_leader_user_id`"] = v + return q +} + +func (q groupInsertSQL) ValueCreatedAt(v time.Time) groupInsertSQL { + q.setMap["`created_at`"] = v + return q +} + +func (q groupInsertSQL) ValueUpdatedAt(v MysqlNullTime) groupInsertSQL { + q.setMap["`updated_at`"] = v + return q +} + +func (q groupInsertSQL) ToSql() (string, []interface{}, error) { + query, vs, err := q.groupInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + return query + ";", vs, nil +} + +func (q groupInsertSQL) groupInsertSQLToSql() (string, []interface{}, error) { + var err error + var s interface{} = Group{} + if t, ok := s.(groupDefaultInsertHooker); ok { + q, err = t.DefaultInsertHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + qs, vs, err := q.setMap.ToInsertSql() + if err != nil { + return "", []interface{}{}, err + } + + query := "INSERT INTO `group` " + qs + + return query, vs, nil +} + +func (q groupInsertSQL) OnDuplicateKeyUpdate() groupInsertOnDuplicateKeyUpdateSQL { + return groupInsertOnDuplicateKeyUpdateSQL{ + insertSQL: q, + onDuplicateKeyUpdateMap: sqlla.SetMap{}, + } +} + +func (q groupInsertSQL) Exec(db sqlla.DB) (Group, error) { + query, args, err := q.ToSql() + if err != nil { + return Group{}, err + } + result, err := db.Exec(query, args...) + if err != nil { + return Group{}, err + } + id, err := result.LastInsertId() + if err != nil { + return Group{}, err + } + return NewGroupSQL().Select().PkColumn(id).Single(db) +} + +func (q groupInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (Group, error) { + query, args, err := q.ToSql() + if err != nil { + return Group{}, err + } + result, err := db.ExecContext(ctx, query, args...) + if err != nil { + return Group{}, err + } + id, err := result.LastInsertId() + if err != nil { + return Group{}, err + } + return NewGroupSQL().Select().PkColumn(id).SingleContext(ctx, db) +} + +func (q groupInsertSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type groupDefaultInsertHooker interface { + DefaultInsertHook(groupInsertSQL) (groupInsertSQL, error) +} + +type groupInsertSQLToSqler interface { + groupInsertSQLToSql() (string, []interface{}, error) +} + +type groupInsertOnDuplicateKeyUpdateSQL struct { + insertSQL groupInsertSQLToSqler + onDuplicateKeyUpdateMap sqlla.SetMap +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateID(v GroupID) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateID(v sqlla.SetMapRawValue) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateID() groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = sqlla.SetMapRawValue("VALUES(`id`)") + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateName(v string) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`name`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateName(v sqlla.SetMapRawValue) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`name`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateName() groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`name`"] = sqlla.SetMapRawValue("VALUES(`name`)") + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateLeaderUserID(v UserId) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`leader_user_id`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateLeaderUserID(v sqlla.SetMapRawValue) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`leader_user_id`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateLeaderUserID() groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`leader_user_id`"] = sqlla.SetMapRawValue("VALUES(`leader_user_id`)") + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateSubLeaderUserID(v sql.Null[T]) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`sub_leader_user_id`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateSubLeaderUserID(v sqlla.SetMapRawValue) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`sub_leader_user_id`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateSubLeaderUserID() groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`sub_leader_user_id`"] = sqlla.SetMapRawValue("VALUES(`sub_leader_user_id`)") + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateCreatedAt(v time.Time) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateCreatedAt(v sqlla.SetMapRawValue) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateCreatedAt() groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = sqlla.SetMapRawValue("VALUES(`created_at`)") + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v MysqlNullTime) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUpdatedAt(v sqlla.SetMapRawValue) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUpdatedAt() groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = sqlla.SetMapRawValue("VALUES(`updated_at`)") + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ToSql() (string, []interface{}, error) { + var err error + var s interface{} = Group{} + if t, ok := s.(groupDefaultInsertOnDuplicateKeyUpdateHooker); ok { + q, err = t.DefaultInsertOnDuplicateKeyUpdateHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + + query, vs, err := q.insertSQL.groupInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + + os, ovs, err := q.onDuplicateKeyUpdateMap.ToUpdateSql() + if err != nil { + return "", []interface{}{}, err + } + query += " ON DUPLICATE KEY UPDATE" + os + vs = append(vs, ovs...) + + return query + ";", vs, nil +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) (Group, error) { + query, args, err := q.ToSql() + if err != nil { + return Group{}, err + } + result, err := db.ExecContext(ctx, query, args...) + if err != nil { + return Group{}, err + } + id, err := result.LastInsertId() + if err != nil { + return Group{}, err + } + return NewGroupSQL().Select().PkColumn(id).SingleContext(ctx, db) +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type groupDefaultInsertOnDuplicateKeyUpdateHooker interface { + DefaultInsertOnDuplicateKeyUpdateHook(groupInsertOnDuplicateKeyUpdateSQL) (groupInsertOnDuplicateKeyUpdateSQL, error) +} + +type groupBulkInsertSQL struct { + insertSQLs []groupInsertSQL +} + +func (q groupSQL) BulkInsert() *groupBulkInsertSQL { + return &groupBulkInsertSQL{ + insertSQLs: []groupInsertSQL{}, + } +} + +func (q *groupBulkInsertSQL) Append(iqs ...groupInsertSQL) { + q.insertSQLs = append(q.insertSQLs, iqs...) +} + +func (q *groupBulkInsertSQL) groupInsertSQLToSql() (string, []interface{}, error) { + if len(q.insertSQLs) == 0 { + return "", []interface{}{}, fmt.Errorf("sqlla: This groupBulkInsertSQL's InsertSQL was empty") + } + iqs := make([]groupInsertSQL, len(q.insertSQLs)) + copy(iqs, q.insertSQLs) + + var s interface{} = Group{} + if t, ok := s.(groupDefaultInsertHooker); ok { + for i, iq := range iqs { + var err error + iq, err = t.DefaultInsertHook(iq) + if err != nil { + return "", []interface{}{}, err + } + iqs[i] = iq + } + } + + sms := make(sqlla.SetMaps, 0, len(q.insertSQLs)) + for _, iq := range q.insertSQLs { + sms = append(sms, iq.setMap) + } + + query, vs, err := sms.ToInsertSql() + if err != nil { + return "", []interface{}{}, err + } + + return "INSERT INTO `group` " + query, vs, nil +} + +func (q *groupBulkInsertSQL) ToSql() (string, []interface{}, error) { + query, vs, err := q.groupInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + return query + ";", vs, nil +} + +func (q *groupBulkInsertSQL) OnDuplicateKeyUpdate() groupInsertOnDuplicateKeyUpdateSQL { + return groupInsertOnDuplicateKeyUpdateSQL{ + insertSQL: q, + onDuplicateKeyUpdateMap: sqlla.SetMap{}, + } +} + +func (q *groupBulkInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type groupDeleteSQL struct { + groupSQL +} + +func (q groupSQL) Delete() groupDeleteSQL { + return groupDeleteSQL{ + q, + } +} + +func (q groupDeleteSQL) ID(v GroupID, exprs ...sqlla.Operator) groupDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) IDIn(vs ...GroupID) groupDeleteSQL { + _vs := make([]uint64, 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, uint64(v)) + } + where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) Name(v string, exprs ...sqlla.Operator) groupDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprString{Value: v, Op: op, Column: "`name`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) NameIn(vs ...string) groupDeleteSQL { + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`name`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) LeaderUserID(v UserId, exprs ...sqlla.Operator) groupDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: "`leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) LeaderUserIDIn(vs ...UserId) groupDeleteSQL { + _vs := make([]uint64, 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, uint64(v)) + } + where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) SubLeaderUserID(v sql.Null[T], exprs ...sqlla.Operator) groupDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNull[T]{Value: v, Op: op, Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) SubLeaderUserIDIn(vs ...sql.Null[T]) groupDeleteSQL { + where := sqlla.ExprMultiNull[T]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) groupDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) CreatedAtIn(vs ...time.Time) groupDeleteSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) UpdatedAt(v MysqlNullTime, exprs ...sqlla.Operator) groupDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNullTime{Value: mysql.NullTime(v), Op: op, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) UpdatedAtIn(vs ...MysqlNullTime) groupDeleteSQL { + _vs := make([]mysql.NullTime, 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, mysql.NullTime(v)) + } + where := sqlla.ExprMultiNullTime{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) ToSql() (string, []interface{}, error) { + wheres, vs, err := q.where.ToSql() + if err != nil { + return "", nil, err + } + + query := "DELETE FROM `group`" + if wheres != "" { + query += " WHERE" + wheres + } + + return query + ";", vs, nil +} + +func (q groupDeleteSQL) Exec(db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + return db.Exec(query, args...) +} + +func (q groupDeleteSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + return db.ExecContext(ctx, query, args...) +} +func (s Group) Delete(db sqlla.DB) (sql.Result, error) { + query, args, err := NewGroupSQL().Delete().ID(s.ID).ToSql() + if err != nil { + return nil, err + } + return db.Exec(query, args...) +} + +func (s Group) DeleteContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := NewGroupSQL().Delete().ID(s.ID).ToSql() + if err != nil { + return nil, err + } + return db.ExecContext(ctx, query, args...) +} diff --git a/_example/group.go b/_example/group.go new file mode 100644 index 0000000..3ada9f9 --- /dev/null +++ b/_example/group.go @@ -0,0 +1,24 @@ +package example + +import ( + "database/sql" + "time" + + "github.com/go-sql-driver/mysql" +) + +//go:generate go run ../cmd/sqlla/main.go + +type GroupID uint64 + +//sqlla:table group +//genddl:table group +type Group struct { + ID GroupID `db:"id,primarykey,autoincrement"` + Name string `db:"name"` + LeaderUserID UserId `db:"leader_user_id"` + SubLeaderUserID sql.Null[UserId] `db:"sub_leader_user_id"` + + CreatedAt time.Time `db:"created_at"` + UpdatedAt mysql.NullTime `db:"updated_at"` +} diff --git a/_example/sqlite3.sql b/_example/sqlite3.sql index eba5cb3..0a7fabf 100644 --- a/_example/sqlite3.sql +++ b/_example/sqlite3.sql @@ -1,48 +1 @@ -- generated by github.com/mackee/go-genddl. DO NOT EDIT!!! - -DROP TABLE IF EXISTS "user"; - -CREATE TABLE "user" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "name" TEXT NOT NULL, - "age" INTEGER NULL, - "rate" REAL NOT NULL DEFAULT 0, - "icon_image" BLOB NOT NULL, - "created_at" DATETIME NOT NULL, - "updated_at" DATETIME NULL, - UNIQUE ("name") -) ; - - -DROP TABLE IF EXISTS "user_external"; - -CREATE TABLE "user_external" ( - "id" INTEGER NOT NULL PRIMARY KEY, - "user_id" INTEGER NOT NULL, - "icon_image" BLOB NULL, - "created_at" DATETIME NOT NULL, - "updated_at" DATETIME NOT NULL -) ; - - -DROP TABLE IF EXISTS "user_item"; - -CREATE TABLE "user_item" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "user_id" INTEGER NOT NULL, - "item_id" TEXT NOT NULL, - "is_used" INTEGER NOT NULL, - "has_extension" INTEGER NULL, - "used_at" DATETIME NULL -) ; - - -DROP TABLE IF EXISTS "user_sns"; - -CREATE TABLE "user_sns" ( - "id" INTEGER NOT NULL PRIMARY KEY, - "sns_type" TEXT NOT NULL, - "created_at" DATETIME NOT NULL, - "updated_at" DATETIME NOT NULL -) ; - diff --git a/_example/tools.go b/_example/tools.go new file mode 100644 index 0000000..2bb6aa4 --- /dev/null +++ b/_example/tools.go @@ -0,0 +1,5 @@ +package example + +import ( + _ "github.com/mackee/go-genddl" +) diff --git a/_example/user.gen.go b/_example/user.gen.go index e71f599..e69de29 100644 --- a/_example/user.gen.go +++ b/_example/user.gen.go @@ -1,1271 +0,0 @@ -// Code generated by github.com/mackee/go-sqlla/v2/cmd/sqlla - DO NOT EDIT. -package example - -import ( - "context" - "fmt" - "strconv" - "strings" - - "database/sql" - "github.com/go-sql-driver/mysql" - "time" - - "github.com/mackee/go-sqlla/v2" -) - -type userSQL struct { - where sqlla.Where -} - -func NewUserSQL() userSQL { - q := userSQL{} - return q -} - -var userAllColumns = []string{ - "`id`", "`name`", "`age`", "`rate`", "`icon_image`", "`created_at`", "`updated_at`", -} - -type userSelectSQL struct { - userSQL - Columns []string - order string - limit *uint64 - offset *uint64 - tableAlias string - joinClauses []string - - additionalWhereClause string - additionalWhereClauseArgs []interface{} - - groupByColumns []string - - isForUpdate bool -} - -func (q userSQL) Select() userSelectSQL { - return userSelectSQL{ - q, - userAllColumns, - "", - nil, - nil, - "", - nil, - "", - nil, - nil, - false, - } -} - -func (q userSelectSQL) Or(qs ...userSelectSQL) userSelectSQL { - ws := make([]sqlla.Where, 0, len(qs)) - for _, q := range qs { - ws = append(ws, q.where) - } - q.where = append(q.where, sqlla.ExprOr(ws)) - return q -} - -func (q userSelectSQL) Limit(l uint64) userSelectSQL { - q.limit = &l - return q -} - -func (q userSelectSQL) Offset(o uint64) userSelectSQL { - q.offset = &o - return q -} - -func (q userSelectSQL) ForUpdate() userSelectSQL { - q.isForUpdate = true - return q -} - -func (q userSelectSQL) TableAlias(alias string) userSelectSQL { - q.tableAlias = "`" + alias + "`" - return q -} - -func (q userSelectSQL) SetColumns(columns ...string) userSelectSQL { - q.Columns = make([]string, 0, len(columns)) - for _, column := range columns { - if strings.ContainsAny(column, "(.`") { - q.Columns = append(q.Columns, column) - } else { - q.Columns = append(q.Columns, "`"+column+"`") - } - } - return q -} - -func (q userSelectSQL) JoinClause(clause string) userSelectSQL { - q.joinClauses = append(q.joinClauses, clause) - return q -} - -func (q userSelectSQL) AdditionalWhereClause(clause string, args ...interface{}) userSelectSQL { - q.additionalWhereClause = clause - q.additionalWhereClauseArgs = args - return q -} - -func (q userSelectSQL) appendColumnPrefix(column string) string { - if q.tableAlias == "" || strings.ContainsAny(column, "(.") { - return column - } - return q.tableAlias + "." + column -} - -func (q userSelectSQL) GroupBy(columns ...string) userSelectSQL { - q.groupByColumns = make([]string, 0, len(columns)) - for _, column := range columns { - if strings.ContainsAny(column, "(.`") { - q.groupByColumns = append(q.groupByColumns, column) - } else { - q.groupByColumns = append(q.groupByColumns, "`"+column+"`") - } - } - return q -} - -func (q userSelectSQL) ID(v UserId, exprs ...sqlla.Operator) userSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: q.appendColumnPrefix("`id`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) IDIn(vs ...UserId) userSelectSQL { - _vs := make([]uint64, 0, len(vs)) - for _, v := range vs { - _vs = append(_vs, uint64(v)) - } - where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`id`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) PkColumn(pk int64, exprs ...sqlla.Operator) userSelectSQL { - v := UserId(pk) - return q.ID(v, exprs...) -} - -func (q userSelectSQL) OrderByID(order sqlla.Order) userSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`id`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userSelectSQL) Name(v string, exprs ...sqlla.Operator) userSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprString{Value: v, Op: op, Column: q.appendColumnPrefix("`name`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) NameIn(vs ...string) userSelectSQL { - where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`name`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) OrderByName(order sqlla.Order) userSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`name`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userSelectSQL) Age(v sql.NullInt64, exprs ...sqlla.Operator) userSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprNullInt64{Value: v, Op: op, Column: q.appendColumnPrefix("`age`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) AgeIn(vs ...sql.NullInt64) userSelectSQL { - where := sqlla.ExprMultiNullInt64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`age`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) OrderByAge(order sqlla.Order) userSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`age`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userSelectSQL) Rate(v float64, exprs ...sqlla.Operator) userSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprFloat64{Value: v, Op: op, Column: q.appendColumnPrefix("`rate`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) RateIn(vs ...float64) userSelectSQL { - where := sqlla.ExprMultiFloat64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`rate`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) OrderByRate(order sqlla.Order) userSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`rate`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userSelectSQL) IconImage(v []byte, exprs ...sqlla.Operator) userSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprBytes{Value: v, Op: op, Column: q.appendColumnPrefix("`icon_image`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) IconImageIn(vs ...[]byte) userSelectSQL { - where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`icon_image`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) OrderByIconImage(order sqlla.Order) userSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`icon_image`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userSelectSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: q.appendColumnPrefix("`created_at`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) CreatedAtIn(vs ...time.Time) userSelectSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`created_at`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) OrderByCreatedAt(order sqlla.Order) userSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`created_at`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userSelectSQL) UpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) userSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: q.appendColumnPrefix("`updated_at`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) UpdatedAtIn(vs ...mysql.NullTime) userSelectSQL { - where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`updated_at`")} - q.where = append(q.where, where) - return q -} - -func (q userSelectSQL) OrderByUpdatedAt(order sqlla.Order) userSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`updated_at`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userSelectSQL) ToSql() (string, []interface{}, error) { - columns := strings.Join(q.Columns, ", ") - wheres, vs, err := q.where.ToSql() - if err != nil { - return "", nil, err - } - - tableName := "`user`" - if q.tableAlias != "" { - tableName = tableName + " AS " + q.tableAlias - pcs := make([]string, 0, len(q.Columns)) - for _, column := range q.Columns { - pcs = append(pcs, q.appendColumnPrefix(column)) - } - columns = strings.Join(pcs, ", ") - } - query := "SELECT " + columns + " FROM " + tableName - if len(q.joinClauses) > 0 { - jc := strings.Join(q.joinClauses, " ") - query += " " + jc - } - if wheres != "" { - query += " WHERE" + wheres - } - if q.additionalWhereClause != "" { - query += " " + q.additionalWhereClause - if len(q.additionalWhereClauseArgs) > 0 { - vs = append(vs, q.additionalWhereClauseArgs...) - } - } - if len(q.groupByColumns) > 0 { - query += " GROUP BY " - gbcs := make([]string, 0, len(q.groupByColumns)) - for _, column := range q.groupByColumns { - gbcs = append(gbcs, q.appendColumnPrefix(column)) - } - query += strings.Join(gbcs, ", ") - } - query += q.order - if q.limit != nil { - query += " LIMIT " + strconv.FormatUint(*q.limit, 10) - } - if q.offset != nil { - query += " OFFSET " + strconv.FormatUint(*q.offset, 10) - } - - if q.isForUpdate { - query += " FOR UPDATE" - } - - return query + ";", vs, nil -} - -func (s User) Select() userSelectSQL { - return NewUserSQL().Select().ID(s.Id) -} -func (q userSelectSQL) Single(db sqlla.DB) (User, error) { - q.Columns = userAllColumns - query, args, err := q.ToSql() - if err != nil { - return User{}, err - } - - row := db.QueryRow(query, args...) - return q.Scan(row) -} - -func (q userSelectSQL) SingleContext(ctx context.Context, db sqlla.DB) (User, error) { - q.Columns = userAllColumns - query, args, err := q.ToSql() - if err != nil { - return User{}, err - } - - row := db.QueryRowContext(ctx, query, args...) - return q.Scan(row) -} - -func (q userSelectSQL) All(db sqlla.DB) ([]User, error) { - rs := make([]User, 0, 10) - q.Columns = userAllColumns - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - - rows, err := db.Query(query, args...) - if err != nil { - return nil, err - } - defer rows.Close() - for rows.Next() { - r, err := q.Scan(rows) - if err != nil { - return nil, err - } - rs = append(rs, r) - } - return rs, nil -} - -func (q userSelectSQL) AllContext(ctx context.Context, db sqlla.DB) ([]User, error) { - rs := make([]User, 0, 10) - q.Columns = userAllColumns - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - - rows, err := db.QueryContext(ctx, query, args...) - if err != nil { - return nil, err - } - defer rows.Close() - for rows.Next() { - r, err := q.Scan(rows) - if err != nil { - return nil, err - } - rs = append(rs, r) - } - return rs, nil -} - -func (q userSelectSQL) Scan(s sqlla.Scanner) (User, error) { - var row User - err := s.Scan( - &row.Id, - &row.Name, - &row.Age, - &row.Rate, - &row.IconImage, - &row.CreatedAt, - &row.UpdatedAt, - ) - return row, err -} - -type userUpdateSQL struct { - userSQL - setMap sqlla.SetMap - Columns []string -} - -func (q userSQL) Update() userUpdateSQL { - return userUpdateSQL{ - userSQL: q, - setMap: sqlla.SetMap{}, - } -} - -func (q userUpdateSQL) SetID(v UserId) userUpdateSQL { - q.setMap["`id`"] = v - return q -} - -func (q userUpdateSQL) WhereID(v UserId, exprs ...sqlla.Operator) userUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) WhereIDIn(vs ...UserId) userUpdateSQL { - _vs := make([]uint64, 0, len(vs)) - for _, v := range vs { - _vs = append(_vs, uint64(v)) - } - where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) SetName(v string) userUpdateSQL { - q.setMap["`name`"] = v - return q -} - -func (q userUpdateSQL) WhereName(v string, exprs ...sqlla.Operator) userUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprString{Value: v, Op: op, Column: "`name`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) WhereNameIn(vs ...string) userUpdateSQL { - where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`name`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) SetAge(v sql.NullInt64) userUpdateSQL { - q.setMap["`age`"] = v - return q -} - -func (q userUpdateSQL) WhereAge(v sql.NullInt64, exprs ...sqlla.Operator) userUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprNullInt64{Value: v, Op: op, Column: "`age`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) WhereAgeIn(vs ...sql.NullInt64) userUpdateSQL { - where := sqlla.ExprMultiNullInt64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`age`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) SetRate(v float64) userUpdateSQL { - q.setMap["`rate`"] = v - return q -} - -func (q userUpdateSQL) WhereRate(v float64, exprs ...sqlla.Operator) userUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprFloat64{Value: v, Op: op, Column: "`rate`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) WhereRateIn(vs ...float64) userUpdateSQL { - where := sqlla.ExprMultiFloat64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`rate`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) SetIconImage(v []byte) userUpdateSQL { - q.setMap["`icon_image`"] = v - return q -} - -func (q userUpdateSQL) WhereIconImage(v []byte, exprs ...sqlla.Operator) userUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprBytes{Value: v, Op: op, Column: "`icon_image`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) WhereIconImageIn(vs ...[]byte) userUpdateSQL { - where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`icon_image`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) SetCreatedAt(v time.Time) userUpdateSQL { - q.setMap["`created_at`"] = v - return q -} - -func (q userUpdateSQL) WhereCreatedAt(v time.Time, exprs ...sqlla.Operator) userUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) WhereCreatedAtIn(vs ...time.Time) userUpdateSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) SetUpdatedAt(v mysql.NullTime) userUpdateSQL { - q.setMap["`updated_at`"] = v - return q -} - -func (q userUpdateSQL) WhereUpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) userUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) WhereUpdatedAtIn(vs ...mysql.NullTime) userUpdateSQL { - where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userUpdateSQL) ToSql() (string, []interface{}, error) { - var err error - var s interface{} = User{} - if t, ok := s.(userDefaultUpdateHooker); ok { - q, err = t.DefaultUpdateHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - setColumns, svs, err := q.setMap.ToUpdateSql() - if err != nil { - return "", []interface{}{}, err - } - wheres, wvs, err := q.where.ToSql() - if err != nil { - return "", []interface{}{}, err - } - - query := "UPDATE `user` SET" + setColumns - if wheres != "" { - query += " WHERE" + wheres - } - - return query + ";", append(svs, wvs...), nil -} -func (s User) Update() userUpdateSQL { - return NewUserSQL().Update().WhereID(s.Id) -} - -func (q userUpdateSQL) Exec(db sqlla.DB) ([]User, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - _, err = db.Exec(query, args...) - if err != nil { - return nil, err - } - qq := q.userSQL - - return qq.Select().All(db) -} - -func (q userUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) ([]User, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - _, err = db.ExecContext(ctx, query, args...) - if err != nil { - return nil, err - } - qq := q.userSQL - - return qq.Select().AllContext(ctx, db) -} - -type userDefaultUpdateHooker interface { - DefaultUpdateHook(userUpdateSQL) (userUpdateSQL, error) -} - -type userInsertSQL struct { - userSQL - setMap sqlla.SetMap - Columns []string -} - -func (q userSQL) Insert() userInsertSQL { - return userInsertSQL{ - userSQL: q, - setMap: sqlla.SetMap{}, - } -} - -func (q userInsertSQL) ValueID(v UserId) userInsertSQL { - q.setMap["`id`"] = v - return q -} - -func (q userInsertSQL) ValueName(v string) userInsertSQL { - q.setMap["`name`"] = v - return q -} - -func (q userInsertSQL) ValueAge(v sql.NullInt64) userInsertSQL { - q.setMap["`age`"] = v - return q -} - -func (q userInsertSQL) ValueRate(v float64) userInsertSQL { - q.setMap["`rate`"] = v - return q -} - -func (q userInsertSQL) ValueIconImage(v []byte) userInsertSQL { - q.setMap["`icon_image`"] = v - return q -} - -func (q userInsertSQL) ValueCreatedAt(v time.Time) userInsertSQL { - q.setMap["`created_at`"] = v - return q -} - -func (q userInsertSQL) ValueUpdatedAt(v mysql.NullTime) userInsertSQL { - q.setMap["`updated_at`"] = v - return q -} - -func (q userInsertSQL) ToSql() (string, []interface{}, error) { - query, vs, err := q.userInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - return query + ";", vs, nil -} - -func (q userInsertSQL) userInsertSQLToSql() (string, []interface{}, error) { - var err error - var s interface{} = User{} - if t, ok := s.(userDefaultInsertHooker); ok { - q, err = t.DefaultInsertHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - qs, vs, err := q.setMap.ToInsertSql() - if err != nil { - return "", []interface{}{}, err - } - - query := "INSERT INTO `user` " + qs - - return query, vs, nil -} - -func (q userInsertSQL) OnDuplicateKeyUpdate() userInsertOnDuplicateKeyUpdateSQL { - return userInsertOnDuplicateKeyUpdateSQL{ - insertSQL: q, - onDuplicateKeyUpdateMap: sqlla.SetMap{}, - } -} - -func (q userInsertSQL) Exec(db sqlla.DB) (User, error) { - query, args, err := q.ToSql() - if err != nil { - return User{}, err - } - result, err := db.Exec(query, args...) - if err != nil { - return User{}, err - } - id, err := result.LastInsertId() - if err != nil { - return User{}, err - } - return NewUserSQL().Select().PkColumn(id).Single(db) -} - -func (q userInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (User, error) { - query, args, err := q.ToSql() - if err != nil { - return User{}, err - } - result, err := db.ExecContext(ctx, query, args...) - if err != nil { - return User{}, err - } - id, err := result.LastInsertId() - if err != nil { - return User{}, err - } - return NewUserSQL().Select().PkColumn(id).SingleContext(ctx, db) -} - -func (q userInsertSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userDefaultInsertHooker interface { - DefaultInsertHook(userInsertSQL) (userInsertSQL, error) -} - -type userInsertSQLToSqler interface { - userInsertSQLToSql() (string, []interface{}, error) -} - -type userInsertOnDuplicateKeyUpdateSQL struct { - insertSQL userInsertSQLToSqler - onDuplicateKeyUpdateMap sqlla.SetMap -} - -func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateID(v UserId) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateID(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateID() userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = sqlla.SetMapRawValue("VALUES(`id`)") - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateName(v string) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`name`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateName(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`name`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateName() userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`name`"] = sqlla.SetMapRawValue("VALUES(`name`)") - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateAge(v sql.NullInt64) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`age`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateAge(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`age`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateAge() userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`age`"] = sqlla.SetMapRawValue("VALUES(`age`)") - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateRate(v float64) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`rate`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateRate(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`rate`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateRate() userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`rate`"] = sqlla.SetMapRawValue("VALUES(`rate`)") - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateIconImage(v []byte) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`icon_image`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateIconImage(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`icon_image`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateIconImage() userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`icon_image`"] = sqlla.SetMapRawValue("VALUES(`icon_image`)") - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateCreatedAt(v time.Time) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`created_at`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateCreatedAt(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`created_at`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateCreatedAt() userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`created_at`"] = sqlla.SetMapRawValue("VALUES(`created_at`)") - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v mysql.NullTime) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`updated_at`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUpdatedAt(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`updated_at`"] = v - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUpdatedAt() userInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`updated_at`"] = sqlla.SetMapRawValue("VALUES(`updated_at`)") - return q -} - -func (q userInsertOnDuplicateKeyUpdateSQL) ToSql() (string, []interface{}, error) { - var err error - var s interface{} = User{} - if t, ok := s.(userDefaultInsertOnDuplicateKeyUpdateHooker); ok { - q, err = t.DefaultInsertOnDuplicateKeyUpdateHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - - query, vs, err := q.insertSQL.userInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - - os, ovs, err := q.onDuplicateKeyUpdateMap.ToUpdateSql() - if err != nil { - return "", []interface{}{}, err - } - query += " ON DUPLICATE KEY UPDATE" + os - vs = append(vs, ovs...) - - return query + ";", vs, nil -} - -func (q userInsertOnDuplicateKeyUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) (User, error) { - query, args, err := q.ToSql() - if err != nil { - return User{}, err - } - result, err := db.ExecContext(ctx, query, args...) - if err != nil { - return User{}, err - } - id, err := result.LastInsertId() - if err != nil { - return User{}, err - } - return NewUserSQL().Select().PkColumn(id).SingleContext(ctx, db) -} - -func (q userInsertOnDuplicateKeyUpdateSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userDefaultInsertOnDuplicateKeyUpdateHooker interface { - DefaultInsertOnDuplicateKeyUpdateHook(userInsertOnDuplicateKeyUpdateSQL) (userInsertOnDuplicateKeyUpdateSQL, error) -} - -type userBulkInsertSQL struct { - insertSQLs []userInsertSQL -} - -func (q userSQL) BulkInsert() *userBulkInsertSQL { - return &userBulkInsertSQL{ - insertSQLs: []userInsertSQL{}, - } -} - -func (q *userBulkInsertSQL) Append(iqs ...userInsertSQL) { - q.insertSQLs = append(q.insertSQLs, iqs...) -} - -func (q *userBulkInsertSQL) userInsertSQLToSql() (string, []interface{}, error) { - if len(q.insertSQLs) == 0 { - return "", []interface{}{}, fmt.Errorf("sqlla: This userBulkInsertSQL's InsertSQL was empty") - } - iqs := make([]userInsertSQL, len(q.insertSQLs)) - copy(iqs, q.insertSQLs) - - var s interface{} = User{} - if t, ok := s.(userDefaultInsertHooker); ok { - for i, iq := range iqs { - var err error - iq, err = t.DefaultInsertHook(iq) - if err != nil { - return "", []interface{}{}, err - } - iqs[i] = iq - } - } - - sms := make(sqlla.SetMaps, 0, len(q.insertSQLs)) - for _, iq := range q.insertSQLs { - sms = append(sms, iq.setMap) - } - - query, vs, err := sms.ToInsertSql() - if err != nil { - return "", []interface{}{}, err - } - - return "INSERT INTO `user` " + query, vs, nil -} - -func (q *userBulkInsertSQL) ToSql() (string, []interface{}, error) { - query, vs, err := q.userInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - return query + ";", vs, nil -} - -func (q *userBulkInsertSQL) OnDuplicateKeyUpdate() userInsertOnDuplicateKeyUpdateSQL { - return userInsertOnDuplicateKeyUpdateSQL{ - insertSQL: q, - onDuplicateKeyUpdateMap: sqlla.SetMap{}, - } -} - -func (q *userBulkInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userDeleteSQL struct { - userSQL -} - -func (q userSQL) Delete() userDeleteSQL { - return userDeleteSQL{ - q, - } -} - -func (q userDeleteSQL) ID(v UserId, exprs ...sqlla.Operator) userDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) IDIn(vs ...UserId) userDeleteSQL { - _vs := make([]uint64, 0, len(vs)) - for _, v := range vs { - _vs = append(_vs, uint64(v)) - } - where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) Name(v string, exprs ...sqlla.Operator) userDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprString{Value: v, Op: op, Column: "`name`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) NameIn(vs ...string) userDeleteSQL { - where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`name`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) Age(v sql.NullInt64, exprs ...sqlla.Operator) userDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprNullInt64{Value: v, Op: op, Column: "`age`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) AgeIn(vs ...sql.NullInt64) userDeleteSQL { - where := sqlla.ExprMultiNullInt64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`age`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) Rate(v float64, exprs ...sqlla.Operator) userDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprFloat64{Value: v, Op: op, Column: "`rate`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) RateIn(vs ...float64) userDeleteSQL { - where := sqlla.ExprMultiFloat64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`rate`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) IconImage(v []byte, exprs ...sqlla.Operator) userDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprBytes{Value: v, Op: op, Column: "`icon_image`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) IconImageIn(vs ...[]byte) userDeleteSQL { - where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`icon_image`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) CreatedAtIn(vs ...time.Time) userDeleteSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) UpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) userDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) UpdatedAtIn(vs ...mysql.NullTime) userDeleteSQL { - where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userDeleteSQL) ToSql() (string, []interface{}, error) { - wheres, vs, err := q.where.ToSql() - if err != nil { - return "", nil, err - } - - query := "DELETE FROM `user`" - if wheres != "" { - query += " WHERE" + wheres - } - - return query + ";", vs, nil -} - -func (q userDeleteSQL) Exec(db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - return db.Exec(query, args...) -} - -func (q userDeleteSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - return db.ExecContext(ctx, query, args...) -} -func (s User) Delete(db sqlla.DB) (sql.Result, error) { - query, args, err := NewUserSQL().Delete().ID(s.Id).ToSql() - if err != nil { - return nil, err - } - return db.Exec(query, args...) -} - -func (s User) DeleteContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := NewUserSQL().Delete().ID(s.Id).ToSql() - if err != nil { - return nil, err - } - return db.ExecContext(ctx, query, args...) -} diff --git a/_example/user.go b/_example/user.go index 3ee1b82..e938034 100644 --- a/_example/user.go +++ b/_example/user.go @@ -9,7 +9,7 @@ import ( ) //go:generate go run ../cmd/sqlla/main.go -//go:generate genddl -outpath=./sqlite3.sql -driver=sqlite3 +//go:generate go run github.com/mackee/go-genddl/cmd/genddl -outpath=./sqlite3.sql -driver=sqlite3 type UserId uint64 diff --git a/_example/user_external.gen.go b/_example/user_external.gen.go index d8b2a14..e69de29 100644 --- a/_example/user_external.gen.go +++ b/_example/user_external.gen.go @@ -1,1076 +0,0 @@ -// Code generated by github.com/mackee/go-sqlla/v2/cmd/sqlla - DO NOT EDIT. -package example - -import ( - "context" - "fmt" - "strconv" - "strings" - - "database/sql" - "time" - - "github.com/mackee/go-sqlla/v2" -) - -type userExternalSQL struct { - where sqlla.Where -} - -func NewUserExternalSQL() userExternalSQL { - q := userExternalSQL{} - return q -} - -var userExternalAllColumns = []string{ - "`id`", "`user_id`", "`icon_image`", "`created_at`", "`updated_at`", -} - -type userExternalSelectSQL struct { - userExternalSQL - Columns []string - order string - limit *uint64 - offset *uint64 - tableAlias string - joinClauses []string - - additionalWhereClause string - additionalWhereClauseArgs []interface{} - - groupByColumns []string - - isForUpdate bool -} - -func (q userExternalSQL) Select() userExternalSelectSQL { - return userExternalSelectSQL{ - q, - userExternalAllColumns, - "", - nil, - nil, - "", - nil, - "", - nil, - nil, - false, - } -} - -func (q userExternalSelectSQL) Or(qs ...userExternalSelectSQL) userExternalSelectSQL { - ws := make([]sqlla.Where, 0, len(qs)) - for _, q := range qs { - ws = append(ws, q.where) - } - q.where = append(q.where, sqlla.ExprOr(ws)) - return q -} - -func (q userExternalSelectSQL) Limit(l uint64) userExternalSelectSQL { - q.limit = &l - return q -} - -func (q userExternalSelectSQL) Offset(o uint64) userExternalSelectSQL { - q.offset = &o - return q -} - -func (q userExternalSelectSQL) ForUpdate() userExternalSelectSQL { - q.isForUpdate = true - return q -} - -func (q userExternalSelectSQL) TableAlias(alias string) userExternalSelectSQL { - q.tableAlias = "`" + alias + "`" - return q -} - -func (q userExternalSelectSQL) SetColumns(columns ...string) userExternalSelectSQL { - q.Columns = make([]string, 0, len(columns)) - for _, column := range columns { - if strings.ContainsAny(column, "(.`") { - q.Columns = append(q.Columns, column) - } else { - q.Columns = append(q.Columns, "`"+column+"`") - } - } - return q -} - -func (q userExternalSelectSQL) JoinClause(clause string) userExternalSelectSQL { - q.joinClauses = append(q.joinClauses, clause) - return q -} - -func (q userExternalSelectSQL) AdditionalWhereClause(clause string, args ...interface{}) userExternalSelectSQL { - q.additionalWhereClause = clause - q.additionalWhereClauseArgs = args - return q -} - -func (q userExternalSelectSQL) appendColumnPrefix(column string) string { - if q.tableAlias == "" || strings.ContainsAny(column, "(.") { - return column - } - return q.tableAlias + "." + column -} - -func (q userExternalSelectSQL) GroupBy(columns ...string) userExternalSelectSQL { - q.groupByColumns = make([]string, 0, len(columns)) - for _, column := range columns { - if strings.ContainsAny(column, "(.`") { - q.groupByColumns = append(q.groupByColumns, column) - } else { - q.groupByColumns = append(q.groupByColumns, "`"+column+"`") - } - } - return q -} - -func (q userExternalSelectSQL) ID(v uint64, exprs ...sqlla.Operator) userExternalSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: q.appendColumnPrefix("`id`")} - q.where = append(q.where, where) - return q -} - -func (q userExternalSelectSQL) IDIn(vs ...uint64) userExternalSelectSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`id`")} - q.where = append(q.where, where) - return q -} - -func (q userExternalSelectSQL) PkColumn(pk int64, exprs ...sqlla.Operator) userExternalSelectSQL { - v := uint64(pk) - return q.ID(v, exprs...) -} - -func (q userExternalSelectSQL) OrderByID(order sqlla.Order) userExternalSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`id`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userExternalSelectSQL) UserID(v uint64, exprs ...sqlla.Operator) userExternalSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: q.appendColumnPrefix("`user_id`")} - q.where = append(q.where, where) - return q -} - -func (q userExternalSelectSQL) UserIDIn(vs ...uint64) userExternalSelectSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`user_id`")} - q.where = append(q.where, where) - return q -} - -func (q userExternalSelectSQL) OrderByUserID(order sqlla.Order) userExternalSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`user_id`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userExternalSelectSQL) IconImage(v []byte, exprs ...sqlla.Operator) userExternalSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprBytes{Value: v, Op: op, Column: q.appendColumnPrefix("`icon_image`")} - q.where = append(q.where, where) - return q -} - -func (q userExternalSelectSQL) IconImageIn(vs ...[]byte) userExternalSelectSQL { - where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`icon_image`")} - q.where = append(q.where, where) - return q -} - -func (q userExternalSelectSQL) OrderByIconImage(order sqlla.Order) userExternalSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`icon_image`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userExternalSelectSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userExternalSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: q.appendColumnPrefix("`created_at`")} - q.where = append(q.where, where) - return q -} - -func (q userExternalSelectSQL) CreatedAtIn(vs ...time.Time) userExternalSelectSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`created_at`")} - q.where = append(q.where, where) - return q -} - -func (q userExternalSelectSQL) OrderByCreatedAt(order sqlla.Order) userExternalSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`created_at`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userExternalSelectSQL) UpdatedAt(v time.Time, exprs ...sqlla.Operator) userExternalSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: q.appendColumnPrefix("`updated_at`")} - q.where = append(q.where, where) - return q -} - -func (q userExternalSelectSQL) UpdatedAtIn(vs ...time.Time) userExternalSelectSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`updated_at`")} - q.where = append(q.where, where) - return q -} - -func (q userExternalSelectSQL) OrderByUpdatedAt(order sqlla.Order) userExternalSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`updated_at`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userExternalSelectSQL) ToSql() (string, []interface{}, error) { - columns := strings.Join(q.Columns, ", ") - wheres, vs, err := q.where.ToSql() - if err != nil { - return "", nil, err - } - - tableName := "`user_external`" - if q.tableAlias != "" { - tableName = tableName + " AS " + q.tableAlias - pcs := make([]string, 0, len(q.Columns)) - for _, column := range q.Columns { - pcs = append(pcs, q.appendColumnPrefix(column)) - } - columns = strings.Join(pcs, ", ") - } - query := "SELECT " + columns + " FROM " + tableName - if len(q.joinClauses) > 0 { - jc := strings.Join(q.joinClauses, " ") - query += " " + jc - } - if wheres != "" { - query += " WHERE" + wheres - } - if q.additionalWhereClause != "" { - query += " " + q.additionalWhereClause - if len(q.additionalWhereClauseArgs) > 0 { - vs = append(vs, q.additionalWhereClauseArgs...) - } - } - if len(q.groupByColumns) > 0 { - query += " GROUP BY " - gbcs := make([]string, 0, len(q.groupByColumns)) - for _, column := range q.groupByColumns { - gbcs = append(gbcs, q.appendColumnPrefix(column)) - } - query += strings.Join(gbcs, ", ") - } - query += q.order - if q.limit != nil { - query += " LIMIT " + strconv.FormatUint(*q.limit, 10) - } - if q.offset != nil { - query += " OFFSET " + strconv.FormatUint(*q.offset, 10) - } - - if q.isForUpdate { - query += " FOR UPDATE" - } - - return query + ";", vs, nil -} - -func (s UserExternal) Select() userExternalSelectSQL { - return NewUserExternalSQL().Select().ID(s.Id) -} -func (q userExternalSelectSQL) Single(db sqlla.DB) (UserExternal, error) { - q.Columns = userExternalAllColumns - query, args, err := q.ToSql() - if err != nil { - return UserExternal{}, err - } - - row := db.QueryRow(query, args...) - return q.Scan(row) -} - -func (q userExternalSelectSQL) SingleContext(ctx context.Context, db sqlla.DB) (UserExternal, error) { - q.Columns = userExternalAllColumns - query, args, err := q.ToSql() - if err != nil { - return UserExternal{}, err - } - - row := db.QueryRowContext(ctx, query, args...) - return q.Scan(row) -} - -func (q userExternalSelectSQL) All(db sqlla.DB) ([]UserExternal, error) { - rs := make([]UserExternal, 0, 10) - q.Columns = userExternalAllColumns - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - - rows, err := db.Query(query, args...) - if err != nil { - return nil, err - } - defer rows.Close() - for rows.Next() { - r, err := q.Scan(rows) - if err != nil { - return nil, err - } - rs = append(rs, r) - } - return rs, nil -} - -func (q userExternalSelectSQL) AllContext(ctx context.Context, db sqlla.DB) ([]UserExternal, error) { - rs := make([]UserExternal, 0, 10) - q.Columns = userExternalAllColumns - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - - rows, err := db.QueryContext(ctx, query, args...) - if err != nil { - return nil, err - } - defer rows.Close() - for rows.Next() { - r, err := q.Scan(rows) - if err != nil { - return nil, err - } - rs = append(rs, r) - } - return rs, nil -} - -func (q userExternalSelectSQL) Scan(s sqlla.Scanner) (UserExternal, error) { - var row UserExternal - err := s.Scan( - &row.Id, - &row.UserId, - &row.IconImage, - &row.CreatedAt, - &row.UpdatedAt, - ) - return row, err -} - -type userExternalUpdateSQL struct { - userExternalSQL - setMap sqlla.SetMap - Columns []string -} - -func (q userExternalSQL) Update() userExternalUpdateSQL { - return userExternalUpdateSQL{ - userExternalSQL: q, - setMap: sqlla.SetMap{}, - } -} - -func (q userExternalUpdateSQL) SetID(v uint64) userExternalUpdateSQL { - q.setMap["`id`"] = v - return q -} - -func (q userExternalUpdateSQL) WhereID(v uint64, exprs ...sqlla.Operator) userExternalUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalUpdateSQL) WhereIDIn(vs ...uint64) userExternalUpdateSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalUpdateSQL) SetUserID(v uint64) userExternalUpdateSQL { - q.setMap["`user_id`"] = v - return q -} - -func (q userExternalUpdateSQL) WhereUserID(v uint64, exprs ...sqlla.Operator) userExternalUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: "`user_id`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalUpdateSQL) WhereUserIDIn(vs ...uint64) userExternalUpdateSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`user_id`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalUpdateSQL) SetIconImage(v []byte) userExternalUpdateSQL { - q.setMap["`icon_image`"] = v - return q -} - -func (q userExternalUpdateSQL) WhereIconImage(v []byte, exprs ...sqlla.Operator) userExternalUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprBytes{Value: v, Op: op, Column: "`icon_image`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalUpdateSQL) WhereIconImageIn(vs ...[]byte) userExternalUpdateSQL { - where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`icon_image`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalUpdateSQL) SetCreatedAt(v time.Time) userExternalUpdateSQL { - q.setMap["`created_at`"] = v - return q -} - -func (q userExternalUpdateSQL) WhereCreatedAt(v time.Time, exprs ...sqlla.Operator) userExternalUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalUpdateSQL) WhereCreatedAtIn(vs ...time.Time) userExternalUpdateSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalUpdateSQL) SetUpdatedAt(v time.Time) userExternalUpdateSQL { - q.setMap["`updated_at`"] = v - return q -} - -func (q userExternalUpdateSQL) WhereUpdatedAt(v time.Time, exprs ...sqlla.Operator) userExternalUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalUpdateSQL) WhereUpdatedAtIn(vs ...time.Time) userExternalUpdateSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalUpdateSQL) ToSql() (string, []interface{}, error) { - var err error - var s interface{} = UserExternal{} - if t, ok := s.(userExternalDefaultUpdateHooker); ok { - q, err = t.DefaultUpdateHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - setColumns, svs, err := q.setMap.ToUpdateSql() - if err != nil { - return "", []interface{}{}, err - } - wheres, wvs, err := q.where.ToSql() - if err != nil { - return "", []interface{}{}, err - } - - query := "UPDATE `user_external` SET" + setColumns - if wheres != "" { - query += " WHERE" + wheres - } - - return query + ";", append(svs, wvs...), nil -} -func (s UserExternal) Update() userExternalUpdateSQL { - return NewUserExternalSQL().Update().WhereID(s.Id) -} - -func (q userExternalUpdateSQL) Exec(db sqlla.DB) ([]UserExternal, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - _, err = db.Exec(query, args...) - if err != nil { - return nil, err - } - qq := q.userExternalSQL - - return qq.Select().All(db) -} - -func (q userExternalUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) ([]UserExternal, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - _, err = db.ExecContext(ctx, query, args...) - if err != nil { - return nil, err - } - qq := q.userExternalSQL - - return qq.Select().AllContext(ctx, db) -} - -type userExternalDefaultUpdateHooker interface { - DefaultUpdateHook(userExternalUpdateSQL) (userExternalUpdateSQL, error) -} - -type userExternalInsertSQL struct { - userExternalSQL - setMap sqlla.SetMap - Columns []string -} - -func (q userExternalSQL) Insert() userExternalInsertSQL { - return userExternalInsertSQL{ - userExternalSQL: q, - setMap: sqlla.SetMap{}, - } -} - -func (q userExternalInsertSQL) ValueID(v uint64) userExternalInsertSQL { - q.setMap["`id`"] = v - return q -} - -func (q userExternalInsertSQL) ValueUserID(v uint64) userExternalInsertSQL { - q.setMap["`user_id`"] = v - return q -} - -func (q userExternalInsertSQL) ValueIconImage(v []byte) userExternalInsertSQL { - q.setMap["`icon_image`"] = v - return q -} - -func (q userExternalInsertSQL) ValueCreatedAt(v time.Time) userExternalInsertSQL { - q.setMap["`created_at`"] = v - return q -} - -func (q userExternalInsertSQL) ValueUpdatedAt(v time.Time) userExternalInsertSQL { - q.setMap["`updated_at`"] = v - return q -} - -func (q userExternalInsertSQL) ToSql() (string, []interface{}, error) { - query, vs, err := q.userExternalInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - return query + ";", vs, nil -} - -func (q userExternalInsertSQL) userExternalInsertSQLToSql() (string, []interface{}, error) { - var err error - var s interface{} = UserExternal{} - if t, ok := s.(userExternalDefaultInsertHooker); ok { - q, err = t.DefaultInsertHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - qs, vs, err := q.setMap.ToInsertSql() - if err != nil { - return "", []interface{}{}, err - } - - query := "INSERT INTO `user_external` " + qs - - return query, vs, nil -} - -func (q userExternalInsertSQL) OnDuplicateKeyUpdate() userExternalInsertOnDuplicateKeyUpdateSQL { - return userExternalInsertOnDuplicateKeyUpdateSQL{ - insertSQL: q, - onDuplicateKeyUpdateMap: sqlla.SetMap{}, - } -} - -func (q userExternalInsertSQL) Exec(db sqlla.DB) (UserExternal, error) { - query, args, err := q.ToSql() - if err != nil { - return UserExternal{}, err - } - result, err := db.Exec(query, args...) - if err != nil { - return UserExternal{}, err - } - id, err := result.LastInsertId() - if err != nil { - return UserExternal{}, err - } - return NewUserExternalSQL().Select().PkColumn(id).Single(db) -} - -func (q userExternalInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserExternal, error) { - query, args, err := q.ToSql() - if err != nil { - return UserExternal{}, err - } - result, err := db.ExecContext(ctx, query, args...) - if err != nil { - return UserExternal{}, err - } - id, err := result.LastInsertId() - if err != nil { - return UserExternal{}, err - } - return NewUserExternalSQL().Select().PkColumn(id).SingleContext(ctx, db) -} - -func (q userExternalInsertSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userExternalDefaultInsertHooker interface { - DefaultInsertHook(userExternalInsertSQL) (userExternalInsertSQL, error) -} - -type userExternalInsertSQLToSqler interface { - userExternalInsertSQLToSql() (string, []interface{}, error) -} - -type userExternalInsertOnDuplicateKeyUpdateSQL struct { - insertSQL userExternalInsertSQLToSqler - onDuplicateKeyUpdateMap sqlla.SetMap -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateID(v uint64) userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = v - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateID(v sqlla.SetMapRawValue) userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = v - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) SameOnUpdateID() userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = sqlla.SetMapRawValue("VALUES(`id`)") - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUserID(v uint64) userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`user_id`"] = v - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUserID(v sqlla.SetMapRawValue) userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`user_id`"] = v - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUserID() userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`user_id`"] = sqlla.SetMapRawValue("VALUES(`user_id`)") - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateIconImage(v []byte) userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`icon_image`"] = v - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateIconImage(v sqlla.SetMapRawValue) userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`icon_image`"] = v - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) SameOnUpdateIconImage() userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`icon_image`"] = sqlla.SetMapRawValue("VALUES(`icon_image`)") - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateCreatedAt(v time.Time) userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`created_at`"] = v - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateCreatedAt(v sqlla.SetMapRawValue) userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`created_at`"] = v - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) SameOnUpdateCreatedAt() userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`created_at`"] = sqlla.SetMapRawValue("VALUES(`created_at`)") - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v time.Time) userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`updated_at`"] = v - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUpdatedAt(v sqlla.SetMapRawValue) userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`updated_at`"] = v - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUpdatedAt() userExternalInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`updated_at`"] = sqlla.SetMapRawValue("VALUES(`updated_at`)") - return q -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) ToSql() (string, []interface{}, error) { - var err error - var s interface{} = UserExternal{} - if t, ok := s.(userExternalDefaultInsertOnDuplicateKeyUpdateHooker); ok { - q, err = t.DefaultInsertOnDuplicateKeyUpdateHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - - query, vs, err := q.insertSQL.userExternalInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - - os, ovs, err := q.onDuplicateKeyUpdateMap.ToUpdateSql() - if err != nil { - return "", []interface{}{}, err - } - query += " ON DUPLICATE KEY UPDATE" + os - vs = append(vs, ovs...) - - return query + ";", vs, nil -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserExternal, error) { - query, args, err := q.ToSql() - if err != nil { - return UserExternal{}, err - } - result, err := db.ExecContext(ctx, query, args...) - if err != nil { - return UserExternal{}, err - } - id, err := result.LastInsertId() - if err != nil { - return UserExternal{}, err - } - return NewUserExternalSQL().Select().PkColumn(id).SingleContext(ctx, db) -} - -func (q userExternalInsertOnDuplicateKeyUpdateSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userExternalDefaultInsertOnDuplicateKeyUpdateHooker interface { - DefaultInsertOnDuplicateKeyUpdateHook(userExternalInsertOnDuplicateKeyUpdateSQL) (userExternalInsertOnDuplicateKeyUpdateSQL, error) -} - -type userExternalBulkInsertSQL struct { - insertSQLs []userExternalInsertSQL -} - -func (q userExternalSQL) BulkInsert() *userExternalBulkInsertSQL { - return &userExternalBulkInsertSQL{ - insertSQLs: []userExternalInsertSQL{}, - } -} - -func (q *userExternalBulkInsertSQL) Append(iqs ...userExternalInsertSQL) { - q.insertSQLs = append(q.insertSQLs, iqs...) -} - -func (q *userExternalBulkInsertSQL) userExternalInsertSQLToSql() (string, []interface{}, error) { - if len(q.insertSQLs) == 0 { - return "", []interface{}{}, fmt.Errorf("sqlla: This userExternalBulkInsertSQL's InsertSQL was empty") - } - iqs := make([]userExternalInsertSQL, len(q.insertSQLs)) - copy(iqs, q.insertSQLs) - - var s interface{} = UserExternal{} - if t, ok := s.(userExternalDefaultInsertHooker); ok { - for i, iq := range iqs { - var err error - iq, err = t.DefaultInsertHook(iq) - if err != nil { - return "", []interface{}{}, err - } - iqs[i] = iq - } - } - - sms := make(sqlla.SetMaps, 0, len(q.insertSQLs)) - for _, iq := range q.insertSQLs { - sms = append(sms, iq.setMap) - } - - query, vs, err := sms.ToInsertSql() - if err != nil { - return "", []interface{}{}, err - } - - return "INSERT INTO `user_external` " + query, vs, nil -} - -func (q *userExternalBulkInsertSQL) ToSql() (string, []interface{}, error) { - query, vs, err := q.userExternalInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - return query + ";", vs, nil -} - -func (q *userExternalBulkInsertSQL) OnDuplicateKeyUpdate() userExternalInsertOnDuplicateKeyUpdateSQL { - return userExternalInsertOnDuplicateKeyUpdateSQL{ - insertSQL: q, - onDuplicateKeyUpdateMap: sqlla.SetMap{}, - } -} - -func (q *userExternalBulkInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userExternalDeleteSQL struct { - userExternalSQL -} - -func (q userExternalSQL) Delete() userExternalDeleteSQL { - return userExternalDeleteSQL{ - q, - } -} - -func (q userExternalDeleteSQL) ID(v uint64, exprs ...sqlla.Operator) userExternalDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalDeleteSQL) IDIn(vs ...uint64) userExternalDeleteSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalDeleteSQL) UserID(v uint64, exprs ...sqlla.Operator) userExternalDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: "`user_id`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalDeleteSQL) UserIDIn(vs ...uint64) userExternalDeleteSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`user_id`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalDeleteSQL) IconImage(v []byte, exprs ...sqlla.Operator) userExternalDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprBytes{Value: v, Op: op, Column: "`icon_image`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalDeleteSQL) IconImageIn(vs ...[]byte) userExternalDeleteSQL { - where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`icon_image`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalDeleteSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userExternalDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalDeleteSQL) CreatedAtIn(vs ...time.Time) userExternalDeleteSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalDeleteSQL) UpdatedAt(v time.Time, exprs ...sqlla.Operator) userExternalDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalDeleteSQL) UpdatedAtIn(vs ...time.Time) userExternalDeleteSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userExternalDeleteSQL) ToSql() (string, []interface{}, error) { - wheres, vs, err := q.where.ToSql() - if err != nil { - return "", nil, err - } - - query := "DELETE FROM `user_external`" - if wheres != "" { - query += " WHERE" + wheres - } - - return query + ";", vs, nil -} - -func (q userExternalDeleteSQL) Exec(db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - return db.Exec(query, args...) -} - -func (q userExternalDeleteSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - return db.ExecContext(ctx, query, args...) -} -func (s UserExternal) Delete(db sqlla.DB) (sql.Result, error) { - query, args, err := NewUserExternalSQL().Delete().ID(s.Id).ToSql() - if err != nil { - return nil, err - } - return db.Exec(query, args...) -} - -func (s UserExternal) DeleteContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := NewUserExternalSQL().Delete().ID(s.Id).ToSql() - if err != nil { - return nil, err - } - return db.ExecContext(ctx, query, args...) -} diff --git a/_example/user_item.gen.go b/_example/user_item.gen.go index a08ccf1..e69de29 100644 --- a/_example/user_item.gen.go +++ b/_example/user_item.gen.go @@ -1,1166 +0,0 @@ -// Code generated by github.com/mackee/go-sqlla/v2/cmd/sqlla - DO NOT EDIT. -package example - -import ( - "context" - "fmt" - "strconv" - "strings" - - "database/sql" - - "github.com/mackee/go-sqlla/v2" -) - -type userItemSQL struct { - where sqlla.Where -} - -func NewUserItemSQL() userItemSQL { - q := userItemSQL{} - return q -} - -var userItemAllColumns = []string{ - "`id`", "`user_id`", "`item_id`", "`is_used`", "`has_extension`", "`used_at`", -} - -type userItemSelectSQL struct { - userItemSQL - Columns []string - order string - limit *uint64 - offset *uint64 - tableAlias string - joinClauses []string - - additionalWhereClause string - additionalWhereClauseArgs []interface{} - - groupByColumns []string - - isForUpdate bool -} - -func (q userItemSQL) Select() userItemSelectSQL { - return userItemSelectSQL{ - q, - userItemAllColumns, - "", - nil, - nil, - "", - nil, - "", - nil, - nil, - false, - } -} - -func (q userItemSelectSQL) Or(qs ...userItemSelectSQL) userItemSelectSQL { - ws := make([]sqlla.Where, 0, len(qs)) - for _, q := range qs { - ws = append(ws, q.where) - } - q.where = append(q.where, sqlla.ExprOr(ws)) - return q -} - -func (q userItemSelectSQL) Limit(l uint64) userItemSelectSQL { - q.limit = &l - return q -} - -func (q userItemSelectSQL) Offset(o uint64) userItemSelectSQL { - q.offset = &o - return q -} - -func (q userItemSelectSQL) ForUpdate() userItemSelectSQL { - q.isForUpdate = true - return q -} - -func (q userItemSelectSQL) TableAlias(alias string) userItemSelectSQL { - q.tableAlias = "`" + alias + "`" - return q -} - -func (q userItemSelectSQL) SetColumns(columns ...string) userItemSelectSQL { - q.Columns = make([]string, 0, len(columns)) - for _, column := range columns { - if strings.ContainsAny(column, "(.`") { - q.Columns = append(q.Columns, column) - } else { - q.Columns = append(q.Columns, "`"+column+"`") - } - } - return q -} - -func (q userItemSelectSQL) JoinClause(clause string) userItemSelectSQL { - q.joinClauses = append(q.joinClauses, clause) - return q -} - -func (q userItemSelectSQL) AdditionalWhereClause(clause string, args ...interface{}) userItemSelectSQL { - q.additionalWhereClause = clause - q.additionalWhereClauseArgs = args - return q -} - -func (q userItemSelectSQL) appendColumnPrefix(column string) string { - if q.tableAlias == "" || strings.ContainsAny(column, "(.") { - return column - } - return q.tableAlias + "." + column -} - -func (q userItemSelectSQL) GroupBy(columns ...string) userItemSelectSQL { - q.groupByColumns = make([]string, 0, len(columns)) - for _, column := range columns { - if strings.ContainsAny(column, "(.`") { - q.groupByColumns = append(q.groupByColumns, column) - } else { - q.groupByColumns = append(q.groupByColumns, "`"+column+"`") - } - } - return q -} - -func (q userItemSelectSQL) ID(v uint64, exprs ...sqlla.Operator) userItemSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: q.appendColumnPrefix("`id`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) IDIn(vs ...uint64) userItemSelectSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`id`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) PkColumn(pk int64, exprs ...sqlla.Operator) userItemSelectSQL { - v := uint64(pk) - return q.ID(v, exprs...) -} - -func (q userItemSelectSQL) OrderByID(order sqlla.Order) userItemSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`id`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userItemSelectSQL) UserID(v uint64, exprs ...sqlla.Operator) userItemSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: q.appendColumnPrefix("`user_id`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) UserIDIn(vs ...uint64) userItemSelectSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`user_id`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) OrderByUserID(order sqlla.Order) userItemSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`user_id`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userItemSelectSQL) ItemID(v string, exprs ...sqlla.Operator) userItemSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprString{Value: v, Op: op, Column: q.appendColumnPrefix("`item_id`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) ItemIDIn(vs ...string) userItemSelectSQL { - where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`item_id`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) OrderByItemID(order sqlla.Order) userItemSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`item_id`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userItemSelectSQL) IsUsed(v bool, exprs ...sqlla.Operator) userItemSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprBool{Value: v, Op: op, Column: q.appendColumnPrefix("`is_used`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) IsUsedIn(vs ...bool) userItemSelectSQL { - where := sqlla.ExprMultiBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`is_used`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) OrderByIsUsed(order sqlla.Order) userItemSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`is_used`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userItemSelectSQL) HasExtension(v sql.NullBool, exprs ...sqlla.Operator) userItemSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprNullBool{Value: v, Op: op, Column: q.appendColumnPrefix("`has_extension`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) HasExtensionIn(vs ...sql.NullBool) userItemSelectSQL { - where := sqlla.ExprMultiNullBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`has_extension`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) OrderByHasExtension(order sqlla.Order) userItemSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`has_extension`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userItemSelectSQL) UsedAt(v sql.NullTime, exprs ...sqlla.Operator) userItemSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprNullTime{Value: v, Op: op, Column: q.appendColumnPrefix("`used_at`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) UsedAtIn(vs ...sql.NullTime) userItemSelectSQL { - where := sqlla.ExprMultiNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`used_at`")} - q.where = append(q.where, where) - return q -} - -func (q userItemSelectSQL) OrderByUsedAt(order sqlla.Order) userItemSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`used_at`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userItemSelectSQL) ToSql() (string, []interface{}, error) { - columns := strings.Join(q.Columns, ", ") - wheres, vs, err := q.where.ToSql() - if err != nil { - return "", nil, err - } - - tableName := "`user_item`" - if q.tableAlias != "" { - tableName = tableName + " AS " + q.tableAlias - pcs := make([]string, 0, len(q.Columns)) - for _, column := range q.Columns { - pcs = append(pcs, q.appendColumnPrefix(column)) - } - columns = strings.Join(pcs, ", ") - } - query := "SELECT " + columns + " FROM " + tableName - if len(q.joinClauses) > 0 { - jc := strings.Join(q.joinClauses, " ") - query += " " + jc - } - if wheres != "" { - query += " WHERE" + wheres - } - if q.additionalWhereClause != "" { - query += " " + q.additionalWhereClause - if len(q.additionalWhereClauseArgs) > 0 { - vs = append(vs, q.additionalWhereClauseArgs...) - } - } - if len(q.groupByColumns) > 0 { - query += " GROUP BY " - gbcs := make([]string, 0, len(q.groupByColumns)) - for _, column := range q.groupByColumns { - gbcs = append(gbcs, q.appendColumnPrefix(column)) - } - query += strings.Join(gbcs, ", ") - } - query += q.order - if q.limit != nil { - query += " LIMIT " + strconv.FormatUint(*q.limit, 10) - } - if q.offset != nil { - query += " OFFSET " + strconv.FormatUint(*q.offset, 10) - } - - if q.isForUpdate { - query += " FOR UPDATE" - } - - return query + ";", vs, nil -} - -func (s UserItem) Select() userItemSelectSQL { - return NewUserItemSQL().Select().ID(s.Id) -} -func (q userItemSelectSQL) Single(db sqlla.DB) (UserItem, error) { - q.Columns = userItemAllColumns - query, args, err := q.ToSql() - if err != nil { - return UserItem{}, err - } - - row := db.QueryRow(query, args...) - return q.Scan(row) -} - -func (q userItemSelectSQL) SingleContext(ctx context.Context, db sqlla.DB) (UserItem, error) { - q.Columns = userItemAllColumns - query, args, err := q.ToSql() - if err != nil { - return UserItem{}, err - } - - row := db.QueryRowContext(ctx, query, args...) - return q.Scan(row) -} - -func (q userItemSelectSQL) All(db sqlla.DB) ([]UserItem, error) { - rs := make([]UserItem, 0, 10) - q.Columns = userItemAllColumns - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - - rows, err := db.Query(query, args...) - if err != nil { - return nil, err - } - defer rows.Close() - for rows.Next() { - r, err := q.Scan(rows) - if err != nil { - return nil, err - } - rs = append(rs, r) - } - return rs, nil -} - -func (q userItemSelectSQL) AllContext(ctx context.Context, db sqlla.DB) ([]UserItem, error) { - rs := make([]UserItem, 0, 10) - q.Columns = userItemAllColumns - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - - rows, err := db.QueryContext(ctx, query, args...) - if err != nil { - return nil, err - } - defer rows.Close() - for rows.Next() { - r, err := q.Scan(rows) - if err != nil { - return nil, err - } - rs = append(rs, r) - } - return rs, nil -} - -func (q userItemSelectSQL) Scan(s sqlla.Scanner) (UserItem, error) { - var row UserItem - err := s.Scan( - &row.Id, - &row.UserId, - &row.ItemId, - &row.IsUsed, - &row.HasExtension, - &row.UsedAt, - ) - return row, err -} - -type userItemUpdateSQL struct { - userItemSQL - setMap sqlla.SetMap - Columns []string -} - -func (q userItemSQL) Update() userItemUpdateSQL { - return userItemUpdateSQL{ - userItemSQL: q, - setMap: sqlla.SetMap{}, - } -} - -func (q userItemUpdateSQL) SetID(v uint64) userItemUpdateSQL { - q.setMap["`id`"] = v - return q -} - -func (q userItemUpdateSQL) WhereID(v uint64, exprs ...sqlla.Operator) userItemUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) WhereIDIn(vs ...uint64) userItemUpdateSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) SetUserID(v uint64) userItemUpdateSQL { - q.setMap["`user_id`"] = v - return q -} - -func (q userItemUpdateSQL) WhereUserID(v uint64, exprs ...sqlla.Operator) userItemUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: "`user_id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) WhereUserIDIn(vs ...uint64) userItemUpdateSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`user_id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) SetItemID(v string) userItemUpdateSQL { - q.setMap["`item_id`"] = v - return q -} - -func (q userItemUpdateSQL) WhereItemID(v string, exprs ...sqlla.Operator) userItemUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprString{Value: v, Op: op, Column: "`item_id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) WhereItemIDIn(vs ...string) userItemUpdateSQL { - where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`item_id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) SetIsUsed(v bool) userItemUpdateSQL { - q.setMap["`is_used`"] = v - return q -} - -func (q userItemUpdateSQL) WhereIsUsed(v bool, exprs ...sqlla.Operator) userItemUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprBool{Value: v, Op: op, Column: "`is_used`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) WhereIsUsedIn(vs ...bool) userItemUpdateSQL { - where := sqlla.ExprMultiBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`is_used`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) SetHasExtension(v sql.NullBool) userItemUpdateSQL { - q.setMap["`has_extension`"] = v - return q -} - -func (q userItemUpdateSQL) WhereHasExtension(v sql.NullBool, exprs ...sqlla.Operator) userItemUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprNullBool{Value: v, Op: op, Column: "`has_extension`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) WhereHasExtensionIn(vs ...sql.NullBool) userItemUpdateSQL { - where := sqlla.ExprMultiNullBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`has_extension`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) SetUsedAt(v sql.NullTime) userItemUpdateSQL { - q.setMap["`used_at`"] = v - return q -} - -func (q userItemUpdateSQL) WhereUsedAt(v sql.NullTime, exprs ...sqlla.Operator) userItemUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprNullTime{Value: v, Op: op, Column: "`used_at`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) WhereUsedAtIn(vs ...sql.NullTime) userItemUpdateSQL { - where := sqlla.ExprMultiNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`used_at`"} - q.where = append(q.where, where) - return q -} - -func (q userItemUpdateSQL) ToSql() (string, []interface{}, error) { - var err error - var s interface{} = UserItem{} - if t, ok := s.(userItemDefaultUpdateHooker); ok { - q, err = t.DefaultUpdateHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - setColumns, svs, err := q.setMap.ToUpdateSql() - if err != nil { - return "", []interface{}{}, err - } - wheres, wvs, err := q.where.ToSql() - if err != nil { - return "", []interface{}{}, err - } - - query := "UPDATE `user_item` SET" + setColumns - if wheres != "" { - query += " WHERE" + wheres - } - - return query + ";", append(svs, wvs...), nil -} -func (s UserItem) Update() userItemUpdateSQL { - return NewUserItemSQL().Update().WhereID(s.Id) -} - -func (q userItemUpdateSQL) Exec(db sqlla.DB) ([]UserItem, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - _, err = db.Exec(query, args...) - if err != nil { - return nil, err - } - qq := q.userItemSQL - - return qq.Select().All(db) -} - -func (q userItemUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) ([]UserItem, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - _, err = db.ExecContext(ctx, query, args...) - if err != nil { - return nil, err - } - qq := q.userItemSQL - - return qq.Select().AllContext(ctx, db) -} - -type userItemDefaultUpdateHooker interface { - DefaultUpdateHook(userItemUpdateSQL) (userItemUpdateSQL, error) -} - -type userItemInsertSQL struct { - userItemSQL - setMap sqlla.SetMap - Columns []string -} - -func (q userItemSQL) Insert() userItemInsertSQL { - return userItemInsertSQL{ - userItemSQL: q, - setMap: sqlla.SetMap{}, - } -} - -func (q userItemInsertSQL) ValueID(v uint64) userItemInsertSQL { - q.setMap["`id`"] = v - return q -} - -func (q userItemInsertSQL) ValueUserID(v uint64) userItemInsertSQL { - q.setMap["`user_id`"] = v - return q -} - -func (q userItemInsertSQL) ValueItemID(v string) userItemInsertSQL { - q.setMap["`item_id`"] = v - return q -} - -func (q userItemInsertSQL) ValueIsUsed(v bool) userItemInsertSQL { - q.setMap["`is_used`"] = v - return q -} - -func (q userItemInsertSQL) ValueHasExtension(v sql.NullBool) userItemInsertSQL { - q.setMap["`has_extension`"] = v - return q -} - -func (q userItemInsertSQL) ValueUsedAt(v sql.NullTime) userItemInsertSQL { - q.setMap["`used_at`"] = v - return q -} - -func (q userItemInsertSQL) ToSql() (string, []interface{}, error) { - query, vs, err := q.userItemInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - return query + ";", vs, nil -} - -func (q userItemInsertSQL) userItemInsertSQLToSql() (string, []interface{}, error) { - var err error - var s interface{} = UserItem{} - if t, ok := s.(userItemDefaultInsertHooker); ok { - q, err = t.DefaultInsertHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - qs, vs, err := q.setMap.ToInsertSql() - if err != nil { - return "", []interface{}{}, err - } - - query := "INSERT INTO `user_item` " + qs - - return query, vs, nil -} - -func (q userItemInsertSQL) OnDuplicateKeyUpdate() userItemInsertOnDuplicateKeyUpdateSQL { - return userItemInsertOnDuplicateKeyUpdateSQL{ - insertSQL: q, - onDuplicateKeyUpdateMap: sqlla.SetMap{}, - } -} - -func (q userItemInsertSQL) Exec(db sqlla.DB) (UserItem, error) { - query, args, err := q.ToSql() - if err != nil { - return UserItem{}, err - } - result, err := db.Exec(query, args...) - if err != nil { - return UserItem{}, err - } - id, err := result.LastInsertId() - if err != nil { - return UserItem{}, err - } - return NewUserItemSQL().Select().PkColumn(id).Single(db) -} - -func (q userItemInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserItem, error) { - query, args, err := q.ToSql() - if err != nil { - return UserItem{}, err - } - result, err := db.ExecContext(ctx, query, args...) - if err != nil { - return UserItem{}, err - } - id, err := result.LastInsertId() - if err != nil { - return UserItem{}, err - } - return NewUserItemSQL().Select().PkColumn(id).SingleContext(ctx, db) -} - -func (q userItemInsertSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userItemDefaultInsertHooker interface { - DefaultInsertHook(userItemInsertSQL) (userItemInsertSQL, error) -} - -type userItemInsertSQLToSqler interface { - userItemInsertSQLToSql() (string, []interface{}, error) -} - -type userItemInsertOnDuplicateKeyUpdateSQL struct { - insertSQL userItemInsertSQLToSqler - onDuplicateKeyUpdateMap sqlla.SetMap -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateID(v uint64) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateID(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateID() userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = sqlla.SetMapRawValue("VALUES(`id`)") - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUserID(v uint64) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`user_id`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUserID(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`user_id`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUserID() userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`user_id`"] = sqlla.SetMapRawValue("VALUES(`user_id`)") - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateItemID(v string) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`item_id`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateItemID(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`item_id`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateItemID() userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`item_id`"] = sqlla.SetMapRawValue("VALUES(`item_id`)") - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateIsUsed(v bool) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`is_used`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateIsUsed(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`is_used`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateIsUsed() userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`is_used`"] = sqlla.SetMapRawValue("VALUES(`is_used`)") - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateHasExtension(v sql.NullBool) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`has_extension`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateHasExtension(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`has_extension`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateHasExtension() userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`has_extension`"] = sqlla.SetMapRawValue("VALUES(`has_extension`)") - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUsedAt(v sql.NullTime) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`used_at`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUsedAt(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`used_at`"] = v - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUsedAt() userItemInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`used_at`"] = sqlla.SetMapRawValue("VALUES(`used_at`)") - return q -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) ToSql() (string, []interface{}, error) { - var err error - var s interface{} = UserItem{} - if t, ok := s.(userItemDefaultInsertOnDuplicateKeyUpdateHooker); ok { - q, err = t.DefaultInsertOnDuplicateKeyUpdateHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - - query, vs, err := q.insertSQL.userItemInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - - os, ovs, err := q.onDuplicateKeyUpdateMap.ToUpdateSql() - if err != nil { - return "", []interface{}{}, err - } - query += " ON DUPLICATE KEY UPDATE" + os - vs = append(vs, ovs...) - - return query + ";", vs, nil -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserItem, error) { - query, args, err := q.ToSql() - if err != nil { - return UserItem{}, err - } - result, err := db.ExecContext(ctx, query, args...) - if err != nil { - return UserItem{}, err - } - id, err := result.LastInsertId() - if err != nil { - return UserItem{}, err - } - return NewUserItemSQL().Select().PkColumn(id).SingleContext(ctx, db) -} - -func (q userItemInsertOnDuplicateKeyUpdateSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userItemDefaultInsertOnDuplicateKeyUpdateHooker interface { - DefaultInsertOnDuplicateKeyUpdateHook(userItemInsertOnDuplicateKeyUpdateSQL) (userItemInsertOnDuplicateKeyUpdateSQL, error) -} - -type userItemBulkInsertSQL struct { - insertSQLs []userItemInsertSQL -} - -func (q userItemSQL) BulkInsert() *userItemBulkInsertSQL { - return &userItemBulkInsertSQL{ - insertSQLs: []userItemInsertSQL{}, - } -} - -func (q *userItemBulkInsertSQL) Append(iqs ...userItemInsertSQL) { - q.insertSQLs = append(q.insertSQLs, iqs...) -} - -func (q *userItemBulkInsertSQL) userItemInsertSQLToSql() (string, []interface{}, error) { - if len(q.insertSQLs) == 0 { - return "", []interface{}{}, fmt.Errorf("sqlla: This userItemBulkInsertSQL's InsertSQL was empty") - } - iqs := make([]userItemInsertSQL, len(q.insertSQLs)) - copy(iqs, q.insertSQLs) - - var s interface{} = UserItem{} - if t, ok := s.(userItemDefaultInsertHooker); ok { - for i, iq := range iqs { - var err error - iq, err = t.DefaultInsertHook(iq) - if err != nil { - return "", []interface{}{}, err - } - iqs[i] = iq - } - } - - sms := make(sqlla.SetMaps, 0, len(q.insertSQLs)) - for _, iq := range q.insertSQLs { - sms = append(sms, iq.setMap) - } - - query, vs, err := sms.ToInsertSql() - if err != nil { - return "", []interface{}{}, err - } - - return "INSERT INTO `user_item` " + query, vs, nil -} - -func (q *userItemBulkInsertSQL) ToSql() (string, []interface{}, error) { - query, vs, err := q.userItemInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - return query + ";", vs, nil -} - -func (q *userItemBulkInsertSQL) OnDuplicateKeyUpdate() userItemInsertOnDuplicateKeyUpdateSQL { - return userItemInsertOnDuplicateKeyUpdateSQL{ - insertSQL: q, - onDuplicateKeyUpdateMap: sqlla.SetMap{}, - } -} - -func (q *userItemBulkInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userItemDeleteSQL struct { - userItemSQL -} - -func (q userItemSQL) Delete() userItemDeleteSQL { - return userItemDeleteSQL{ - q, - } -} - -func (q userItemDeleteSQL) ID(v uint64, exprs ...sqlla.Operator) userItemDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) IDIn(vs ...uint64) userItemDeleteSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) UserID(v uint64, exprs ...sqlla.Operator) userItemDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: "`user_id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) UserIDIn(vs ...uint64) userItemDeleteSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`user_id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) ItemID(v string, exprs ...sqlla.Operator) userItemDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprString{Value: v, Op: op, Column: "`item_id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) ItemIDIn(vs ...string) userItemDeleteSQL { - where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`item_id`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) IsUsed(v bool, exprs ...sqlla.Operator) userItemDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprBool{Value: v, Op: op, Column: "`is_used`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) IsUsedIn(vs ...bool) userItemDeleteSQL { - where := sqlla.ExprMultiBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`is_used`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) HasExtension(v sql.NullBool, exprs ...sqlla.Operator) userItemDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprNullBool{Value: v, Op: op, Column: "`has_extension`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) HasExtensionIn(vs ...sql.NullBool) userItemDeleteSQL { - where := sqlla.ExprMultiNullBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`has_extension`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) UsedAt(v sql.NullTime, exprs ...sqlla.Operator) userItemDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprNullTime{Value: v, Op: op, Column: "`used_at`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) UsedAtIn(vs ...sql.NullTime) userItemDeleteSQL { - where := sqlla.ExprMultiNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`used_at`"} - q.where = append(q.where, where) - return q -} - -func (q userItemDeleteSQL) ToSql() (string, []interface{}, error) { - wheres, vs, err := q.where.ToSql() - if err != nil { - return "", nil, err - } - - query := "DELETE FROM `user_item`" - if wheres != "" { - query += " WHERE" + wheres - } - - return query + ";", vs, nil -} - -func (q userItemDeleteSQL) Exec(db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - return db.Exec(query, args...) -} - -func (q userItemDeleteSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - return db.ExecContext(ctx, query, args...) -} -func (s UserItem) Delete(db sqlla.DB) (sql.Result, error) { - query, args, err := NewUserItemSQL().Delete().ID(s.Id).ToSql() - if err != nil { - return nil, err - } - return db.Exec(query, args...) -} - -func (s UserItem) DeleteContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := NewUserItemSQL().Delete().ID(s.Id).ToSql() - if err != nil { - return nil, err - } - return db.ExecContext(ctx, query, args...) -} diff --git a/_example/user_sns.gen.go b/_example/user_sns.gen.go index aa3fa40..e69de29 100644 --- a/_example/user_sns.gen.go +++ b/_example/user_sns.gen.go @@ -1,985 +0,0 @@ -// Code generated by github.com/mackee/go-sqlla/v2/cmd/sqlla - DO NOT EDIT. -package example - -import ( - "context" - "fmt" - "strconv" - "strings" - - "database/sql" - "time" - - "github.com/mackee/go-sqlla/v2" -) - -type userSNSSQL struct { - where sqlla.Where -} - -func NewUserSNSSQL() userSNSSQL { - q := userSNSSQL{} - return q -} - -var userSNSAllColumns = []string{ - "`id`", "`sns_type`", "`created_at`", "`updated_at`", -} - -type userSNSSelectSQL struct { - userSNSSQL - Columns []string - order string - limit *uint64 - offset *uint64 - tableAlias string - joinClauses []string - - additionalWhereClause string - additionalWhereClauseArgs []interface{} - - groupByColumns []string - - isForUpdate bool -} - -func (q userSNSSQL) Select() userSNSSelectSQL { - return userSNSSelectSQL{ - q, - userSNSAllColumns, - "", - nil, - nil, - "", - nil, - "", - nil, - nil, - false, - } -} - -func (q userSNSSelectSQL) Or(qs ...userSNSSelectSQL) userSNSSelectSQL { - ws := make([]sqlla.Where, 0, len(qs)) - for _, q := range qs { - ws = append(ws, q.where) - } - q.where = append(q.where, sqlla.ExprOr(ws)) - return q -} - -func (q userSNSSelectSQL) Limit(l uint64) userSNSSelectSQL { - q.limit = &l - return q -} - -func (q userSNSSelectSQL) Offset(o uint64) userSNSSelectSQL { - q.offset = &o - return q -} - -func (q userSNSSelectSQL) ForUpdate() userSNSSelectSQL { - q.isForUpdate = true - return q -} - -func (q userSNSSelectSQL) TableAlias(alias string) userSNSSelectSQL { - q.tableAlias = "`" + alias + "`" - return q -} - -func (q userSNSSelectSQL) SetColumns(columns ...string) userSNSSelectSQL { - q.Columns = make([]string, 0, len(columns)) - for _, column := range columns { - if strings.ContainsAny(column, "(.`") { - q.Columns = append(q.Columns, column) - } else { - q.Columns = append(q.Columns, "`"+column+"`") - } - } - return q -} - -func (q userSNSSelectSQL) JoinClause(clause string) userSNSSelectSQL { - q.joinClauses = append(q.joinClauses, clause) - return q -} - -func (q userSNSSelectSQL) AdditionalWhereClause(clause string, args ...interface{}) userSNSSelectSQL { - q.additionalWhereClause = clause - q.additionalWhereClauseArgs = args - return q -} - -func (q userSNSSelectSQL) appendColumnPrefix(column string) string { - if q.tableAlias == "" || strings.ContainsAny(column, "(.") { - return column - } - return q.tableAlias + "." + column -} - -func (q userSNSSelectSQL) GroupBy(columns ...string) userSNSSelectSQL { - q.groupByColumns = make([]string, 0, len(columns)) - for _, column := range columns { - if strings.ContainsAny(column, "(.`") { - q.groupByColumns = append(q.groupByColumns, column) - } else { - q.groupByColumns = append(q.groupByColumns, "`"+column+"`") - } - } - return q -} - -func (q userSNSSelectSQL) ID(v uint64, exprs ...sqlla.Operator) userSNSSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: q.appendColumnPrefix("`id`")} - q.where = append(q.where, where) - return q -} - -func (q userSNSSelectSQL) IDIn(vs ...uint64) userSNSSelectSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`id`")} - q.where = append(q.where, where) - return q -} - -func (q userSNSSelectSQL) PkColumn(pk int64, exprs ...sqlla.Operator) userSNSSelectSQL { - v := uint64(pk) - return q.ID(v, exprs...) -} - -func (q userSNSSelectSQL) OrderByID(order sqlla.Order) userSNSSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`id`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userSNSSelectSQL) SNSType(v string, exprs ...sqlla.Operator) userSNSSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprString{Value: v, Op: op, Column: q.appendColumnPrefix("`sns_type`")} - q.where = append(q.where, where) - return q -} - -func (q userSNSSelectSQL) SNSTypeIn(vs ...string) userSNSSelectSQL { - where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`sns_type`")} - q.where = append(q.where, where) - return q -} - -func (q userSNSSelectSQL) OrderBySNSType(order sqlla.Order) userSNSSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`sns_type`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userSNSSelectSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userSNSSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: q.appendColumnPrefix("`created_at`")} - q.where = append(q.where, where) - return q -} - -func (q userSNSSelectSQL) CreatedAtIn(vs ...time.Time) userSNSSelectSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`created_at`")} - q.where = append(q.where, where) - return q -} - -func (q userSNSSelectSQL) OrderByCreatedAt(order sqlla.Order) userSNSSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`created_at`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userSNSSelectSQL) UpdatedAt(v time.Time, exprs ...sqlla.Operator) userSNSSelectSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: q.appendColumnPrefix("`updated_at`")} - q.where = append(q.where, where) - return q -} - -func (q userSNSSelectSQL) UpdatedAtIn(vs ...time.Time) userSNSSelectSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`updated_at`")} - q.where = append(q.where, where) - return q -} - -func (q userSNSSelectSQL) OrderByUpdatedAt(order sqlla.Order) userSNSSelectSQL { - q.order = " ORDER BY " + q.appendColumnPrefix("`updated_at`") - if order == sqlla.Asc { - q.order += " ASC" - } else { - q.order += " DESC" - } - - return q -} - -func (q userSNSSelectSQL) ToSql() (string, []interface{}, error) { - columns := strings.Join(q.Columns, ", ") - wheres, vs, err := q.where.ToSql() - if err != nil { - return "", nil, err - } - - tableName := "`user_sns`" - if q.tableAlias != "" { - tableName = tableName + " AS " + q.tableAlias - pcs := make([]string, 0, len(q.Columns)) - for _, column := range q.Columns { - pcs = append(pcs, q.appendColumnPrefix(column)) - } - columns = strings.Join(pcs, ", ") - } - query := "SELECT " + columns + " FROM " + tableName - if len(q.joinClauses) > 0 { - jc := strings.Join(q.joinClauses, " ") - query += " " + jc - } - if wheres != "" { - query += " WHERE" + wheres - } - if q.additionalWhereClause != "" { - query += " " + q.additionalWhereClause - if len(q.additionalWhereClauseArgs) > 0 { - vs = append(vs, q.additionalWhereClauseArgs...) - } - } - if len(q.groupByColumns) > 0 { - query += " GROUP BY " - gbcs := make([]string, 0, len(q.groupByColumns)) - for _, column := range q.groupByColumns { - gbcs = append(gbcs, q.appendColumnPrefix(column)) - } - query += strings.Join(gbcs, ", ") - } - query += q.order - if q.limit != nil { - query += " LIMIT " + strconv.FormatUint(*q.limit, 10) - } - if q.offset != nil { - query += " OFFSET " + strconv.FormatUint(*q.offset, 10) - } - - if q.isForUpdate { - query += " FOR UPDATE" - } - - return query + ";", vs, nil -} - -func (s UserSNS) Select() userSNSSelectSQL { - return NewUserSNSSQL().Select().ID(s.ID) -} -func (q userSNSSelectSQL) Single(db sqlla.DB) (UserSNS, error) { - q.Columns = userSNSAllColumns - query, args, err := q.ToSql() - if err != nil { - return UserSNS{}, err - } - - row := db.QueryRow(query, args...) - return q.Scan(row) -} - -func (q userSNSSelectSQL) SingleContext(ctx context.Context, db sqlla.DB) (UserSNS, error) { - q.Columns = userSNSAllColumns - query, args, err := q.ToSql() - if err != nil { - return UserSNS{}, err - } - - row := db.QueryRowContext(ctx, query, args...) - return q.Scan(row) -} - -func (q userSNSSelectSQL) All(db sqlla.DB) ([]UserSNS, error) { - rs := make([]UserSNS, 0, 10) - q.Columns = userSNSAllColumns - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - - rows, err := db.Query(query, args...) - if err != nil { - return nil, err - } - defer rows.Close() - for rows.Next() { - r, err := q.Scan(rows) - if err != nil { - return nil, err - } - rs = append(rs, r) - } - return rs, nil -} - -func (q userSNSSelectSQL) AllContext(ctx context.Context, db sqlla.DB) ([]UserSNS, error) { - rs := make([]UserSNS, 0, 10) - q.Columns = userSNSAllColumns - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - - rows, err := db.QueryContext(ctx, query, args...) - if err != nil { - return nil, err - } - defer rows.Close() - for rows.Next() { - r, err := q.Scan(rows) - if err != nil { - return nil, err - } - rs = append(rs, r) - } - return rs, nil -} - -func (q userSNSSelectSQL) Scan(s sqlla.Scanner) (UserSNS, error) { - var row UserSNS - err := s.Scan( - &row.ID, - &row.SNSType, - &row.CreatedAt, - &row.UpdatedAt, - ) - return row, err -} - -type userSNSUpdateSQL struct { - userSNSSQL - setMap sqlla.SetMap - Columns []string -} - -func (q userSNSSQL) Update() userSNSUpdateSQL { - return userSNSUpdateSQL{ - userSNSSQL: q, - setMap: sqlla.SetMap{}, - } -} - -func (q userSNSUpdateSQL) SetID(v uint64) userSNSUpdateSQL { - q.setMap["`id`"] = v - return q -} - -func (q userSNSUpdateSQL) WhereID(v uint64, exprs ...sqlla.Operator) userSNSUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSUpdateSQL) WhereIDIn(vs ...uint64) userSNSUpdateSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSUpdateSQL) SetSNSType(v string) userSNSUpdateSQL { - q.setMap["`sns_type`"] = v - return q -} - -func (q userSNSUpdateSQL) WhereSNSType(v string, exprs ...sqlla.Operator) userSNSUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprString{Value: v, Op: op, Column: "`sns_type`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSUpdateSQL) WhereSNSTypeIn(vs ...string) userSNSUpdateSQL { - where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sns_type`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSUpdateSQL) SetCreatedAt(v time.Time) userSNSUpdateSQL { - q.setMap["`created_at`"] = v - return q -} - -func (q userSNSUpdateSQL) WhereCreatedAt(v time.Time, exprs ...sqlla.Operator) userSNSUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSUpdateSQL) WhereCreatedAtIn(vs ...time.Time) userSNSUpdateSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSUpdateSQL) SetUpdatedAt(v time.Time) userSNSUpdateSQL { - q.setMap["`updated_at`"] = v - return q -} - -func (q userSNSUpdateSQL) WhereUpdatedAt(v time.Time, exprs ...sqlla.Operator) userSNSUpdateSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSUpdateSQL) WhereUpdatedAtIn(vs ...time.Time) userSNSUpdateSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSUpdateSQL) ToSql() (string, []interface{}, error) { - var err error - var s interface{} = UserSNS{} - if t, ok := s.(userSNSDefaultUpdateHooker); ok { - q, err = t.DefaultUpdateHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - setColumns, svs, err := q.setMap.ToUpdateSql() - if err != nil { - return "", []interface{}{}, err - } - wheres, wvs, err := q.where.ToSql() - if err != nil { - return "", []interface{}{}, err - } - - query := "UPDATE `user_sns` SET" + setColumns - if wheres != "" { - query += " WHERE" + wheres - } - - return query + ";", append(svs, wvs...), nil -} -func (s UserSNS) Update() userSNSUpdateSQL { - return NewUserSNSSQL().Update().WhereID(s.ID) -} - -func (q userSNSUpdateSQL) Exec(db sqlla.DB) ([]UserSNS, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - _, err = db.Exec(query, args...) - if err != nil { - return nil, err - } - qq := q.userSNSSQL - - return qq.Select().All(db) -} - -func (q userSNSUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) ([]UserSNS, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - _, err = db.ExecContext(ctx, query, args...) - if err != nil { - return nil, err - } - qq := q.userSNSSQL - - return qq.Select().AllContext(ctx, db) -} - -type userSNSDefaultUpdateHooker interface { - DefaultUpdateHook(userSNSUpdateSQL) (userSNSUpdateSQL, error) -} - -type userSNSInsertSQL struct { - userSNSSQL - setMap sqlla.SetMap - Columns []string -} - -func (q userSNSSQL) Insert() userSNSInsertSQL { - return userSNSInsertSQL{ - userSNSSQL: q, - setMap: sqlla.SetMap{}, - } -} - -func (q userSNSInsertSQL) ValueID(v uint64) userSNSInsertSQL { - q.setMap["`id`"] = v - return q -} - -func (q userSNSInsertSQL) ValueSNSType(v string) userSNSInsertSQL { - q.setMap["`sns_type`"] = v - return q -} - -func (q userSNSInsertSQL) ValueCreatedAt(v time.Time) userSNSInsertSQL { - q.setMap["`created_at`"] = v - return q -} - -func (q userSNSInsertSQL) ValueUpdatedAt(v time.Time) userSNSInsertSQL { - q.setMap["`updated_at`"] = v - return q -} - -func (q userSNSInsertSQL) ToSql() (string, []interface{}, error) { - query, vs, err := q.userSNSInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - return query + ";", vs, nil -} - -func (q userSNSInsertSQL) userSNSInsertSQLToSql() (string, []interface{}, error) { - var err error - var s interface{} = UserSNS{} - if t, ok := s.(userSNSDefaultInsertHooker); ok { - q, err = t.DefaultInsertHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - qs, vs, err := q.setMap.ToInsertSql() - if err != nil { - return "", []interface{}{}, err - } - - query := "INSERT INTO `user_sns` " + qs - - return query, vs, nil -} - -func (q userSNSInsertSQL) OnDuplicateKeyUpdate() userSNSInsertOnDuplicateKeyUpdateSQL { - return userSNSInsertOnDuplicateKeyUpdateSQL{ - insertSQL: q, - onDuplicateKeyUpdateMap: sqlla.SetMap{}, - } -} - -func (q userSNSInsertSQL) Exec(db sqlla.DB) (UserSNS, error) { - query, args, err := q.ToSql() - if err != nil { - return UserSNS{}, err - } - result, err := db.Exec(query, args...) - if err != nil { - return UserSNS{}, err - } - id, err := result.LastInsertId() - if err != nil { - return UserSNS{}, err - } - return NewUserSNSSQL().Select().PkColumn(id).Single(db) -} - -func (q userSNSInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserSNS, error) { - query, args, err := q.ToSql() - if err != nil { - return UserSNS{}, err - } - result, err := db.ExecContext(ctx, query, args...) - if err != nil { - return UserSNS{}, err - } - id, err := result.LastInsertId() - if err != nil { - return UserSNS{}, err - } - return NewUserSNSSQL().Select().PkColumn(id).SingleContext(ctx, db) -} - -func (q userSNSInsertSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userSNSDefaultInsertHooker interface { - DefaultInsertHook(userSNSInsertSQL) (userSNSInsertSQL, error) -} - -type userSNSInsertSQLToSqler interface { - userSNSInsertSQLToSql() (string, []interface{}, error) -} - -type userSNSInsertOnDuplicateKeyUpdateSQL struct { - insertSQL userSNSInsertSQLToSqler - onDuplicateKeyUpdateMap sqlla.SetMap -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateID(v uint64) userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = v - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateID(v sqlla.SetMapRawValue) userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = v - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) SameOnUpdateID() userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`id`"] = sqlla.SetMapRawValue("VALUES(`id`)") - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateSNSType(v string) userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`sns_type`"] = v - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateSNSType(v sqlla.SetMapRawValue) userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`sns_type`"] = v - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) SameOnUpdateSNSType() userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`sns_type`"] = sqlla.SetMapRawValue("VALUES(`sns_type`)") - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateCreatedAt(v time.Time) userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`created_at`"] = v - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateCreatedAt(v sqlla.SetMapRawValue) userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`created_at`"] = v - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) SameOnUpdateCreatedAt() userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`created_at`"] = sqlla.SetMapRawValue("VALUES(`created_at`)") - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v time.Time) userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`updated_at`"] = v - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUpdatedAt(v sqlla.SetMapRawValue) userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`updated_at`"] = v - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUpdatedAt() userSNSInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`updated_at`"] = sqlla.SetMapRawValue("VALUES(`updated_at`)") - return q -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) ToSql() (string, []interface{}, error) { - var err error - var s interface{} = UserSNS{} - if t, ok := s.(userSNSDefaultInsertOnDuplicateKeyUpdateHooker); ok { - q, err = t.DefaultInsertOnDuplicateKeyUpdateHook(q) - if err != nil { - return "", []interface{}{}, err - } - } - - query, vs, err := q.insertSQL.userSNSInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - - os, ovs, err := q.onDuplicateKeyUpdateMap.ToUpdateSql() - if err != nil { - return "", []interface{}{}, err - } - query += " ON DUPLICATE KEY UPDATE" + os - vs = append(vs, ovs...) - - return query + ";", vs, nil -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserSNS, error) { - query, args, err := q.ToSql() - if err != nil { - return UserSNS{}, err - } - result, err := db.ExecContext(ctx, query, args...) - if err != nil { - return UserSNS{}, err - } - id, err := result.LastInsertId() - if err != nil { - return UserSNS{}, err - } - return NewUserSNSSQL().Select().PkColumn(id).SingleContext(ctx, db) -} - -func (q userSNSInsertOnDuplicateKeyUpdateSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userSNSDefaultInsertOnDuplicateKeyUpdateHooker interface { - DefaultInsertOnDuplicateKeyUpdateHook(userSNSInsertOnDuplicateKeyUpdateSQL) (userSNSInsertOnDuplicateKeyUpdateSQL, error) -} - -type userSNSBulkInsertSQL struct { - insertSQLs []userSNSInsertSQL -} - -func (q userSNSSQL) BulkInsert() *userSNSBulkInsertSQL { - return &userSNSBulkInsertSQL{ - insertSQLs: []userSNSInsertSQL{}, - } -} - -func (q *userSNSBulkInsertSQL) Append(iqs ...userSNSInsertSQL) { - q.insertSQLs = append(q.insertSQLs, iqs...) -} - -func (q *userSNSBulkInsertSQL) userSNSInsertSQLToSql() (string, []interface{}, error) { - if len(q.insertSQLs) == 0 { - return "", []interface{}{}, fmt.Errorf("sqlla: This userSNSBulkInsertSQL's InsertSQL was empty") - } - iqs := make([]userSNSInsertSQL, len(q.insertSQLs)) - copy(iqs, q.insertSQLs) - - var s interface{} = UserSNS{} - if t, ok := s.(userSNSDefaultInsertHooker); ok { - for i, iq := range iqs { - var err error - iq, err = t.DefaultInsertHook(iq) - if err != nil { - return "", []interface{}{}, err - } - iqs[i] = iq - } - } - - sms := make(sqlla.SetMaps, 0, len(q.insertSQLs)) - for _, iq := range q.insertSQLs { - sms = append(sms, iq.setMap) - } - - query, vs, err := sms.ToInsertSql() - if err != nil { - return "", []interface{}{}, err - } - - return "INSERT INTO `user_sns` " + query, vs, nil -} - -func (q *userSNSBulkInsertSQL) ToSql() (string, []interface{}, error) { - query, vs, err := q.userSNSInsertSQLToSql() - if err != nil { - return "", []interface{}{}, err - } - return query + ";", vs, nil -} - -func (q *userSNSBulkInsertSQL) OnDuplicateKeyUpdate() userSNSInsertOnDuplicateKeyUpdateSQL { - return userSNSInsertOnDuplicateKeyUpdateSQL{ - insertSQL: q, - onDuplicateKeyUpdateMap: sqlla.SetMap{}, - } -} - -func (q *userSNSBulkInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - result, err := db.ExecContext(ctx, query, args...) - return result, err -} - -type userSNSDeleteSQL struct { - userSNSSQL -} - -func (q userSNSSQL) Delete() userSNSDeleteSQL { - return userSNSDeleteSQL{ - q, - } -} - -func (q userSNSDeleteSQL) ID(v uint64, exprs ...sqlla.Operator) userSNSDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSDeleteSQL) IDIn(vs ...uint64) userSNSDeleteSQL { - where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSDeleteSQL) SNSType(v string, exprs ...sqlla.Operator) userSNSDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprString{Value: v, Op: op, Column: "`sns_type`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSDeleteSQL) SNSTypeIn(vs ...string) userSNSDeleteSQL { - where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sns_type`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSDeleteSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userSNSDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSDeleteSQL) CreatedAtIn(vs ...time.Time) userSNSDeleteSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSDeleteSQL) UpdatedAt(v time.Time, exprs ...sqlla.Operator) userSNSDeleteSQL { - var op sqlla.Operator - if len(exprs) == 0 { - op = sqlla.OpEqual - } else { - op = exprs[0] - } - where := sqlla.ExprTime{Value: v, Op: op, Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSDeleteSQL) UpdatedAtIn(vs ...time.Time) userSNSDeleteSQL { - where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} - q.where = append(q.where, where) - return q -} - -func (q userSNSDeleteSQL) ToSql() (string, []interface{}, error) { - wheres, vs, err := q.where.ToSql() - if err != nil { - return "", nil, err - } - - query := "DELETE FROM `user_sns`" - if wheres != "" { - query += " WHERE" + wheres - } - - return query + ";", vs, nil -} - -func (q userSNSDeleteSQL) Exec(db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - return db.Exec(query, args...) -} - -func (q userSNSDeleteSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := q.ToSql() - if err != nil { - return nil, err - } - return db.ExecContext(ctx, query, args...) -} -func (s UserSNS) Delete(db sqlla.DB) (sql.Result, error) { - query, args, err := NewUserSNSSQL().Delete().ID(s.ID).ToSql() - if err != nil { - return nil, err - } - return db.Exec(query, args...) -} - -func (s UserSNS) DeleteContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { - query, args, err := NewUserSNSSQL().Delete().ID(s.ID).ToSql() - if err != nil { - return nil, err - } - return db.ExecContext(ctx, query, args...) -} diff --git a/_example/user_withmysql_test.go b/_example/user_withmysql_test.go index 3b0243a..95ab742 100644 --- a/_example/user_withmysql_test.go +++ b/_example/user_withmysql_test.go @@ -22,7 +22,7 @@ import ( var db *sql.DB -//go:generate genddl -outpath=./mysql.sql -driver=mysql +//go:generate go run github.com/mackee/go-genddl/cmd/genddl -outpath=./mysql.sql -driver=mysql func TestMain(m *testing.M) { // uses a sensible default on windows (tcp/http) and linux/osx (socket) @@ -244,5 +244,4 @@ func TestBulkInsertOnDuplicateKeyUpdate__WithMySQL(t *testing.T) { } } } - } diff --git a/column.go b/column.go index f2b0c0a..0768678 100644 --- a/column.go +++ b/column.go @@ -56,10 +56,7 @@ type SetMapIterator struct { func (s *SetMapIterator) Iterate() bool { s.cursor++ - if len(s.keys)-1 < s.cursor { - return false - } - return true + return len(s.keys)-1 >= s.cursor } func (s *SetMapIterator) Key() string { diff --git a/expr.go b/expr.go index fe8666d..ae7a282 100644 --- a/expr.go +++ b/expr.go @@ -628,3 +628,64 @@ func (e ExprMultiBytes) ToSql() (string, []interface{}, error) { } return e.Column + " " + ops, vs, nil } + +type ExprValue[T any] struct { + Column string + Value T + Op Operator +} + +func (e ExprValue[T]) ToSql() (string, []interface{}, error) { + v := e.Value + ops, err := e.Op.ToSql() + if err != nil { + return "", nil, err + } + return e.Column + " " + ops + " ?", []interface{}{v}, nil +} + +type ExprMultiValue[T any] struct { + Column string + Values []T + Op Operator +} + +func (e ExprMultiValue[T]) ToSql() (string, []interface{}, error) { + ops, err := e.Op.ToSql() + if err != nil { + return "", nil, err + } + vs := make([]interface{}, 0, len(e.Values)) + for _, v := range e.Values { + vs = append(vs, interface{}(v)) + } + return e.Column + " " + ops, vs, nil +} + +type ExprNull[T any] struct { + Column string + Value sql.Null[T] + Op Operator +} + +func (e ExprNull[T]) ToSql() (string, []interface{}, error) { + var ops, placeholder string + var err error + vs := []interface{}{} + if !e.Value.Valid { + if e.Op == OpNot { + ops, err = opIsNotNull.ToSql() + } else { + ops, err = opIsNull.ToSql() + } + } else { + ops, err = e.Op.ToSql() + placeholder = " ?" + vs = append(vs, e.Value) + } + if err != nil { + return "", nil, err + } + + return e.Column + " " + ops + placeholder, vs, nil +} diff --git a/generator.go b/generator.go index c5880da..0ce06c5 100644 --- a/generator.go +++ b/generator.go @@ -3,8 +3,10 @@ package sqlla import ( + "bufio" "bytes" "embed" + "fmt" "go/format" "io" "log" @@ -65,6 +67,12 @@ func WriteCode(w io.Writer, table *Table) error { if err != nil { return errors.Wrapf(err, "fail to render") } + scanner := bufio.NewScanner(bytes.NewReader(buf.Bytes())) + i := 0 + for scanner.Scan() { + i++ + fmt.Printf("%05d: %s\n", i, scanner.Text()) + } bs, err := format.Source(buf.Bytes()) if err != nil { return errors.Wrapf(err, "fail to format: table=%s", table.Name) diff --git a/main.go b/main.go index 2af21c2..db04f28 100644 --- a/main.go +++ b/main.go @@ -81,6 +81,10 @@ var supportedNonPrimitiveTypes = map[string]struct{}{ "sql.NullBool": {}, } +var supportedGenericsTypes = map[string]struct{}{ + "sql.Null": {}, +} + var altTypeNames = map[string]string{ "[]byte": "Bytes", "mysql.NullTime": "MysqlNullTime", @@ -124,7 +128,7 @@ func toTable(tablePkg *types.Package, annotationComment string, gd *ast.GenDecl, } } t := ti.TypeOf(field.Type) - var typeName, pkgName string + var typeName, pkgName, typeParameter string baseTypeName := t.String() nt, ok := t.(*types.Named) if ok { @@ -135,7 +139,18 @@ func toTable(tablePkg *types.Package, annotationComment string, gd *ast.GenDecl, typeName = nt.Obj().Name() } baseTypeName = typeName - if _, ok := supportedNonPrimitiveTypes[typeName]; !ok { + if _, ok := supportedGenericsTypes[typeName]; ok { + tps := nt.TypeParams() + if tps == nil { + return nil, fmt.Errorf("toTable: has not type params: table=%s, field=%s", table.TableName, columnName) + } + tpsStr := make([]string, tps.Len()) + for i := 0; i < tps.Len(); i++ { + tp := tps.At(i) + tpsStr[i] = tp.String() + } + typeParameter = strings.Join(tpsStr, ",") + } else if _, ok := supportedNonPrimitiveTypes[typeName]; !ok { bt := nt.Underlying() for _, ok := bt.Underlying().(*types.Named); ok; bt = bt.Underlying() { } @@ -145,15 +160,16 @@ func toTable(tablePkg *types.Package, annotationComment string, gd *ast.GenDecl, typeName = t.String() } column := Column{ - Field: field, - Name: columnName, - IsPk: isPk, - TypeName: typeName, - BaseTypeName: baseTypeName, - PkgName: pkgName, + Field: field, + Name: columnName, + IsPk: isPk, + typeName: typeName, + baseTypeName: baseTypeName, + PkgName: pkgName, + typeParameter: typeParameter, } if alt, ok := altTypeNames[baseTypeName]; ok { - column.AltTypeName = alt + column.altTypeName = alt } table.AddColumn(column) } diff --git a/table.go b/table.go index d009648..13c0206 100644 --- a/table.go +++ b/table.go @@ -66,15 +66,69 @@ func (t Table) Render(w io.Writer) error { type Columns []Column type Column struct { - Field *ast.Field - Name string - MethodName string - TypeName string - PkgName string - BaseTypeName string - AltTypeName string - TableName string - IsPk bool + Field *ast.Field + Name string + MethodName string + typeName string + PkgName string + baseTypeName string + altTypeName string + typeParameter string + TableName string + IsPk bool +} + +func (c Column) HasUnderlyingType() bool { + return c.baseTypeName != c.typeName +} + +func (c Column) TypeName() string { + tn := c.typeName + if c.altTypeName != "" { + tn = c.altTypeName + } + if c.typeParameter != "" { + return tn + "[" + c.typeParameter + "]" + } + return tn +} + +func (c Column) BaseTypeName() string { + if c.typeParameter != "" { + return c.baseTypeName + "[" + c.typeParameter + "]" + } + return c.baseTypeName +} + +func (c Column) AltTypeName() string { + if c.altTypeName == "" { + return "" + } + if c.typeParameter != "" { + return c.altTypeName + "[" + c.typeParameter + "]" + } + return c.altTypeName +} + +func (c Column) ExprTypeName() string { + if atn := c.AltTypeName(); atn != "" { + return "Expr" + atn + } + return "Expr" + c.BaseTypeName() +} + +func (c Column) ExprMultiTypeName() string { + if atn := c.AltTypeName(); atn != "" { + return "ExprMulti" + atn + } + return "ExprMulti" + c.BaseTypeName() +} + +func (c Column) ExprValueIdentifier() string { + if c.typeName != c.baseTypeName { + return c.baseTypeName + "(v)" + } + return "v" } func (c Column) String() string { diff --git a/template/select_column.tmpl b/template/select_column.tmpl index 06acf29..b2ec354 100644 --- a/template/select_column.tmpl +++ b/template/select_column.tmpl @@ -7,28 +7,20 @@ func (q {{ $smallTableName }}SelectSQL) {{ .MethodName }}(v {{ .TypeName }}, exp op = exprs[0] } -{{- if ne .BaseTypeName .TypeName }} - where := sqlla.Expr{{ .BaseTypeName | Exprize | Title }}{Value: {{ .BaseTypeName }}(v), Op: op, Column: q.appendColumnPrefix("`{{ .Name }}`")} -{{- else if .AltTypeName }} - where := sqlla.Expr{{ .AltTypeName | Exprize | Title }}{Value: v, Op: op, Column: q.appendColumnPrefix("`{{ .Name }}`")} -{{- else }} - where := sqlla.Expr{{ .BaseTypeName | Exprize | Title }}{Value: v, Op: op, Column: q.appendColumnPrefix("`{{ .Name }}`")} -{{- end }} + where := sqlla.{{ .ExprTypeName | Exprize | Title }}{Value: {{ .ExprValueIdentifier }}, Op: op, Column: q.appendColumnPrefix("`{{ .Name }}`")} q.where = append(q.where, where) return q } func (q {{ $smallTableName }}SelectSQL) {{ .MethodName }}In(vs ...{{ .TypeName }}) {{ $smallTableName }}SelectSQL { -{{- if ne .BaseTypeName .TypeName }} +{{- if .HasUnderlyingType }} _vs := make([]{{ .BaseTypeName }}, 0, len(vs)) for _, v := range vs { _vs = append(_vs, {{ .BaseTypeName }}(v)) } - where := sqlla.ExprMulti{{ .BaseTypeName | Exprize | Title }}{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`{{ .Name }}`")} -{{- else if .AltTypeName }} - where := sqlla.ExprMulti{{ .AltTypeName | Exprize | Title }}{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`{{ .Name }}`")} + where := sqlla.{{ .ExprMultiTypeName | Exprize | Title }}{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`{{ .Name }}`")} {{- else }} - where := sqlla.ExprMulti{{ .BaseTypeName | Exprize | Title }}{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`{{ .Name }}`")} + where := sqlla.{{ .ExprMultiTypeName | Exprize | Title }}{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`{{ .Name }}`")} {{- end }} q.where = append(q.where, where) return q From 8dde16f9f9f48ca968ee504affac77f17c023256 Mon Sep 17 00:00:00 2001 From: mackee Date: Sun, 2 Jun 2024 01:23:07 +0900 Subject: [PATCH 02/11] refactor: generate name that expr type from Column method --- _example/go.mod | 1 + _example/go.sum | 2 + _example/group.gen.go | 60 +- _example/user.gen.go | 1271 +++++++++++++++++++++++++++++++++ _example/user_external.gen.go | 1076 ++++++++++++++++++++++++++++ _example/user_item.gen.go | 1166 ++++++++++++++++++++++++++++++ _example/user_sns.gen.go | 985 +++++++++++++++++++++++++ cmd/mysql2schema/main.go | 10 +- generator.go | 19 +- table.go | 31 +- template/delete_column.tmpl | 17 +- template/select_column.tmpl | 7 +- template/update_column.tmpl | 17 +- 13 files changed, 4566 insertions(+), 96 deletions(-) diff --git a/_example/go.mod b/_example/go.mod index 3d6e6c3..a2b495f 100644 --- a/_example/go.mod +++ b/_example/go.mod @@ -14,6 +14,7 @@ require ( require ( github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 // indirect + github.com/Masterminds/goutils v1.1.1 // indirect github.com/Microsoft/go-winio v0.5.2 // indirect github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect github.com/cenkalti/backoff/v4 v4.1.3 // indirect diff --git a/_example/go.sum b/_example/go.sum index 00015ec..65023ed 100644 --- a/_example/go.sum +++ b/_example/go.sum @@ -1,6 +1,8 @@ github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 h1:w+iIsaOQNcT7OZ575w+acHgRric5iCyQh+xv+KJ4HB8= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= +github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Microsoft/go-winio v0.5.2 h1:a9IhgEQBCUEk6QCdml9CiJGhAws+YwffDHEMp1VMrpA= github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY= github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw= diff --git a/_example/group.gen.go b/_example/group.gen.go index 287efa6..f0ed76a 100644 --- a/_example/group.gen.go +++ b/_example/group.gen.go @@ -138,8 +138,7 @@ func (q groupSelectSQL) ID(v GroupID, exprs ...sqlla.Operator) groupSelectSQL { } else { op = exprs[0] } - - where := sqlla.Expruint64{Value: uint64(v), Op: op, Column: q.appendColumnPrefix("`id`")} + where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: q.appendColumnPrefix("`id`")} q.where = append(q.where, where) return q } @@ -149,7 +148,7 @@ func (q groupSelectSQL) IDIn(vs ...GroupID) groupSelectSQL { for _, v := range vs { _vs = append(_vs, uint64(v)) } - where := sqlla.ExprMultiuint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`id`")} + where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`id`")} q.where = append(q.where, where) return q } @@ -177,14 +176,13 @@ func (q groupSelectSQL) Name(v string, exprs ...sqlla.Operator) groupSelectSQL { } else { op = exprs[0] } - - where := sqlla.Exprstring{Value: v, Op: op, Column: q.appendColumnPrefix("`name`")} + where := sqlla.ExprString{Value: v, Op: op, Column: q.appendColumnPrefix("`name`")} q.where = append(q.where, where) return q } func (q groupSelectSQL) NameIn(vs ...string) groupSelectSQL { - where := sqlla.ExprMultistring{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`name`")} + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`name`")} q.where = append(q.where, where) return q } @@ -207,8 +205,7 @@ func (q groupSelectSQL) LeaderUserID(v UserId, exprs ...sqlla.Operator) groupSel } else { op = exprs[0] } - - where := sqlla.Expruint64{Value: uint64(v), Op: op, Column: q.appendColumnPrefix("`leader_user_id`")} + where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: q.appendColumnPrefix("`leader_user_id`")} q.where = append(q.where, where) return q } @@ -218,7 +215,7 @@ func (q groupSelectSQL) LeaderUserIDIn(vs ...UserId) groupSelectSQL { for _, v := range vs { _vs = append(_vs, uint64(v)) } - where := sqlla.ExprMultiuint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`leader_user_id`")} + where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`leader_user_id`")} q.where = append(q.where, where) return q } @@ -241,14 +238,13 @@ func (q groupSelectSQL) SubLeaderUserID(v sql.Null[T], exprs ...sqlla.Operator) } else { op = exprs[0] } - - where := sqlla.Exprsql.Null[T]{Value: v, Op: op, Column: q.appendColumnPrefix("`sub_leader_user_id`")} + where := sqlla.ExprNull[T]{Value: v, Op: op, Column: q.appendColumnPrefix("`sub_leader_user_id`")} q.where = append(q.where, where) return q } func (q groupSelectSQL) SubLeaderUserIDIn(vs ...sql.Null[T]) groupSelectSQL { - where := sqlla.ExprMultisql.Null[T]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`sub_leader_user_id`")} + where := sqlla.ExprMultiNull[T]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`sub_leader_user_id`")} q.where = append(q.where, where) return q } @@ -271,14 +267,13 @@ func (q groupSelectSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) groupSel } else { op = exprs[0] } - - where := sqlla.Exprtime.Time{Value: v, Op: op, Column: q.appendColumnPrefix("`created_at`")} + where := sqlla.ExprTime{Value: v, Op: op, Column: q.appendColumnPrefix("`created_at`")} q.where = append(q.where, where) return q } func (q groupSelectSQL) CreatedAtIn(vs ...time.Time) groupSelectSQL { - where := sqlla.ExprMultitime.Time{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`created_at`")} + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`created_at`")} q.where = append(q.where, where) return q } @@ -294,20 +289,19 @@ func (q groupSelectSQL) OrderByCreatedAt(order sqlla.Order) groupSelectSQL { return q } -func (q groupSelectSQL) UpdatedAt(v MysqlNullTime, exprs ...sqlla.Operator) groupSelectSQL { +func (q groupSelectSQL) UpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) groupSelectSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: q.appendColumnPrefix("`updated_at`")} q.where = append(q.where, where) return q } -func (q groupSelectSQL) UpdatedAtIn(vs ...MysqlNullTime) groupSelectSQL { +func (q groupSelectSQL) UpdatedAtIn(vs ...mysql.NullTime) groupSelectSQL { where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`updated_at`")} q.where = append(q.where, where) return q @@ -597,29 +591,25 @@ func (q groupUpdateSQL) WhereCreatedAtIn(vs ...time.Time) groupUpdateSQL { return q } -func (q groupUpdateSQL) SetUpdatedAt(v MysqlNullTime) groupUpdateSQL { +func (q groupUpdateSQL) SetUpdatedAt(v mysql.NullTime) groupUpdateSQL { q.setMap["`updated_at`"] = v return q } -func (q groupUpdateSQL) WhereUpdatedAt(v MysqlNullTime, exprs ...sqlla.Operator) groupUpdateSQL { +func (q groupUpdateSQL) WhereUpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) groupUpdateSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprNullTime{Value: mysql.NullTime(v), Op: op, Column: "`updated_at`"} + where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: "`updated_at`"} q.where = append(q.where, where) return q } -func (q groupUpdateSQL) WhereUpdatedAtIn(vs ...MysqlNullTime) groupUpdateSQL { - _vs := make([]mysql.NullTime, 0, len(vs)) - for _, v := range vs { - _vs = append(_vs, mysql.NullTime(v)) - } - where := sqlla.ExprMultiNullTime{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} +func (q groupUpdateSQL) WhereUpdatedAtIn(vs ...mysql.NullTime) groupUpdateSQL { + where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} q.where = append(q.where, where) return q } @@ -723,7 +713,7 @@ func (q groupInsertSQL) ValueCreatedAt(v time.Time) groupInsertSQL { return q } -func (q groupInsertSQL) ValueUpdatedAt(v MysqlNullTime) groupInsertSQL { +func (q groupInsertSQL) ValueUpdatedAt(v mysql.NullTime) groupInsertSQL { q.setMap["`updated_at`"] = v return q } @@ -891,7 +881,7 @@ func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateCreatedAt() groupInsertO return q } -func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v MysqlNullTime) groupInsertOnDuplicateKeyUpdateSQL { +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v mysql.NullTime) groupInsertOnDuplicateKeyUpdateSQL { q.onDuplicateKeyUpdateMap["`updated_at`"] = v return q } @@ -1138,24 +1128,20 @@ func (q groupDeleteSQL) CreatedAtIn(vs ...time.Time) groupDeleteSQL { return q } -func (q groupDeleteSQL) UpdatedAt(v MysqlNullTime, exprs ...sqlla.Operator) groupDeleteSQL { +func (q groupDeleteSQL) UpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) groupDeleteSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprNullTime{Value: mysql.NullTime(v), Op: op, Column: "`updated_at`"} + where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: "`updated_at`"} q.where = append(q.where, where) return q } -func (q groupDeleteSQL) UpdatedAtIn(vs ...MysqlNullTime) groupDeleteSQL { - _vs := make([]mysql.NullTime, 0, len(vs)) - for _, v := range vs { - _vs = append(_vs, mysql.NullTime(v)) - } - where := sqlla.ExprMultiNullTime{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} +func (q groupDeleteSQL) UpdatedAtIn(vs ...mysql.NullTime) groupDeleteSQL { + where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} q.where = append(q.where, where) return q } diff --git a/_example/user.gen.go b/_example/user.gen.go index e69de29..e71f599 100644 --- a/_example/user.gen.go +++ b/_example/user.gen.go @@ -0,0 +1,1271 @@ +// Code generated by github.com/mackee/go-sqlla/v2/cmd/sqlla - DO NOT EDIT. +package example + +import ( + "context" + "fmt" + "strconv" + "strings" + + "database/sql" + "github.com/go-sql-driver/mysql" + "time" + + "github.com/mackee/go-sqlla/v2" +) + +type userSQL struct { + where sqlla.Where +} + +func NewUserSQL() userSQL { + q := userSQL{} + return q +} + +var userAllColumns = []string{ + "`id`", "`name`", "`age`", "`rate`", "`icon_image`", "`created_at`", "`updated_at`", +} + +type userSelectSQL struct { + userSQL + Columns []string + order string + limit *uint64 + offset *uint64 + tableAlias string + joinClauses []string + + additionalWhereClause string + additionalWhereClauseArgs []interface{} + + groupByColumns []string + + isForUpdate bool +} + +func (q userSQL) Select() userSelectSQL { + return userSelectSQL{ + q, + userAllColumns, + "", + nil, + nil, + "", + nil, + "", + nil, + nil, + false, + } +} + +func (q userSelectSQL) Or(qs ...userSelectSQL) userSelectSQL { + ws := make([]sqlla.Where, 0, len(qs)) + for _, q := range qs { + ws = append(ws, q.where) + } + q.where = append(q.where, sqlla.ExprOr(ws)) + return q +} + +func (q userSelectSQL) Limit(l uint64) userSelectSQL { + q.limit = &l + return q +} + +func (q userSelectSQL) Offset(o uint64) userSelectSQL { + q.offset = &o + return q +} + +func (q userSelectSQL) ForUpdate() userSelectSQL { + q.isForUpdate = true + return q +} + +func (q userSelectSQL) TableAlias(alias string) userSelectSQL { + q.tableAlias = "`" + alias + "`" + return q +} + +func (q userSelectSQL) SetColumns(columns ...string) userSelectSQL { + q.Columns = make([]string, 0, len(columns)) + for _, column := range columns { + if strings.ContainsAny(column, "(.`") { + q.Columns = append(q.Columns, column) + } else { + q.Columns = append(q.Columns, "`"+column+"`") + } + } + return q +} + +func (q userSelectSQL) JoinClause(clause string) userSelectSQL { + q.joinClauses = append(q.joinClauses, clause) + return q +} + +func (q userSelectSQL) AdditionalWhereClause(clause string, args ...interface{}) userSelectSQL { + q.additionalWhereClause = clause + q.additionalWhereClauseArgs = args + return q +} + +func (q userSelectSQL) appendColumnPrefix(column string) string { + if q.tableAlias == "" || strings.ContainsAny(column, "(.") { + return column + } + return q.tableAlias + "." + column +} + +func (q userSelectSQL) GroupBy(columns ...string) userSelectSQL { + q.groupByColumns = make([]string, 0, len(columns)) + for _, column := range columns { + if strings.ContainsAny(column, "(.`") { + q.groupByColumns = append(q.groupByColumns, column) + } else { + q.groupByColumns = append(q.groupByColumns, "`"+column+"`") + } + } + return q +} + +func (q userSelectSQL) ID(v UserId, exprs ...sqlla.Operator) userSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: q.appendColumnPrefix("`id`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) IDIn(vs ...UserId) userSelectSQL { + _vs := make([]uint64, 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, uint64(v)) + } + where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`id`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) PkColumn(pk int64, exprs ...sqlla.Operator) userSelectSQL { + v := UserId(pk) + return q.ID(v, exprs...) +} + +func (q userSelectSQL) OrderByID(order sqlla.Order) userSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`id`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userSelectSQL) Name(v string, exprs ...sqlla.Operator) userSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprString{Value: v, Op: op, Column: q.appendColumnPrefix("`name`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) NameIn(vs ...string) userSelectSQL { + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`name`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) OrderByName(order sqlla.Order) userSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`name`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userSelectSQL) Age(v sql.NullInt64, exprs ...sqlla.Operator) userSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNullInt64{Value: v, Op: op, Column: q.appendColumnPrefix("`age`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) AgeIn(vs ...sql.NullInt64) userSelectSQL { + where := sqlla.ExprMultiNullInt64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`age`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) OrderByAge(order sqlla.Order) userSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`age`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userSelectSQL) Rate(v float64, exprs ...sqlla.Operator) userSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprFloat64{Value: v, Op: op, Column: q.appendColumnPrefix("`rate`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) RateIn(vs ...float64) userSelectSQL { + where := sqlla.ExprMultiFloat64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`rate`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) OrderByRate(order sqlla.Order) userSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`rate`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userSelectSQL) IconImage(v []byte, exprs ...sqlla.Operator) userSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprBytes{Value: v, Op: op, Column: q.appendColumnPrefix("`icon_image`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) IconImageIn(vs ...[]byte) userSelectSQL { + where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`icon_image`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) OrderByIconImage(order sqlla.Order) userSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`icon_image`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userSelectSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: q.appendColumnPrefix("`created_at`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) CreatedAtIn(vs ...time.Time) userSelectSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`created_at`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) OrderByCreatedAt(order sqlla.Order) userSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`created_at`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userSelectSQL) UpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) userSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: q.appendColumnPrefix("`updated_at`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) UpdatedAtIn(vs ...mysql.NullTime) userSelectSQL { + where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`updated_at`")} + q.where = append(q.where, where) + return q +} + +func (q userSelectSQL) OrderByUpdatedAt(order sqlla.Order) userSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`updated_at`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userSelectSQL) ToSql() (string, []interface{}, error) { + columns := strings.Join(q.Columns, ", ") + wheres, vs, err := q.where.ToSql() + if err != nil { + return "", nil, err + } + + tableName := "`user`" + if q.tableAlias != "" { + tableName = tableName + " AS " + q.tableAlias + pcs := make([]string, 0, len(q.Columns)) + for _, column := range q.Columns { + pcs = append(pcs, q.appendColumnPrefix(column)) + } + columns = strings.Join(pcs, ", ") + } + query := "SELECT " + columns + " FROM " + tableName + if len(q.joinClauses) > 0 { + jc := strings.Join(q.joinClauses, " ") + query += " " + jc + } + if wheres != "" { + query += " WHERE" + wheres + } + if q.additionalWhereClause != "" { + query += " " + q.additionalWhereClause + if len(q.additionalWhereClauseArgs) > 0 { + vs = append(vs, q.additionalWhereClauseArgs...) + } + } + if len(q.groupByColumns) > 0 { + query += " GROUP BY " + gbcs := make([]string, 0, len(q.groupByColumns)) + for _, column := range q.groupByColumns { + gbcs = append(gbcs, q.appendColumnPrefix(column)) + } + query += strings.Join(gbcs, ", ") + } + query += q.order + if q.limit != nil { + query += " LIMIT " + strconv.FormatUint(*q.limit, 10) + } + if q.offset != nil { + query += " OFFSET " + strconv.FormatUint(*q.offset, 10) + } + + if q.isForUpdate { + query += " FOR UPDATE" + } + + return query + ";", vs, nil +} + +func (s User) Select() userSelectSQL { + return NewUserSQL().Select().ID(s.Id) +} +func (q userSelectSQL) Single(db sqlla.DB) (User, error) { + q.Columns = userAllColumns + query, args, err := q.ToSql() + if err != nil { + return User{}, err + } + + row := db.QueryRow(query, args...) + return q.Scan(row) +} + +func (q userSelectSQL) SingleContext(ctx context.Context, db sqlla.DB) (User, error) { + q.Columns = userAllColumns + query, args, err := q.ToSql() + if err != nil { + return User{}, err + } + + row := db.QueryRowContext(ctx, query, args...) + return q.Scan(row) +} + +func (q userSelectSQL) All(db sqlla.DB) ([]User, error) { + rs := make([]User, 0, 10) + q.Columns = userAllColumns + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := db.Query(query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + r, err := q.Scan(rows) + if err != nil { + return nil, err + } + rs = append(rs, r) + } + return rs, nil +} + +func (q userSelectSQL) AllContext(ctx context.Context, db sqlla.DB) ([]User, error) { + rs := make([]User, 0, 10) + q.Columns = userAllColumns + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + r, err := q.Scan(rows) + if err != nil { + return nil, err + } + rs = append(rs, r) + } + return rs, nil +} + +func (q userSelectSQL) Scan(s sqlla.Scanner) (User, error) { + var row User + err := s.Scan( + &row.Id, + &row.Name, + &row.Age, + &row.Rate, + &row.IconImage, + &row.CreatedAt, + &row.UpdatedAt, + ) + return row, err +} + +type userUpdateSQL struct { + userSQL + setMap sqlla.SetMap + Columns []string +} + +func (q userSQL) Update() userUpdateSQL { + return userUpdateSQL{ + userSQL: q, + setMap: sqlla.SetMap{}, + } +} + +func (q userUpdateSQL) SetID(v UserId) userUpdateSQL { + q.setMap["`id`"] = v + return q +} + +func (q userUpdateSQL) WhereID(v UserId, exprs ...sqlla.Operator) userUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) WhereIDIn(vs ...UserId) userUpdateSQL { + _vs := make([]uint64, 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, uint64(v)) + } + where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) SetName(v string) userUpdateSQL { + q.setMap["`name`"] = v + return q +} + +func (q userUpdateSQL) WhereName(v string, exprs ...sqlla.Operator) userUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprString{Value: v, Op: op, Column: "`name`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) WhereNameIn(vs ...string) userUpdateSQL { + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`name`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) SetAge(v sql.NullInt64) userUpdateSQL { + q.setMap["`age`"] = v + return q +} + +func (q userUpdateSQL) WhereAge(v sql.NullInt64, exprs ...sqlla.Operator) userUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNullInt64{Value: v, Op: op, Column: "`age`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) WhereAgeIn(vs ...sql.NullInt64) userUpdateSQL { + where := sqlla.ExprMultiNullInt64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`age`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) SetRate(v float64) userUpdateSQL { + q.setMap["`rate`"] = v + return q +} + +func (q userUpdateSQL) WhereRate(v float64, exprs ...sqlla.Operator) userUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprFloat64{Value: v, Op: op, Column: "`rate`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) WhereRateIn(vs ...float64) userUpdateSQL { + where := sqlla.ExprMultiFloat64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`rate`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) SetIconImage(v []byte) userUpdateSQL { + q.setMap["`icon_image`"] = v + return q +} + +func (q userUpdateSQL) WhereIconImage(v []byte, exprs ...sqlla.Operator) userUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprBytes{Value: v, Op: op, Column: "`icon_image`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) WhereIconImageIn(vs ...[]byte) userUpdateSQL { + where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`icon_image`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) SetCreatedAt(v time.Time) userUpdateSQL { + q.setMap["`created_at`"] = v + return q +} + +func (q userUpdateSQL) WhereCreatedAt(v time.Time, exprs ...sqlla.Operator) userUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) WhereCreatedAtIn(vs ...time.Time) userUpdateSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) SetUpdatedAt(v mysql.NullTime) userUpdateSQL { + q.setMap["`updated_at`"] = v + return q +} + +func (q userUpdateSQL) WhereUpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) userUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) WhereUpdatedAtIn(vs ...mysql.NullTime) userUpdateSQL { + where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userUpdateSQL) ToSql() (string, []interface{}, error) { + var err error + var s interface{} = User{} + if t, ok := s.(userDefaultUpdateHooker); ok { + q, err = t.DefaultUpdateHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + setColumns, svs, err := q.setMap.ToUpdateSql() + if err != nil { + return "", []interface{}{}, err + } + wheres, wvs, err := q.where.ToSql() + if err != nil { + return "", []interface{}{}, err + } + + query := "UPDATE `user` SET" + setColumns + if wheres != "" { + query += " WHERE" + wheres + } + + return query + ";", append(svs, wvs...), nil +} +func (s User) Update() userUpdateSQL { + return NewUserSQL().Update().WhereID(s.Id) +} + +func (q userUpdateSQL) Exec(db sqlla.DB) ([]User, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + _, err = db.Exec(query, args...) + if err != nil { + return nil, err + } + qq := q.userSQL + + return qq.Select().All(db) +} + +func (q userUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) ([]User, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + _, err = db.ExecContext(ctx, query, args...) + if err != nil { + return nil, err + } + qq := q.userSQL + + return qq.Select().AllContext(ctx, db) +} + +type userDefaultUpdateHooker interface { + DefaultUpdateHook(userUpdateSQL) (userUpdateSQL, error) +} + +type userInsertSQL struct { + userSQL + setMap sqlla.SetMap + Columns []string +} + +func (q userSQL) Insert() userInsertSQL { + return userInsertSQL{ + userSQL: q, + setMap: sqlla.SetMap{}, + } +} + +func (q userInsertSQL) ValueID(v UserId) userInsertSQL { + q.setMap["`id`"] = v + return q +} + +func (q userInsertSQL) ValueName(v string) userInsertSQL { + q.setMap["`name`"] = v + return q +} + +func (q userInsertSQL) ValueAge(v sql.NullInt64) userInsertSQL { + q.setMap["`age`"] = v + return q +} + +func (q userInsertSQL) ValueRate(v float64) userInsertSQL { + q.setMap["`rate`"] = v + return q +} + +func (q userInsertSQL) ValueIconImage(v []byte) userInsertSQL { + q.setMap["`icon_image`"] = v + return q +} + +func (q userInsertSQL) ValueCreatedAt(v time.Time) userInsertSQL { + q.setMap["`created_at`"] = v + return q +} + +func (q userInsertSQL) ValueUpdatedAt(v mysql.NullTime) userInsertSQL { + q.setMap["`updated_at`"] = v + return q +} + +func (q userInsertSQL) ToSql() (string, []interface{}, error) { + query, vs, err := q.userInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + return query + ";", vs, nil +} + +func (q userInsertSQL) userInsertSQLToSql() (string, []interface{}, error) { + var err error + var s interface{} = User{} + if t, ok := s.(userDefaultInsertHooker); ok { + q, err = t.DefaultInsertHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + qs, vs, err := q.setMap.ToInsertSql() + if err != nil { + return "", []interface{}{}, err + } + + query := "INSERT INTO `user` " + qs + + return query, vs, nil +} + +func (q userInsertSQL) OnDuplicateKeyUpdate() userInsertOnDuplicateKeyUpdateSQL { + return userInsertOnDuplicateKeyUpdateSQL{ + insertSQL: q, + onDuplicateKeyUpdateMap: sqlla.SetMap{}, + } +} + +func (q userInsertSQL) Exec(db sqlla.DB) (User, error) { + query, args, err := q.ToSql() + if err != nil { + return User{}, err + } + result, err := db.Exec(query, args...) + if err != nil { + return User{}, err + } + id, err := result.LastInsertId() + if err != nil { + return User{}, err + } + return NewUserSQL().Select().PkColumn(id).Single(db) +} + +func (q userInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (User, error) { + query, args, err := q.ToSql() + if err != nil { + return User{}, err + } + result, err := db.ExecContext(ctx, query, args...) + if err != nil { + return User{}, err + } + id, err := result.LastInsertId() + if err != nil { + return User{}, err + } + return NewUserSQL().Select().PkColumn(id).SingleContext(ctx, db) +} + +func (q userInsertSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userDefaultInsertHooker interface { + DefaultInsertHook(userInsertSQL) (userInsertSQL, error) +} + +type userInsertSQLToSqler interface { + userInsertSQLToSql() (string, []interface{}, error) +} + +type userInsertOnDuplicateKeyUpdateSQL struct { + insertSQL userInsertSQLToSqler + onDuplicateKeyUpdateMap sqlla.SetMap +} + +func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateID(v UserId) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateID(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateID() userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = sqlla.SetMapRawValue("VALUES(`id`)") + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateName(v string) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`name`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateName(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`name`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateName() userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`name`"] = sqlla.SetMapRawValue("VALUES(`name`)") + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateAge(v sql.NullInt64) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`age`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateAge(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`age`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateAge() userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`age`"] = sqlla.SetMapRawValue("VALUES(`age`)") + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateRate(v float64) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`rate`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateRate(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`rate`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateRate() userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`rate`"] = sqlla.SetMapRawValue("VALUES(`rate`)") + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateIconImage(v []byte) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`icon_image`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateIconImage(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`icon_image`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateIconImage() userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`icon_image`"] = sqlla.SetMapRawValue("VALUES(`icon_image`)") + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateCreatedAt(v time.Time) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateCreatedAt(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateCreatedAt() userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = sqlla.SetMapRawValue("VALUES(`created_at`)") + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v mysql.NullTime) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUpdatedAt(v sqlla.SetMapRawValue) userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = v + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUpdatedAt() userInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = sqlla.SetMapRawValue("VALUES(`updated_at`)") + return q +} + +func (q userInsertOnDuplicateKeyUpdateSQL) ToSql() (string, []interface{}, error) { + var err error + var s interface{} = User{} + if t, ok := s.(userDefaultInsertOnDuplicateKeyUpdateHooker); ok { + q, err = t.DefaultInsertOnDuplicateKeyUpdateHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + + query, vs, err := q.insertSQL.userInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + + os, ovs, err := q.onDuplicateKeyUpdateMap.ToUpdateSql() + if err != nil { + return "", []interface{}{}, err + } + query += " ON DUPLICATE KEY UPDATE" + os + vs = append(vs, ovs...) + + return query + ";", vs, nil +} + +func (q userInsertOnDuplicateKeyUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) (User, error) { + query, args, err := q.ToSql() + if err != nil { + return User{}, err + } + result, err := db.ExecContext(ctx, query, args...) + if err != nil { + return User{}, err + } + id, err := result.LastInsertId() + if err != nil { + return User{}, err + } + return NewUserSQL().Select().PkColumn(id).SingleContext(ctx, db) +} + +func (q userInsertOnDuplicateKeyUpdateSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userDefaultInsertOnDuplicateKeyUpdateHooker interface { + DefaultInsertOnDuplicateKeyUpdateHook(userInsertOnDuplicateKeyUpdateSQL) (userInsertOnDuplicateKeyUpdateSQL, error) +} + +type userBulkInsertSQL struct { + insertSQLs []userInsertSQL +} + +func (q userSQL) BulkInsert() *userBulkInsertSQL { + return &userBulkInsertSQL{ + insertSQLs: []userInsertSQL{}, + } +} + +func (q *userBulkInsertSQL) Append(iqs ...userInsertSQL) { + q.insertSQLs = append(q.insertSQLs, iqs...) +} + +func (q *userBulkInsertSQL) userInsertSQLToSql() (string, []interface{}, error) { + if len(q.insertSQLs) == 0 { + return "", []interface{}{}, fmt.Errorf("sqlla: This userBulkInsertSQL's InsertSQL was empty") + } + iqs := make([]userInsertSQL, len(q.insertSQLs)) + copy(iqs, q.insertSQLs) + + var s interface{} = User{} + if t, ok := s.(userDefaultInsertHooker); ok { + for i, iq := range iqs { + var err error + iq, err = t.DefaultInsertHook(iq) + if err != nil { + return "", []interface{}{}, err + } + iqs[i] = iq + } + } + + sms := make(sqlla.SetMaps, 0, len(q.insertSQLs)) + for _, iq := range q.insertSQLs { + sms = append(sms, iq.setMap) + } + + query, vs, err := sms.ToInsertSql() + if err != nil { + return "", []interface{}{}, err + } + + return "INSERT INTO `user` " + query, vs, nil +} + +func (q *userBulkInsertSQL) ToSql() (string, []interface{}, error) { + query, vs, err := q.userInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + return query + ";", vs, nil +} + +func (q *userBulkInsertSQL) OnDuplicateKeyUpdate() userInsertOnDuplicateKeyUpdateSQL { + return userInsertOnDuplicateKeyUpdateSQL{ + insertSQL: q, + onDuplicateKeyUpdateMap: sqlla.SetMap{}, + } +} + +func (q *userBulkInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userDeleteSQL struct { + userSQL +} + +func (q userSQL) Delete() userDeleteSQL { + return userDeleteSQL{ + q, + } +} + +func (q userDeleteSQL) ID(v UserId, exprs ...sqlla.Operator) userDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: uint64(v), Op: op, Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) IDIn(vs ...UserId) userDeleteSQL { + _vs := make([]uint64, 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, uint64(v)) + } + where := sqlla.ExprMultiUint64{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) Name(v string, exprs ...sqlla.Operator) userDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprString{Value: v, Op: op, Column: "`name`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) NameIn(vs ...string) userDeleteSQL { + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`name`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) Age(v sql.NullInt64, exprs ...sqlla.Operator) userDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNullInt64{Value: v, Op: op, Column: "`age`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) AgeIn(vs ...sql.NullInt64) userDeleteSQL { + where := sqlla.ExprMultiNullInt64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`age`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) Rate(v float64, exprs ...sqlla.Operator) userDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprFloat64{Value: v, Op: op, Column: "`rate`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) RateIn(vs ...float64) userDeleteSQL { + where := sqlla.ExprMultiFloat64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`rate`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) IconImage(v []byte, exprs ...sqlla.Operator) userDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprBytes{Value: v, Op: op, Column: "`icon_image`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) IconImageIn(vs ...[]byte) userDeleteSQL { + where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`icon_image`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) CreatedAtIn(vs ...time.Time) userDeleteSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) UpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) userDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) UpdatedAtIn(vs ...mysql.NullTime) userDeleteSQL { + where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userDeleteSQL) ToSql() (string, []interface{}, error) { + wheres, vs, err := q.where.ToSql() + if err != nil { + return "", nil, err + } + + query := "DELETE FROM `user`" + if wheres != "" { + query += " WHERE" + wheres + } + + return query + ";", vs, nil +} + +func (q userDeleteSQL) Exec(db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + return db.Exec(query, args...) +} + +func (q userDeleteSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + return db.ExecContext(ctx, query, args...) +} +func (s User) Delete(db sqlla.DB) (sql.Result, error) { + query, args, err := NewUserSQL().Delete().ID(s.Id).ToSql() + if err != nil { + return nil, err + } + return db.Exec(query, args...) +} + +func (s User) DeleteContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := NewUserSQL().Delete().ID(s.Id).ToSql() + if err != nil { + return nil, err + } + return db.ExecContext(ctx, query, args...) +} diff --git a/_example/user_external.gen.go b/_example/user_external.gen.go index e69de29..d8b2a14 100644 --- a/_example/user_external.gen.go +++ b/_example/user_external.gen.go @@ -0,0 +1,1076 @@ +// Code generated by github.com/mackee/go-sqlla/v2/cmd/sqlla - DO NOT EDIT. +package example + +import ( + "context" + "fmt" + "strconv" + "strings" + + "database/sql" + "time" + + "github.com/mackee/go-sqlla/v2" +) + +type userExternalSQL struct { + where sqlla.Where +} + +func NewUserExternalSQL() userExternalSQL { + q := userExternalSQL{} + return q +} + +var userExternalAllColumns = []string{ + "`id`", "`user_id`", "`icon_image`", "`created_at`", "`updated_at`", +} + +type userExternalSelectSQL struct { + userExternalSQL + Columns []string + order string + limit *uint64 + offset *uint64 + tableAlias string + joinClauses []string + + additionalWhereClause string + additionalWhereClauseArgs []interface{} + + groupByColumns []string + + isForUpdate bool +} + +func (q userExternalSQL) Select() userExternalSelectSQL { + return userExternalSelectSQL{ + q, + userExternalAllColumns, + "", + nil, + nil, + "", + nil, + "", + nil, + nil, + false, + } +} + +func (q userExternalSelectSQL) Or(qs ...userExternalSelectSQL) userExternalSelectSQL { + ws := make([]sqlla.Where, 0, len(qs)) + for _, q := range qs { + ws = append(ws, q.where) + } + q.where = append(q.where, sqlla.ExprOr(ws)) + return q +} + +func (q userExternalSelectSQL) Limit(l uint64) userExternalSelectSQL { + q.limit = &l + return q +} + +func (q userExternalSelectSQL) Offset(o uint64) userExternalSelectSQL { + q.offset = &o + return q +} + +func (q userExternalSelectSQL) ForUpdate() userExternalSelectSQL { + q.isForUpdate = true + return q +} + +func (q userExternalSelectSQL) TableAlias(alias string) userExternalSelectSQL { + q.tableAlias = "`" + alias + "`" + return q +} + +func (q userExternalSelectSQL) SetColumns(columns ...string) userExternalSelectSQL { + q.Columns = make([]string, 0, len(columns)) + for _, column := range columns { + if strings.ContainsAny(column, "(.`") { + q.Columns = append(q.Columns, column) + } else { + q.Columns = append(q.Columns, "`"+column+"`") + } + } + return q +} + +func (q userExternalSelectSQL) JoinClause(clause string) userExternalSelectSQL { + q.joinClauses = append(q.joinClauses, clause) + return q +} + +func (q userExternalSelectSQL) AdditionalWhereClause(clause string, args ...interface{}) userExternalSelectSQL { + q.additionalWhereClause = clause + q.additionalWhereClauseArgs = args + return q +} + +func (q userExternalSelectSQL) appendColumnPrefix(column string) string { + if q.tableAlias == "" || strings.ContainsAny(column, "(.") { + return column + } + return q.tableAlias + "." + column +} + +func (q userExternalSelectSQL) GroupBy(columns ...string) userExternalSelectSQL { + q.groupByColumns = make([]string, 0, len(columns)) + for _, column := range columns { + if strings.ContainsAny(column, "(.`") { + q.groupByColumns = append(q.groupByColumns, column) + } else { + q.groupByColumns = append(q.groupByColumns, "`"+column+"`") + } + } + return q +} + +func (q userExternalSelectSQL) ID(v uint64, exprs ...sqlla.Operator) userExternalSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: q.appendColumnPrefix("`id`")} + q.where = append(q.where, where) + return q +} + +func (q userExternalSelectSQL) IDIn(vs ...uint64) userExternalSelectSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`id`")} + q.where = append(q.where, where) + return q +} + +func (q userExternalSelectSQL) PkColumn(pk int64, exprs ...sqlla.Operator) userExternalSelectSQL { + v := uint64(pk) + return q.ID(v, exprs...) +} + +func (q userExternalSelectSQL) OrderByID(order sqlla.Order) userExternalSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`id`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userExternalSelectSQL) UserID(v uint64, exprs ...sqlla.Operator) userExternalSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: q.appendColumnPrefix("`user_id`")} + q.where = append(q.where, where) + return q +} + +func (q userExternalSelectSQL) UserIDIn(vs ...uint64) userExternalSelectSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`user_id`")} + q.where = append(q.where, where) + return q +} + +func (q userExternalSelectSQL) OrderByUserID(order sqlla.Order) userExternalSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`user_id`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userExternalSelectSQL) IconImage(v []byte, exprs ...sqlla.Operator) userExternalSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprBytes{Value: v, Op: op, Column: q.appendColumnPrefix("`icon_image`")} + q.where = append(q.where, where) + return q +} + +func (q userExternalSelectSQL) IconImageIn(vs ...[]byte) userExternalSelectSQL { + where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`icon_image`")} + q.where = append(q.where, where) + return q +} + +func (q userExternalSelectSQL) OrderByIconImage(order sqlla.Order) userExternalSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`icon_image`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userExternalSelectSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userExternalSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: q.appendColumnPrefix("`created_at`")} + q.where = append(q.where, where) + return q +} + +func (q userExternalSelectSQL) CreatedAtIn(vs ...time.Time) userExternalSelectSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`created_at`")} + q.where = append(q.where, where) + return q +} + +func (q userExternalSelectSQL) OrderByCreatedAt(order sqlla.Order) userExternalSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`created_at`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userExternalSelectSQL) UpdatedAt(v time.Time, exprs ...sqlla.Operator) userExternalSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: q.appendColumnPrefix("`updated_at`")} + q.where = append(q.where, where) + return q +} + +func (q userExternalSelectSQL) UpdatedAtIn(vs ...time.Time) userExternalSelectSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`updated_at`")} + q.where = append(q.where, where) + return q +} + +func (q userExternalSelectSQL) OrderByUpdatedAt(order sqlla.Order) userExternalSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`updated_at`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userExternalSelectSQL) ToSql() (string, []interface{}, error) { + columns := strings.Join(q.Columns, ", ") + wheres, vs, err := q.where.ToSql() + if err != nil { + return "", nil, err + } + + tableName := "`user_external`" + if q.tableAlias != "" { + tableName = tableName + " AS " + q.tableAlias + pcs := make([]string, 0, len(q.Columns)) + for _, column := range q.Columns { + pcs = append(pcs, q.appendColumnPrefix(column)) + } + columns = strings.Join(pcs, ", ") + } + query := "SELECT " + columns + " FROM " + tableName + if len(q.joinClauses) > 0 { + jc := strings.Join(q.joinClauses, " ") + query += " " + jc + } + if wheres != "" { + query += " WHERE" + wheres + } + if q.additionalWhereClause != "" { + query += " " + q.additionalWhereClause + if len(q.additionalWhereClauseArgs) > 0 { + vs = append(vs, q.additionalWhereClauseArgs...) + } + } + if len(q.groupByColumns) > 0 { + query += " GROUP BY " + gbcs := make([]string, 0, len(q.groupByColumns)) + for _, column := range q.groupByColumns { + gbcs = append(gbcs, q.appendColumnPrefix(column)) + } + query += strings.Join(gbcs, ", ") + } + query += q.order + if q.limit != nil { + query += " LIMIT " + strconv.FormatUint(*q.limit, 10) + } + if q.offset != nil { + query += " OFFSET " + strconv.FormatUint(*q.offset, 10) + } + + if q.isForUpdate { + query += " FOR UPDATE" + } + + return query + ";", vs, nil +} + +func (s UserExternal) Select() userExternalSelectSQL { + return NewUserExternalSQL().Select().ID(s.Id) +} +func (q userExternalSelectSQL) Single(db sqlla.DB) (UserExternal, error) { + q.Columns = userExternalAllColumns + query, args, err := q.ToSql() + if err != nil { + return UserExternal{}, err + } + + row := db.QueryRow(query, args...) + return q.Scan(row) +} + +func (q userExternalSelectSQL) SingleContext(ctx context.Context, db sqlla.DB) (UserExternal, error) { + q.Columns = userExternalAllColumns + query, args, err := q.ToSql() + if err != nil { + return UserExternal{}, err + } + + row := db.QueryRowContext(ctx, query, args...) + return q.Scan(row) +} + +func (q userExternalSelectSQL) All(db sqlla.DB) ([]UserExternal, error) { + rs := make([]UserExternal, 0, 10) + q.Columns = userExternalAllColumns + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := db.Query(query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + r, err := q.Scan(rows) + if err != nil { + return nil, err + } + rs = append(rs, r) + } + return rs, nil +} + +func (q userExternalSelectSQL) AllContext(ctx context.Context, db sqlla.DB) ([]UserExternal, error) { + rs := make([]UserExternal, 0, 10) + q.Columns = userExternalAllColumns + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + r, err := q.Scan(rows) + if err != nil { + return nil, err + } + rs = append(rs, r) + } + return rs, nil +} + +func (q userExternalSelectSQL) Scan(s sqlla.Scanner) (UserExternal, error) { + var row UserExternal + err := s.Scan( + &row.Id, + &row.UserId, + &row.IconImage, + &row.CreatedAt, + &row.UpdatedAt, + ) + return row, err +} + +type userExternalUpdateSQL struct { + userExternalSQL + setMap sqlla.SetMap + Columns []string +} + +func (q userExternalSQL) Update() userExternalUpdateSQL { + return userExternalUpdateSQL{ + userExternalSQL: q, + setMap: sqlla.SetMap{}, + } +} + +func (q userExternalUpdateSQL) SetID(v uint64) userExternalUpdateSQL { + q.setMap["`id`"] = v + return q +} + +func (q userExternalUpdateSQL) WhereID(v uint64, exprs ...sqlla.Operator) userExternalUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalUpdateSQL) WhereIDIn(vs ...uint64) userExternalUpdateSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalUpdateSQL) SetUserID(v uint64) userExternalUpdateSQL { + q.setMap["`user_id`"] = v + return q +} + +func (q userExternalUpdateSQL) WhereUserID(v uint64, exprs ...sqlla.Operator) userExternalUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: "`user_id`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalUpdateSQL) WhereUserIDIn(vs ...uint64) userExternalUpdateSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`user_id`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalUpdateSQL) SetIconImage(v []byte) userExternalUpdateSQL { + q.setMap["`icon_image`"] = v + return q +} + +func (q userExternalUpdateSQL) WhereIconImage(v []byte, exprs ...sqlla.Operator) userExternalUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprBytes{Value: v, Op: op, Column: "`icon_image`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalUpdateSQL) WhereIconImageIn(vs ...[]byte) userExternalUpdateSQL { + where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`icon_image`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalUpdateSQL) SetCreatedAt(v time.Time) userExternalUpdateSQL { + q.setMap["`created_at`"] = v + return q +} + +func (q userExternalUpdateSQL) WhereCreatedAt(v time.Time, exprs ...sqlla.Operator) userExternalUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalUpdateSQL) WhereCreatedAtIn(vs ...time.Time) userExternalUpdateSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalUpdateSQL) SetUpdatedAt(v time.Time) userExternalUpdateSQL { + q.setMap["`updated_at`"] = v + return q +} + +func (q userExternalUpdateSQL) WhereUpdatedAt(v time.Time, exprs ...sqlla.Operator) userExternalUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalUpdateSQL) WhereUpdatedAtIn(vs ...time.Time) userExternalUpdateSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalUpdateSQL) ToSql() (string, []interface{}, error) { + var err error + var s interface{} = UserExternal{} + if t, ok := s.(userExternalDefaultUpdateHooker); ok { + q, err = t.DefaultUpdateHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + setColumns, svs, err := q.setMap.ToUpdateSql() + if err != nil { + return "", []interface{}{}, err + } + wheres, wvs, err := q.where.ToSql() + if err != nil { + return "", []interface{}{}, err + } + + query := "UPDATE `user_external` SET" + setColumns + if wheres != "" { + query += " WHERE" + wheres + } + + return query + ";", append(svs, wvs...), nil +} +func (s UserExternal) Update() userExternalUpdateSQL { + return NewUserExternalSQL().Update().WhereID(s.Id) +} + +func (q userExternalUpdateSQL) Exec(db sqlla.DB) ([]UserExternal, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + _, err = db.Exec(query, args...) + if err != nil { + return nil, err + } + qq := q.userExternalSQL + + return qq.Select().All(db) +} + +func (q userExternalUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) ([]UserExternal, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + _, err = db.ExecContext(ctx, query, args...) + if err != nil { + return nil, err + } + qq := q.userExternalSQL + + return qq.Select().AllContext(ctx, db) +} + +type userExternalDefaultUpdateHooker interface { + DefaultUpdateHook(userExternalUpdateSQL) (userExternalUpdateSQL, error) +} + +type userExternalInsertSQL struct { + userExternalSQL + setMap sqlla.SetMap + Columns []string +} + +func (q userExternalSQL) Insert() userExternalInsertSQL { + return userExternalInsertSQL{ + userExternalSQL: q, + setMap: sqlla.SetMap{}, + } +} + +func (q userExternalInsertSQL) ValueID(v uint64) userExternalInsertSQL { + q.setMap["`id`"] = v + return q +} + +func (q userExternalInsertSQL) ValueUserID(v uint64) userExternalInsertSQL { + q.setMap["`user_id`"] = v + return q +} + +func (q userExternalInsertSQL) ValueIconImage(v []byte) userExternalInsertSQL { + q.setMap["`icon_image`"] = v + return q +} + +func (q userExternalInsertSQL) ValueCreatedAt(v time.Time) userExternalInsertSQL { + q.setMap["`created_at`"] = v + return q +} + +func (q userExternalInsertSQL) ValueUpdatedAt(v time.Time) userExternalInsertSQL { + q.setMap["`updated_at`"] = v + return q +} + +func (q userExternalInsertSQL) ToSql() (string, []interface{}, error) { + query, vs, err := q.userExternalInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + return query + ";", vs, nil +} + +func (q userExternalInsertSQL) userExternalInsertSQLToSql() (string, []interface{}, error) { + var err error + var s interface{} = UserExternal{} + if t, ok := s.(userExternalDefaultInsertHooker); ok { + q, err = t.DefaultInsertHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + qs, vs, err := q.setMap.ToInsertSql() + if err != nil { + return "", []interface{}{}, err + } + + query := "INSERT INTO `user_external` " + qs + + return query, vs, nil +} + +func (q userExternalInsertSQL) OnDuplicateKeyUpdate() userExternalInsertOnDuplicateKeyUpdateSQL { + return userExternalInsertOnDuplicateKeyUpdateSQL{ + insertSQL: q, + onDuplicateKeyUpdateMap: sqlla.SetMap{}, + } +} + +func (q userExternalInsertSQL) Exec(db sqlla.DB) (UserExternal, error) { + query, args, err := q.ToSql() + if err != nil { + return UserExternal{}, err + } + result, err := db.Exec(query, args...) + if err != nil { + return UserExternal{}, err + } + id, err := result.LastInsertId() + if err != nil { + return UserExternal{}, err + } + return NewUserExternalSQL().Select().PkColumn(id).Single(db) +} + +func (q userExternalInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserExternal, error) { + query, args, err := q.ToSql() + if err != nil { + return UserExternal{}, err + } + result, err := db.ExecContext(ctx, query, args...) + if err != nil { + return UserExternal{}, err + } + id, err := result.LastInsertId() + if err != nil { + return UserExternal{}, err + } + return NewUserExternalSQL().Select().PkColumn(id).SingleContext(ctx, db) +} + +func (q userExternalInsertSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userExternalDefaultInsertHooker interface { + DefaultInsertHook(userExternalInsertSQL) (userExternalInsertSQL, error) +} + +type userExternalInsertSQLToSqler interface { + userExternalInsertSQLToSql() (string, []interface{}, error) +} + +type userExternalInsertOnDuplicateKeyUpdateSQL struct { + insertSQL userExternalInsertSQLToSqler + onDuplicateKeyUpdateMap sqlla.SetMap +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateID(v uint64) userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = v + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateID(v sqlla.SetMapRawValue) userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = v + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) SameOnUpdateID() userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = sqlla.SetMapRawValue("VALUES(`id`)") + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUserID(v uint64) userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`user_id`"] = v + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUserID(v sqlla.SetMapRawValue) userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`user_id`"] = v + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUserID() userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`user_id`"] = sqlla.SetMapRawValue("VALUES(`user_id`)") + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateIconImage(v []byte) userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`icon_image`"] = v + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateIconImage(v sqlla.SetMapRawValue) userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`icon_image`"] = v + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) SameOnUpdateIconImage() userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`icon_image`"] = sqlla.SetMapRawValue("VALUES(`icon_image`)") + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateCreatedAt(v time.Time) userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = v + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateCreatedAt(v sqlla.SetMapRawValue) userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = v + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) SameOnUpdateCreatedAt() userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = sqlla.SetMapRawValue("VALUES(`created_at`)") + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v time.Time) userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = v + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUpdatedAt(v sqlla.SetMapRawValue) userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = v + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUpdatedAt() userExternalInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = sqlla.SetMapRawValue("VALUES(`updated_at`)") + return q +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) ToSql() (string, []interface{}, error) { + var err error + var s interface{} = UserExternal{} + if t, ok := s.(userExternalDefaultInsertOnDuplicateKeyUpdateHooker); ok { + q, err = t.DefaultInsertOnDuplicateKeyUpdateHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + + query, vs, err := q.insertSQL.userExternalInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + + os, ovs, err := q.onDuplicateKeyUpdateMap.ToUpdateSql() + if err != nil { + return "", []interface{}{}, err + } + query += " ON DUPLICATE KEY UPDATE" + os + vs = append(vs, ovs...) + + return query + ";", vs, nil +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserExternal, error) { + query, args, err := q.ToSql() + if err != nil { + return UserExternal{}, err + } + result, err := db.ExecContext(ctx, query, args...) + if err != nil { + return UserExternal{}, err + } + id, err := result.LastInsertId() + if err != nil { + return UserExternal{}, err + } + return NewUserExternalSQL().Select().PkColumn(id).SingleContext(ctx, db) +} + +func (q userExternalInsertOnDuplicateKeyUpdateSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userExternalDefaultInsertOnDuplicateKeyUpdateHooker interface { + DefaultInsertOnDuplicateKeyUpdateHook(userExternalInsertOnDuplicateKeyUpdateSQL) (userExternalInsertOnDuplicateKeyUpdateSQL, error) +} + +type userExternalBulkInsertSQL struct { + insertSQLs []userExternalInsertSQL +} + +func (q userExternalSQL) BulkInsert() *userExternalBulkInsertSQL { + return &userExternalBulkInsertSQL{ + insertSQLs: []userExternalInsertSQL{}, + } +} + +func (q *userExternalBulkInsertSQL) Append(iqs ...userExternalInsertSQL) { + q.insertSQLs = append(q.insertSQLs, iqs...) +} + +func (q *userExternalBulkInsertSQL) userExternalInsertSQLToSql() (string, []interface{}, error) { + if len(q.insertSQLs) == 0 { + return "", []interface{}{}, fmt.Errorf("sqlla: This userExternalBulkInsertSQL's InsertSQL was empty") + } + iqs := make([]userExternalInsertSQL, len(q.insertSQLs)) + copy(iqs, q.insertSQLs) + + var s interface{} = UserExternal{} + if t, ok := s.(userExternalDefaultInsertHooker); ok { + for i, iq := range iqs { + var err error + iq, err = t.DefaultInsertHook(iq) + if err != nil { + return "", []interface{}{}, err + } + iqs[i] = iq + } + } + + sms := make(sqlla.SetMaps, 0, len(q.insertSQLs)) + for _, iq := range q.insertSQLs { + sms = append(sms, iq.setMap) + } + + query, vs, err := sms.ToInsertSql() + if err != nil { + return "", []interface{}{}, err + } + + return "INSERT INTO `user_external` " + query, vs, nil +} + +func (q *userExternalBulkInsertSQL) ToSql() (string, []interface{}, error) { + query, vs, err := q.userExternalInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + return query + ";", vs, nil +} + +func (q *userExternalBulkInsertSQL) OnDuplicateKeyUpdate() userExternalInsertOnDuplicateKeyUpdateSQL { + return userExternalInsertOnDuplicateKeyUpdateSQL{ + insertSQL: q, + onDuplicateKeyUpdateMap: sqlla.SetMap{}, + } +} + +func (q *userExternalBulkInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userExternalDeleteSQL struct { + userExternalSQL +} + +func (q userExternalSQL) Delete() userExternalDeleteSQL { + return userExternalDeleteSQL{ + q, + } +} + +func (q userExternalDeleteSQL) ID(v uint64, exprs ...sqlla.Operator) userExternalDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalDeleteSQL) IDIn(vs ...uint64) userExternalDeleteSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalDeleteSQL) UserID(v uint64, exprs ...sqlla.Operator) userExternalDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: "`user_id`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalDeleteSQL) UserIDIn(vs ...uint64) userExternalDeleteSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`user_id`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalDeleteSQL) IconImage(v []byte, exprs ...sqlla.Operator) userExternalDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprBytes{Value: v, Op: op, Column: "`icon_image`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalDeleteSQL) IconImageIn(vs ...[]byte) userExternalDeleteSQL { + where := sqlla.ExprMultiBytes{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`icon_image`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalDeleteSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userExternalDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalDeleteSQL) CreatedAtIn(vs ...time.Time) userExternalDeleteSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalDeleteSQL) UpdatedAt(v time.Time, exprs ...sqlla.Operator) userExternalDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalDeleteSQL) UpdatedAtIn(vs ...time.Time) userExternalDeleteSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userExternalDeleteSQL) ToSql() (string, []interface{}, error) { + wheres, vs, err := q.where.ToSql() + if err != nil { + return "", nil, err + } + + query := "DELETE FROM `user_external`" + if wheres != "" { + query += " WHERE" + wheres + } + + return query + ";", vs, nil +} + +func (q userExternalDeleteSQL) Exec(db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + return db.Exec(query, args...) +} + +func (q userExternalDeleteSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + return db.ExecContext(ctx, query, args...) +} +func (s UserExternal) Delete(db sqlla.DB) (sql.Result, error) { + query, args, err := NewUserExternalSQL().Delete().ID(s.Id).ToSql() + if err != nil { + return nil, err + } + return db.Exec(query, args...) +} + +func (s UserExternal) DeleteContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := NewUserExternalSQL().Delete().ID(s.Id).ToSql() + if err != nil { + return nil, err + } + return db.ExecContext(ctx, query, args...) +} diff --git a/_example/user_item.gen.go b/_example/user_item.gen.go index e69de29..a08ccf1 100644 --- a/_example/user_item.gen.go +++ b/_example/user_item.gen.go @@ -0,0 +1,1166 @@ +// Code generated by github.com/mackee/go-sqlla/v2/cmd/sqlla - DO NOT EDIT. +package example + +import ( + "context" + "fmt" + "strconv" + "strings" + + "database/sql" + + "github.com/mackee/go-sqlla/v2" +) + +type userItemSQL struct { + where sqlla.Where +} + +func NewUserItemSQL() userItemSQL { + q := userItemSQL{} + return q +} + +var userItemAllColumns = []string{ + "`id`", "`user_id`", "`item_id`", "`is_used`", "`has_extension`", "`used_at`", +} + +type userItemSelectSQL struct { + userItemSQL + Columns []string + order string + limit *uint64 + offset *uint64 + tableAlias string + joinClauses []string + + additionalWhereClause string + additionalWhereClauseArgs []interface{} + + groupByColumns []string + + isForUpdate bool +} + +func (q userItemSQL) Select() userItemSelectSQL { + return userItemSelectSQL{ + q, + userItemAllColumns, + "", + nil, + nil, + "", + nil, + "", + nil, + nil, + false, + } +} + +func (q userItemSelectSQL) Or(qs ...userItemSelectSQL) userItemSelectSQL { + ws := make([]sqlla.Where, 0, len(qs)) + for _, q := range qs { + ws = append(ws, q.where) + } + q.where = append(q.where, sqlla.ExprOr(ws)) + return q +} + +func (q userItemSelectSQL) Limit(l uint64) userItemSelectSQL { + q.limit = &l + return q +} + +func (q userItemSelectSQL) Offset(o uint64) userItemSelectSQL { + q.offset = &o + return q +} + +func (q userItemSelectSQL) ForUpdate() userItemSelectSQL { + q.isForUpdate = true + return q +} + +func (q userItemSelectSQL) TableAlias(alias string) userItemSelectSQL { + q.tableAlias = "`" + alias + "`" + return q +} + +func (q userItemSelectSQL) SetColumns(columns ...string) userItemSelectSQL { + q.Columns = make([]string, 0, len(columns)) + for _, column := range columns { + if strings.ContainsAny(column, "(.`") { + q.Columns = append(q.Columns, column) + } else { + q.Columns = append(q.Columns, "`"+column+"`") + } + } + return q +} + +func (q userItemSelectSQL) JoinClause(clause string) userItemSelectSQL { + q.joinClauses = append(q.joinClauses, clause) + return q +} + +func (q userItemSelectSQL) AdditionalWhereClause(clause string, args ...interface{}) userItemSelectSQL { + q.additionalWhereClause = clause + q.additionalWhereClauseArgs = args + return q +} + +func (q userItemSelectSQL) appendColumnPrefix(column string) string { + if q.tableAlias == "" || strings.ContainsAny(column, "(.") { + return column + } + return q.tableAlias + "." + column +} + +func (q userItemSelectSQL) GroupBy(columns ...string) userItemSelectSQL { + q.groupByColumns = make([]string, 0, len(columns)) + for _, column := range columns { + if strings.ContainsAny(column, "(.`") { + q.groupByColumns = append(q.groupByColumns, column) + } else { + q.groupByColumns = append(q.groupByColumns, "`"+column+"`") + } + } + return q +} + +func (q userItemSelectSQL) ID(v uint64, exprs ...sqlla.Operator) userItemSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: q.appendColumnPrefix("`id`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) IDIn(vs ...uint64) userItemSelectSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`id`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) PkColumn(pk int64, exprs ...sqlla.Operator) userItemSelectSQL { + v := uint64(pk) + return q.ID(v, exprs...) +} + +func (q userItemSelectSQL) OrderByID(order sqlla.Order) userItemSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`id`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userItemSelectSQL) UserID(v uint64, exprs ...sqlla.Operator) userItemSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: q.appendColumnPrefix("`user_id`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) UserIDIn(vs ...uint64) userItemSelectSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`user_id`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) OrderByUserID(order sqlla.Order) userItemSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`user_id`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userItemSelectSQL) ItemID(v string, exprs ...sqlla.Operator) userItemSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprString{Value: v, Op: op, Column: q.appendColumnPrefix("`item_id`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) ItemIDIn(vs ...string) userItemSelectSQL { + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`item_id`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) OrderByItemID(order sqlla.Order) userItemSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`item_id`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userItemSelectSQL) IsUsed(v bool, exprs ...sqlla.Operator) userItemSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprBool{Value: v, Op: op, Column: q.appendColumnPrefix("`is_used`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) IsUsedIn(vs ...bool) userItemSelectSQL { + where := sqlla.ExprMultiBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`is_used`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) OrderByIsUsed(order sqlla.Order) userItemSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`is_used`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userItemSelectSQL) HasExtension(v sql.NullBool, exprs ...sqlla.Operator) userItemSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNullBool{Value: v, Op: op, Column: q.appendColumnPrefix("`has_extension`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) HasExtensionIn(vs ...sql.NullBool) userItemSelectSQL { + where := sqlla.ExprMultiNullBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`has_extension`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) OrderByHasExtension(order sqlla.Order) userItemSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`has_extension`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userItemSelectSQL) UsedAt(v sql.NullTime, exprs ...sqlla.Operator) userItemSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNullTime{Value: v, Op: op, Column: q.appendColumnPrefix("`used_at`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) UsedAtIn(vs ...sql.NullTime) userItemSelectSQL { + where := sqlla.ExprMultiNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`used_at`")} + q.where = append(q.where, where) + return q +} + +func (q userItemSelectSQL) OrderByUsedAt(order sqlla.Order) userItemSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`used_at`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userItemSelectSQL) ToSql() (string, []interface{}, error) { + columns := strings.Join(q.Columns, ", ") + wheres, vs, err := q.where.ToSql() + if err != nil { + return "", nil, err + } + + tableName := "`user_item`" + if q.tableAlias != "" { + tableName = tableName + " AS " + q.tableAlias + pcs := make([]string, 0, len(q.Columns)) + for _, column := range q.Columns { + pcs = append(pcs, q.appendColumnPrefix(column)) + } + columns = strings.Join(pcs, ", ") + } + query := "SELECT " + columns + " FROM " + tableName + if len(q.joinClauses) > 0 { + jc := strings.Join(q.joinClauses, " ") + query += " " + jc + } + if wheres != "" { + query += " WHERE" + wheres + } + if q.additionalWhereClause != "" { + query += " " + q.additionalWhereClause + if len(q.additionalWhereClauseArgs) > 0 { + vs = append(vs, q.additionalWhereClauseArgs...) + } + } + if len(q.groupByColumns) > 0 { + query += " GROUP BY " + gbcs := make([]string, 0, len(q.groupByColumns)) + for _, column := range q.groupByColumns { + gbcs = append(gbcs, q.appendColumnPrefix(column)) + } + query += strings.Join(gbcs, ", ") + } + query += q.order + if q.limit != nil { + query += " LIMIT " + strconv.FormatUint(*q.limit, 10) + } + if q.offset != nil { + query += " OFFSET " + strconv.FormatUint(*q.offset, 10) + } + + if q.isForUpdate { + query += " FOR UPDATE" + } + + return query + ";", vs, nil +} + +func (s UserItem) Select() userItemSelectSQL { + return NewUserItemSQL().Select().ID(s.Id) +} +func (q userItemSelectSQL) Single(db sqlla.DB) (UserItem, error) { + q.Columns = userItemAllColumns + query, args, err := q.ToSql() + if err != nil { + return UserItem{}, err + } + + row := db.QueryRow(query, args...) + return q.Scan(row) +} + +func (q userItemSelectSQL) SingleContext(ctx context.Context, db sqlla.DB) (UserItem, error) { + q.Columns = userItemAllColumns + query, args, err := q.ToSql() + if err != nil { + return UserItem{}, err + } + + row := db.QueryRowContext(ctx, query, args...) + return q.Scan(row) +} + +func (q userItemSelectSQL) All(db sqlla.DB) ([]UserItem, error) { + rs := make([]UserItem, 0, 10) + q.Columns = userItemAllColumns + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := db.Query(query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + r, err := q.Scan(rows) + if err != nil { + return nil, err + } + rs = append(rs, r) + } + return rs, nil +} + +func (q userItemSelectSQL) AllContext(ctx context.Context, db sqlla.DB) ([]UserItem, error) { + rs := make([]UserItem, 0, 10) + q.Columns = userItemAllColumns + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + r, err := q.Scan(rows) + if err != nil { + return nil, err + } + rs = append(rs, r) + } + return rs, nil +} + +func (q userItemSelectSQL) Scan(s sqlla.Scanner) (UserItem, error) { + var row UserItem + err := s.Scan( + &row.Id, + &row.UserId, + &row.ItemId, + &row.IsUsed, + &row.HasExtension, + &row.UsedAt, + ) + return row, err +} + +type userItemUpdateSQL struct { + userItemSQL + setMap sqlla.SetMap + Columns []string +} + +func (q userItemSQL) Update() userItemUpdateSQL { + return userItemUpdateSQL{ + userItemSQL: q, + setMap: sqlla.SetMap{}, + } +} + +func (q userItemUpdateSQL) SetID(v uint64) userItemUpdateSQL { + q.setMap["`id`"] = v + return q +} + +func (q userItemUpdateSQL) WhereID(v uint64, exprs ...sqlla.Operator) userItemUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) WhereIDIn(vs ...uint64) userItemUpdateSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) SetUserID(v uint64) userItemUpdateSQL { + q.setMap["`user_id`"] = v + return q +} + +func (q userItemUpdateSQL) WhereUserID(v uint64, exprs ...sqlla.Operator) userItemUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: "`user_id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) WhereUserIDIn(vs ...uint64) userItemUpdateSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`user_id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) SetItemID(v string) userItemUpdateSQL { + q.setMap["`item_id`"] = v + return q +} + +func (q userItemUpdateSQL) WhereItemID(v string, exprs ...sqlla.Operator) userItemUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprString{Value: v, Op: op, Column: "`item_id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) WhereItemIDIn(vs ...string) userItemUpdateSQL { + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`item_id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) SetIsUsed(v bool) userItemUpdateSQL { + q.setMap["`is_used`"] = v + return q +} + +func (q userItemUpdateSQL) WhereIsUsed(v bool, exprs ...sqlla.Operator) userItemUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprBool{Value: v, Op: op, Column: "`is_used`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) WhereIsUsedIn(vs ...bool) userItemUpdateSQL { + where := sqlla.ExprMultiBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`is_used`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) SetHasExtension(v sql.NullBool) userItemUpdateSQL { + q.setMap["`has_extension`"] = v + return q +} + +func (q userItemUpdateSQL) WhereHasExtension(v sql.NullBool, exprs ...sqlla.Operator) userItemUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNullBool{Value: v, Op: op, Column: "`has_extension`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) WhereHasExtensionIn(vs ...sql.NullBool) userItemUpdateSQL { + where := sqlla.ExprMultiNullBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`has_extension`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) SetUsedAt(v sql.NullTime) userItemUpdateSQL { + q.setMap["`used_at`"] = v + return q +} + +func (q userItemUpdateSQL) WhereUsedAt(v sql.NullTime, exprs ...sqlla.Operator) userItemUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNullTime{Value: v, Op: op, Column: "`used_at`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) WhereUsedAtIn(vs ...sql.NullTime) userItemUpdateSQL { + where := sqlla.ExprMultiNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`used_at`"} + q.where = append(q.where, where) + return q +} + +func (q userItemUpdateSQL) ToSql() (string, []interface{}, error) { + var err error + var s interface{} = UserItem{} + if t, ok := s.(userItemDefaultUpdateHooker); ok { + q, err = t.DefaultUpdateHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + setColumns, svs, err := q.setMap.ToUpdateSql() + if err != nil { + return "", []interface{}{}, err + } + wheres, wvs, err := q.where.ToSql() + if err != nil { + return "", []interface{}{}, err + } + + query := "UPDATE `user_item` SET" + setColumns + if wheres != "" { + query += " WHERE" + wheres + } + + return query + ";", append(svs, wvs...), nil +} +func (s UserItem) Update() userItemUpdateSQL { + return NewUserItemSQL().Update().WhereID(s.Id) +} + +func (q userItemUpdateSQL) Exec(db sqlla.DB) ([]UserItem, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + _, err = db.Exec(query, args...) + if err != nil { + return nil, err + } + qq := q.userItemSQL + + return qq.Select().All(db) +} + +func (q userItemUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) ([]UserItem, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + _, err = db.ExecContext(ctx, query, args...) + if err != nil { + return nil, err + } + qq := q.userItemSQL + + return qq.Select().AllContext(ctx, db) +} + +type userItemDefaultUpdateHooker interface { + DefaultUpdateHook(userItemUpdateSQL) (userItemUpdateSQL, error) +} + +type userItemInsertSQL struct { + userItemSQL + setMap sqlla.SetMap + Columns []string +} + +func (q userItemSQL) Insert() userItemInsertSQL { + return userItemInsertSQL{ + userItemSQL: q, + setMap: sqlla.SetMap{}, + } +} + +func (q userItemInsertSQL) ValueID(v uint64) userItemInsertSQL { + q.setMap["`id`"] = v + return q +} + +func (q userItemInsertSQL) ValueUserID(v uint64) userItemInsertSQL { + q.setMap["`user_id`"] = v + return q +} + +func (q userItemInsertSQL) ValueItemID(v string) userItemInsertSQL { + q.setMap["`item_id`"] = v + return q +} + +func (q userItemInsertSQL) ValueIsUsed(v bool) userItemInsertSQL { + q.setMap["`is_used`"] = v + return q +} + +func (q userItemInsertSQL) ValueHasExtension(v sql.NullBool) userItemInsertSQL { + q.setMap["`has_extension`"] = v + return q +} + +func (q userItemInsertSQL) ValueUsedAt(v sql.NullTime) userItemInsertSQL { + q.setMap["`used_at`"] = v + return q +} + +func (q userItemInsertSQL) ToSql() (string, []interface{}, error) { + query, vs, err := q.userItemInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + return query + ";", vs, nil +} + +func (q userItemInsertSQL) userItemInsertSQLToSql() (string, []interface{}, error) { + var err error + var s interface{} = UserItem{} + if t, ok := s.(userItemDefaultInsertHooker); ok { + q, err = t.DefaultInsertHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + qs, vs, err := q.setMap.ToInsertSql() + if err != nil { + return "", []interface{}{}, err + } + + query := "INSERT INTO `user_item` " + qs + + return query, vs, nil +} + +func (q userItemInsertSQL) OnDuplicateKeyUpdate() userItemInsertOnDuplicateKeyUpdateSQL { + return userItemInsertOnDuplicateKeyUpdateSQL{ + insertSQL: q, + onDuplicateKeyUpdateMap: sqlla.SetMap{}, + } +} + +func (q userItemInsertSQL) Exec(db sqlla.DB) (UserItem, error) { + query, args, err := q.ToSql() + if err != nil { + return UserItem{}, err + } + result, err := db.Exec(query, args...) + if err != nil { + return UserItem{}, err + } + id, err := result.LastInsertId() + if err != nil { + return UserItem{}, err + } + return NewUserItemSQL().Select().PkColumn(id).Single(db) +} + +func (q userItemInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserItem, error) { + query, args, err := q.ToSql() + if err != nil { + return UserItem{}, err + } + result, err := db.ExecContext(ctx, query, args...) + if err != nil { + return UserItem{}, err + } + id, err := result.LastInsertId() + if err != nil { + return UserItem{}, err + } + return NewUserItemSQL().Select().PkColumn(id).SingleContext(ctx, db) +} + +func (q userItemInsertSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userItemDefaultInsertHooker interface { + DefaultInsertHook(userItemInsertSQL) (userItemInsertSQL, error) +} + +type userItemInsertSQLToSqler interface { + userItemInsertSQLToSql() (string, []interface{}, error) +} + +type userItemInsertOnDuplicateKeyUpdateSQL struct { + insertSQL userItemInsertSQLToSqler + onDuplicateKeyUpdateMap sqlla.SetMap +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateID(v uint64) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateID(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateID() userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = sqlla.SetMapRawValue("VALUES(`id`)") + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUserID(v uint64) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`user_id`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUserID(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`user_id`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUserID() userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`user_id`"] = sqlla.SetMapRawValue("VALUES(`user_id`)") + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateItemID(v string) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`item_id`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateItemID(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`item_id`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateItemID() userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`item_id`"] = sqlla.SetMapRawValue("VALUES(`item_id`)") + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateIsUsed(v bool) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`is_used`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateIsUsed(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`is_used`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateIsUsed() userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`is_used`"] = sqlla.SetMapRawValue("VALUES(`is_used`)") + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateHasExtension(v sql.NullBool) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`has_extension`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateHasExtension(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`has_extension`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateHasExtension() userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`has_extension`"] = sqlla.SetMapRawValue("VALUES(`has_extension`)") + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUsedAt(v sql.NullTime) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`used_at`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUsedAt(v sqlla.SetMapRawValue) userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`used_at`"] = v + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUsedAt() userItemInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`used_at`"] = sqlla.SetMapRawValue("VALUES(`used_at`)") + return q +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) ToSql() (string, []interface{}, error) { + var err error + var s interface{} = UserItem{} + if t, ok := s.(userItemDefaultInsertOnDuplicateKeyUpdateHooker); ok { + q, err = t.DefaultInsertOnDuplicateKeyUpdateHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + + query, vs, err := q.insertSQL.userItemInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + + os, ovs, err := q.onDuplicateKeyUpdateMap.ToUpdateSql() + if err != nil { + return "", []interface{}{}, err + } + query += " ON DUPLICATE KEY UPDATE" + os + vs = append(vs, ovs...) + + return query + ";", vs, nil +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserItem, error) { + query, args, err := q.ToSql() + if err != nil { + return UserItem{}, err + } + result, err := db.ExecContext(ctx, query, args...) + if err != nil { + return UserItem{}, err + } + id, err := result.LastInsertId() + if err != nil { + return UserItem{}, err + } + return NewUserItemSQL().Select().PkColumn(id).SingleContext(ctx, db) +} + +func (q userItemInsertOnDuplicateKeyUpdateSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userItemDefaultInsertOnDuplicateKeyUpdateHooker interface { + DefaultInsertOnDuplicateKeyUpdateHook(userItemInsertOnDuplicateKeyUpdateSQL) (userItemInsertOnDuplicateKeyUpdateSQL, error) +} + +type userItemBulkInsertSQL struct { + insertSQLs []userItemInsertSQL +} + +func (q userItemSQL) BulkInsert() *userItemBulkInsertSQL { + return &userItemBulkInsertSQL{ + insertSQLs: []userItemInsertSQL{}, + } +} + +func (q *userItemBulkInsertSQL) Append(iqs ...userItemInsertSQL) { + q.insertSQLs = append(q.insertSQLs, iqs...) +} + +func (q *userItemBulkInsertSQL) userItemInsertSQLToSql() (string, []interface{}, error) { + if len(q.insertSQLs) == 0 { + return "", []interface{}{}, fmt.Errorf("sqlla: This userItemBulkInsertSQL's InsertSQL was empty") + } + iqs := make([]userItemInsertSQL, len(q.insertSQLs)) + copy(iqs, q.insertSQLs) + + var s interface{} = UserItem{} + if t, ok := s.(userItemDefaultInsertHooker); ok { + for i, iq := range iqs { + var err error + iq, err = t.DefaultInsertHook(iq) + if err != nil { + return "", []interface{}{}, err + } + iqs[i] = iq + } + } + + sms := make(sqlla.SetMaps, 0, len(q.insertSQLs)) + for _, iq := range q.insertSQLs { + sms = append(sms, iq.setMap) + } + + query, vs, err := sms.ToInsertSql() + if err != nil { + return "", []interface{}{}, err + } + + return "INSERT INTO `user_item` " + query, vs, nil +} + +func (q *userItemBulkInsertSQL) ToSql() (string, []interface{}, error) { + query, vs, err := q.userItemInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + return query + ";", vs, nil +} + +func (q *userItemBulkInsertSQL) OnDuplicateKeyUpdate() userItemInsertOnDuplicateKeyUpdateSQL { + return userItemInsertOnDuplicateKeyUpdateSQL{ + insertSQL: q, + onDuplicateKeyUpdateMap: sqlla.SetMap{}, + } +} + +func (q *userItemBulkInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userItemDeleteSQL struct { + userItemSQL +} + +func (q userItemSQL) Delete() userItemDeleteSQL { + return userItemDeleteSQL{ + q, + } +} + +func (q userItemDeleteSQL) ID(v uint64, exprs ...sqlla.Operator) userItemDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) IDIn(vs ...uint64) userItemDeleteSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) UserID(v uint64, exprs ...sqlla.Operator) userItemDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: "`user_id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) UserIDIn(vs ...uint64) userItemDeleteSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`user_id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) ItemID(v string, exprs ...sqlla.Operator) userItemDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprString{Value: v, Op: op, Column: "`item_id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) ItemIDIn(vs ...string) userItemDeleteSQL { + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`item_id`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) IsUsed(v bool, exprs ...sqlla.Operator) userItemDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprBool{Value: v, Op: op, Column: "`is_used`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) IsUsedIn(vs ...bool) userItemDeleteSQL { + where := sqlla.ExprMultiBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`is_used`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) HasExtension(v sql.NullBool, exprs ...sqlla.Operator) userItemDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNullBool{Value: v, Op: op, Column: "`has_extension`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) HasExtensionIn(vs ...sql.NullBool) userItemDeleteSQL { + where := sqlla.ExprMultiNullBool{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`has_extension`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) UsedAt(v sql.NullTime, exprs ...sqlla.Operator) userItemDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNullTime{Value: v, Op: op, Column: "`used_at`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) UsedAtIn(vs ...sql.NullTime) userItemDeleteSQL { + where := sqlla.ExprMultiNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`used_at`"} + q.where = append(q.where, where) + return q +} + +func (q userItemDeleteSQL) ToSql() (string, []interface{}, error) { + wheres, vs, err := q.where.ToSql() + if err != nil { + return "", nil, err + } + + query := "DELETE FROM `user_item`" + if wheres != "" { + query += " WHERE" + wheres + } + + return query + ";", vs, nil +} + +func (q userItemDeleteSQL) Exec(db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + return db.Exec(query, args...) +} + +func (q userItemDeleteSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + return db.ExecContext(ctx, query, args...) +} +func (s UserItem) Delete(db sqlla.DB) (sql.Result, error) { + query, args, err := NewUserItemSQL().Delete().ID(s.Id).ToSql() + if err != nil { + return nil, err + } + return db.Exec(query, args...) +} + +func (s UserItem) DeleteContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := NewUserItemSQL().Delete().ID(s.Id).ToSql() + if err != nil { + return nil, err + } + return db.ExecContext(ctx, query, args...) +} diff --git a/_example/user_sns.gen.go b/_example/user_sns.gen.go index e69de29..aa3fa40 100644 --- a/_example/user_sns.gen.go +++ b/_example/user_sns.gen.go @@ -0,0 +1,985 @@ +// Code generated by github.com/mackee/go-sqlla/v2/cmd/sqlla - DO NOT EDIT. +package example + +import ( + "context" + "fmt" + "strconv" + "strings" + + "database/sql" + "time" + + "github.com/mackee/go-sqlla/v2" +) + +type userSNSSQL struct { + where sqlla.Where +} + +func NewUserSNSSQL() userSNSSQL { + q := userSNSSQL{} + return q +} + +var userSNSAllColumns = []string{ + "`id`", "`sns_type`", "`created_at`", "`updated_at`", +} + +type userSNSSelectSQL struct { + userSNSSQL + Columns []string + order string + limit *uint64 + offset *uint64 + tableAlias string + joinClauses []string + + additionalWhereClause string + additionalWhereClauseArgs []interface{} + + groupByColumns []string + + isForUpdate bool +} + +func (q userSNSSQL) Select() userSNSSelectSQL { + return userSNSSelectSQL{ + q, + userSNSAllColumns, + "", + nil, + nil, + "", + nil, + "", + nil, + nil, + false, + } +} + +func (q userSNSSelectSQL) Or(qs ...userSNSSelectSQL) userSNSSelectSQL { + ws := make([]sqlla.Where, 0, len(qs)) + for _, q := range qs { + ws = append(ws, q.where) + } + q.where = append(q.where, sqlla.ExprOr(ws)) + return q +} + +func (q userSNSSelectSQL) Limit(l uint64) userSNSSelectSQL { + q.limit = &l + return q +} + +func (q userSNSSelectSQL) Offset(o uint64) userSNSSelectSQL { + q.offset = &o + return q +} + +func (q userSNSSelectSQL) ForUpdate() userSNSSelectSQL { + q.isForUpdate = true + return q +} + +func (q userSNSSelectSQL) TableAlias(alias string) userSNSSelectSQL { + q.tableAlias = "`" + alias + "`" + return q +} + +func (q userSNSSelectSQL) SetColumns(columns ...string) userSNSSelectSQL { + q.Columns = make([]string, 0, len(columns)) + for _, column := range columns { + if strings.ContainsAny(column, "(.`") { + q.Columns = append(q.Columns, column) + } else { + q.Columns = append(q.Columns, "`"+column+"`") + } + } + return q +} + +func (q userSNSSelectSQL) JoinClause(clause string) userSNSSelectSQL { + q.joinClauses = append(q.joinClauses, clause) + return q +} + +func (q userSNSSelectSQL) AdditionalWhereClause(clause string, args ...interface{}) userSNSSelectSQL { + q.additionalWhereClause = clause + q.additionalWhereClauseArgs = args + return q +} + +func (q userSNSSelectSQL) appendColumnPrefix(column string) string { + if q.tableAlias == "" || strings.ContainsAny(column, "(.") { + return column + } + return q.tableAlias + "." + column +} + +func (q userSNSSelectSQL) GroupBy(columns ...string) userSNSSelectSQL { + q.groupByColumns = make([]string, 0, len(columns)) + for _, column := range columns { + if strings.ContainsAny(column, "(.`") { + q.groupByColumns = append(q.groupByColumns, column) + } else { + q.groupByColumns = append(q.groupByColumns, "`"+column+"`") + } + } + return q +} + +func (q userSNSSelectSQL) ID(v uint64, exprs ...sqlla.Operator) userSNSSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: q.appendColumnPrefix("`id`")} + q.where = append(q.where, where) + return q +} + +func (q userSNSSelectSQL) IDIn(vs ...uint64) userSNSSelectSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`id`")} + q.where = append(q.where, where) + return q +} + +func (q userSNSSelectSQL) PkColumn(pk int64, exprs ...sqlla.Operator) userSNSSelectSQL { + v := uint64(pk) + return q.ID(v, exprs...) +} + +func (q userSNSSelectSQL) OrderByID(order sqlla.Order) userSNSSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`id`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userSNSSelectSQL) SNSType(v string, exprs ...sqlla.Operator) userSNSSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprString{Value: v, Op: op, Column: q.appendColumnPrefix("`sns_type`")} + q.where = append(q.where, where) + return q +} + +func (q userSNSSelectSQL) SNSTypeIn(vs ...string) userSNSSelectSQL { + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`sns_type`")} + q.where = append(q.where, where) + return q +} + +func (q userSNSSelectSQL) OrderBySNSType(order sqlla.Order) userSNSSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`sns_type`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userSNSSelectSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userSNSSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: q.appendColumnPrefix("`created_at`")} + q.where = append(q.where, where) + return q +} + +func (q userSNSSelectSQL) CreatedAtIn(vs ...time.Time) userSNSSelectSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`created_at`")} + q.where = append(q.where, where) + return q +} + +func (q userSNSSelectSQL) OrderByCreatedAt(order sqlla.Order) userSNSSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`created_at`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userSNSSelectSQL) UpdatedAt(v time.Time, exprs ...sqlla.Operator) userSNSSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: q.appendColumnPrefix("`updated_at`")} + q.where = append(q.where, where) + return q +} + +func (q userSNSSelectSQL) UpdatedAtIn(vs ...time.Time) userSNSSelectSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`updated_at`")} + q.where = append(q.where, where) + return q +} + +func (q userSNSSelectSQL) OrderByUpdatedAt(order sqlla.Order) userSNSSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`updated_at`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + +func (q userSNSSelectSQL) ToSql() (string, []interface{}, error) { + columns := strings.Join(q.Columns, ", ") + wheres, vs, err := q.where.ToSql() + if err != nil { + return "", nil, err + } + + tableName := "`user_sns`" + if q.tableAlias != "" { + tableName = tableName + " AS " + q.tableAlias + pcs := make([]string, 0, len(q.Columns)) + for _, column := range q.Columns { + pcs = append(pcs, q.appendColumnPrefix(column)) + } + columns = strings.Join(pcs, ", ") + } + query := "SELECT " + columns + " FROM " + tableName + if len(q.joinClauses) > 0 { + jc := strings.Join(q.joinClauses, " ") + query += " " + jc + } + if wheres != "" { + query += " WHERE" + wheres + } + if q.additionalWhereClause != "" { + query += " " + q.additionalWhereClause + if len(q.additionalWhereClauseArgs) > 0 { + vs = append(vs, q.additionalWhereClauseArgs...) + } + } + if len(q.groupByColumns) > 0 { + query += " GROUP BY " + gbcs := make([]string, 0, len(q.groupByColumns)) + for _, column := range q.groupByColumns { + gbcs = append(gbcs, q.appendColumnPrefix(column)) + } + query += strings.Join(gbcs, ", ") + } + query += q.order + if q.limit != nil { + query += " LIMIT " + strconv.FormatUint(*q.limit, 10) + } + if q.offset != nil { + query += " OFFSET " + strconv.FormatUint(*q.offset, 10) + } + + if q.isForUpdate { + query += " FOR UPDATE" + } + + return query + ";", vs, nil +} + +func (s UserSNS) Select() userSNSSelectSQL { + return NewUserSNSSQL().Select().ID(s.ID) +} +func (q userSNSSelectSQL) Single(db sqlla.DB) (UserSNS, error) { + q.Columns = userSNSAllColumns + query, args, err := q.ToSql() + if err != nil { + return UserSNS{}, err + } + + row := db.QueryRow(query, args...) + return q.Scan(row) +} + +func (q userSNSSelectSQL) SingleContext(ctx context.Context, db sqlla.DB) (UserSNS, error) { + q.Columns = userSNSAllColumns + query, args, err := q.ToSql() + if err != nil { + return UserSNS{}, err + } + + row := db.QueryRowContext(ctx, query, args...) + return q.Scan(row) +} + +func (q userSNSSelectSQL) All(db sqlla.DB) ([]UserSNS, error) { + rs := make([]UserSNS, 0, 10) + q.Columns = userSNSAllColumns + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := db.Query(query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + r, err := q.Scan(rows) + if err != nil { + return nil, err + } + rs = append(rs, r) + } + return rs, nil +} + +func (q userSNSSelectSQL) AllContext(ctx context.Context, db sqlla.DB) ([]UserSNS, error) { + rs := make([]UserSNS, 0, 10) + q.Columns = userSNSAllColumns + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + r, err := q.Scan(rows) + if err != nil { + return nil, err + } + rs = append(rs, r) + } + return rs, nil +} + +func (q userSNSSelectSQL) Scan(s sqlla.Scanner) (UserSNS, error) { + var row UserSNS + err := s.Scan( + &row.ID, + &row.SNSType, + &row.CreatedAt, + &row.UpdatedAt, + ) + return row, err +} + +type userSNSUpdateSQL struct { + userSNSSQL + setMap sqlla.SetMap + Columns []string +} + +func (q userSNSSQL) Update() userSNSUpdateSQL { + return userSNSUpdateSQL{ + userSNSSQL: q, + setMap: sqlla.SetMap{}, + } +} + +func (q userSNSUpdateSQL) SetID(v uint64) userSNSUpdateSQL { + q.setMap["`id`"] = v + return q +} + +func (q userSNSUpdateSQL) WhereID(v uint64, exprs ...sqlla.Operator) userSNSUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSUpdateSQL) WhereIDIn(vs ...uint64) userSNSUpdateSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSUpdateSQL) SetSNSType(v string) userSNSUpdateSQL { + q.setMap["`sns_type`"] = v + return q +} + +func (q userSNSUpdateSQL) WhereSNSType(v string, exprs ...sqlla.Operator) userSNSUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprString{Value: v, Op: op, Column: "`sns_type`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSUpdateSQL) WhereSNSTypeIn(vs ...string) userSNSUpdateSQL { + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sns_type`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSUpdateSQL) SetCreatedAt(v time.Time) userSNSUpdateSQL { + q.setMap["`created_at`"] = v + return q +} + +func (q userSNSUpdateSQL) WhereCreatedAt(v time.Time, exprs ...sqlla.Operator) userSNSUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSUpdateSQL) WhereCreatedAtIn(vs ...time.Time) userSNSUpdateSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSUpdateSQL) SetUpdatedAt(v time.Time) userSNSUpdateSQL { + q.setMap["`updated_at`"] = v + return q +} + +func (q userSNSUpdateSQL) WhereUpdatedAt(v time.Time, exprs ...sqlla.Operator) userSNSUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSUpdateSQL) WhereUpdatedAtIn(vs ...time.Time) userSNSUpdateSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSUpdateSQL) ToSql() (string, []interface{}, error) { + var err error + var s interface{} = UserSNS{} + if t, ok := s.(userSNSDefaultUpdateHooker); ok { + q, err = t.DefaultUpdateHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + setColumns, svs, err := q.setMap.ToUpdateSql() + if err != nil { + return "", []interface{}{}, err + } + wheres, wvs, err := q.where.ToSql() + if err != nil { + return "", []interface{}{}, err + } + + query := "UPDATE `user_sns` SET" + setColumns + if wheres != "" { + query += " WHERE" + wheres + } + + return query + ";", append(svs, wvs...), nil +} +func (s UserSNS) Update() userSNSUpdateSQL { + return NewUserSNSSQL().Update().WhereID(s.ID) +} + +func (q userSNSUpdateSQL) Exec(db sqlla.DB) ([]UserSNS, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + _, err = db.Exec(query, args...) + if err != nil { + return nil, err + } + qq := q.userSNSSQL + + return qq.Select().All(db) +} + +func (q userSNSUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) ([]UserSNS, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + _, err = db.ExecContext(ctx, query, args...) + if err != nil { + return nil, err + } + qq := q.userSNSSQL + + return qq.Select().AllContext(ctx, db) +} + +type userSNSDefaultUpdateHooker interface { + DefaultUpdateHook(userSNSUpdateSQL) (userSNSUpdateSQL, error) +} + +type userSNSInsertSQL struct { + userSNSSQL + setMap sqlla.SetMap + Columns []string +} + +func (q userSNSSQL) Insert() userSNSInsertSQL { + return userSNSInsertSQL{ + userSNSSQL: q, + setMap: sqlla.SetMap{}, + } +} + +func (q userSNSInsertSQL) ValueID(v uint64) userSNSInsertSQL { + q.setMap["`id`"] = v + return q +} + +func (q userSNSInsertSQL) ValueSNSType(v string) userSNSInsertSQL { + q.setMap["`sns_type`"] = v + return q +} + +func (q userSNSInsertSQL) ValueCreatedAt(v time.Time) userSNSInsertSQL { + q.setMap["`created_at`"] = v + return q +} + +func (q userSNSInsertSQL) ValueUpdatedAt(v time.Time) userSNSInsertSQL { + q.setMap["`updated_at`"] = v + return q +} + +func (q userSNSInsertSQL) ToSql() (string, []interface{}, error) { + query, vs, err := q.userSNSInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + return query + ";", vs, nil +} + +func (q userSNSInsertSQL) userSNSInsertSQLToSql() (string, []interface{}, error) { + var err error + var s interface{} = UserSNS{} + if t, ok := s.(userSNSDefaultInsertHooker); ok { + q, err = t.DefaultInsertHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + qs, vs, err := q.setMap.ToInsertSql() + if err != nil { + return "", []interface{}{}, err + } + + query := "INSERT INTO `user_sns` " + qs + + return query, vs, nil +} + +func (q userSNSInsertSQL) OnDuplicateKeyUpdate() userSNSInsertOnDuplicateKeyUpdateSQL { + return userSNSInsertOnDuplicateKeyUpdateSQL{ + insertSQL: q, + onDuplicateKeyUpdateMap: sqlla.SetMap{}, + } +} + +func (q userSNSInsertSQL) Exec(db sqlla.DB) (UserSNS, error) { + query, args, err := q.ToSql() + if err != nil { + return UserSNS{}, err + } + result, err := db.Exec(query, args...) + if err != nil { + return UserSNS{}, err + } + id, err := result.LastInsertId() + if err != nil { + return UserSNS{}, err + } + return NewUserSNSSQL().Select().PkColumn(id).Single(db) +} + +func (q userSNSInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserSNS, error) { + query, args, err := q.ToSql() + if err != nil { + return UserSNS{}, err + } + result, err := db.ExecContext(ctx, query, args...) + if err != nil { + return UserSNS{}, err + } + id, err := result.LastInsertId() + if err != nil { + return UserSNS{}, err + } + return NewUserSNSSQL().Select().PkColumn(id).SingleContext(ctx, db) +} + +func (q userSNSInsertSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userSNSDefaultInsertHooker interface { + DefaultInsertHook(userSNSInsertSQL) (userSNSInsertSQL, error) +} + +type userSNSInsertSQLToSqler interface { + userSNSInsertSQLToSql() (string, []interface{}, error) +} + +type userSNSInsertOnDuplicateKeyUpdateSQL struct { + insertSQL userSNSInsertSQLToSqler + onDuplicateKeyUpdateMap sqlla.SetMap +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateID(v uint64) userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = v + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateID(v sqlla.SetMapRawValue) userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = v + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) SameOnUpdateID() userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`id`"] = sqlla.SetMapRawValue("VALUES(`id`)") + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateSNSType(v string) userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`sns_type`"] = v + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateSNSType(v sqlla.SetMapRawValue) userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`sns_type`"] = v + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) SameOnUpdateSNSType() userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`sns_type`"] = sqlla.SetMapRawValue("VALUES(`sns_type`)") + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateCreatedAt(v time.Time) userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = v + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateCreatedAt(v sqlla.SetMapRawValue) userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = v + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) SameOnUpdateCreatedAt() userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`created_at`"] = sqlla.SetMapRawValue("VALUES(`created_at`)") + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v time.Time) userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = v + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateUpdatedAt(v sqlla.SetMapRawValue) userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = v + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) SameOnUpdateUpdatedAt() userSNSInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = sqlla.SetMapRawValue("VALUES(`updated_at`)") + return q +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) ToSql() (string, []interface{}, error) { + var err error + var s interface{} = UserSNS{} + if t, ok := s.(userSNSDefaultInsertOnDuplicateKeyUpdateHooker); ok { + q, err = t.DefaultInsertOnDuplicateKeyUpdateHook(q) + if err != nil { + return "", []interface{}{}, err + } + } + + query, vs, err := q.insertSQL.userSNSInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + + os, ovs, err := q.onDuplicateKeyUpdateMap.ToUpdateSql() + if err != nil { + return "", []interface{}{}, err + } + query += " ON DUPLICATE KEY UPDATE" + os + vs = append(vs, ovs...) + + return query + ";", vs, nil +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) ExecContext(ctx context.Context, db sqlla.DB) (UserSNS, error) { + query, args, err := q.ToSql() + if err != nil { + return UserSNS{}, err + } + result, err := db.ExecContext(ctx, query, args...) + if err != nil { + return UserSNS{}, err + } + id, err := result.LastInsertId() + if err != nil { + return UserSNS{}, err + } + return NewUserSNSSQL().Select().PkColumn(id).SingleContext(ctx, db) +} + +func (q userSNSInsertOnDuplicateKeyUpdateSQL) ExecContextWithoutSelect(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userSNSDefaultInsertOnDuplicateKeyUpdateHooker interface { + DefaultInsertOnDuplicateKeyUpdateHook(userSNSInsertOnDuplicateKeyUpdateSQL) (userSNSInsertOnDuplicateKeyUpdateSQL, error) +} + +type userSNSBulkInsertSQL struct { + insertSQLs []userSNSInsertSQL +} + +func (q userSNSSQL) BulkInsert() *userSNSBulkInsertSQL { + return &userSNSBulkInsertSQL{ + insertSQLs: []userSNSInsertSQL{}, + } +} + +func (q *userSNSBulkInsertSQL) Append(iqs ...userSNSInsertSQL) { + q.insertSQLs = append(q.insertSQLs, iqs...) +} + +func (q *userSNSBulkInsertSQL) userSNSInsertSQLToSql() (string, []interface{}, error) { + if len(q.insertSQLs) == 0 { + return "", []interface{}{}, fmt.Errorf("sqlla: This userSNSBulkInsertSQL's InsertSQL was empty") + } + iqs := make([]userSNSInsertSQL, len(q.insertSQLs)) + copy(iqs, q.insertSQLs) + + var s interface{} = UserSNS{} + if t, ok := s.(userSNSDefaultInsertHooker); ok { + for i, iq := range iqs { + var err error + iq, err = t.DefaultInsertHook(iq) + if err != nil { + return "", []interface{}{}, err + } + iqs[i] = iq + } + } + + sms := make(sqlla.SetMaps, 0, len(q.insertSQLs)) + for _, iq := range q.insertSQLs { + sms = append(sms, iq.setMap) + } + + query, vs, err := sms.ToInsertSql() + if err != nil { + return "", []interface{}{}, err + } + + return "INSERT INTO `user_sns` " + query, vs, nil +} + +func (q *userSNSBulkInsertSQL) ToSql() (string, []interface{}, error) { + query, vs, err := q.userSNSInsertSQLToSql() + if err != nil { + return "", []interface{}{}, err + } + return query + ";", vs, nil +} + +func (q *userSNSBulkInsertSQL) OnDuplicateKeyUpdate() userSNSInsertOnDuplicateKeyUpdateSQL { + return userSNSInsertOnDuplicateKeyUpdateSQL{ + insertSQL: q, + onDuplicateKeyUpdateMap: sqlla.SetMap{}, + } +} + +func (q *userSNSBulkInsertSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + result, err := db.ExecContext(ctx, query, args...) + return result, err +} + +type userSNSDeleteSQL struct { + userSNSSQL +} + +func (q userSNSSQL) Delete() userSNSDeleteSQL { + return userSNSDeleteSQL{ + q, + } +} + +func (q userSNSDeleteSQL) ID(v uint64, exprs ...sqlla.Operator) userSNSDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprUint64{Value: v, Op: op, Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSDeleteSQL) IDIn(vs ...uint64) userSNSDeleteSQL { + where := sqlla.ExprMultiUint64{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`id`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSDeleteSQL) SNSType(v string, exprs ...sqlla.Operator) userSNSDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprString{Value: v, Op: op, Column: "`sns_type`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSDeleteSQL) SNSTypeIn(vs ...string) userSNSDeleteSQL { + where := sqlla.ExprMultiString{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sns_type`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSDeleteSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) userSNSDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSDeleteSQL) CreatedAtIn(vs ...time.Time) userSNSDeleteSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`created_at`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSDeleteSQL) UpdatedAt(v time.Time, exprs ...sqlla.Operator) userSNSDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprTime{Value: v, Op: op, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSDeleteSQL) UpdatedAtIn(vs ...time.Time) userSNSDeleteSQL { + where := sqlla.ExprMultiTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q userSNSDeleteSQL) ToSql() (string, []interface{}, error) { + wheres, vs, err := q.where.ToSql() + if err != nil { + return "", nil, err + } + + query := "DELETE FROM `user_sns`" + if wheres != "" { + query += " WHERE" + wheres + } + + return query + ";", vs, nil +} + +func (q userSNSDeleteSQL) Exec(db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + return db.Exec(query, args...) +} + +func (q userSNSDeleteSQL) ExecContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := q.ToSql() + if err != nil { + return nil, err + } + return db.ExecContext(ctx, query, args...) +} +func (s UserSNS) Delete(db sqlla.DB) (sql.Result, error) { + query, args, err := NewUserSNSSQL().Delete().ID(s.ID).ToSql() + if err != nil { + return nil, err + } + return db.Exec(query, args...) +} + +func (s UserSNS) DeleteContext(ctx context.Context, db sqlla.DB) (sql.Result, error) { + query, args, err := NewUserSNSSQL().Delete().ID(s.ID).ToSql() + if err != nil { + return nil, err + } + return db.ExecContext(ctx, query, args...) +} diff --git a/cmd/mysql2schema/main.go b/cmd/mysql2schema/main.go index 6b328e4..90ab5a9 100644 --- a/cmd/mysql2schema/main.go +++ b/cmd/mysql2schema/main.go @@ -188,9 +188,13 @@ func outputSchema(db *sql.DB, table string, out io.Writer) error { } outBuf.WriteString(schemaType) if c.IsPk { - outBuf.WriteString(fmt.Sprintf(" `db:\"%s,primarykey\"`\n", c.Name)) + if _, err := fmt.Fprintf(outBuf, " `db:\"%s,primarykey\"`\n", c.Name); err != nil { + return err + } } else { - outBuf.WriteString(fmt.Sprintf(" `db:\"%s\"`\n", c.Name)) + if _, err := fmt.Fprintf(outBuf, " `db:\"%s\"`\n", c.Name); err != nil { + return err + } } } outBuf.WriteString("}") @@ -246,6 +250,6 @@ func sqlTypeToSchemaType(c Column) (string, error) { } return "time.Time", nil default: - return "", fmt.Errorf("unexpected column type: %+v\n", c) + return "", fmt.Errorf("unexpected column type: %+v", c) } } diff --git a/generator.go b/generator.go index 0ce06c5..1be7a66 100644 --- a/generator.go +++ b/generator.go @@ -6,14 +6,13 @@ import ( "bufio" "bytes" "embed" - "fmt" "go/format" "io" "log" "strings" "text/template" - "unicode" + "github.com/Masterminds/goutils" "github.com/pkg/errors" "github.com/serenize/snaker" ) @@ -29,21 +28,11 @@ var tmpl = template.New("table") func init() { tmpl = tmpl.Funcs( template.FuncMap{ - "Title": strings.Title, - "Exprize": func(s string) string { - s = strings.TrimPrefix(s, "sql.") - s = strings.TrimPrefix(s, "time.") - s = strings.TrimPrefix(s, "mysql.") - - return s + "Title": func(s string) string { + return goutils.Capitalize(s) }, "Untitle": func(s string) string { - s0 := rune(s[0]) - if !unicode.IsUpper(s0) { - return s - } - s0l := unicode.ToLower(rune(s[0])) - return string(s0l) + s[1:] + return goutils.Uncapitalize(s) }, "toLower": strings.ToLower, "toSnake": snaker.CamelToSnake, diff --git a/table.go b/table.go index 13c0206..1c7984e 100644 --- a/table.go +++ b/table.go @@ -8,6 +8,7 @@ import ( "io" "strings" + "github.com/Masterminds/goutils" "github.com/serenize/snaker" ) @@ -34,7 +35,7 @@ func (t *Table) AddColumn(c Column) { if t.NamingIsStructName() { c.MethodName = c.FieldName() } else { - c.MethodName = strings.Title(snaker.SnakeToCamel(c.Name)) + c.MethodName = goutils.Capitalize(snaker.SnakeToCamel(c.Name)) } if c.IsPk { t.PkColumn = &c @@ -84,9 +85,6 @@ func (c Column) HasUnderlyingType() bool { func (c Column) TypeName() string { tn := c.typeName - if c.altTypeName != "" { - tn = c.altTypeName - } if c.typeParameter != "" { return tn + "[" + c.typeParameter + "]" } @@ -110,18 +108,29 @@ func (c Column) AltTypeName() string { return c.altTypeName } -func (c Column) ExprTypeName() string { +func (c Column) typeNameForExpr() string { + tname := c.BaseTypeName() if atn := c.AltTypeName(); atn != "" { - return "Expr" + atn + tname = atn } - return "Expr" + c.BaseTypeName() + tname = c.exprize(tname) + tname = goutils.Capitalize(tname) + return tname +} + +func (c Column) ExprTypeName() string { + return "Expr" + c.typeNameForExpr() +} + +func (c Column) exprize(s string) string { + s = strings.TrimPrefix(s, "sql.") + s = strings.TrimPrefix(s, "time.") + s = strings.TrimPrefix(s, "mysql.") + return s } func (c Column) ExprMultiTypeName() string { - if atn := c.AltTypeName(); atn != "" { - return "ExprMulti" + atn - } - return "ExprMulti" + c.BaseTypeName() + return "ExprMulti" + c.typeNameForExpr() } func (c Column) ExprValueIdentifier() string { diff --git a/template/delete_column.tmpl b/template/delete_column.tmpl index 043ff97..d83cd4c 100644 --- a/template/delete_column.tmpl +++ b/template/delete_column.tmpl @@ -6,30 +6,21 @@ func (q {{ $smallTableName }}DeleteSQL) {{ .MethodName }}(v {{ .TypeName }}, exp } else { op = exprs[0] } - -{{- if ne .BaseTypeName .TypeName }} - where := sqlla.Expr{{ .BaseTypeName | Exprize | Title }}{Value: {{ .BaseTypeName }}(v), Op: op, Column: "`{{ .Name }}`"} -{{- else if .AltTypeName }} - where := sqlla.Expr{{ .AltTypeName | Exprize | Title }}{Value: v, Op: op, Column: "`{{ .Name }}`"} -{{- else }} - where := sqlla.Expr{{ .BaseTypeName | Exprize | Title }}{Value: v, Op: op, Column: "`{{ .Name }}`"} -{{- end }} + where := sqlla.{{ .ExprTypeName }}{Value: {{ .ExprValueIdentifier }}, Op: op, Column: "`{{ .Name }}`"} q.where = append(q.where, where) return q } func (q {{ $smallTableName }}DeleteSQL) {{ .MethodName }}In(vs ...{{ .TypeName }}) {{ $smallTableName }}DeleteSQL { -{{- if ne .BaseTypeName .TypeName }} +{{- if .HasUnderlyingType }} _vs := make([]{{ .BaseTypeName }}, 0, len(vs)) for _, v := range vs { _vs = append(_vs, {{ .BaseTypeName }}(v)) } - where := sqlla.ExprMulti{{ .BaseTypeName | Exprize | Title }}{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} -{{- else if .AltTypeName }} - where := sqlla.ExprMulti{{ .AltTypeName | Exprize | Title }}{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} + where := sqlla.{{ .ExprMultiTypeName }}{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} {{- else }} - where := sqlla.ExprMulti{{ .BaseTypeName | Exprize | Title }}{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} + where := sqlla.{{ .ExprMultiTypeName }}{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} {{- end }} q.where = append(q.where, where) return q diff --git a/template/select_column.tmpl b/template/select_column.tmpl index b2ec354..2e33161 100644 --- a/template/select_column.tmpl +++ b/template/select_column.tmpl @@ -6,8 +6,7 @@ func (q {{ $smallTableName }}SelectSQL) {{ .MethodName }}(v {{ .TypeName }}, exp } else { op = exprs[0] } - - where := sqlla.{{ .ExprTypeName | Exprize | Title }}{Value: {{ .ExprValueIdentifier }}, Op: op, Column: q.appendColumnPrefix("`{{ .Name }}`")} + where := sqlla.{{ .ExprTypeName }}{Value: {{ .ExprValueIdentifier }}, Op: op, Column: q.appendColumnPrefix("`{{ .Name }}`")} q.where = append(q.where, where) return q } @@ -18,9 +17,9 @@ func (q {{ $smallTableName }}SelectSQL) {{ .MethodName }}In(vs ...{{ .TypeName } for _, v := range vs { _vs = append(_vs, {{ .BaseTypeName }}(v)) } - where := sqlla.{{ .ExprMultiTypeName | Exprize | Title }}{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`{{ .Name }}`")} + where := sqlla.{{ .ExprMultiTypeName }}{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`{{ .Name }}`")} {{- else }} - where := sqlla.{{ .ExprMultiTypeName | Exprize | Title }}{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`{{ .Name }}`")} + where := sqlla.{{ .ExprMultiTypeName }}{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`{{ .Name }}`")} {{- end }} q.where = append(q.where, where) return q diff --git a/template/update_column.tmpl b/template/update_column.tmpl index 0a7d72b..a1ae9de 100644 --- a/template/update_column.tmpl +++ b/template/update_column.tmpl @@ -11,29 +11,20 @@ func (q {{ $smallTableName }}UpdateSQL) Where{{ .MethodName }}(v {{ .TypeName }} } else { op = exprs[0] } - -{{- if ne .BaseTypeName .TypeName }} - where := sqlla.Expr{{ .BaseTypeName | Exprize | Title }}{Value: {{ .BaseTypeName }}(v), Op: op, Column: "`{{ .Name }}`"} -{{- else if .AltTypeName }} - where := sqlla.Expr{{ .AltTypeName | Exprize | Title }}{Value: v, Op: op, Column: "`{{ .Name }}`"} -{{- else }} - where := sqlla.Expr{{ .BaseTypeName | Exprize | Title }}{Value: v, Op: op, Column: "`{{ .Name }}`"} -{{- end }} + where := sqlla.{{ .ExprTypeName }}{Value: {{ .ExprValueIdentifier }}, Op: op, Column: "`{{ .Name }}`"} q.where = append(q.where, where) return q } func (q {{ $smallTableName }}UpdateSQL) Where{{ .MethodName }}In(vs ...{{ .TypeName }}) {{ $smallTableName }}UpdateSQL { -{{- if ne .BaseTypeName .TypeName }} +{{- if .HasUnderlyingType }} _vs := make([]{{ .BaseTypeName }}, 0, len(vs)) for _, v := range vs { _vs = append(_vs, {{ .BaseTypeName }}(v)) } - where := sqlla.ExprMulti{{ .BaseTypeName | Exprize | Title }}{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} -{{- else if .AltTypeName }} - where := sqlla.ExprMulti{{ .AltTypeName | Exprize | Title }}{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} + where := sqlla.{{ .ExprMultiTypeName }}{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} {{- else }} - where := sqlla.ExprMulti{{ .BaseTypeName | Exprize | Title }}{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} + where := sqlla.{{ .ExprMultiTypeName }}{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} {{- end }} q.where = append(q.where, where) return q From 615ad6ca6c9a909d43957cba4e0cd53c321db658 Mon Sep 17 00:00:00 2001 From: mackee Date: Mon, 3 Jun 2024 00:53:31 +0900 Subject: [PATCH 03/11] feat: detection type args that local or other package --- _example/group.gen.go | 124 ++++++++++++++++++++++++++++++++++++------ _example/group.go | 10 ++-- _example/id/id.go | 3 + generator.go | 2 +- go.mod | 1 + go.sum | 2 + main.go | 26 +++++++-- 7 files changed, 141 insertions(+), 27 deletions(-) create mode 100644 _example/id/id.go diff --git a/_example/group.gen.go b/_example/group.gen.go index f0ed76a..77a6df0 100644 --- a/_example/group.gen.go +++ b/_example/group.gen.go @@ -9,6 +9,7 @@ import ( "database/sql" "github.com/go-sql-driver/mysql" + "github.com/mackee/go-sqlla/_example/id" "time" "github.com/mackee/go-sqlla/v2" @@ -24,7 +25,7 @@ func NewGroupSQL() groupSQL { } var groupAllColumns = []string{ - "`id`", "`name`", "`leader_user_id`", "`sub_leader_user_id`", "`created_at`", "`updated_at`", + "`id`", "`name`", "`leader_user_id`", "`sub_leader_user_id`", "`child_group_id`", "`created_at`", "`updated_at`", } type groupSelectSQL struct { @@ -231,20 +232,20 @@ func (q groupSelectSQL) OrderByLeaderUserID(order sqlla.Order) groupSelectSQL { return q } -func (q groupSelectSQL) SubLeaderUserID(v sql.Null[T], exprs ...sqlla.Operator) groupSelectSQL { +func (q groupSelectSQL) SubLeaderUserID(v sql.Null[UserId], exprs ...sqlla.Operator) groupSelectSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprNull[T]{Value: v, Op: op, Column: q.appendColumnPrefix("`sub_leader_user_id`")} + where := sqlla.ExprNull[UserId]{Value: v, Op: op, Column: q.appendColumnPrefix("`sub_leader_user_id`")} q.where = append(q.where, where) return q } -func (q groupSelectSQL) SubLeaderUserIDIn(vs ...sql.Null[T]) groupSelectSQL { - where := sqlla.ExprMultiNull[T]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`sub_leader_user_id`")} +func (q groupSelectSQL) SubLeaderUserIDIn(vs ...sql.Null[UserId]) groupSelectSQL { + where := sqlla.ExprMultiNull[UserId]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`sub_leader_user_id`")} q.where = append(q.where, where) return q } @@ -260,6 +261,35 @@ func (q groupSelectSQL) OrderBySubLeaderUserID(order sqlla.Order) groupSelectSQL return q } +func (q groupSelectSQL) ChildGroupID(v sql.Null[id.GroupID], exprs ...sqlla.Operator) groupSelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNull[id.GroupID]{Value: v, Op: op, Column: q.appendColumnPrefix("`child_group_id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) ChildGroupIDIn(vs ...sql.Null[id.GroupID]) groupSelectSQL { + where := sqlla.ExprMultiNull[id.GroupID]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`child_group_id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) OrderByChildGroupID(order sqlla.Order) groupSelectSQL { + q.order = " ORDER BY " + q.appendColumnPrefix("`child_group_id`") + if order == sqlla.Asc { + q.order += " ASC" + } else { + q.order += " DESC" + } + + return q +} + func (q groupSelectSQL) CreatedAt(v time.Time, exprs ...sqlla.Operator) groupSelectSQL { var op sqlla.Operator if len(exprs) == 0 { @@ -449,6 +479,7 @@ func (q groupSelectSQL) Scan(s sqlla.Scanner) (Group, error) { &row.Name, &row.LeaderUserID, &row.SubLeaderUserID, + &row.ChildGroupID, &row.CreatedAt, &row.UpdatedAt, ) @@ -545,25 +576,48 @@ func (q groupUpdateSQL) WhereLeaderUserIDIn(vs ...UserId) groupUpdateSQL { return q } -func (q groupUpdateSQL) SetSubLeaderUserID(v sql.Null[T]) groupUpdateSQL { +func (q groupUpdateSQL) SetSubLeaderUserID(v sql.Null[UserId]) groupUpdateSQL { q.setMap["`sub_leader_user_id`"] = v return q } -func (q groupUpdateSQL) WhereSubLeaderUserID(v sql.Null[T], exprs ...sqlla.Operator) groupUpdateSQL { +func (q groupUpdateSQL) WhereSubLeaderUserID(v sql.Null[UserId], exprs ...sqlla.Operator) groupUpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNull[UserId]{Value: v, Op: op, Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereSubLeaderUserIDIn(vs ...sql.Null[UserId]) groupUpdateSQL { + where := sqlla.ExprMultiNull[UserId]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) SetChildGroupID(v sql.Null[id.GroupID]) groupUpdateSQL { + q.setMap["`child_group_id`"] = v + return q +} + +func (q groupUpdateSQL) WhereChildGroupID(v sql.Null[id.GroupID], exprs ...sqlla.Operator) groupUpdateSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprNull[T]{Value: v, Op: op, Column: "`sub_leader_user_id`"} + where := sqlla.ExprNull[id.GroupID]{Value: v, Op: op, Column: "`child_group_id`"} q.where = append(q.where, where) return q } -func (q groupUpdateSQL) WhereSubLeaderUserIDIn(vs ...sql.Null[T]) groupUpdateSQL { - where := sqlla.ExprMultiNull[T]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sub_leader_user_id`"} +func (q groupUpdateSQL) WhereChildGroupIDIn(vs ...sql.Null[id.GroupID]) groupUpdateSQL { + where := sqlla.ExprMultiNull[id.GroupID]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`child_group_id`"} q.where = append(q.where, where) return q } @@ -703,11 +757,16 @@ func (q groupInsertSQL) ValueLeaderUserID(v UserId) groupInsertSQL { return q } -func (q groupInsertSQL) ValueSubLeaderUserID(v sql.Null[T]) groupInsertSQL { +func (q groupInsertSQL) ValueSubLeaderUserID(v sql.Null[UserId]) groupInsertSQL { q.setMap["`sub_leader_user_id`"] = v return q } +func (q groupInsertSQL) ValueChildGroupID(v sql.Null[id.GroupID]) groupInsertSQL { + q.setMap["`child_group_id`"] = v + return q +} + func (q groupInsertSQL) ValueCreatedAt(v time.Time) groupInsertSQL { q.setMap["`created_at`"] = v return q @@ -851,7 +910,7 @@ func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateLeaderUserID() groupInse return q } -func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateSubLeaderUserID(v sql.Null[T]) groupInsertOnDuplicateKeyUpdateSQL { +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateSubLeaderUserID(v sql.Null[UserId]) groupInsertOnDuplicateKeyUpdateSQL { q.onDuplicateKeyUpdateMap["`sub_leader_user_id`"] = v return q } @@ -866,6 +925,21 @@ func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateSubLeaderUserID() groupI return q } +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateChildGroupID(v sql.Null[id.GroupID]) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`child_group_id`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) RawValueOnUpdateChildGroupID(v sqlla.SetMapRawValue) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`child_group_id`"] = v + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateChildGroupID() groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`child_group_id`"] = sqlla.SetMapRawValue("VALUES(`child_group_id`)") + return q +} + func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateCreatedAt(v time.Time) groupInsertOnDuplicateKeyUpdateSQL { q.onDuplicateKeyUpdateMap["`created_at`"] = v return q @@ -1092,20 +1166,38 @@ func (q groupDeleteSQL) LeaderUserIDIn(vs ...UserId) groupDeleteSQL { return q } -func (q groupDeleteSQL) SubLeaderUserID(v sql.Null[T], exprs ...sqlla.Operator) groupDeleteSQL { +func (q groupDeleteSQL) SubLeaderUserID(v sql.Null[UserId], exprs ...sqlla.Operator) groupDeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNull[UserId]{Value: v, Op: op, Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) SubLeaderUserIDIn(vs ...sql.Null[UserId]) groupDeleteSQL { + where := sqlla.ExprMultiNull[UserId]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) ChildGroupID(v sql.Null[id.GroupID], exprs ...sqlla.Operator) groupDeleteSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprNull[T]{Value: v, Op: op, Column: "`sub_leader_user_id`"} + where := sqlla.ExprNull[id.GroupID]{Value: v, Op: op, Column: "`child_group_id`"} q.where = append(q.where, where) return q } -func (q groupDeleteSQL) SubLeaderUserIDIn(vs ...sql.Null[T]) groupDeleteSQL { - where := sqlla.ExprMultiNull[T]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sub_leader_user_id`"} +func (q groupDeleteSQL) ChildGroupIDIn(vs ...sql.Null[id.GroupID]) groupDeleteSQL { + where := sqlla.ExprMultiNull[id.GroupID]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`child_group_id`"} q.where = append(q.where, where) return q } diff --git a/_example/group.go b/_example/group.go index 3ada9f9..c5c0b3d 100644 --- a/_example/group.go +++ b/_example/group.go @@ -5,6 +5,7 @@ import ( "time" "github.com/go-sql-driver/mysql" + "github.com/mackee/go-sqlla/_example/id" ) //go:generate go run ../cmd/sqlla/main.go @@ -14,10 +15,11 @@ type GroupID uint64 //sqlla:table group //genddl:table group type Group struct { - ID GroupID `db:"id,primarykey,autoincrement"` - Name string `db:"name"` - LeaderUserID UserId `db:"leader_user_id"` - SubLeaderUserID sql.Null[UserId] `db:"sub_leader_user_id"` + ID GroupID `db:"id,primarykey,autoincrement"` + Name string `db:"name"` + LeaderUserID UserId `db:"leader_user_id"` + SubLeaderUserID sql.Null[UserId] `db:"sub_leader_user_id"` + ChildGroupID sql.Null[id.GroupID] `db:"child_group_id"` CreatedAt time.Time `db:"created_at"` UpdatedAt mysql.NullTime `db:"updated_at"` diff --git a/_example/id/id.go b/_example/id/id.go new file mode 100644 index 0000000..2a55c0a --- /dev/null +++ b/_example/id/id.go @@ -0,0 +1,3 @@ +package id + +type GroupID uint64 diff --git a/generator.go b/generator.go index 1be7a66..d764866 100644 --- a/generator.go +++ b/generator.go @@ -60,7 +60,7 @@ func WriteCode(w io.Writer, table *Table) error { i := 0 for scanner.Scan() { i++ - fmt.Printf("%05d: %s\n", i, scanner.Text()) + // fmt.Printf("%05d: %s\n", i, scanner.Text()) } bs, err := format.Source(buf.Bytes()) if err != nil { diff --git a/go.mod b/go.mod index 9a9056c..c6c9680 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/mackee/go-sqlla/v2 go 1.20 require ( + github.com/Masterminds/goutils v1.1.1 github.com/go-sql-driver/mysql v1.6.0 github.com/pkg/errors v0.9.1 github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e diff --git a/go.sum b/go.sum index b1afe48..73ee8ec 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= +github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= diff --git a/main.go b/main.go index db04f28..b1d4504 100644 --- a/main.go +++ b/main.go @@ -94,8 +94,10 @@ func toTable(tablePkg *types.Package, annotationComment string, gd *ast.GenDecl, table := new(Table) table.Package = tablePkg table.PackageName = tablePkg.Name() + table.additionalPackagesMap = make(map[string]struct{}) table.TableName = trimAnnotation(annotationComment) + qualifier := types.RelativeTo(tablePkg) spec := gd.Specs[0] ts, ok := spec.(*ast.TypeSpec) @@ -140,14 +142,26 @@ func toTable(tablePkg *types.Package, annotationComment string, gd *ast.GenDecl, } baseTypeName = typeName if _, ok := supportedGenericsTypes[typeName]; ok { - tps := nt.TypeParams() - if tps == nil { + tas := nt.TypeArgs() + if tas == nil { return nil, fmt.Errorf("toTable: has not type params: table=%s, field=%s", table.TableName, columnName) } - tpsStr := make([]string, tps.Len()) - for i := 0; i < tps.Len(); i++ { - tp := tps.At(i) - tpsStr[i] = tp.String() + tpsStr := make([]string, tas.Len()) + for i := 0; i < tas.Len(); i++ { + ta := tas.At(i) + switch ata := ta.(type) { + case *types.Named: + tn := ata.Obj() + tpsStr[i] = tn.Id() + if qualifier(tn.Pkg()) != "" { + tpsStr[i] = tn.Pkg().Name() + "." + tn.Id() + table.additionalPackagesMap[tn.Pkg().Path()] = struct{}{} + } + case *types.Basic: + tpsStr[i] = ata.Name() + default: + return nil, fmt.Errorf("toTable: unsupported type param: table=%s, field=%s, type=%s", table.TableName, columnName, ta.String()) + } } typeParameter = strings.Join(tpsStr, ",") } else if _, ok := supportedNonPrimitiveTypes[typeName]; !ok { From 73d41db835a75dd4857b9e6b4db827443e4c9450 Mon Sep 17 00:00:00 2001 From: mackee Date: Fri, 5 Jul 2024 10:28:08 +0900 Subject: [PATCH 04/11] refactor: move Column to column.go. impl Column.IsNullT() --- column.go | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ table.go | 89 ---------------------------------------------------- 2 files changed, 94 insertions(+), 89 deletions(-) diff --git a/column.go b/column.go index 0768678..2ed8765 100644 --- a/column.go +++ b/column.go @@ -2,10 +2,104 @@ package sqlla import ( "fmt" + "go/ast" "sort" "strings" + + "github.com/Masterminds/goutils" ) +type Columns []Column + +type Column struct { + Field *ast.Field + Name string + MethodName string + typeName string + PkgName string + baseTypeName string + altTypeName string + typeParameter string + TableName string + IsPk bool +} + +func (c Column) HasUnderlyingType() bool { + return c.baseTypeName != c.typeName +} + +func (c Column) TypeName() string { + tn := c.typeName + if c.typeParameter != "" { + return tn + "[" + c.typeParameter + "]" + } + return tn +} + +func (c Column) BaseTypeName() string { + if c.typeParameter != "" { + return c.baseTypeName + "[" + c.typeParameter + "]" + } + return c.baseTypeName +} + +func (c Column) AltTypeName() string { + if c.altTypeName == "" { + return "" + } + if c.typeParameter != "" { + return c.altTypeName + "[" + c.typeParameter + "]" + } + return c.altTypeName +} + +func (c Column) IsNullT() bool { + return c.baseTypeName == "sql.Null" && c.typeParameter != "" +} + +func (c Column) typeNameForExpr() string { + tname := c.BaseTypeName() + if atn := c.AltTypeName(); atn != "" { + tname = atn + } + tname = c.exprize(tname) + tname = goutils.Capitalize(tname) + return tname +} + +func (c Column) ExprTypeName() string { + return "Expr" + c.typeNameForExpr() +} + +func (c Column) exprize(s string) string { + s = strings.TrimPrefix(s, "sql.") + s = strings.TrimPrefix(s, "time.") + s = strings.TrimPrefix(s, "mysql.") + return s +} + +func (c Column) ExprMultiTypeName() string { + return "ExprMulti" + c.typeNameForExpr() +} + +func (c Column) ExprValueIdentifier() string { + if c.typeName != c.baseTypeName { + return c.baseTypeName + "(v)" + } + return "v" +} + +func (c Column) String() string { + return c.Name +} + +func (c Column) FieldName() string { + if len(c.Field.Names) > 0 { + return c.Field.Names[0].Name + } + return "" +} + type Where []Expr func (wh Where) ToSql() (string, []interface{}, error) { diff --git a/table.go b/table.go index 1c7984e..ce9c709 100644 --- a/table.go +++ b/table.go @@ -3,10 +3,8 @@ package sqlla import ( - "go/ast" "go/types" "io" - "strings" "github.com/Masterminds/goutils" "github.com/serenize/snaker" @@ -63,90 +61,3 @@ func (t *Table) HasPk() bool { func (t Table) Render(w io.Writer) error { return nil } - -type Columns []Column - -type Column struct { - Field *ast.Field - Name string - MethodName string - typeName string - PkgName string - baseTypeName string - altTypeName string - typeParameter string - TableName string - IsPk bool -} - -func (c Column) HasUnderlyingType() bool { - return c.baseTypeName != c.typeName -} - -func (c Column) TypeName() string { - tn := c.typeName - if c.typeParameter != "" { - return tn + "[" + c.typeParameter + "]" - } - return tn -} - -func (c Column) BaseTypeName() string { - if c.typeParameter != "" { - return c.baseTypeName + "[" + c.typeParameter + "]" - } - return c.baseTypeName -} - -func (c Column) AltTypeName() string { - if c.altTypeName == "" { - return "" - } - if c.typeParameter != "" { - return c.altTypeName + "[" + c.typeParameter + "]" - } - return c.altTypeName -} - -func (c Column) typeNameForExpr() string { - tname := c.BaseTypeName() - if atn := c.AltTypeName(); atn != "" { - tname = atn - } - tname = c.exprize(tname) - tname = goutils.Capitalize(tname) - return tname -} - -func (c Column) ExprTypeName() string { - return "Expr" + c.typeNameForExpr() -} - -func (c Column) exprize(s string) string { - s = strings.TrimPrefix(s, "sql.") - s = strings.TrimPrefix(s, "time.") - s = strings.TrimPrefix(s, "mysql.") - return s -} - -func (c Column) ExprMultiTypeName() string { - return "ExprMulti" + c.typeNameForExpr() -} - -func (c Column) ExprValueIdentifier() string { - if c.typeName != c.baseTypeName { - return c.baseTypeName + "(v)" - } - return "v" -} - -func (c Column) String() string { - return c.Name -} - -func (c Column) FieldName() string { - if len(c.Field.Names) > 0 { - return c.Field.Names[0].Name - } - return "" -} From 51bb22fcc0d550728d1aa5d296c481d813cc3f14 Mon Sep 17 00:00:00 2001 From: mackee Date: Fri, 5 Jul 2024 16:12:12 +0900 Subject: [PATCH 05/11] refactor: to be testable analysis methods --- column_test.go | 46 ++++++++++++++++++++ go.mod | 4 ++ go.sum | 6 +++ main.go | 76 ++++++++++++++++++++++------------ main_priv.go | 7 ++++ testdata/nullt/repoa/go.mod | 3 ++ testdata/nullt/repoa/schema.go | 15 +++++++ 7 files changed, 130 insertions(+), 27 deletions(-) create mode 100644 column_test.go create mode 100644 main_priv.go create mode 100644 testdata/nullt/repoa/go.mod create mode 100644 testdata/nullt/repoa/schema.go diff --git a/column_test.go b/column_test.go new file mode 100644 index 0000000..badd76a --- /dev/null +++ b/column_test.go @@ -0,0 +1,46 @@ +package sqlla_test + +import ( + "errors" + "os" + "path/filepath" + "testing" + + "github.com/mackee/go-sqlla/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestColumnNullT(t *testing.T) { + cwd, err := os.Getwd() + t.Cleanup(func() { + require.NoError(t, os.Chdir(cwd)) + }) + + require.NoError(t, err) + fullpath, err := filepath.Abs(filepath.Join("./testdata", "nullt", "repoa", "schema.go")) + require.NoError(t, err) + dir := filepath.Dir(fullpath) + require.NoError(t, os.Chdir(dir)) + + pkgs, err := sqlla.ToPackages(dir) + require.NoError(t, err) + var table *sqlla.Table + for _, pkg := range pkgs { + files := pkg.Syntax + for _, f := range files { + for _, decl := range f.Decls { + _table, err := sqlla.DeclToTable(pkg, decl, fullpath) + if errors.Is(err, sqlla.ErrNotTargetDecl) { + continue + } + require.NoError(t, err) + table = _table + } + } + } + require.NotNil(t, table) + assert.False(t, table.Columns[0].IsNullT()) // ID + assert.True(t, table.Columns[1].IsNullT()) // ModifiedAt + assert.False(t, table.Columns[2].IsNullT()) // FIXME: not supported yet +} diff --git a/go.mod b/go.mod index c6c9680..2820a91 100644 --- a/go.mod +++ b/go.mod @@ -11,8 +11,12 @@ require ( ) require ( + github.com/davecgh/go-spew v1.1.1 // indirect github.com/onsi/ginkgo v1.16.5 // indirect github.com/onsi/gomega v1.17.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/testify v1.9.0 // indirect golang.org/x/mod v0.16.0 // indirect golang.org/x/sys v0.12.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 73ee8ec..c4bfca1 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,7 @@ github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= @@ -36,11 +37,14 @@ github.com/onsi/gomega v1.17.0 h1:9Luw4uT5HTjHTN8+aNcSThgH1vdXnmdJ8xIfZ4wyTRE= github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e h1:zWKUYT07mGmVBH+9UgnHXd/ekCK99C8EbDSAt5qsjXE= github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e/go.mod h1:Yow6lPLSAXx2ifx470yD/nUe22Dv5vBvxK/UK9UUTVs= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -103,3 +107,5 @@ gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index b1d4504..ee51e00 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package sqlla import ( + "errors" "fmt" "go/ast" "go/types" @@ -14,6 +15,17 @@ import ( "golang.org/x/tools/go/packages" ) +func toPackages(dir string) ([]*packages.Package, error) { + conf := &packages.Config{ + Mode: packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo, + } + pkgs, err := packages.Load(conf, dir) + if err != nil { + return nil, fmt.Errorf("error toPackages: %w", err) + } + return pkgs, nil +} + func Run(from, ext string) { fullpath, err := filepath.Abs(from) if err != nil { @@ -21,10 +33,7 @@ func Run(from, ext string) { } dir := filepath.Dir(fullpath) - conf := &packages.Config{ - Mode: packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo, - } - pkgs, err := packages.Load(conf, dir) + pkgs, err := toPackages(dir) if err != nil { panic(err) } @@ -32,30 +41,11 @@ func Run(from, ext string) { files := pkg.Syntax for _, f := range files { for _, decl := range f.Decls { - pos := pkg.Fset.Position(decl.Pos()) - if pos.Filename != fullpath { - continue - } - genDecl, ok := decl.(*ast.GenDecl) - if !ok { - continue - } - if genDecl.Doc == nil { - continue - } - var hasAnnotation bool - var annotationComment string - for _, comment := range genDecl.Doc.List { - if trimmed := trimAnnotation(comment.Text); trimmed != comment.Text { - hasAnnotation = true - annotationComment = comment.Text - } - } - if !hasAnnotation { - continue - } - table, err := toTable(pkg.Types, annotationComment, genDecl, pkg.TypesInfo) + table, err := declToTable(pkg, decl, fullpath) if err != nil { + if errors.Is(err, errNotTargetDecl) { + continue + } panic(err) } filename := filepath.Join(dir, table.TableName+ext) @@ -71,6 +61,38 @@ func Run(from, ext string) { } } +var errNotTargetDecl = fmt.Errorf("not target decl") + +func declToTable(pkg *packages.Package, decl ast.Decl, fullpath string) (*Table, error) { + pos := pkg.Fset.Position(decl.Pos()) + if pos.Filename != fullpath { + return nil, errNotTargetDecl + } + genDecl, ok := decl.(*ast.GenDecl) + if !ok { + return nil, errNotTargetDecl + } + if genDecl.Doc == nil { + return nil, errNotTargetDecl + } + var hasAnnotation bool + var annotationComment string + for _, comment := range genDecl.Doc.List { + if trimmed := trimAnnotation(comment.Text); trimmed != comment.Text { + hasAnnotation = true + annotationComment = comment.Text + } + } + if !hasAnnotation { + return nil, errNotTargetDecl + } + table, err := toTable(pkg.Types, annotationComment, genDecl, pkg.TypesInfo) + if err != nil { + return nil, fmt.Errorf("error toTable: %w", err) + } + return table, nil +} + var supportedNonPrimitiveTypes = map[string]struct{}{ "time.Time": {}, "mysql.NullTime": {}, diff --git a/main_priv.go b/main_priv.go new file mode 100644 index 0000000..0ccb536 --- /dev/null +++ b/main_priv.go @@ -0,0 +1,7 @@ +package sqlla + +var ( + ToPackages = toPackages + DeclToTable = declToTable + ErrNotTargetDecl = errNotTargetDecl +) diff --git a/testdata/nullt/repoa/go.mod b/testdata/nullt/repoa/go.mod new file mode 100644 index 0000000..ef9c055 --- /dev/null +++ b/testdata/nullt/repoa/go.mod @@ -0,0 +1,3 @@ +module gopher.example/repoa + +go 1.22.4 diff --git a/testdata/nullt/repoa/schema.go b/testdata/nullt/repoa/schema.go new file mode 100644 index 0000000..768e405 --- /dev/null +++ b/testdata/nullt/repoa/schema.go @@ -0,0 +1,15 @@ +package repoa + +import ( + "database/sql" + "time" +) + +type NullableTime sql.Null[time.Time] + +//sqlla:table product +type Product struct { + ID uint64 `db:"id,primarykey,autoincrement"` + ModifiedAt sql.Null[time.Time] `db:"modified_at"` + RemovedAt NullableTime `db:"removed_at"` +} From 18c2233fc9b3899d684999e0a518576e80abe30e Mon Sep 17 00:00:00 2001 From: mackee Date: Mon, 8 Jul 2024 10:35:19 +0900 Subject: [PATCH 06/11] feat: implements specific methods when a column is defined as Null[T] --- _example/go.mod | 4 +- _example/go.sum | 130 +-------------------- _example/group.gen.go | 180 ++++++++++++++++++++++++------ column.go | 4 + column_test.go | 4 +- generator.go | 10 +- template/delete_column.tmpl | 4 + template/delete_column_nullt.tmpl | 36 ++++++ template/insert_column.tmpl | 13 +++ template/select_column.tmpl | 7 +- template/select_column_nullt.tmpl | 36 ++++++ template/update_column.tmpl | 4 + template/update_column_nullt.tmpl | 45 ++++++++ 13 files changed, 309 insertions(+), 168 deletions(-) create mode 100644 template/delete_column_nullt.tmpl create mode 100644 template/select_column_nullt.tmpl create mode 100644 template/update_column_nullt.tmpl diff --git a/_example/go.mod b/_example/go.mod index a2b495f..b5415de 100644 --- a/_example/go.mod +++ b/_example/go.mod @@ -1,6 +1,8 @@ module github.com/mackee/go-sqlla/_example -go 1.17 +go 1.22 + +toolchain go1.22.4 replace github.com/mackee/go-sqlla/v2 => ../ diff --git a/_example/go.sum b/_example/go.sum index 65023ed..eee0809 100644 --- a/_example/go.sum +++ b/_example/go.sum @@ -1,6 +1,5 @@ github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 h1:w+iIsaOQNcT7OZ575w+acHgRric5iCyQh+xv+KJ4HB8= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Microsoft/go-winio v0.5.2 h1:a9IhgEQBCUEk6QCdml9CiJGhAws+YwffDHEMp1VMrpA= @@ -9,65 +8,37 @@ github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEV github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk= github.com/cenkalti/backoff/v4 v4.1.3 h1:cFAlzYUlVYDysBEH2T5hyJZMh3+5+WCBvSnK6Q8UtC4= github.com/cenkalti/backoff/v4 v4.1.3/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= -github.com/checkpoint-restore/go-criu/v5 v5.3.0/go.mod h1:E/eQpaFtUKGOOSEBZgmKAcn+zUUwWxqcaKZlF54wK8E= -github.com/cilium/ebpf v0.7.0/go.mod h1:/oI2+1shJiTGAMgl6/RgJr36Eo1jzrRcAWbcXO2usCA= -github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= github.com/containerd/continuity v0.3.0 h1:nisirsYROK15TAMVukJOUyGJjz4BNQJBVsNvAXZJ/eg= github.com/containerd/continuity v0.3.0/go.mod h1:wJEAIwKOm/pBZuBd0JmeTvnLquTB1Ag8espWhkykbPM= -github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/cyphar/filepath-securejoin v0.2.3/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4= -github.com/cyphar/filepath-securejoin v0.2.4/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/docker/cli v20.10.14+incompatible h1:dSBKJOVesDgHo7rbxlYjYsXe7gPzrTT+/cKQgpDAazg= github.com/docker/cli v20.10.14+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= -github.com/docker/docker v20.10.7+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker v24.0.9+incompatible h1:HPGzNmwfLZWdxHqK9/II92pyi1EpYKsAqcl4G0Of9v0= github.com/docker/docker v24.0.9+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw= github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= -github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= -github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/godbus/dbus/v5 v5.0.6/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/lib/pq v0.0.0-20180327071824-d34b9ff171c2 h1:hRGSmZu7j271trc9sneMrpOW7GN5ngLm8YUZIPzf394= github.com/lib/pq v0.0.0-20180327071824-d34b9ff171c2/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/mackee/go-genddl v0.0.0-20220809061459-645eadea7290 h1:/Es4hR6SMmW6Cak1aKoD/zhZvpArKKa4oMuZZ6NmMmQ= @@ -76,32 +47,20 @@ github.com/mattn/go-sqlite3 v1.14.9 h1:10HX2Td0ocZpYEjhilsuo6WWtUqttj2Kb0KtD86/K github.com/mattn/go-sqlite3 v1.14.9/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag= github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/moby/sys/mountinfo v0.5.0/go.mod h1:3bMD3Rg+zkqx8MRYPi7Pyb0Ie97QEBmdxbhnCLlSvSU= github.com/moby/term v0.0.0-20201216013528-df9cb8a40635 h1:rzf0wL0CHVc8CEsgyygG0Mn9CNCCPZqOPaz8RiiHYQk= github.com/moby/term v0.0.0-20201216013528-df9cb8a40635/go.mod h1:FBS0z0QWA44HXygs7VXDUOGoN/1TV3RuWkLO04am3wc= -github.com/mrunalp/fileutils v0.5.0/go.mod h1:M1WthSahJixYnrXQl/DFQuteStB1weuxD2QJNHXfbSQ= -github.com/mrunalp/fileutils v0.5.1/go.mod h1:M1WthSahJixYnrXQl/DFQuteStB1weuxD2QJNHXfbSQ= -github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.17.0 h1:9Luw4uT5HTjHTN8+aNcSThgH1vdXnmdJ8xIfZ4wyTRE= github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM= github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= -github.com/opencontainers/runc v1.1.2/go.mod h1:Tj1hFw6eFWp/o33uxGf5yF2BX5yz2Z6iptFpuvbbKqc= github.com/opencontainers/runc v1.1.12 h1:BOIssBaW1La0/qbNZHXOOa71dZfZEQOzW7dqQf3phss= github.com/opencontainers/runc v1.1.12/go.mod h1:S+lQwSfncpBha7XTy/5lBwWgm5+y5Ma/O44Ekby9FK8= -github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= -github.com/opencontainers/selinux v1.10.0/go.mod h1:2i0OySw99QjzBBQByd1Gr9gSjvuho1lHsJxIJ3gGbJI= github.com/ory/dockertest/v3 v3.9.1 h1:v4dkG+dlu76goxMiTT2j8zV7s4oPPEppKT8K8p2f1kY= github.com/ory/dockertest/v3 v3.9.1/go.mod h1:42Ir9hmvaAPm0Mgibk6mBPi7SFvTXxEcnztDYOJ//uM= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -109,12 +68,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/seccomp/libseccomp-golang v0.9.2-0.20210429002308-3879420cc921/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= -github.com/seccomp/libseccomp-golang v0.9.2-0.20220502022130-f33da4d89646/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e h1:zWKUYT07mGmVBH+9UgnHXd/ekCK99C8EbDSAt5qsjXE= github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e/go.mod h1:Yow6lPLSAXx2ifx470yD/nUe22Dv5vBvxK/UK9UUTVs= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= @@ -122,13 +77,8 @@ github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= -github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= -github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= @@ -137,103 +87,43 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17 github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= -golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191115151921-52ab43148777/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200831180312-196b9ba8737a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210906170528-6f6e22806c34/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211116061358-0a5406a5449c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220405210540-1e041c57c461/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220808155132-1c4a2a72c664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= -golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -242,27 +132,15 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f h1:uF6paiQQebLeSXkrTqHqz0MXhXXS1KgF41eUdBNvxK0= golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= gotest.tools/v3 v3.2.0 h1:I0DwBVMGAx26dttAj1BtJLAkVGncrkkUXfJLC4Flt/I= gotest.tools/v3 v3.2.0/go.mod h1:Mcr9QNxkg0uMvy/YElmo4SpXgJKWgQvYrT7Kw5RzJ1A= diff --git a/_example/group.gen.go b/_example/group.gen.go index 77a6df0..1371728 100644 --- a/_example/group.gen.go +++ b/_example/group.gen.go @@ -232,20 +232,36 @@ func (q groupSelectSQL) OrderByLeaderUserID(order sqlla.Order) groupSelectSQL { return q } -func (q groupSelectSQL) SubLeaderUserID(v sql.Null[UserId], exprs ...sqlla.Operator) groupSelectSQL { +func (q groupSelectSQL) SubLeaderUserID(v UserId, exprs ...sqlla.Operator) groupSelectSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprNull[UserId]{Value: v, Op: op, Column: q.appendColumnPrefix("`sub_leader_user_id`")} + where := sqlla.ExprNull[UserId]{Value: sql.Null[UserId]{V: v, Valid: true}, Op: op, Column: q.appendColumnPrefix("`sub_leader_user_id`")} q.where = append(q.where, where) return q } -func (q groupSelectSQL) SubLeaderUserIDIn(vs ...sql.Null[UserId]) groupSelectSQL { - where := sqlla.ExprMultiNull[UserId]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`sub_leader_user_id`")} +func (q groupSelectSQL) SubLeaderUserIDIsNull() groupSelectSQL { + where := sqlla.ExprNull[UserId]{Value: sql.Null[UserId]{Valid: false}, Op: sqlla.OpEqual, Column: q.appendColumnPrefix("`sub_leader_user_id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) SubLeaderUserIDIsNotNull() groupSelectSQL { + where := sqlla.ExprNull[UserId]{Value: sql.Null[UserId]{Valid: false}, Op: sqlla.OpNot, Column: q.appendColumnPrefix("`sub_leader_user_id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) SubLeaderUserIDIn(vs ...UserId) groupSelectSQL { + _vs := make([]sql.Null[UserId], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[UserId]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[UserId]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`sub_leader_user_id`")} q.where = append(q.where, where) return q } @@ -261,20 +277,36 @@ func (q groupSelectSQL) OrderBySubLeaderUserID(order sqlla.Order) groupSelectSQL return q } -func (q groupSelectSQL) ChildGroupID(v sql.Null[id.GroupID], exprs ...sqlla.Operator) groupSelectSQL { +func (q groupSelectSQL) ChildGroupID(v id.GroupID, exprs ...sqlla.Operator) groupSelectSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprNull[id.GroupID]{Value: v, Op: op, Column: q.appendColumnPrefix("`child_group_id`")} + where := sqlla.ExprNull[id.GroupID]{Value: sql.Null[id.GroupID]{V: v, Valid: true}, Op: op, Column: q.appendColumnPrefix("`child_group_id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) ChildGroupIDIsNull() groupSelectSQL { + where := sqlla.ExprNull[id.GroupID]{Value: sql.Null[id.GroupID]{Valid: false}, Op: sqlla.OpEqual, Column: q.appendColumnPrefix("`child_group_id`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) ChildGroupIDIsNotNull() groupSelectSQL { + where := sqlla.ExprNull[id.GroupID]{Value: sql.Null[id.GroupID]{Valid: false}, Op: sqlla.OpNot, Column: q.appendColumnPrefix("`child_group_id`")} q.where = append(q.where, where) return q } -func (q groupSelectSQL) ChildGroupIDIn(vs ...sql.Null[id.GroupID]) groupSelectSQL { - where := sqlla.ExprMultiNull[id.GroupID]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`child_group_id`")} +func (q groupSelectSQL) ChildGroupIDIn(vs ...id.GroupID) groupSelectSQL { + _vs := make([]sql.Null[id.GroupID], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[id.GroupID]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[id.GroupID]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`child_group_id`")} q.where = append(q.where, where) return q } @@ -576,48 +608,90 @@ func (q groupUpdateSQL) WhereLeaderUserIDIn(vs ...UserId) groupUpdateSQL { return q } -func (q groupUpdateSQL) SetSubLeaderUserID(v sql.Null[UserId]) groupUpdateSQL { - q.setMap["`sub_leader_user_id`"] = v +func (q groupUpdateSQL) SetSubLeaderUserID(v UserId) groupUpdateSQL { + q.setMap["`sub_leader_user_id`"] = sql.Null[UserId]{V: v, Valid: true} + return q +} + +func (q groupUpdateSQL) SetSubLeaderUserIDToNull() groupUpdateSQL { + q.setMap["`sub_leader_user_id`"] = sql.Null[UserId]{Valid: false} return q } -func (q groupUpdateSQL) WhereSubLeaderUserID(v sql.Null[UserId], exprs ...sqlla.Operator) groupUpdateSQL { +func (q groupUpdateSQL) WhereSubLeaderUserID(v UserId, exprs ...sqlla.Operator) groupUpdateSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprNull[UserId]{Value: v, Op: op, Column: "`sub_leader_user_id`"} + where := sqlla.ExprNull[UserId]{Value: sql.Null[UserId]{V: v, Valid: true}, Op: op, Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereSubLeaderUserIDIsNull() groupUpdateSQL { + where := sqlla.ExprNull[UserId]{Value: sql.Null[UserId]{Valid: false}, Op: sqlla.OpEqual, Column: "`sub_leader_user_id`"} q.where = append(q.where, where) return q } -func (q groupUpdateSQL) WhereSubLeaderUserIDIn(vs ...sql.Null[UserId]) groupUpdateSQL { - where := sqlla.ExprMultiNull[UserId]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sub_leader_user_id`"} +func (q groupUpdateSQL) WhereSubLeaderUserIDIsNotNull() groupUpdateSQL { + where := sqlla.ExprNull[UserId]{Value: sql.Null[UserId]{Valid: false}, Op: sqlla.OpNot, Column: "`sub_leader_user_id`"} q.where = append(q.where, where) return q } -func (q groupUpdateSQL) SetChildGroupID(v sql.Null[id.GroupID]) groupUpdateSQL { - q.setMap["`child_group_id`"] = v +func (q groupUpdateSQL) WhereSubLeaderUserIDIn(vs ...UserId) groupUpdateSQL { + _vs := make([]sql.Null[UserId], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[UserId]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[UserId]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) SetChildGroupID(v id.GroupID) groupUpdateSQL { + q.setMap["`child_group_id`"] = sql.Null[id.GroupID]{V: v, Valid: true} + return q +} + +func (q groupUpdateSQL) SetChildGroupIDToNull() groupUpdateSQL { + q.setMap["`child_group_id`"] = sql.Null[id.GroupID]{Valid: false} return q } -func (q groupUpdateSQL) WhereChildGroupID(v sql.Null[id.GroupID], exprs ...sqlla.Operator) groupUpdateSQL { +func (q groupUpdateSQL) WhereChildGroupID(v id.GroupID, exprs ...sqlla.Operator) groupUpdateSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprNull[id.GroupID]{Value: v, Op: op, Column: "`child_group_id`"} + where := sqlla.ExprNull[id.GroupID]{Value: sql.Null[id.GroupID]{V: v, Valid: true}, Op: op, Column: "`child_group_id`"} q.where = append(q.where, where) return q } -func (q groupUpdateSQL) WhereChildGroupIDIn(vs ...sql.Null[id.GroupID]) groupUpdateSQL { - where := sqlla.ExprMultiNull[id.GroupID]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`child_group_id`"} +func (q groupUpdateSQL) WhereChildGroupIDIsNull() groupUpdateSQL { + where := sqlla.ExprNull[id.GroupID]{Value: sql.Null[id.GroupID]{Valid: false}, Op: sqlla.OpEqual, Column: "`child_group_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereChildGroupIDIsNotNull() groupUpdateSQL { + where := sqlla.ExprNull[id.GroupID]{Value: sql.Null[id.GroupID]{Valid: false}, Op: sqlla.OpNot, Column: "`child_group_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereChildGroupIDIn(vs ...id.GroupID) groupUpdateSQL { + _vs := make([]sql.Null[id.GroupID], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[id.GroupID]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[id.GroupID]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`child_group_id`"} q.where = append(q.where, where) return q } @@ -757,13 +831,23 @@ func (q groupInsertSQL) ValueLeaderUserID(v UserId) groupInsertSQL { return q } -func (q groupInsertSQL) ValueSubLeaderUserID(v sql.Null[UserId]) groupInsertSQL { - q.setMap["`sub_leader_user_id`"] = v +func (q groupInsertSQL) ValueSubLeaderUserID(v UserId) groupInsertSQL { + q.setMap["`sub_leader_user_id`"] = sql.Null[UserId]{V: v, Valid: true} return q } -func (q groupInsertSQL) ValueChildGroupID(v sql.Null[id.GroupID]) groupInsertSQL { - q.setMap["`child_group_id`"] = v +func (q groupInsertSQL) ValueSubLeaderUserIDIsNull() groupInsertSQL { + q.setMap["`sub_leader_user_id`"] = sql.Null[UserId]{Valid: false} + return q +} + +func (q groupInsertSQL) ValueChildGroupID(v id.GroupID) groupInsertSQL { + q.setMap["`child_group_id`"] = sql.Null[id.GroupID]{V: v, Valid: true} + return q +} + +func (q groupInsertSQL) ValueChildGroupIDIsNull() groupInsertSQL { + q.setMap["`child_group_id`"] = sql.Null[id.GroupID]{Valid: false} return q } @@ -1166,38 +1250,70 @@ func (q groupDeleteSQL) LeaderUserIDIn(vs ...UserId) groupDeleteSQL { return q } -func (q groupDeleteSQL) SubLeaderUserID(v sql.Null[UserId], exprs ...sqlla.Operator) groupDeleteSQL { +func (q groupDeleteSQL) SubLeaderUserID(v UserId, exprs ...sqlla.Operator) groupDeleteSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprNull[UserId]{Value: v, Op: op, Column: "`sub_leader_user_id`"} + where := sqlla.ExprNull[UserId]{Value: sql.Null[UserId]{V: v, Valid: true}, Op: op, Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) SubLeaderUserIDIsNull() groupDeleteSQL { + where := sqlla.ExprNull[UserId]{Value: sql.Null[UserId]{Valid: false}, Op: sqlla.OpEqual, Column: "`sub_leader_user_id`"} q.where = append(q.where, where) return q } -func (q groupDeleteSQL) SubLeaderUserIDIn(vs ...sql.Null[UserId]) groupDeleteSQL { - where := sqlla.ExprMultiNull[UserId]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sub_leader_user_id`"} +func (q groupDeleteSQL) SubLeaderUserIDIsNotNull() groupDeleteSQL { + where := sqlla.ExprNull[UserId]{Value: sql.Null[UserId]{Valid: false}, Op: sqlla.OpNot, Column: "`sub_leader_user_id`"} q.where = append(q.where, where) return q } -func (q groupDeleteSQL) ChildGroupID(v sql.Null[id.GroupID], exprs ...sqlla.Operator) groupDeleteSQL { +func (q groupDeleteSQL) SubLeaderUserIDIn(vs ...UserId) groupDeleteSQL { + _vs := make([]sql.Null[UserId], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[UserId]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[UserId]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`sub_leader_user_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) ChildGroupID(v id.GroupID, exprs ...sqlla.Operator) groupDeleteSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprNull[id.GroupID]{Value: v, Op: op, Column: "`child_group_id`"} + where := sqlla.ExprNull[id.GroupID]{Value: sql.Null[id.GroupID]{V: v, Valid: true}, Op: op, Column: "`child_group_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) ChildGroupIDIsNull() groupDeleteSQL { + where := sqlla.ExprNull[id.GroupID]{Value: sql.Null[id.GroupID]{Valid: false}, Op: sqlla.OpEqual, Column: "`child_group_id`"} q.where = append(q.where, where) return q } -func (q groupDeleteSQL) ChildGroupIDIn(vs ...sql.Null[id.GroupID]) groupDeleteSQL { - where := sqlla.ExprMultiNull[id.GroupID]{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`child_group_id`"} +func (q groupDeleteSQL) ChildGroupIDIsNotNull() groupDeleteSQL { + where := sqlla.ExprNull[id.GroupID]{Value: sql.Null[id.GroupID]{Valid: false}, Op: sqlla.OpNot, Column: "`child_group_id`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) ChildGroupIDIn(vs ...id.GroupID) groupDeleteSQL { + _vs := make([]sql.Null[id.GroupID], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[id.GroupID]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[id.GroupID]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`child_group_id`"} q.where = append(q.where, where) return q } diff --git a/column.go b/column.go index 2ed8765..e7c3885 100644 --- a/column.go +++ b/column.go @@ -57,6 +57,10 @@ func (c Column) IsNullT() bool { return c.baseTypeName == "sql.Null" && c.typeParameter != "" } +func (c Column) TypeParameter() string { + return c.typeParameter +} + func (c Column) typeNameForExpr() string { tname := c.BaseTypeName() if atn := c.AltTypeName(); atn != "" { diff --git a/column_test.go b/column_test.go index badd76a..11a1e8a 100644 --- a/column_test.go +++ b/column_test.go @@ -42,5 +42,7 @@ func TestColumnNullT(t *testing.T) { require.NotNil(t, table) assert.False(t, table.Columns[0].IsNullT()) // ID assert.True(t, table.Columns[1].IsNullT()) // ModifiedAt - assert.False(t, table.Columns[2].IsNullT()) // FIXME: not supported yet + assert.Equal(t, table.Columns[1].TypeParameter(), "time.Time") + assert.False(t, table.Columns[2].IsNullT()) // FIXME: not supported yet + assert.Equal(t, table.Columns[2].TypeParameter(), "") // FIXME: not supported yet } diff --git a/generator.go b/generator.go index d764866..e610592 100644 --- a/generator.go +++ b/generator.go @@ -3,7 +3,6 @@ package sqlla import ( - "bufio" "bytes" "embed" "go/format" @@ -56,14 +55,11 @@ func WriteCode(w io.Writer, table *Table) error { if err != nil { return errors.Wrapf(err, "fail to render") } - scanner := bufio.NewScanner(bytes.NewReader(buf.Bytes())) - i := 0 - for scanner.Scan() { - i++ - // fmt.Printf("%05d: %s\n", i, scanner.Text()) - } bs, err := format.Source(buf.Bytes()) if err != nil { + if _, err := w.Write(buf.Bytes()); err != nil { + return errors.Wrapf(err, "fail to write: table=%s", table.Name) + } return errors.Wrapf(err, "fail to format: table=%s", table.Name) } _, err = w.Write(bs) diff --git a/template/delete_column.tmpl b/template/delete_column.tmpl index d83cd4c..4719070 100644 --- a/template/delete_column.tmpl +++ b/template/delete_column.tmpl @@ -1,4 +1,7 @@ {{ define "DeleteColumn" }}{{ $smallTableName := .TableName | toCamel | Untitle }} +{{- if .IsNullT }} +{{- template "DeleteColumnNullT" . }} +{{- else }} func (q {{ $smallTableName }}DeleteSQL) {{ .MethodName }}(v {{ .TypeName }}, exprs ...sqlla.Operator) {{ $smallTableName }}DeleteSQL { var op sqlla.Operator if len(exprs) == 0 { @@ -25,4 +28,5 @@ func (q {{ $smallTableName }}DeleteSQL) {{ .MethodName }}In(vs ...{{ .TypeName } q.where = append(q.where, where) return q } +{{- end }} {{ end }} diff --git a/template/delete_column_nullt.tmpl b/template/delete_column_nullt.tmpl new file mode 100644 index 0000000..2de244f --- /dev/null +++ b/template/delete_column_nullt.tmpl @@ -0,0 +1,36 @@ +{{ define "DeleteColumnNullT" }} +{{ $smallTableName := .TableName | toCamel | Untitle }} +func (q {{ $smallTableName }}DeleteSQL) {{ .MethodName }}(v {{ .TypeParameter }}, exprs ...sqlla.Operator) {{ $smallTableName }}DeleteSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNull[{{ .TypeParameter }}]{Value: sql.Null[{{ .TypeParameter }}]{ V: v, Valid: true }, Op: op, Column: "`{{ .Name }}`"} + q.where = append(q.where, where) + return q +} + +func (q {{ $smallTableName }}DeleteSQL) {{ .MethodName }}IsNull() {{ $smallTableName }}DeleteSQL { + where := sqlla.ExprNull[{{ .TypeParameter }}]{Value: sql.Null[{{ .TypeParameter }}]{ Valid: false }, Op: sqlla.OpEqual, Column: "`{{ .Name }}`"} + q.where = append(q.where, where) + return q +} + +func (q {{ $smallTableName }}DeleteSQL) {{ .MethodName }}IsNotNull() {{ $smallTableName }}DeleteSQL { + where := sqlla.ExprNull[{{ .TypeParameter }}]{Value: sql.Null[{{ .TypeParameter }}]{ Valid: false }, Op: sqlla.OpNot, Column: "`{{ .Name }}`"} + q.where = append(q.where, where) + return q +} + +func (q {{ $smallTableName }}DeleteSQL) {{ .MethodName }}In(vs ...{{ .TypeParameter }}) {{ $smallTableName }}DeleteSQL { + _vs := make([]sql.Null[{{ .TypeParameter }}], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[{{ .TypeParameter }}]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[{{ .TypeParameter }}]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} + q.where = append(q.where, where) + return q +} +{{- end }} diff --git a/template/insert_column.tmpl b/template/insert_column.tmpl index 5dfad97..f939cfa 100644 --- a/template/insert_column.tmpl +++ b/template/insert_column.tmpl @@ -1,7 +1,20 @@ {{ define "InsertColumn" }}{{ $smallTableName := .TableName | toCamel | Untitle }} +{{- if .IsNullT }} +func (q {{ $smallTableName }}InsertSQL) Value{{ .MethodName }}(v {{ .TypeParameter }}) {{ $smallTableName }}InsertSQL { + q.setMap["`{{ .Name }}`"] = sql.Null[{{ .TypeParameter }}]{ V: v, Valid: true } + return q +} + +func (q {{ $smallTableName }}InsertSQL) Value{{ .MethodName }}IsNull() {{ $smallTableName }}InsertSQL { + q.setMap["`{{ .Name }}`"] = sql.Null[{{ .TypeParameter }}]{ Valid: false } + return q +} + +{{- else }} func (q {{ $smallTableName }}InsertSQL) Value{{ .MethodName }}(v {{ .TypeName }}) {{ $smallTableName }}InsertSQL { q.setMap["`{{ .Name }}`"] = v return q } +{{- end }} {{ end }} diff --git a/template/select_column.tmpl b/template/select_column.tmpl index 2e33161..8fd8877 100644 --- a/template/select_column.tmpl +++ b/template/select_column.tmpl @@ -1,4 +1,8 @@ -{{ define "SelectColumn" }}{{ $smallTableName := .TableName | toCamel | Untitle }} +{{ define "SelectColumn" }} +{{- $smallTableName := .TableName | toCamel | Untitle }} +{{- if .IsNullT }} +{{- template "SelectColumnNullT" . }} +{{- else }} func (q {{ $smallTableName }}SelectSQL) {{ .MethodName }}(v {{ .TypeName }}, exprs ...sqlla.Operator) {{ $smallTableName }}SelectSQL { var op sqlla.Operator if len(exprs) == 0 { @@ -24,6 +28,7 @@ func (q {{ $smallTableName }}SelectSQL) {{ .MethodName }}In(vs ...{{ .TypeName } q.where = append(q.where, where) return q } +{{- end }} {{ if .IsPk -}} func (q {{ $smallTableName }}SelectSQL) PkColumn(pk int64, exprs ...sqlla.Operator) {{ $smallTableName }}SelectSQL { diff --git a/template/select_column_nullt.tmpl b/template/select_column_nullt.tmpl new file mode 100644 index 0000000..9d52fe1 --- /dev/null +++ b/template/select_column_nullt.tmpl @@ -0,0 +1,36 @@ +{{ define "SelectColumnNullT" }} +{{ $smallTableName := .TableName | toCamel | Untitle }} +func (q {{ $smallTableName }}SelectSQL) {{ .MethodName }}(v {{ .TypeParameter }}, exprs ...sqlla.Operator) {{ $smallTableName }}SelectSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNull[{{ .TypeParameter }}]{Value: sql.Null[{{ .TypeParameter }}]{ V: v, Valid: true }, Op: op, Column: q.appendColumnPrefix("`{{ .Name }}`")} + q.where = append(q.where, where) + return q +} + +func (q {{ $smallTableName }}SelectSQL) {{ .MethodName }}IsNull() {{ $smallTableName }}SelectSQL { + where := sqlla.ExprNull[{{ .TypeParameter }}]{Value: sql.Null[{{ .TypeParameter }}]{ Valid: false }, Op: sqlla.OpEqual, Column: q.appendColumnPrefix("`{{ .Name }}`")} + q.where = append(q.where, where) + return q +} + +func (q {{ $smallTableName }}SelectSQL) {{ .MethodName }}IsNotNull() {{ $smallTableName }}SelectSQL { + where := sqlla.ExprNull[{{ .TypeParameter }}]{Value: sql.Null[{{ .TypeParameter }}]{ Valid: false }, Op: sqlla.OpNot, Column: q.appendColumnPrefix("`{{ .Name }}`")} + q.where = append(q.where, where) + return q +} + +func (q {{ $smallTableName }}SelectSQL) {{ .MethodName }}In(vs ...{{ .TypeParameter }}) {{ $smallTableName }}SelectSQL { + _vs := make([]sql.Null[{{ .TypeParameter }}], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[{{ .TypeParameter }}]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[{{ .TypeParameter }}]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`{{ .Name }}`")} + q.where = append(q.where, where) + return q +} +{{- end }} diff --git a/template/update_column.tmpl b/template/update_column.tmpl index a1ae9de..7b39f6e 100644 --- a/template/update_column.tmpl +++ b/template/update_column.tmpl @@ -1,4 +1,7 @@ {{ define "UpdateColumn" }}{{ $smallTableName := .TableName | toCamel | Untitle }} +{{- if .IsNullT }} +{{- template "UpdateColumnNullT" . }} +{{- else }} func (q {{ $smallTableName }}UpdateSQL) Set{{ .MethodName }}(v {{ .TypeName }}) {{ $smallTableName }}UpdateSQL { q.setMap["`{{ .Name }}`"] = v return q @@ -29,4 +32,5 @@ func (q {{ $smallTableName }}UpdateSQL) Where{{ .MethodName }}In(vs ...{{ .TypeN q.where = append(q.where, where) return q } +{{- end }} {{ end }} diff --git a/template/update_column_nullt.tmpl b/template/update_column_nullt.tmpl new file mode 100644 index 0000000..138007a --- /dev/null +++ b/template/update_column_nullt.tmpl @@ -0,0 +1,45 @@ +{{ define "UpdateColumnNullT" }}{{ $smallTableName := .TableName | toCamel | Untitle }} +func (q {{ $smallTableName }}UpdateSQL) Set{{ .MethodName }}(v {{ .TypeParameter }}) {{ $smallTableName }}UpdateSQL { + q.setMap["`{{ .Name }}`"] = sql.Null[{{ .TypeParameter }}]{ V: v, Valid: true } + return q +} + +func (q {{ $smallTableName }}UpdateSQL) Set{{ .MethodName }}ToNull() {{ $smallTableName }}UpdateSQL { + q.setMap["`{{ .Name }}`"] = sql.Null[{{ .TypeParameter }}]{ Valid: false } + return q +} + +func (q {{ $smallTableName }}UpdateSQL) Where{{ .MethodName }}(v {{ .TypeParameter }}, exprs ...sqlla.Operator) {{ $smallTableName }}UpdateSQL { + var op sqlla.Operator + if len(exprs) == 0 { + op = sqlla.OpEqual + } else { + op = exprs[0] + } + where := sqlla.ExprNull[{{ .TypeParameter }}]{Value: sql.Null[{{ .TypeParameter }}]{ V: v, Valid: true }, Op: op, Column: "`{{ .Name }}`"} + q.where = append(q.where, where) + return q +} + +func (q {{ $smallTableName }}UpdateSQL) Where{{ .MethodName }}IsNull() {{ $smallTableName }}UpdateSQL { + where := sqlla.ExprNull[{{ .TypeParameter }}]{Value: sql.Null[{{ .TypeParameter }}]{ Valid: false }, Op: sqlla.OpEqual, Column: "`{{ .Name }}`"} + q.where = append(q.where, where) + return q +} + +func (q {{ $smallTableName }}UpdateSQL) Where{{ .MethodName }}IsNotNull() {{ $smallTableName }}UpdateSQL { + where := sqlla.ExprNull[{{ .TypeParameter }}]{Value: sql.Null[{{ .TypeParameter }}]{ Valid: false }, Op: sqlla.OpNot, Column: "`{{ .Name }}`"} + q.where = append(q.where, where) + return q +} + +func (q {{ $smallTableName }}UpdateSQL) Where{{ .MethodName }}In(vs ...{{ .TypeParameter }}) {{ $smallTableName }}UpdateSQL { + _vs := make([]sql.Null[{{ .TypeParameter }}], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[{{ .TypeParameter }}]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[{{ .TypeParameter }}]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`{{ .Name }}`"} + q.where = append(q.where, where) + return q +} +{{ end }} From d9a8d0f615e154ed2bcac98af23be7fa281f76ed Mon Sep 17 00:00:00 2001 From: mackee Date: Tue, 9 Jul 2024 19:40:09 +0900 Subject: [PATCH 07/11] feat: write testing for sql.Null[T] --- _example/go.mod | 12 +-- _example/go.sum | 34 +++--- _example/group.gen.go | 93 +++++++++++++---- _example/group.go | 5 +- _example/group_priv_test.go | 3 + _example/group_test.go | 199 ++++++++++++++++++++++++++++++++++++ _example/mysql.sql | 24 +++++ _example/sqlite3.sql | 60 +++++++++++ _example/user_priv_test.go | 3 + _example/user_test.go | 117 +++++++++++---------- 10 files changed, 446 insertions(+), 104 deletions(-) create mode 100644 _example/group_priv_test.go create mode 100644 _example/group_test.go create mode 100644 _example/user_priv_test.go diff --git a/_example/go.mod b/_example/go.mod index b5415de..4172ac8 100644 --- a/_example/go.mod +++ b/_example/go.mod @@ -8,7 +8,7 @@ replace github.com/mackee/go-sqlla/v2 => ../ require ( github.com/go-sql-driver/mysql v1.6.0 - github.com/mackee/go-genddl v0.0.0-20220809061459-645eadea7290 + github.com/mackee/go-genddl v0.0.0-20240709095411-bc59661f6bd5 github.com/mackee/go-sqlla/v2 v2.11.0 github.com/mattn/go-sqlite3 v1.14.9 github.com/ory/dockertest/v3 v3.9.1 @@ -40,10 +40,10 @@ require ( github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - golang.org/x/mod v0.16.0 // indirect - golang.org/x/net v0.17.0 // indirect - golang.org/x/sys v0.13.0 // indirect - golang.org/x/tools v0.13.0 // indirect - golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f // indirect + golang.org/x/mod v0.19.0 // indirect + golang.org/x/net v0.27.0 // indirect + golang.org/x/sync v0.7.0 // indirect + golang.org/x/sys v0.22.0 // indirect + golang.org/x/tools v0.23.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/_example/go.sum b/_example/go.sum index eee0809..faa7772 100644 --- a/_example/go.sum +++ b/_example/go.sum @@ -31,8 +31,8 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= @@ -41,8 +41,8 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/lib/pq v0.0.0-20180327071824-d34b9ff171c2 h1:hRGSmZu7j271trc9sneMrpOW7GN5ngLm8YUZIPzf394= github.com/lib/pq v0.0.0-20180327071824-d34b9ff171c2/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/mackee/go-genddl v0.0.0-20220809061459-645eadea7290 h1:/Es4hR6SMmW6Cak1aKoD/zhZvpArKKa4oMuZZ6NmMmQ= -github.com/mackee/go-genddl v0.0.0-20220809061459-645eadea7290/go.mod h1:fxvUHq3EojHfIqYh1n6QKq+ePU8+xx63MHQsd1IHebo= +github.com/mackee/go-genddl v0.0.0-20240709095411-bc59661f6bd5 h1:34zL9amaNC1Ks8pRGsggto7t5rb6gJ+G8ttbTVZ4XSM= +github.com/mackee/go-genddl v0.0.0-20240709095411-bc59661f6bd5/go.mod h1:d4RIUwTtlb0aVfO1GZMeRoIrPyE6jPlbnMkx010K/ug= github.com/mattn/go-sqlite3 v1.14.9 h1:10HX2Td0ocZpYEjhilsuo6WWtUqttj2Kb0KtD86/KYA= github.com/mattn/go-sqlite3 v1.14.9/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag= @@ -92,20 +92,20 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= -golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8= +golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= -golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys= +golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= -golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -113,25 +113,23 @@ golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200831180312-196b9ba8737a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= -golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= +golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= -golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= -golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= +golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg= +golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f h1:uF6paiQQebLeSXkrTqHqz0MXhXXS1KgF41eUdBNvxK0= -golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= diff --git a/_example/group.gen.go b/_example/group.gen.go index 1371728..7aa6a44 100644 --- a/_example/group.gen.go +++ b/_example/group.gen.go @@ -8,7 +8,6 @@ import ( "strings" "database/sql" - "github.com/go-sql-driver/mysql" "github.com/mackee/go-sqlla/_example/id" "time" @@ -351,20 +350,36 @@ func (q groupSelectSQL) OrderByCreatedAt(order sqlla.Order) groupSelectSQL { return q } -func (q groupSelectSQL) UpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) groupSelectSQL { +func (q groupSelectSQL) UpdatedAt(v time.Time, exprs ...sqlla.Operator) groupSelectSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: q.appendColumnPrefix("`updated_at`")} + where := sqlla.ExprNull[time.Time]{Value: sql.Null[time.Time]{V: v, Valid: true}, Op: op, Column: q.appendColumnPrefix("`updated_at`")} q.where = append(q.where, where) return q } -func (q groupSelectSQL) UpdatedAtIn(vs ...mysql.NullTime) groupSelectSQL { - where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`updated_at`")} +func (q groupSelectSQL) UpdatedAtIsNull() groupSelectSQL { + where := sqlla.ExprNull[time.Time]{Value: sql.Null[time.Time]{Valid: false}, Op: sqlla.OpEqual, Column: q.appendColumnPrefix("`updated_at`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) UpdatedAtIsNotNull() groupSelectSQL { + where := sqlla.ExprNull[time.Time]{Value: sql.Null[time.Time]{Valid: false}, Op: sqlla.OpNot, Column: q.appendColumnPrefix("`updated_at`")} + q.where = append(q.where, where) + return q +} + +func (q groupSelectSQL) UpdatedAtIn(vs ...time.Time) groupSelectSQL { + _vs := make([]sql.Null[time.Time], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[time.Time]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[time.Time]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: q.appendColumnPrefix("`updated_at`")} q.where = append(q.where, where) return q } @@ -719,25 +734,46 @@ func (q groupUpdateSQL) WhereCreatedAtIn(vs ...time.Time) groupUpdateSQL { return q } -func (q groupUpdateSQL) SetUpdatedAt(v mysql.NullTime) groupUpdateSQL { - q.setMap["`updated_at`"] = v +func (q groupUpdateSQL) SetUpdatedAt(v time.Time) groupUpdateSQL { + q.setMap["`updated_at`"] = sql.Null[time.Time]{V: v, Valid: true} return q } -func (q groupUpdateSQL) WhereUpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) groupUpdateSQL { +func (q groupUpdateSQL) SetUpdatedAtToNull() groupUpdateSQL { + q.setMap["`updated_at`"] = sql.Null[time.Time]{Valid: false} + return q +} + +func (q groupUpdateSQL) WhereUpdatedAt(v time.Time, exprs ...sqlla.Operator) groupUpdateSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: "`updated_at`"} + where := sqlla.ExprNull[time.Time]{Value: sql.Null[time.Time]{V: v, Valid: true}, Op: op, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereUpdatedAtIsNull() groupUpdateSQL { + where := sqlla.ExprNull[time.Time]{Value: sql.Null[time.Time]{Valid: false}, Op: sqlla.OpEqual, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupUpdateSQL) WhereUpdatedAtIsNotNull() groupUpdateSQL { + where := sqlla.ExprNull[time.Time]{Value: sql.Null[time.Time]{Valid: false}, Op: sqlla.OpNot, Column: "`updated_at`"} q.where = append(q.where, where) return q } -func (q groupUpdateSQL) WhereUpdatedAtIn(vs ...mysql.NullTime) groupUpdateSQL { - where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} +func (q groupUpdateSQL) WhereUpdatedAtIn(vs ...time.Time) groupUpdateSQL { + _vs := make([]sql.Null[time.Time], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[time.Time]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[time.Time]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} q.where = append(q.where, where) return q } @@ -856,8 +892,13 @@ func (q groupInsertSQL) ValueCreatedAt(v time.Time) groupInsertSQL { return q } -func (q groupInsertSQL) ValueUpdatedAt(v mysql.NullTime) groupInsertSQL { - q.setMap["`updated_at`"] = v +func (q groupInsertSQL) ValueUpdatedAt(v time.Time) groupInsertSQL { + q.setMap["`updated_at`"] = sql.Null[time.Time]{V: v, Valid: true} + return q +} + +func (q groupInsertSQL) ValueUpdatedAtIsNull() groupInsertSQL { + q.setMap["`updated_at`"] = sql.Null[time.Time]{Valid: false} return q } @@ -1039,7 +1080,7 @@ func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateCreatedAt() groupInsertO return q } -func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v mysql.NullTime) groupInsertOnDuplicateKeyUpdateSQL { +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v sql.Null[time.Time]) groupInsertOnDuplicateKeyUpdateSQL { q.onDuplicateKeyUpdateMap["`updated_at`"] = v return q } @@ -1336,20 +1377,36 @@ func (q groupDeleteSQL) CreatedAtIn(vs ...time.Time) groupDeleteSQL { return q } -func (q groupDeleteSQL) UpdatedAt(v mysql.NullTime, exprs ...sqlla.Operator) groupDeleteSQL { +func (q groupDeleteSQL) UpdatedAt(v time.Time, exprs ...sqlla.Operator) groupDeleteSQL { var op sqlla.Operator if len(exprs) == 0 { op = sqlla.OpEqual } else { op = exprs[0] } - where := sqlla.ExprMysqlNullTime{Value: v, Op: op, Column: "`updated_at`"} + where := sqlla.ExprNull[time.Time]{Value: sql.Null[time.Time]{V: v, Valid: true}, Op: op, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) UpdatedAtIsNull() groupDeleteSQL { + where := sqlla.ExprNull[time.Time]{Value: sql.Null[time.Time]{Valid: false}, Op: sqlla.OpEqual, Column: "`updated_at`"} q.where = append(q.where, where) return q } -func (q groupDeleteSQL) UpdatedAtIn(vs ...mysql.NullTime) groupDeleteSQL { - where := sqlla.ExprMultiMysqlNullTime{Values: vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} +func (q groupDeleteSQL) UpdatedAtIsNotNull() groupDeleteSQL { + where := sqlla.ExprNull[time.Time]{Value: sql.Null[time.Time]{Valid: false}, Op: sqlla.OpNot, Column: "`updated_at`"} + q.where = append(q.where, where) + return q +} + +func (q groupDeleteSQL) UpdatedAtIn(vs ...time.Time) groupDeleteSQL { + _vs := make([]sql.Null[time.Time], 0, len(vs)) + for _, v := range vs { + _vs = append(_vs, sql.Null[time.Time]{V: v, Valid: true}) + } + where := sqlla.ExprMultiValue[sql.Null[time.Time]]{Values: _vs, Op: sqlla.MakeInOperator(len(vs)), Column: "`updated_at`"} q.where = append(q.where, where) return q } diff --git a/_example/group.go b/_example/group.go index c5c0b3d..c630d60 100644 --- a/_example/group.go +++ b/_example/group.go @@ -4,7 +4,6 @@ import ( "database/sql" "time" - "github.com/go-sql-driver/mysql" "github.com/mackee/go-sqlla/_example/id" ) @@ -21,6 +20,6 @@ type Group struct { SubLeaderUserID sql.Null[UserId] `db:"sub_leader_user_id"` ChildGroupID sql.Null[id.GroupID] `db:"child_group_id"` - CreatedAt time.Time `db:"created_at"` - UpdatedAt mysql.NullTime `db:"updated_at"` + CreatedAt time.Time `db:"created_at"` + UpdatedAt sql.Null[time.Time] `db:"updated_at"` } diff --git a/_example/group_priv_test.go b/_example/group_priv_test.go new file mode 100644 index 0000000..5b72e52 --- /dev/null +++ b/_example/group_priv_test.go @@ -0,0 +1,3 @@ +package example + +var GroupAllColumns = groupAllColumns diff --git a/_example/group_test.go b/_example/group_test.go new file mode 100644 index 0000000..c251fc4 --- /dev/null +++ b/_example/group_test.go @@ -0,0 +1,199 @@ +package example_test + +import ( + "database/sql" + "reflect" + "strings" + "testing" + + example "github.com/mackee/go-sqlla/_example" + "github.com/mackee/go-sqlla/_example/id" + "github.com/mackee/go-sqlla/v2" +) + +var groupAllColumns = strings.Join(example.GroupAllColumns, ", ") + +type queryTestCase struct { + name string + query interface { + ToSql() (string, []interface{}, error) + } + expect string + args []interface{} +} + +func (q queryTestCase) assert(t *testing.T) { + t.Helper() + t.Run(q.name, func(t *testing.T) { + query, args, err := q.query.ToSql() + if err != nil { + t.Error("unexpected error:", err) + } + if query != q.expect { + t.Errorf("unexpected query: got=%s, expect=%s", query, q.expect) + } + if !reflect.DeepEqual(args, q.args) { + t.Errorf("unexpected args: got=%#v, expect=%#v:", args, q.args) + } + }) +} + +type queryTestCases []queryTestCase + +func (q queryTestCases) assert(t *testing.T) { + t.Helper() + for _, tc := range q { + tc.assert(t) + } +} + +func TestSelectNullable(t *testing.T) { + testCases := queryTestCases{ + { + name: "IS NULL", + query: example.NewGroupSQL().Select().SubLeaderUserIDIsNull(), + expect: "SELECT " + groupAllColumns + " FROM `group` WHERE `sub_leader_user_id` IS NULL;", + args: []interface{}{}, + }, + { + name: "IS NOT NULL", + query: example.NewGroupSQL().Select().ChildGroupIDIsNotNull(), + expect: "SELECT " + groupAllColumns + " FROM `group` WHERE `child_group_id` IS NOT NULL;", + args: []interface{}{}, + }, + { + name: "query by type parameter", + query: example.NewGroupSQL().Select().SubLeaderUserID(42), + expect: "SELECT " + groupAllColumns + " FROM `group` WHERE `sub_leader_user_id` = ?;", + args: []interface{}{sql.Null[example.UserId]{V: 42, Valid: true}}, + }, + { + name: "query by type parameter with operator", + query: example.NewGroupSQL().Select().SubLeaderUserID(42, sqlla.OpLess), + expect: "SELECT " + groupAllColumns + " FROM `group` WHERE `sub_leader_user_id` < ?;", + args: []interface{}{sql.Null[example.UserId]{V: 42, Valid: true}}, + }, + { + name: "query by type parameters multiple", + query: example.NewGroupSQL().Select().SubLeaderUserIDIn(42, 43, 44), + expect: "SELECT " + groupAllColumns + " FROM `group` WHERE `sub_leader_user_id` IN (?,?,?);", + args: []interface{}{ + sql.Null[example.UserId]{V: 42, Valid: true}, + sql.Null[example.UserId]{V: 43, Valid: true}, + sql.Null[example.UserId]{V: 44, Valid: true}, + }, + }, + } + testCases.assert(t) +} + +func TestUpdateNullable(t *testing.T) { + testCases := queryTestCases{ + { + name: "SET NOT NULL WHERE IS NULL", + query: example.NewGroupSQL().Update().SetSubLeaderUserID(42).WhereSubLeaderUserIDIsNull(), + expect: "UPDATE `group` SET `sub_leader_user_id` = ? WHERE `sub_leader_user_id` IS NULL;", + args: []interface{}{sql.Null[example.UserId]{V: example.UserId(42), Valid: true}}, + }, + { + name: "SET NULL WHERE IS NULL", + query: example.NewGroupSQL().Update().SetSubLeaderUserIDToNull().WhereSubLeaderUserIDIsNull(), + expect: "UPDATE `group` SET `sub_leader_user_id` = ? WHERE `sub_leader_user_id` IS NULL;", + args: []interface{}{sql.Null[example.UserId]{Valid: false}}, + }, + { + name: "SET NULL WHERE IS NOT NULL", + query: example.NewGroupSQL().Update().SetChildGroupIDToNull().WhereSubLeaderUserIDIsNotNull(), + expect: "UPDATE `group` SET `child_group_id` = ? WHERE `sub_leader_user_id` IS NOT NULL;", + args: []interface{}{sql.Null[id.GroupID]{Valid: false}}, + }, + { + name: "SET NOT NULL WHERE equal type parameters", + query: example.NewGroupSQL().Update().SetChildGroupID(42).WhereChildGroupID(100), + expect: "UPDATE `group` SET `child_group_id` = ? WHERE `child_group_id` = ?;", + args: []interface{}{ + sql.Null[id.GroupID]{V: 42, Valid: true}, + sql.Null[id.GroupID]{V: 100, Valid: true}, + }, + }, + { + name: "SET NOT NULL WHERE type parameters and operator", + query: example.NewGroupSQL().Update().SetChildGroupID(42).WhereChildGroupID(100, sqlla.OpGreater), + expect: "UPDATE `group` SET `child_group_id` = ? WHERE `child_group_id` > ?;", + args: []interface{}{ + sql.Null[id.GroupID]{V: 42, Valid: true}, + sql.Null[id.GroupID]{V: 100, Valid: true}, + }, + }, + { + name: "SET NOT NULL WHERE IN type parameters", + query: example.NewGroupSQL().Update().SetChildGroupID(42).WhereChildGroupIDIn(100, 101, 102), + expect: "UPDATE `group` SET `child_group_id` = ? WHERE `child_group_id` IN(?,?,?);", + args: []interface{}{ + sql.Null[id.GroupID]{V: 42, Valid: true}, + sql.Null[id.GroupID]{V: 100, Valid: true}, + sql.Null[id.GroupID]{V: 101, Valid: true}, + sql.Null[id.GroupID]{V: 102, Valid: true}, + }, + }, + } + testCases.assert(t) +} + +func TestInsertNullable(t *testing.T) { + testCases := queryTestCases{ + { + name: "INSERT NULL column", + query: example.NewGroupSQL().Insert().ValueSubLeaderUserIDIsNull(), + expect: "INSERT INTO `group` (`sub_leader_user_id`) VALUES(?);", + args: []interface{}{sql.Null[example.UserId]{Valid: false}}, + }, + { + name: "INSERT with type parameter", + query: example.NewGroupSQL().Insert().ValueSubLeaderUserID(42), + expect: "INSERT INTO `group` (`sub_leader_user_id`) VALUES(?);", + args: []interface{}{sql.Null[example.UserId]{V: 42, Valid: true}}, + }, + } + testCases.assert(t) +} + +func TestDeleteNullable(t *testing.T) { + testCases := queryTestCases{ + { + name: "IS NULL", + query: example.NewGroupSQL().Delete().SubLeaderUserIDIsNull(), + expect: "DELETE FROM `group` WHERE `sub_leader_user_id` IS NULL;", + args: []interface{}{}, + }, + { + name: "IS NOT NULL", + query: example.NewGroupSQL().Delete().ChildGroupIDIsNotNull(), + expect: "DELETE FROM `group` WHERE `child_group_id` IS NOT NULL;", + args: []interface{}{}, + }, + { + name: "query by type parameter", + query: example.NewGroupSQL().Delete().SubLeaderUserID(42), + expect: "DELETE FROM `group` WHERE `sub_leader_user_id` = ?;", + args: []interface{}{sql.Null[example.UserId]{V: 42, Valid: true}}, + }, + { + name: "query by type parameter with operator", + query: example.NewGroupSQL().Delete().SubLeaderUserID(42, sqlla.OpLess), + expect: "DELETE FROM `group` WHERE `sub_leader_user_id` < ?;", + args: []interface{}{sql.Null[example.UserId]{V: 42, Valid: true}}, + }, + { + name: "query by type parameters multiple", + query: example.NewGroupSQL().Delete().SubLeaderUserIDIn(42, 43, 44), + expect: "DELETE FROM `group` WHERE `sub_leader_user_id` IN(?,?,?);", + args: []interface{}{ + sql.Null[example.UserId]{V: 42, Valid: true}, + sql.Null[example.UserId]{V: 43, Valid: true}, + sql.Null[example.UserId]{V: 44, Valid: true}, + }, + }, + } + testCases.assert(t) +} diff --git a/_example/mysql.sql b/_example/mysql.sql index 9d4e594..8352956 100644 --- a/_example/mysql.sql +++ b/_example/mysql.sql @@ -1,5 +1,18 @@ -- generated by github.com/mackee/go-genddl. DO NOT EDIT!!! +DROP TABLE IF EXISTS `group`; + +CREATE TABLE `group` ( + `id` BIGINT unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, + `name` VARCHAR(191) NOT NULL, + `leader_user_id` BIGINT unsigned NOT NULL, + `sub_leader_user_id` BIGINT unsigned NULL, + `child_group_id` BIGINT unsigned NULL, + `created_at` DATETIME NOT NULL, + `updated_at` DATETIME NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + + DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( @@ -19,6 +32,7 @@ DROP TABLE IF EXISTS `user_external`; CREATE TABLE `user_external` ( `id` BIGINT unsigned NOT NULL PRIMARY KEY, `user_id` BIGINT unsigned NOT NULL, + `icon_image` BLOB NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; @@ -35,3 +49,13 @@ CREATE TABLE `user_item` ( `used_at` DATETIME NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +DROP TABLE IF EXISTS `user_sns`; + +CREATE TABLE `user_sns` ( + `id` BIGINT unsigned NOT NULL PRIMARY KEY, + `sns_type` VARCHAR(191) NOT NULL, + `created_at` DATETIME NOT NULL, + `updated_at` DATETIME NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + diff --git a/_example/sqlite3.sql b/_example/sqlite3.sql index 0a7fabf..8b31935 100644 --- a/_example/sqlite3.sql +++ b/_example/sqlite3.sql @@ -1 +1,61 @@ -- generated by github.com/mackee/go-genddl. DO NOT EDIT!!! + +DROP TABLE IF EXISTS "group"; + +CREATE TABLE "group" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "name" TEXT NOT NULL, + "leader_user_id" INTEGER NOT NULL, + "sub_leader_user_id" INTEGER NULL, + "child_group_id" INTEGER NULL, + "created_at" DATETIME NOT NULL, + "updated_at" DATETIME NULL +) ; + + +DROP TABLE IF EXISTS "user"; + +CREATE TABLE "user" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "name" TEXT NOT NULL, + "age" INTEGER NULL, + "rate" REAL NOT NULL DEFAULT 0, + "icon_image" BLOB NOT NULL, + "created_at" DATETIME NOT NULL, + "updated_at" DATETIME NULL, + UNIQUE ("name") +) ; + + +DROP TABLE IF EXISTS "user_external"; + +CREATE TABLE "user_external" ( + "id" INTEGER NOT NULL PRIMARY KEY, + "user_id" INTEGER NOT NULL, + "icon_image" BLOB NULL, + "created_at" DATETIME NOT NULL, + "updated_at" DATETIME NOT NULL +) ; + + +DROP TABLE IF EXISTS "user_item"; + +CREATE TABLE "user_item" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "user_id" INTEGER NOT NULL, + "item_id" TEXT NOT NULL, + "is_used" INTEGER NOT NULL, + "has_extension" INTEGER NULL, + "used_at" DATETIME NULL +) ; + + +DROP TABLE IF EXISTS "user_sns"; + +CREATE TABLE "user_sns" ( + "id" INTEGER NOT NULL PRIMARY KEY, + "sns_type" TEXT NOT NULL, + "created_at" DATETIME NOT NULL, + "updated_at" DATETIME NOT NULL +) ; + diff --git a/_example/user_priv_test.go b/_example/user_priv_test.go new file mode 100644 index 0000000..d56c2cc --- /dev/null +++ b/_example/user_priv_test.go @@ -0,0 +1,3 @@ +package example + +var UserAllColumns = userAllColumns diff --git a/_example/user_test.go b/_example/user_test.go index aa4eafb..33a248e 100644 --- a/_example/user_test.go +++ b/_example/user_test.go @@ -1,9 +1,9 @@ -package example +package example_test import ( "context" "database/sql" - "io/ioutil" + "io" "os" "reflect" "regexp" @@ -13,19 +13,20 @@ import ( "time" "github.com/go-sql-driver/mysql" + example "github.com/mackee/go-sqlla/_example" "github.com/mackee/go-sqlla/v2" _ "github.com/mattn/go-sqlite3" ) -var columns = "`id`, `name`, `age`, `rate`, `icon_image`, `created_at`, `updated_at`" +var userAllColumns = strings.Join(example.UserAllColumns, ", ") func TestSelect(t *testing.T) { - q := NewUserSQL().Select().Name("hoge") + q := example.NewUserSQL().Select().Name("hoge") query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) } - if query != "SELECT "+columns+" FROM `user` WHERE `name` = ?;" { + if query != "SELECT "+userAllColumns+" FROM `user` WHERE `name` = ?;" { t.Error("unexpected query:", query) } if !reflect.DeepEqual(args, []interface{}{"hoge"}) { @@ -34,12 +35,12 @@ func TestSelect(t *testing.T) { } func TestSelect__OrderByAndLimit(t *testing.T) { - q := NewUserSQL().Select().Name("hoge").OrderByID(sqlla.Asc).Limit(uint64(100)) + q := example.NewUserSQL().Select().Name("hoge").OrderByID(sqlla.Asc).Limit(uint64(100)) query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) } - if query != "SELECT "+columns+" FROM `user` WHERE `name` = ? ORDER BY `id` ASC LIMIT 100;" { + if query != "SELECT "+userAllColumns+" FROM `user` WHERE `name` = ? ORDER BY `id` ASC LIMIT 100;" { t.Error("unexpected query:", query) } if !reflect.DeepEqual(args, []interface{}{"hoge"}) { @@ -48,12 +49,12 @@ func TestSelect__OrderByAndLimit(t *testing.T) { } func TestSelect__InOperator(t *testing.T) { - q := NewUserSQL().Select().IDIn(1, 2, 3, 4, 5) + q := example.NewUserSQL().Select().IDIn(1, 2, 3, 4, 5) query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) } - if query != "SELECT "+columns+" FROM `user` WHERE `id` IN(?,?,?,?,?);" { + if query != "SELECT "+userAllColumns+" FROM `user` WHERE `id` IN(?,?,?,?,?);" { t.Error("unexpected query:", query) } if !reflect.DeepEqual(args, []interface{}{uint64(1), uint64(2), uint64(3), uint64(4), uint64(5)}) { @@ -62,12 +63,12 @@ func TestSelect__InOperator(t *testing.T) { } func TestSelect__NullInt64(t *testing.T) { - q := NewUserSQL().Select().Age(sql.NullInt64{}) + q := example.NewUserSQL().Select().Age(sql.NullInt64{}) query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) } - if query != "SELECT "+columns+" FROM `user` WHERE `age` IS NULL;" { + if query != "SELECT "+userAllColumns+" FROM `user` WHERE `age` IS NULL;" { t.Error("unexpected query:", query) } if !reflect.DeepEqual(args, []interface{}{}) { @@ -76,12 +77,12 @@ func TestSelect__NullInt64(t *testing.T) { } func TestSelect__NullInt64__IsNotNull(t *testing.T) { - q := NewUserSQL().Select().Age(sql.NullInt64{}, sqlla.OpNot) + q := example.NewUserSQL().Select().Age(sql.NullInt64{}, sqlla.OpNot) query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) } - if query != "SELECT "+columns+" FROM `user` WHERE `age` IS NOT NULL;" { + if query != "SELECT "+userAllColumns+" FROM `user` WHERE `age` IS NOT NULL;" { t.Error("unexpected query:", query) } if !reflect.DeepEqual(args, []interface{}{}) { @@ -90,12 +91,12 @@ func TestSelect__NullInt64__IsNotNull(t *testing.T) { } func TestSelect__ForUpdate(t *testing.T) { - q := NewUserSQL().Select().ID(UserId(1)).ForUpdate() + q := example.NewUserSQL().Select().ID(example.UserId(1)).ForUpdate() query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) } - if query != "SELECT "+columns+" FROM `user` WHERE `id` = ? FOR UPDATE;" { + if query != "SELECT "+userAllColumns+" FROM `user` WHERE `id` = ? FOR UPDATE;" { t.Error("unexpected query:", query) } if !reflect.DeepEqual(args, []interface{}{"1"}) { @@ -104,15 +105,15 @@ func TestSelect__ForUpdate(t *testing.T) { } func TestSelect__Or(t *testing.T) { - q := NewUserSQL().Select().Or( - NewUserSQL().Select().ID(UserId(1)), - NewUserSQL().Select().ID(UserId(2)), + q := example.NewUserSQL().Select().Or( + example.NewUserSQL().Select().ID(example.UserId(1)), + example.NewUserSQL().Select().ID(example.UserId(2)), ) query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) } - expectedQuery := "SELECT " + columns + " FROM `user` WHERE (( `id` = ? ) OR ( `id` = ? ));" + expectedQuery := "SELECT " + userAllColumns + " FROM `user` WHERE (( `id` = ? ) OR ( `id` = ? ));" if query != expectedQuery { t.Error("unexpected query:", query, expectedQuery) } @@ -124,11 +125,11 @@ func TestSelect__Or(t *testing.T) { func TestSelect__OrNull(t *testing.T) { now := time.Now() nt := sql.NullTime{Time: now, Valid: true} - q := NewUserItemSQL().Select(). + q := example.NewUserItemSQL().Select(). IDIn(uint64(1), uint64(2)). Or( - NewUserItemSQL().Select().UsedAt(sql.NullTime{}, sqlla.OpIs), - NewUserItemSQL().Select().UsedAt(nt, sqlla.OpLess), + example.NewUserItemSQL().Select().UsedAt(sql.NullTime{}, sqlla.OpIs), + example.NewUserItemSQL().Select().UsedAt(nt, sqlla.OpLess), ) query, args, err := q.ToSql() if err != nil { @@ -144,8 +145,8 @@ func TestSelect__OrNull(t *testing.T) { } func TestSelect__JoinClausesAndTableAlias(t *testing.T) { - query, args, err := NewUserSQL().Select(). - SetColumns(append(userAllColumns, "ui.item_id", "ui.is_used")...). + query, args, err := example.NewUserSQL().Select(). + SetColumns(append(example.UserAllColumns, "ui.item_id", "ui.is_used")...). TableAlias("u"). JoinClause("INNER JOIN user_item AS ui ON u.id = ui.user_id"). Name("hogehoge"). @@ -165,7 +166,7 @@ func TestSelect__JoinClausesAndTableAlias(t *testing.T) { } func TestSelect__SetColumn(t *testing.T) { - query, args, err := NewUserSQL().Select(). + query, args, err := example.NewUserSQL().Select(). SetColumns("rate", "COUNT(u.id)"). TableAlias("u"). OrderByRate(sqlla.Desc). @@ -184,7 +185,7 @@ func TestSelect__SetColumn(t *testing.T) { } func TestSelect__GroupByDottedColumn(t *testing.T) { - query, args, err := NewUserSQL().Select(). + query, args, err := example.NewUserSQL().Select(). SetColumns("rate", "COUNT(u.id)"). TableAlias("u"). OrderByRate(sqlla.Desc). @@ -203,13 +204,13 @@ func TestSelect__GroupByDottedColumn(t *testing.T) { } func TestSelect__LikeOperator(t *testing.T) { - query, args, err := NewUserSQL().Select(). + query, args, err := example.NewUserSQL().Select(). Name("%foobar%", sqlla.OpLike). ToSql() if err != nil { t.Error("unexpected error:", err) } - expectedQuery := "SELECT " + columns + " FROM `user` WHERE `name` LIKE ?;" + expectedQuery := "SELECT " + userAllColumns + " FROM `user` WHERE `name` LIKE ?;" if query != expectedQuery { t.Error("unexpected query:", query, expectedQuery) } @@ -219,7 +220,7 @@ func TestSelect__LikeOperator(t *testing.T) { } func TestUpdate(t *testing.T) { - q := NewUserSQL().Update().SetName("barbar").WhereID(UserId(1)) + q := example.NewUserSQL().Update().SetName("barbar").WhereID(example.UserId(1)) query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) @@ -245,7 +246,7 @@ func TestUpdate(t *testing.T) { } func TestUpdate__InOperator(t *testing.T) { - q := NewUserSQL().Update().SetRate(42).WhereIDIn(UserId(1), UserId(2), UserId(3)) + q := example.NewUserSQL().Update().SetRate(42).WhereIDIn(example.UserId(1), example.UserId(2), example.UserId(3)) query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) @@ -272,11 +273,10 @@ func TestUpdate__InOperator(t *testing.T) { default: t.Error("unexpected query:", query) } - } func TestInsert(t *testing.T) { - q := NewUserSQL().Insert().ValueName("hogehoge") + q := example.NewUserSQL().Insert().ValueName("hogehoge") query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) @@ -292,7 +292,7 @@ func TestInsert(t *testing.T) { func TestInsertOnDuplicateKeyUpdate(t *testing.T) { now := time.Now() - q := NewUserSQL().Insert(). + q := example.NewUserSQL().Insert(). ValueID(1). ValueName("hogehoge"). ValueUpdatedAt(mysql.NullTime{ @@ -321,9 +321,9 @@ func TestInsertOnDuplicateKeyUpdate(t *testing.T) { } func TestBulkInsert(t *testing.T) { - items := NewUserItemSQL().BulkInsert() + items := example.NewUserItemSQL().BulkInsert() for i := 1; i <= 10; i++ { - q := NewUserItemSQL().Insert(). + q := example.NewUserItemSQL().Insert(). ValueUserID(42). ValueItemID(strconv.Itoa(i)) items.Append(q) @@ -342,10 +342,10 @@ func TestBulkInsert(t *testing.T) { } func TestBulkInsertWithOnDuplicateKeyUpdate(t *testing.T) { - items := NewUserItemSQL().BulkInsert() + items := example.NewUserItemSQL().BulkInsert() items.Append( - NewUserItemSQL().Insert().ValueUserID(42).ValueItemID("1").ValueIsUsed(true), - NewUserItemSQL().Insert().ValueUserID(42).ValueItemID("2").ValueIsUsed(true), + example.NewUserItemSQL().Insert().ValueUserID(42).ValueItemID("1").ValueIsUsed(true), + example.NewUserItemSQL().Insert().ValueUserID(42).ValueItemID("2").ValueIsUsed(true), ) now := sql.NullTime{ @@ -369,11 +369,10 @@ func TestBulkInsertWithOnDuplicateKeyUpdate(t *testing.T) { if !reflect.DeepEqual(vs, []interface{}{true, "1", uint64(42), true, "2", uint64(42), now}) { t.Errorf("vs is not valid: %+v", vs) } - } func TestDelete(t *testing.T) { - q := NewUserSQL().Delete().Name("hogehoge") + q := example.NewUserSQL().Delete().Name("hogehoge") query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) @@ -387,7 +386,7 @@ func TestDelete(t *testing.T) { } func TestDelete__In(t *testing.T) { - q := NewUserSQL().Delete().NameIn("hogehoge", "fugafuga") + q := example.NewUserSQL().Delete().NameIn("hogehoge", "fugafuga") query, args, err := q.ToSql() if err != nil { t.Error("unexpected error:", err) @@ -401,7 +400,7 @@ func TestDelete__In(t *testing.T) { } func setupDB(t *testing.T) *sql.DB { - dbFile, err := ioutil.TempFile("", "sqlla_test") + dbFile, err := os.CreateTemp("", "sqlla_test") if err != nil { t.Fatal("cannot create tempfile error:", err) } @@ -415,7 +414,7 @@ func setupDB(t *testing.T) *sql.DB { t.Fatal("cannot open schema file error:", err) } - b, err := ioutil.ReadAll(schemaFile) + b, err := io.ReadAll(schemaFile) if err != nil { t.Fatal("cannot read schema file error:", err) } @@ -433,7 +432,7 @@ func setupDB(t *testing.T) *sql.DB { func TestCRUD__WithSqlite3(t *testing.T) { db := setupDB(t) - query, args, err := NewUserSQL().Insert().ValueName("hogehoge").ValueIconImage([]byte{}).ToSql() + query, args, err := example.NewUserSQL().Insert().ValueName("hogehoge").ValueIconImage([]byte{}).ToSql() if err != nil { t.Error("unexpected error:", err) } @@ -442,7 +441,7 @@ func TestCRUD__WithSqlite3(t *testing.T) { t.Error("cannot insert row error:", err) } - query, args, err = NewUserSQL().Select().Name("hogehoge").ToSql() + query, args, err = example.NewUserSQL().Select().Name("hogehoge").ToSql() if err != nil { t.Error("unexpected error:", err) } @@ -465,7 +464,7 @@ func TestCRUD__WithSqlite3(t *testing.T) { t.Error("empty id:", id) } - query, args, err = NewUserSQL().Select().IDIn(UserId(1)).ToSql() + query, args, err = example.NewUserSQL().Select().IDIn(example.UserId(1)).ToSql() if err != nil { t.Error("unexpected error:", err) } @@ -488,7 +487,7 @@ func TestCRUD__WithSqlite3(t *testing.T) { t.Error("unmatched id:", rescanID) } - query, args, err = NewUserSQL().Update().WhereID(UserId(id)).SetName("barbar").ToSql() + query, args, err = example.NewUserSQL().Update().WhereID(example.UserId(id)).SetName("barbar").ToSql() if err != nil { t.Error("unexpected error:", err) } @@ -500,7 +499,7 @@ func TestCRUD__WithSqlite3(t *testing.T) { t.Error("unexpected row affected:", rows) } - query, args, err = NewUserSQL().Delete().Name("barbar").ToSql() + query, args, err = example.NewUserSQL().Delete().Name("barbar").ToSql() if err != nil { t.Error("unexpected error:", err) } @@ -516,34 +515,34 @@ func TestCRUD__WithSqlite3(t *testing.T) { func TestORM__WithSqlite3(t *testing.T) { db := setupDB(t) - insertedRow, err := NewUserSQL().Insert().ValueName("hogehoge").ValueIconImage([]byte{}).Exec(db) + insertedRow, err := example.NewUserSQL().Insert().ValueName("hogehoge").ValueIconImage([]byte{}).Exec(db) if err != nil { t.Error("cannot insert row error:", err) } - if insertedRow.Id == UserId(0) { + if insertedRow.Id == example.UserId(0) { t.Error("empty id:", insertedRow.Id) } if insertedRow.Name != "hogehoge" { t.Error("unexpected name:", insertedRow.Name) } - singleRow, err := NewUserSQL().Select().ID(insertedRow.Id).Single(db) + singleRow, err := example.NewUserSQL().Select().ID(insertedRow.Id).Single(db) if err != nil { t.Error("cannot select row error:", err) } - if singleRow.Id == UserId(0) { + if singleRow.Id == example.UserId(0) { t.Error("empty id:", singleRow.Id) } if singleRow.Name != "hogehoge" { t.Error("unexpected name:", singleRow.Name) } - _, err = NewUserSQL().Insert().ValueName("fugafuga").ValueIconImage([]byte{}).Exec(db) + _, err = example.NewUserSQL().Insert().ValueName("fugafuga").ValueIconImage([]byte{}).Exec(db) if err != nil { t.Error("cannot insert row error:", err) } - rows, err := NewUserSQL().Select().All(db) + rows, err := example.NewUserSQL().Select().All(db) if err != nil { t.Error("cannot select row error:", err) } @@ -552,7 +551,7 @@ func TestORM__WithSqlite3(t *testing.T) { } for _, row := range rows { - if row.Id == UserId(0) { + if row.Id == example.UserId(0) { t.Error("empty id:", row.Id) } if row.Name != "hogehoge" && row.Name != "fugafuga" { @@ -594,7 +593,7 @@ func TestORM__WithSqlite3__Binary(t *testing.T) { db := setupDB(t) binary := []byte("binary") - insertedRow, err := NewUserSQL().Insert(). + insertedRow, err := example.NewUserSQL().Insert(). ValueName("hogehoge"). ValueIconImage(binary). Exec(db) @@ -605,7 +604,7 @@ func TestORM__WithSqlite3__Binary(t *testing.T) { t.Error("unexpected IconImage:", insertedRow.IconImage) } - singleRow, err := NewUserSQL().Select().ID(insertedRow.Id).Single(db) + singleRow, err := example.NewUserSQL().Select().ID(insertedRow.Id).Single(db) if err != nil { t.Error("cannot select row error:", err) } @@ -632,7 +631,7 @@ func TestORM__WithSqlite3__NullBinary(t *testing.T) { now := time.Now() db := setupDB(t) - _, err := NewUserExternalSQL().Insert(). + _, err := example.NewUserExternalSQL().Insert(). ValueID(42). ValueUserID(4242). ValueIconImage(nil). @@ -643,7 +642,7 @@ func TestORM__WithSqlite3__NullBinary(t *testing.T) { t.Error("cannot insert row error:", err) } - singleRow, err := NewUserExternalSQL().Select().ID(42).SingleContext(ctx, db) + singleRow, err := example.NewUserExternalSQL().Select().ID(42).SingleContext(ctx, db) if err != nil { t.Error("cannot select row error:", err) } From 413a9167bc8ab2ab070d01b545104440e5bec445 Mon Sep 17 00:00:00 2001 From: mackee Date: Wed, 10 Jul 2024 12:05:07 +0900 Subject: [PATCH 08/11] feat: supports sql.Null[T] on ON DUPLICATE KEY UPDATE SET --- _example/group.gen.go | 27 ++++++++++++++----- _example/group_test.go | 22 +++++++++++++++ ...insert_on_duplicate_key_update_column.tmpl | 12 ++++++++- 3 files changed, 54 insertions(+), 7 deletions(-) diff --git a/_example/group.gen.go b/_example/group.gen.go index 7aa6a44..49316ec 100644 --- a/_example/group.gen.go +++ b/_example/group.gen.go @@ -1035,8 +1035,13 @@ func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateLeaderUserID() groupInse return q } -func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateSubLeaderUserID(v sql.Null[UserId]) groupInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`sub_leader_user_id`"] = v +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateSubLeaderUserID(v UserId) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`sub_leader_user_id`"] = sql.Null[UserId]{V: v, Valid: true} + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateSubLeaderUserIDToNull() groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`sub_leader_user_id`"] = sql.Null[UserId]{Valid: false} return q } @@ -1050,8 +1055,13 @@ func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateSubLeaderUserID() groupI return q } -func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateChildGroupID(v sql.Null[id.GroupID]) groupInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`child_group_id`"] = v +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateChildGroupID(v id.GroupID) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`child_group_id`"] = sql.Null[id.GroupID]{V: v, Valid: true} + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateChildGroupIDToNull() groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`child_group_id`"] = sql.Null[id.GroupID]{Valid: false} return q } @@ -1080,8 +1090,13 @@ func (q groupInsertOnDuplicateKeyUpdateSQL) SameOnUpdateCreatedAt() groupInsertO return q } -func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v sql.Null[time.Time]) groupInsertOnDuplicateKeyUpdateSQL { - q.onDuplicateKeyUpdateMap["`updated_at`"] = v +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAt(v time.Time) groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = sql.Null[time.Time]{V: v, Valid: true} + return q +} + +func (q groupInsertOnDuplicateKeyUpdateSQL) ValueOnUpdateUpdatedAtToNull() groupInsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`updated_at`"] = sql.Null[time.Time]{Valid: false} return q } diff --git a/_example/group_test.go b/_example/group_test.go index c251fc4..ab1015c 100644 --- a/_example/group_test.go +++ b/_example/group_test.go @@ -154,6 +154,28 @@ func TestInsertNullable(t *testing.T) { expect: "INSERT INTO `group` (`sub_leader_user_id`) VALUES(?);", args: []interface{}{sql.Null[example.UserId]{V: 42, Valid: true}}, }, + { + name: "INSERT ON DUPLICATE KEY UPDATE SET with type parameter", + query: example.NewGroupSQL().Insert().ValueSubLeaderUserID(42). + OnDuplicateKeyUpdate(). + ValueOnUpdateSubLeaderUserID(43), + expect: "INSERT INTO `group` (`sub_leader_user_id`) VALUES(?) ON DUPLICATE KEY UPDATE `sub_leader_user_id` = ?;", + args: []interface{}{ + sql.Null[example.UserId]{V: 42, Valid: true}, + sql.Null[example.UserId]{V: 43, Valid: true}, + }, + }, + { + name: "INSERT ON DUPLICATE KEY UPDATE SET TO NULL", + query: example.NewGroupSQL().Insert().ValueSubLeaderUserID(42). + OnDuplicateKeyUpdate(). + ValueOnUpdateSubLeaderUserIDToNull(), + expect: "INSERT INTO `group` (`sub_leader_user_id`) VALUES(?) ON DUPLICATE KEY UPDATE `sub_leader_user_id` = ?;", + args: []interface{}{ + sql.Null[example.UserId]{V: 42, Valid: true}, + sql.Null[example.UserId]{Valid: false}, + }, + }, } testCases.assert(t) } diff --git a/template/insert_on_duplicate_key_update_column.tmpl b/template/insert_on_duplicate_key_update_column.tmpl index 35e0c3a..2ab08ee 100644 --- a/template/insert_on_duplicate_key_update_column.tmpl +++ b/template/insert_on_duplicate_key_update_column.tmpl @@ -1,9 +1,20 @@ {{ define "InsertOnDuplicateKeyUpdateColumn" }}{{ $smallTableName := .TableName | toCamel | Untitle }} +{{- if .IsNullT }} +func (q {{ $smallTableName }}InsertOnDuplicateKeyUpdateSQL) ValueOnUpdate{{ .MethodName }} (v {{ .TypeParameter }}) {{ $smallTableName }}InsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`{{ .Name }}`"] = sql.Null[{{ .TypeParameter }}]{ V: v, Valid: true } + return q +} +func (q {{ $smallTableName }}InsertOnDuplicateKeyUpdateSQL) ValueOnUpdate{{ .MethodName }}ToNull () {{ $smallTableName }}InsertOnDuplicateKeyUpdateSQL { + q.onDuplicateKeyUpdateMap["`{{ .Name }}`"] = sql.Null[{{ .TypeParameter }}]{ Valid: false } + return q +} +{{- else }} func (q {{ $smallTableName }}InsertOnDuplicateKeyUpdateSQL) ValueOnUpdate{{ .MethodName }} (v {{ .TypeName }}) {{ $smallTableName }}InsertOnDuplicateKeyUpdateSQL { q.onDuplicateKeyUpdateMap["`{{ .Name }}`"] = v return q } +{{- end }} func (q {{ $smallTableName }}InsertOnDuplicateKeyUpdateSQL) RawValueOnUpdate{{ .MethodName }} (v sqlla.SetMapRawValue) {{ $smallTableName }}InsertOnDuplicateKeyUpdateSQL { q.onDuplicateKeyUpdateMap["`{{ .Name }}`"] = v @@ -14,5 +25,4 @@ func (q {{ $smallTableName }}InsertOnDuplicateKeyUpdateSQL) SameOnUpdate{{ .Meth q.onDuplicateKeyUpdateMap["`{{ .Name }}`"] = sqlla.SetMapRawValue("VALUES(`{{ .Name }}`)") return q } - {{ end }} From 8ee9a6a769db056bd98253be75b5a2b2d819b4dc Mon Sep 17 00:00:00 2001 From: mackee Date: Wed, 10 Jul 2024 12:12:31 +0900 Subject: [PATCH 09/11] feat: add useful comment at sqlla.Operator --- operator.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/operator.go b/operator.go index 1a6bd38..939292d 100644 --- a/operator.go +++ b/operator.go @@ -5,16 +5,16 @@ import ( ) var ( - OpEqual Operator = "=" - OpGreater Operator = ">" - OpGreaterEqual Operator = ">=" - OpLess Operator = "<" - OpLessEqual Operator = "<=" - OpNot Operator = "<>" - OpIs Operator = "IS" + OpEqual Operator = "=" // Operator for equal. Column(value, sqlla.OpEqual) same as Column = value + OpGreater Operator = ">" // Operator for greater. Column(value, sqlla.OpGreater) same as Column > value + OpGreaterEqual Operator = ">=" // Operator for greater equal. Column(value, sqlla.OpGreaterEqual) same as Column >= value + OpLess Operator = "<" // Operator for less. Column(value, sqlla.OpLess) same as Column < value + OpLessEqual Operator = "<=" // Operator for less equal. Column(value, sqlla.OpLessEqual) same as Column <= value + OpNot Operator = "<>" // Operator for not equal. Column(value, sqlla.OpNot) same as Column <> value + OpIs Operator = "IS" // Operator for is. Column(value, sqlla.OpIs) same as Column IS value opIsNull Operator = "IS NULL" opIsNotNull Operator = "IS NOT NULL" - OpLike Operator = "LIKE" + OpLike Operator = "LIKE" // Operator for like. Column(value, sqlla.OpLike) same as Column LIKE value ) type Operator string From 43a2c60ed3c8ca48552b54773b401c5f44b43bf8 Mon Sep 17 00:00:00 2001 From: mackee Date: Wed, 10 Jul 2024 14:10:38 +0900 Subject: [PATCH 10/11] fix: update go.mod to go1.21.x(oldstable). but testing toolchain is 1.22 for using sql.Null[T] --- .github/workflows/go.yml | 4 ++-- go.mod | 4 ++-- go.sum | 3 +++ 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index d459c6d..76146d1 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -7,10 +7,10 @@ jobs: runs-on: ubuntu-latest steps: - - name: Set up Go 1.17 + - name: Set up Go 1.22 uses: actions/setup-go@v2 with: - go-version: 1.17.x + go-version: 1.22.x id: go - name: Check out code into the Go module directory diff --git a/go.mod b/go.mod index 2820a91..6a3bfc1 100644 --- a/go.mod +++ b/go.mod @@ -1,12 +1,13 @@ module github.com/mackee/go-sqlla/v2 -go 1.20 +go 1.21 require ( github.com/Masterminds/goutils v1.1.1 github.com/go-sql-driver/mysql v1.6.0 github.com/pkg/errors v0.9.1 github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e + github.com/stretchr/testify v1.9.0 golang.org/x/tools v0.13.0 ) @@ -15,7 +16,6 @@ require ( github.com/onsi/ginkgo v1.16.5 // indirect github.com/onsi/gomega v1.17.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/stretchr/testify v1.9.0 // indirect golang.org/x/mod v0.16.0 // indirect golang.org/x/sys v0.12.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index c4bfca1..d7d39c8 100644 --- a/go.sum +++ b/go.sum @@ -59,10 +59,12 @@ golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.15.0 h1:ugBLEUaxABaB5AJqW9enI0ACdci2RUd4eP51NTBvuJ8= +golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -98,6 +100,7 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= From 3bfc52f7e414b813715d703213bef2e4bf6ea4ac Mon Sep 17 00:00:00 2001 From: mackee Date: Wed, 10 Jul 2024 14:19:02 +0900 Subject: [PATCH 11/11] fix: test case of select with nullable columns --- _example/group_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_example/group_test.go b/_example/group_test.go index ab1015c..ac06366 100644 --- a/_example/group_test.go +++ b/_example/group_test.go @@ -76,7 +76,7 @@ func TestSelectNullable(t *testing.T) { { name: "query by type parameters multiple", query: example.NewGroupSQL().Select().SubLeaderUserIDIn(42, 43, 44), - expect: "SELECT " + groupAllColumns + " FROM `group` WHERE `sub_leader_user_id` IN (?,?,?);", + expect: "SELECT " + groupAllColumns + " FROM `group` WHERE `sub_leader_user_id` IN(?,?,?);", args: []interface{}{ sql.Null[example.UserId]{V: 42, Valid: true}, sql.Null[example.UserId]{V: 43, Valid: true},