github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/sqlx/helper.go (about)

     1  package sqlx
     2  
     3  import (
     4  	"context"
     5  	"database/sql"
     6  
     7  	"github.com/machinefi/w3bstream/pkg/depends/kit/sqlx/builder"
     8  	"github.com/machinefi/w3bstream/pkg/depends/kit/sqlx/scanner"
     9  )
    10  
    11  func InsertToDB(db DBExecutor, m builder.Model, zeros []string, additions ...builder.Addition) builder.SqlExpr {
    12  	t := db.T(m)
    13  	fvs := FieldValuesFromModel(t, m, zeros...)
    14  	cs, vs := t.ColumnsAndValuesByFieldValues(fvs)
    15  	return builder.Insert().Into(t, additions...).Values(cs, vs...)
    16  }
    17  
    18  func AsAssignments(db DBExecutor, m builder.Model, zeros ...string) builder.Assignments {
    19  	fvs := FieldValuesFromModel(db.T(m), m, zeros...)
    20  	return db.T(m).AssignmentsByFieldValues(fvs)
    21  
    22  }
    23  
    24  func FieldValuesFromModel(table *builder.Table, model builder.Model, zeros ...string) builder.FieldValues {
    25  	fvs := builder.FieldValueFromStructByNoneZero(model, zeros...)
    26  	if autoIncrementCol := table.AutoIncrement(); autoIncrementCol != nil {
    27  		delete(fvs, autoIncrementCol.FieldName)
    28  	}
    29  	return fvs
    30  }
    31  
    32  type ScanIterator = scanner.ScanIterator
    33  
    34  func Scan(ctx context.Context, rows *sql.Rows, v interface{}) error {
    35  	if err := scanner.Scan(ctx, rows, v); err != nil {
    36  		if err == scanner.RecordNotFound {
    37  			return NewSqlError(SqlErrTypeNotFound, "record is not found")
    38  		}
    39  		return err
    40  	}
    41  	return nil
    42  }