1 Commits
Author SHA1 Message Date
gdulai d20184a6f0 WIP: Refactor Exec implementations to be chainable 2026-06-05 12:33:46 +02:00
18 changed files with 482 additions and 834 deletions
+1 -1
View File
@@ -25,7 +25,7 @@ func NewSchemaCache(tables []*schema.Table) *SchemaCache {
func (o *SchemaCache) add(table *schema.Table) { func (o *SchemaCache) add(table *schema.Table) {
o.mu.Lock() o.mu.Lock()
defer o.mu.Unlock() defer o.mu.Unlock()
o.data[table.Type().Name()] = table o.data[table.Type.Name()] = table
} }
func (o *SchemaCache) Get(typeName string) (*schema.Table, bool) { func (o *SchemaCache) Get(typeName string) (*schema.Table, bool) {
-96
View File
@@ -1,96 +0,0 @@
package exec
import (
"database/sql"
"errors"
"reflect"
"git.gdulai.com/gdulai/simpleorm"
"git.gdulai.com/gdulai/simpleorm/schema"
log "gitlab.com/gdulai/simpleloglvl"
)
// Count represents a count query.
type Count[T any] struct {
target schema.Table
whereStmt string
args []any
result int64
}
// CreateCount returns a new instance of Count.
//
// orm is the simpleorm.ORM instance which connects, caches and manages the relations.
func CreateCount[T any](orm *simpleorm.ORM, whereStmt string, args ...any) (Count[T], error) {
table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name())
if !ok {
return Count[T]{}, errors.New("Failed to get table from schema cache")
}
return Count[T]{target: *table, whereStmt: whereStmt, args: args}, nil
}
// Result returns the result of the count query.
func (c *Count[T]) Result() int64 {
return c.result
}
// Execute executes the parsed count query against a connection and returns an error if there was any during the execution.
//
// conn is the simpleorm.DBConnection which handles the database connection.
func (c *Count[T]) Execute(conn *simpleorm.DBConnection) error {
return c.execute(conn, nil)
}
// execute executes the parsed count query against a connection and transaction and returns an error if there was any during the execution.
//
// conn is the simpleorm.DBConnection which handles the database connection.
// tx is the sql.Tx transaction which the count query will be run in.
func (c *Count[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
// Reinit the results, new execution
c.result = -1
dml := c.target.GetCountDML()
if c.whereStmt != "" {
dml += " WHERE " + c.whereStmt
}
log.LogDebug("Preparing sql: %s, with args: %s", dml, c.args)
var stmt *sql.Stmt
var err error
if tx != nil {
stmt, err = tx.Prepare(dml)
} else {
stmt, err = conn.Prepare(dml)
}
if err != nil {
return err
}
defer stmt.Close()
log.LogDebug("Executing statement: %s", stmt)
if len(c.args) == 0 {
err = stmt.QueryRow().Scan(&c.result)
} else {
// Flattent args to make sure it can be parsed correctly
var flatArgs []any
for _, a := range c.args {
if s, ok := a.([]any); ok {
flatArgs = append(flatArgs, s...)
} else {
flatArgs = append(flatArgs, a)
}
}
err = stmt.QueryRow(flatArgs...).Scan(&c.result)
}
if err != nil {
return err
}
return nil
}
-90
View File
@@ -1,90 +0,0 @@
package exec
import (
"database/sql"
"errors"
"reflect"
"git.gdulai.com/gdulai/simpleorm"
"git.gdulai.com/gdulai/simpleorm/schema"
log "gitlab.com/gdulai/simpleloglvl"
)
// Delete represents a delete operation.
type Delete[T any] struct {
target schema.Table // The table from which records will be deleted.
toDelete []T // A slice of model instances to be deleted.
}
// NewDelete creates a new instance of Delete.
//
// Parameters:
// - orm: The ORM instance that manages the database connection and schema
// - toDelete: A slice of model instances to delete
//
// Returns:
// - Delete[T]: A new Delete operation instance
// - error: An error if the table could not be found in the schema cache
func NewDelete[T any](orm *simpleorm.ORM, toDelete []T) (Delete[T], error) {
table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name())
if !ok {
return Delete[T]{}, errors.New("Failed to get table from schema cache")
}
return Delete[T]{target: *table, toDelete: toDelete}, nil
}
// Execute executes the delete operation.
func (d *Delete[T]) Execute(conn *simpleorm.DBConnection) error {
return d.execute(conn, nil)
}
// execute constructs and executes the DELETE SQL statement.
//
// Parameters:
// - conn: The database connection to use for executing the query
// - tx: Optional transaction to use instead of a connection
//
// Returns:
// - error: An error if the operation fails
func (d *Delete[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
count := len(d.toDelete)
dml, err := d.target.GetDeleteDML(count)
if err != nil {
return err
}
var params []any
for _, del := range d.toDelete {
pkCols, err := getPk(del, d.target)
if err != nil {
return err
}
for _, pk := range pkCols {
params = append(params, pk)
}
}
log.LogDebug("%s [%s]", dml, params)
var stmt *sql.Stmt
if tx != nil {
stmt, err = tx.Prepare(dml)
} else {
stmt, err = conn.Prepare(dml)
}
defer stmt.Close()
result, err := stmt.Exec(params...)
if err != nil {
return err
} else {
rowsAffected, _ := result.RowsAffected()
log.LogInfo("Deleted %s row", rowsAffected)
}
return nil
}
+275 -12
View File
@@ -157,11 +157,277 @@ type Exec[T any] interface {
execute(conn *simpleorm.DBConnection, tx *sql.Tx) error execute(conn *simpleorm.DBConnection, tx *sql.Tx) error
} }
type OrderBy struct {
Column string
Direction string
}
type Count[T any] struct {
target schema.Table
whereStmt string
args []any
result int64
}
func CreateCount[T any](orm *simpleorm.ORM, whereStmt string, args ...any) (Count[T], error) {
table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name())
if !ok {
return Count[T]{}, errors.New("Failed to get table from schema cache")
}
return Count[T]{target: *table, whereStmt: whereStmt, args: args}, nil
}
func (c *Count[T]) Result() int64 {
return c.result
}
func (c *Count[T]) Execute(conn *simpleorm.DBConnection) error {
return c.execute(conn, nil)
}
func (c *Count[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
// Reinit the results, new execution
c.result = -1
dml := c.target.GetCountDML()
if c.whereStmt != "" {
dml += " WHERE " + c.whereStmt
}
log.LogDebug("Preparing sql: %s, with args: %s", dml, c.args)
var stmt *sql.Stmt
var err error
if tx != nil {
stmt, err = tx.Prepare(dml)
} else {
stmt, err = conn.Prepare(dml)
}
if err != nil {
return err
}
defer stmt.Close()
log.LogDebug("Executing statement: %s", stmt)
if len(c.args) == 0 {
err = stmt.QueryRow().Scan(&c.result)
} else {
// Flattent args to make sure it can be parsed correctly
var flatArgs []any
for _, a := range c.args {
if s, ok := a.([]any); ok {
flatArgs = append(flatArgs, s...)
} else {
flatArgs = append(flatArgs, a)
}
}
err = stmt.QueryRow(flatArgs...).Scan(&c.result)
}
if err != nil {
return err
}
return nil
}
type Insert[T any] struct {
target schema.Table
toInsert []T
results []T
}
func NewInsert[T any](orm *simpleorm.ORM, toInsert ...T) (Insert[T], error) {
table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name())
if !ok {
return Insert[T]{}, errors.New("Failed to get table from schema cache")
}
return Insert[T]{target: *table, toInsert: toInsert}, nil
}
func (ins *Insert[T]) Results() []T {
return ins.results
}
func (ins *Insert[T]) Execute(conn *simpleorm.DBConnection) error {
return ins.execute(conn, nil)
}
func (ins *Insert[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
dml, err := ins.target.GetInsertDML(len(ins.toInsert))
if err != nil {
return err
}
var params []any
for i := range len(ins.toInsert) {
actualParams := prepareParams(ins.toInsert[i], ins.target)
if len(params) == 0 {
params = make([]any, len(ins.toInsert)*len(actualParams))
}
for j := range actualParams {
params[(i*len(actualParams))+j] = actualParams[j]
}
}
log.LogDebug("%s [%s]", dml, params)
var stmt *sql.Stmt
if tx != nil {
stmt, err = tx.Prepare(dml)
} else {
stmt, err = conn.Prepare(dml)
}
defer stmt.Close()
// Flattent args to make sure it can be parsed correctly
var flatParams []any
for _, param := range params {
if s, ok := param.([]any); ok {
flatParams = append(flatParams, s...)
} else {
flatParams = append(flatParams, param)
}
}
rows, err := stmt.Query(flatParams...)
if err != nil {
return err
}
ins.results, err = readRows[T](ins.target, rows)
if err != nil {
return err
}
return nil
}
type Update[T any] struct {
target schema.Table
toUpdate T
}
func NewUpdate[T any](orm *simpleorm.ORM, toUpdate T) (Update[T], error) {
table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name())
if !ok {
return Update[T]{}, errors.New("Failed to get table from schema cache")
}
return Update[T]{target: *table, toUpdate: toUpdate}, nil
}
func (u Update[T]) Execute(conn *simpleorm.DBConnection) error {
return u.execute(conn, nil)
}
func (u Update[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
dml, err := u.target.GetUpdateDML()
if err != nil {
return err
}
params := prepareParams(u.toUpdate, u.target)
pkCols, err := getPk(u.toUpdate, u.target)
if err != nil {
return err
}
// Put the pks back at the end
for _, pk := range pkCols {
params = append(params, pk)
}
log.LogDebug("%s [%s]", dml, params)
var stmt *sql.Stmt
if tx != nil {
stmt, err = tx.Prepare(dml)
} else {
stmt, err = conn.Prepare(dml)
}
defer stmt.Close()
result, err := stmt.Exec(params...)
if err != nil {
return err
} else {
rowsAffected, _ := result.RowsAffected()
log.LogInfo("Updated %s row", rowsAffected)
}
return nil
}
type Delete[T any] struct {
target schema.Table
toDelete []T
}
func NewDelete[T any](orm *simpleorm.ORM, toDelete []T) (Delete[T], error) {
table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name())
if !ok {
return Delete[T]{}, errors.New("Failed to get table from schema cache")
}
return Delete[T]{target: *table, toDelete: toDelete}, nil
}
func (d *Delete[T]) Execute(conn *simpleorm.DBConnection) error {
return d.execute(conn, nil)
}
func (d *Delete[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
count := len(d.toDelete)
dml, err := d.target.GetDeleteDML(count)
if err != nil {
return err
}
var params []any
for _, del := range d.toDelete {
pkCols, err := getPk(del, d.target)
if err != nil {
return err
}
for _, pk := range pkCols {
params = append(params, pk)
}
}
log.LogDebug("%s [%s]", dml, params)
var stmt *sql.Stmt
if tx != nil {
stmt, err = tx.Prepare(dml)
} else {
stmt, err = conn.Prepare(dml)
}
defer stmt.Close()
result, err := stmt.Exec(params...)
if err != nil {
return err
} else {
rowsAffected, _ := result.RowsAffected()
log.LogInfo("Deleted %s row", rowsAffected)
}
return nil
}
func createSelectResultContainer(t schema.Table) []any { func createSelectResultContainer(t schema.Table) []any {
typ := t.Type() vals := make([]any, t.Type.NumField())
vals := make([]any, typ.NumField())
for i := range vals { for i := range vals {
switch typ.Field(i).Type.Kind().String() { switch t.Type.Field(i).Type.Kind().String() {
case "string": case "string":
var fieldContainer string var fieldContainer string
vals[i] = &fieldContainer vals[i] = &fieldContainer
@@ -177,14 +443,13 @@ func createSelectResultContainer(t schema.Table) []any {
} }
func prepareParams(src any, t schema.Table) []any { func prepareParams(src any, t schema.Table) []any {
typ := t.Type()
var params []any var params []any
for _, col := range t.Columns() { for _, col := range t.Columns {
_, ok := col.Modifiers["pk"] _, ok := col.Modifiers["pk"]
if ok && t.IsPkAuto() { if ok && t.IsPkAuto() {
continue continue
} }
field, ok := typ.FieldByName(col.FieldName) field, ok := t.Type.FieldByName(col.FieldName)
if !ok { if !ok {
continue continue
} }
@@ -196,12 +461,11 @@ func prepareParams(src any, t schema.Table) []any {
} }
func getPk(src any, t schema.Table) ([]any, error) { func getPk(src any, t schema.Table) ([]any, error) {
typ := t.Type()
var values []any var values []any
for _, constraint := range t.Constraints() { for _, constraint := range t.Constraints {
if constraint.Type == "pk" { if constraint.Type == "pk" {
for _, col := range constraint.Columns { for _, col := range constraint.Columns {
field, ok := typ.FieldByName(col.FieldName) field, ok := t.Type.FieldByName(col.FieldName)
if !ok { if !ok {
continue continue
@@ -229,11 +493,10 @@ func readRows[T any](table schema.Table, rows *sql.Rows) ([]T, error) {
return nil, err return nil, err
} }
targetType := table.Type() targetType := table.Type
cols := table.Columns()
parsedResult := reflect.New(targetType) parsedResult := reflect.New(targetType)
for i, fieldVal := range rowContainer { for i, fieldVal := range rowContainer {
col := cols[i] col := table.Columns[i]
targetField := parsedResult.Elem().Field(i) targetField := parsedResult.Elem().Field(i)
rawValue := reflect.Indirect(reflect.ValueOf(fieldVal)) rawValue := reflect.Indirect(reflect.ValueOf(fieldVal))
-122
View File
@@ -1,122 +0,0 @@
package exec
import (
"database/sql"
"errors"
"reflect"
"git.gdulai.com/gdulai/simpleorm"
"git.gdulai.com/gdulai/simpleorm/schema"
log "gitlab.com/gdulai/simpleloglvl"
)
// Insert represents an insert query operation.
type Insert[T any] struct {
target schema.Table
toInsert []T
results []T
}
// Creates a new insert operation for the given model type.
//
// Parameters:
// - orm: The ORM instance that manages the database connection and schema
// - toInsert: A variadic list of model instances to insert
//
// Returns:
// - Insert[T]: A new insert operation instance
// - error: An error if the table could not be found in the schema cache
func NewInsert[T any](orm *simpleorm.ORM, toInsert ...T) (Insert[T], error) {
table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name())
if !ok {
return Insert[T]{}, errors.New("Failed to get table from schema cache")
}
return Insert[T]{target: *table, toInsert: toInsert}, nil
}
// Returns the results of the insert operation.
//
// Returns:
// - []T: A slice of model instances representing the inserted rows
func (ins *Insert[T]) Results() []T {
return ins.results
}
// Executes the insert operation using the provided database connection.
//
// Parameters:
// - conn: The database connection to use for executing the query
//
// Returns:
// - error: An error if the operation fails
func (ins *Insert[T]) Execute(conn *simpleorm.DBConnection) error {
return ins.execute(conn, nil)
}
// Executes the insert operation using the provided database connection or transaction.
//
// Parameters:
// - conn: The database connection to use for executing the query
// - tx: Optional transaction to use instead of a connection
//
// Returns:
// - error: An error if the operation fails
//
// Implementation Details:
// 1. Constructs the SQL INSERT statement using GetInsertDML
// 2. Prepares parameters by flattening nested any values
// 3. Executes the statement and maps results to model instances
func (ins *Insert[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
dml, err := ins.target.GetInsertDML(len(ins.toInsert))
if err != nil {
return err
}
var params []any
for i := range len(ins.toInsert) {
actualParams := prepareParams(ins.toInsert[i], ins.target)
if len(params) == 0 {
params = make([]any, len(ins.toInsert)*len(actualParams))
}
for j := range actualParams {
params[(i*len(actualParams))+j] = actualParams[j]
}
}
log.LogDebug("%s [%s]", dml, params)
var stmt *sql.Stmt
if tx != nil {
stmt, err = tx.Prepare(dml)
} else {
stmt, err = conn.Prepare(dml)
}
defer stmt.Close()
// Flattent args to make sure it can be parsed correctly
var flatParams []any
for _, param := range params {
if s, ok := param.([]any); ok {
flatParams = append(flatParams, s...)
} else {
flatParams = append(flatParams, param)
}
}
rows, err := stmt.Query(flatParams...)
if err != nil {
return err
}
ins.results, err = readRows[T](ins.target, rows)
if err != nil {
return err
}
return nil
}
+3 -18
View File
@@ -17,12 +17,12 @@ type Select[T any] struct {
args []any args []any
limit int64 limit int64
offset int64 offset int64
ordering []schema.OrderBy ordering []OrderBy
results []T results []T
} }
// Creates the select query builder // Creates the select query builder
func NewSelect[T any](orm *simpleorm.ORM) (Select[T], error) { func CreateSelect[T any](orm *simpleorm.ORM) (Select[T], error) {
table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name()) table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name())
if !ok { if !ok {
return Select[T]{}, errors.New("Failed to get table from schema cache") return Select[T]{}, errors.New("Failed to get table from schema cache")
@@ -55,7 +55,7 @@ func (s *Select[T]) Offset(offset int64) *Select[T] {
// Sets the order by part of the select query // Sets the order by part of the select query
// Returns the pointer of the Select instance // Returns the pointer of the Select instance
func (s *Select[T]) OrderBy(ordering ...schema.OrderBy) *Select[T] { func (s *Select[T]) OrderBy(ordering ...OrderBy) *Select[T] {
s.ordering = ordering s.ordering = ordering
return s return s
} }
@@ -65,15 +65,10 @@ func (s *Select[T]) Results() []T {
return s.results return s.results
} }
// Executes the select query based on the Select exec instance
// Returns an error if theres any
func (s *Select[T]) Execute(conn *simpleorm.DBConnection) error { func (s *Select[T]) Execute(conn *simpleorm.DBConnection) error {
return s.execute(conn, nil) return s.execute(conn, nil)
} }
// Executes the select query based on the Select exec instance
// If tx is given, the transaction is used instead of the conn
// Returns an error if theres any
func (s *Select[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error { func (s *Select[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
// Reinit the results, new execution // Reinit the results, new execution
s.results = []T{} s.results = []T{}
@@ -86,15 +81,6 @@ func (s *Select[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
dml += " WHERE " + s.whereStmt dml += " WHERE " + s.whereStmt
} }
if len(s.ordering) > 0 {
orderBy, err := s.target.GetOrderByDML(s.ordering...)
if err != nil {
log.LogError("Failed to create ORDER BY part: %s", err)
} else {
dml += orderBy
}
}
var effectiveArgs []any = s.args var effectiveArgs []any = s.args
if s.limit != -1 { if s.limit != -1 {
dml += " LIMIT ?" dml += " LIMIT ?"
@@ -106,7 +92,6 @@ func (s *Select[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
effectiveArgs = append(effectiveArgs, s.offset) effectiveArgs = append(effectiveArgs, s.offset)
} }
log.LogInfo("Preparing sql: %s", dml)
log.LogDebug("Preparing sql: %s, with args: %s", dml, effectiveArgs) log.LogDebug("Preparing sql: %s, with args: %s", dml, effectiveArgs)
var stmt *sql.Stmt var stmt *sql.Stmt
-85
View File
@@ -1,85 +0,0 @@
package exec
import (
"database/sql"
"errors"
"reflect"
"git.gdulai.com/gdulai/simpleorm"
"git.gdulai.com/gdulai/simpleorm/schema"
log "gitlab.com/gdulai/simpleloglvl"
)
// Update represents an update operation.
type Update[T any] struct {
target schema.Table // The table where records will be updated.
toUpdate T // A model instance with the new values.
}
// NewUpdate creates a new instance of Update.
//
// Parameters:
// - orm: The ORM instance that manages the database connection and schema
// - toUpdate: A model instance with new values
//
// Returns:
// - Update[T]: A new Update operation instance
// - error: An error if the table could not be found in the schema cache
func NewUpdate[T any](orm *simpleorm.ORM, toUpdate T) (Update[T], error) {
table, ok := orm.Cache().Get(reflect.TypeFor[T]().Name())
if !ok {
return Update[T]{}, errors.New("Failed to get table from schema cache")
}
return Update[T]{target: *table, toUpdate: toUpdate}, nil
}
// Execute executes the update operation.
func (u Update[T]) Execute(conn *simpleorm.DBConnection) error {
return u.execute(conn, nil)
}
// execute constructs and executes the UPDATE SQL statement.
//
// Parameters:
// - conn: The database connection to use for executing the query
// - tx: Optional transaction to use instead of a connection
//
// Returns:
// - error: An error if the operation fails
func (u Update[T]) execute(conn *simpleorm.DBConnection, tx *sql.Tx) error {
dml, err := u.target.GetUpdateDML()
if err != nil {
return err
}
params := prepareParams(u.toUpdate, u.target)
pkCols, err := getPk(u.toUpdate, u.target)
if err != nil {
return err
}
// Put the pks back at the end
for _, pk := range pkCols {
params = append(params, pk)
}
log.LogDebug("%s [%s]", dml, params)
var stmt *sql.Stmt
if tx != nil {
stmt, err = tx.Prepare(dml)
} else {
stmt, err = conn.Prepare(dml)
}
defer stmt.Close()
result, err := stmt.Exec(params...)
if err != nil {
return err
} else {
rowsAffected, _ := result.RowsAffected()
log.LogInfo("Updated %s row", rowsAffected)
}
return nil
}
+20 -31
View File
@@ -7,6 +7,7 @@ import (
"strings" "strings"
"git.gdulai.com/gdulai/simpleorm/cache" "git.gdulai.com/gdulai/simpleorm/cache"
"git.gdulai.com/gdulai/simpleorm/parser"
"git.gdulai.com/gdulai/simpleorm/schema" "git.gdulai.com/gdulai/simpleorm/schema"
log "gitlab.com/gdulai/simpleloglvl" log "gitlab.com/gdulai/simpleloglvl"
@@ -17,48 +18,36 @@ type ORM struct {
cache *cache.SchemaCache cache *cache.SchemaCache
} }
// NewOrm inits and creates an instance ORM library. // Inits the ORM library.
// // Param objs is an array which should be an array of the types which describe the tables.
// obj is an array which should be an array of the types which describe the tables.
func NewORM(objs ...any) *ORM { func NewORM(objs ...any) *ORM {
typeParsers := make(map[string]*schema.Parser) var parsers []*parser.Parser
log.LogDebug("[ORM] Parsing entities to tables...")
log.LogDebug("[ORM] Step 1: Parsing table columns")
for _, obj := range objs {
typ := reflect.TypeOf(obj)
log.LogDebug("[ORM] Mapping type for: %s", typ.Name())
parser := schema.NewParser(obj)
parser.ParseColumns()
typeParsers[typ.Name()] = parser
}
log.LogDebug("[ORM] Step 1: Finished parsing columns!")
log.LogDebug("[ORM] Step 2: Parsing constraints...")
for _, parser := range typeParsers {
parser.ParseConstraints(typeParsers)
}
log.LogDebug("[ORM] Step 2: Finished parsing contraints!")
log.LogDebug("[ORM] Step 3: Creating and caching schema...")
var tables []*schema.Table var tables []*schema.Table
for _, parser := range typeParsers { for _, obj := range objs {
tables = append(tables, parser.ParseTable()) log.LogDebug("[ORM] Mapping type for: %s", reflect.TypeOf(obj).Name())
parser := parser.NewParser(obj)
parsers = append(parsers, parser)
tables = append(tables, parser.ParseColumns())
} }
log.LogDebug("[ORM] Tables initiated, creating cache.")
// Create cache with the initialized tables // Create cache with the initialized tables
cache := cache.NewSchemaCache(tables) cache := cache.NewSchemaCache(tables)
log.LogDebug("[ORM] Step 3: Cache created.") log.LogDebug("[ORM] Cache created.")
// Finish the parsing with the constraints and add the to the tables
for _, parser := range parsers {
log.LogDebug("[ORM] Parsing constraing for: %s", parser.Table.Name)
parser.ParseConstraints(cache)
log.LogDebug("[ORM] Parsed constraints for: %s", parser.Table.Name)
}
return &ORM{cache: cache} return &ORM{cache: cache}
} }
// CreateSchmea builds the DDL and returns it as a string // Builds the DDL and returns it as a string
func (orm *ORM) CreateSchema() (string, error) { func (orm *ORM) CreateSchema() (string, error) {
var ddl strings.Builder var ddl strings.Builder
+101
View File
@@ -0,0 +1,101 @@
package parser
import (
"reflect"
"strings"
cache "git.gdulai.com/gdulai/simpleorm/cache"
"git.gdulai.com/gdulai/simpleorm/schema"
"git.gdulai.com/gdulai/simpleorm/util"
log "gitlab.com/gdulai/simpleloglvl"
)
type Parser struct {
typ reflect.Type
Table *schema.Table
}
func NewParser[T any](obj T) *Parser {
objType := reflect.TypeOf(obj)
return &Parser{typ: objType}
}
// This is step 1 of the parsing, it creates the table instance and
func (p *Parser) ParseColumns() *schema.Table {
table := schema.Table{Name: util.CamelToSnake(p.typ.Name()), Type: p.typ}
var columns []schema.Column
for field := range p.typ.Fields() {
field := field
col := schema.NewColumn(util.CamelToSnake((field.Name)), field.Name, determineType(field.Type), field.Tag)
columns = append(columns, col)
}
table.Columns = columns
p.Table = &table
return p.Table
}
func (p *Parser) ParseConstraints(cache *cache.SchemaCache) {
pkConstraint := schema.Constraint{Name: "pk_" + strings.ToLower(p.Table.Name), Type: "pk"}
fkConstraints := make(map[string]schema.Constraint)
for _, col := range p.Table.Columns {
_, ok := col.Modifiers["pk"]
if ok {
pkConstraint.Columns = append(pkConstraint.Columns, col)
continue
}
fkMod, ok := col.Modifiers["fk"]
if !ok {
continue
}
fkModParts := strings.Split(fkMod, ".")
refTable, ok := cache.Get(fkModParts[0])
if !ok {
log.LogError("[ORM] Table %s not found in OrmCache!", fkModParts[0])
return
}
fkId, ok := col.Modifiers["fk_id"]
if fkId == "" {
fkId = "fk_" + strings.ToLower(refTable.Name)
}
fkConstraint, ok := fkConstraints[fkId]
if !ok {
fkConstraint = schema.Constraint{Name: fkId, Type: "fk", RefTable: refTable}
}
fkConstraint.Columns = append(fkConstraint.Columns, col)
refField := fkModParts[1]
for _, refC := range refTable.Columns {
if refC.FieldName == refField {
fkConstraint.RefColumns = append(fkConstraint.RefColumns, refC)
}
}
fkConstraints[fkId] = fkConstraint
}
p.Table.Constraints = append(p.Table.Constraints, pkConstraint)
for _, fkConstraint := range fkConstraints {
p.Table.Constraints = append(p.Table.Constraints, fkConstraint)
}
}
func determineType(typ reflect.Type) string {
typStr := typ.String()
switch typStr {
case "string":
return "TEXT"
case "int", "bool":
return "INTEGER"
case "time.Time", "int64":
return "BIGINT"
}
return "VARCHAR(255)"
}
+3 -3
View File
@@ -23,7 +23,7 @@ func NewRepository[T HasPK](conn *simpleorm.DBConnection, orm *simpleorm.ORM) *R
} }
func (r *Repository[T]) SelectAll() []*T { func (r *Repository[T]) SelectAll() []*T {
selectExec, err := exec.NewSelect[T](r.orm) selectExec, err := exec.CreateSelect[T](r.orm)
if err != nil { if err != nil {
log.LogError("Failed to create select execution: %s", err) log.LogError("Failed to create select execution: %s", err)
return []*T{} return []*T{}
@@ -53,7 +53,7 @@ func (r *Repository[T]) SelectByPk(pks ...any) *T {
var whereStmtBuilder strings.Builder var whereStmtBuilder strings.Builder
for _, constr := range table.Constraints() { for _, constr := range table.Constraints {
if constr.Type != "pk" { if constr.Type != "pk" {
continue continue
} }
@@ -68,7 +68,7 @@ func (r *Repository[T]) SelectByPk(pks ...any) *T {
} }
selectExec, err := exec.NewSelect[T](r.orm) selectExec, err := exec.CreateSelect[T](r.orm)
if err != nil { if err != nil {
log.LogError("Failed to create select execution: %s", err) log.LogError("Failed to create select execution: %s", err)
return nil return nil
+2 -5
View File
@@ -40,14 +40,11 @@ func determineModifiers(tag reflect.StructTag) map[string]string {
func (c *Column) GetDDL() (string, error) { func (c *Column) GetDDL() (string, error) {
var ddlBuilder strings.Builder var ddlBuilder strings.Builder
ddlBuilder.WriteString(c.Name) ddlBuilder.WriteString(c.Name + " " + c.Type)
ddlBuilder.WriteString(" ")
ddlBuilder.WriteString(c.Type)
inlineMods := c.inlineModifiers() inlineMods := c.inlineModifiers()
for _, mod := range inlineMods { for _, mod := range inlineMods {
ddlBuilder.WriteString(" ") ddlBuilder.WriteString(" " + mod)
ddlBuilder.WriteString(mod)
} }
return ddlBuilder.String(), nil return ddlBuilder.String(), nil
+8 -17
View File
@@ -3,16 +3,14 @@ package schema
import ( import (
"errors" "errors"
"strings" "strings"
"git.gdulai.com/gdulai/simpleorm/util"
) )
type Constraint struct { type Constraint struct {
Name string Name string
Type string Type string
Columns []Column Columns []Column
RefTypeName string RefTable *Table
RefColumns []Column RefColumns []Column
} }
func (c *Constraint) GetDDL() (string, error) { func (c *Constraint) GetDDL() (string, error) {
@@ -28,9 +26,7 @@ func (c *Constraint) GetDDL() (string, error) {
func (c *Constraint) getPkDDL() string { func (c *Constraint) getPkDDL() string {
var ddl strings.Builder var ddl strings.Builder
ddl.WriteString("CONSTRAINT ") ddl.WriteString("CONSTRAINT " + c.Name + " PRIMARY KEY(")
ddl.WriteString(c.Name)
ddl.WriteString(" PRIMARY KEY(")
for i, col := range c.Columns { for i, col := range c.Columns {
if i != 0 { if i != 0 {
ddl.WriteString(", ") ddl.WriteString(", ")
@@ -43,9 +39,7 @@ func (c *Constraint) getPkDDL() string {
func (c *Constraint) getFkDDL() string { func (c *Constraint) getFkDDL() string {
var ddl strings.Builder var ddl strings.Builder
ddl.WriteString("CONSTRAINT ") ddl.WriteString("CONSTRAINT " + c.Name + " FOREIGN KEY(")
ddl.WriteString(c.Name)
ddl.WriteString(" FOREIGN KEY(")
for i, col := range c.Columns { for i, col := range c.Columns {
if i != 0 { if i != 0 {
@@ -53,10 +47,7 @@ func (c *Constraint) getFkDDL() string {
} }
ddl.WriteString(col.Name) ddl.WriteString(col.Name)
} }
ddl.WriteString(") REFERENCES " + c.RefTable.Name + "(")
ddl.WriteString(") REFERENCES ")
ddl.WriteString(util.CamelToSnake(c.RefTypeName))
ddl.WriteString("(")
for i, col := range c.RefColumns { for i, col := range c.RefColumns {
if i != 0 { if i != 0 {
-103
View File
@@ -1,103 +0,0 @@
package schema
import (
"reflect"
"strings"
"git.gdulai.com/gdulai/simpleorm/util"
log "gitlab.com/gdulai/simpleloglvl"
)
type Parser struct {
typ reflect.Type
columns []Column
constraints []Constraint
}
func NewParser[T any](obj T) *Parser {
objType := reflect.TypeOf(obj)
return &Parser{typ: objType}
}
// Step 1 of the parsing, it creates the table instance and
func (p *Parser) ParseColumns() {
var columns []Column
for field := range p.typ.Fields() {
field := field
col := NewColumn(util.CamelToSnake((field.Name)), field.Name, determineType(field.Type), field.Tag)
columns = append(columns, col)
}
p.columns = columns
}
// Step 2 of the parsing, it creates the constrains with the table references
func (p *Parser) ParseConstraints(tableParsers map[string]*Parser) {
pkConstraint := Constraint{Name: "pk_" + strings.ToLower(util.CamelToSnake((p.typ.Name()))), Type: "pk"}
fkConstraints := make(map[string]Constraint)
for _, col := range p.columns {
_, ok := col.Modifiers["pk"]
if ok {
pkConstraint.Columns = append(pkConstraint.Columns, col)
continue
}
fkMod, ok := col.Modifiers["fk"]
if !ok {
continue
}
fkModParts := strings.Split(fkMod, ".")
refTypeName := fkModParts[0]
refTableName := util.CamelToSnake(refTypeName)
parser, ok := tableParsers[refTypeName]
if !ok {
log.LogError("[ORM] Reference table not found", refTypeName)
}
fkId, ok := col.Modifiers["fk_id"]
if fkId == "" {
fkId = "fk_" + strings.ToLower(refTableName)
}
fkConstraint, ok := fkConstraints[fkId]
if !ok {
fkConstraint = Constraint{Name: fkId, Type: "fk", RefTypeName: refTypeName}
}
fkConstraint.Columns = append(fkConstraint.Columns, col)
refField := fkModParts[1]
for _, refC := range parser.columns {
if refC.FieldName == refField {
fkConstraint.RefColumns = append(fkConstraint.RefColumns, refC)
}
}
fkConstraints[fkId] = fkConstraint
}
p.constraints = append(p.constraints, pkConstraint)
for _, fkConstraint := range fkConstraints {
p.constraints = append(p.constraints, fkConstraint)
}
}
// Step 3 of the paring, create the schema.Table instance
// Returns the schema.Table pointer
func (p Parser) ParseTable() *Table {
return &Table{name: util.CamelToSnake(p.typ.Name()), typ: p.typ, columns: p.columns, constraints: p.constraints}
}
func determineType(typ reflect.Type) string {
typStr := typ.String()
switch typStr {
case "string":
return "TEXT"
case "int", "bool":
return "INTEGER"
case "time.Time", "int64":
return "BIGINT"
}
return "VARCHAR(255)"
}
+25 -87
View File
@@ -1,47 +1,23 @@
package schema package schema
import ( import (
"errors"
"reflect" "reflect"
"strings" "strings"
"git.gdulai.com/gdulai/simpleorm/util" "git.gdulai.com/gdulai/simpleorm/util"
) )
type OrderBy struct {
Field string
Direction string
}
type Table struct { type Table struct {
name string Name string
typ reflect.Type Type reflect.Type
columns []Column Columns []Column
constraints []Constraint Constraints []Constraint
}
func (t Table) Name() string {
return t.name
}
func (t Table) Type() reflect.Type {
return t.typ
}
func (t Table) Columns() []Column {
return t.columns
}
func (t Table) Constraints() []Constraint {
return t.constraints
} }
func (t Table) GetDDL() (string, error) { func (t Table) GetDDL() (string, error) {
var ddl strings.Builder var ddl strings.Builder
ddl.WriteString("CREATE TABLE IF NOT EXISTS ") ddl.WriteString("CREATE TABLE IF NOT EXISTS " + t.Name + " (")
ddl.WriteString(t.name) for i, col := range t.Columns {
ddl.WriteString(" (")
for i, col := range t.columns {
if i != 0 { if i != 0 {
ddl.WriteString(", ") ddl.WriteString(", ")
} }
@@ -51,13 +27,12 @@ func (t Table) GetDDL() (string, error) {
} }
ddl.WriteString(colDdl) ddl.WriteString(colDdl)
} }
for _, constr := range t.constraints { for _, constr := range t.Constraints {
constrDdl, err := constr.GetDDL() constrDdl, err := constr.GetDDL()
if err != nil { if err != nil {
return "", err return "", err
} }
ddl.WriteString(", ") ddl.WriteString(", " + constrDdl)
ddl.WriteString(constrDdl)
} }
ddl.WriteString(");") ddl.WriteString(");")
@@ -68,7 +43,7 @@ func (t Table) GetSelectDML() (string, error) {
var dml strings.Builder var dml strings.Builder
dml.WriteString("SELECT ") dml.WriteString("SELECT ")
for i, col := range t.columns { for i, col := range t.Columns {
if i != 0 { if i != 0 {
dml.WriteString(", ") dml.WriteString(", ")
} }
@@ -79,24 +54,21 @@ func (t Table) GetSelectDML() (string, error) {
dml.WriteString(colDml) dml.WriteString(colDml)
} }
dml.WriteString(" FROM ") dml.WriteString(" FROM " + t.Name)
dml.WriteString(t.name)
return dml.String(), nil return dml.String(), nil
} }
func (t Table) GetCountDML() string { func (t Table) GetCountDML() string {
return "SELECT COUNT(*) FROM " + t.name return "SELECT COUNT(*) FROM " + t.Name
} }
func (t Table) GetInsertDML(count int) (string, error) { func (t Table) GetInsertDML(count int) (string, error) {
var dml strings.Builder var dml strings.Builder
dml.WriteString("INSERT INTO ") dml.WriteString("INSERT INTO " + util.CamelToSnake(t.Type.Name()) + " (")
dml.WriteString(util.CamelToSnake(t.typ.Name()))
dml.WriteString(" (")
columnsLen := len(t.columns) columnsLen := len(t.Columns)
effectiveColumnsLen := 0 effectiveColumnsLen := 0
for i, col := range t.columns { for i, col := range t.Columns {
_, ok := col.Modifiers["pk"] _, ok := col.Modifiers["pk"]
if ok && t.IsPkAuto() { if ok && t.IsPkAuto() {
continue continue
@@ -139,14 +111,12 @@ func (t Table) GetInsertDML(count int) (string, error) {
func (t Table) GetUpdateDML() (string, error) { func (t Table) GetUpdateDML() (string, error) {
var dml strings.Builder var dml strings.Builder
dml.WriteString("UPDATE ") dml.WriteString("UPDATE " + util.CamelToSnake(t.Type.Name()) + " SET ")
dml.WriteString(util.CamelToSnake(t.typ.Name()))
dml.WriteString(" SET ")
colLen := len(t.columns) colLen := len(t.Columns)
var pkColumns []string var pkColumns []string
// Colum names // Colum names
for i, col := range t.columns { for i, col := range t.Columns {
modifiers := col.Modifiers modifiers := col.Modifiers
_, ok := modifiers["pk"] _, ok := modifiers["pk"]
@@ -163,11 +133,9 @@ func (t Table) GetUpdateDML() (string, error) {
} }
if i != colLen-1 { if i != colLen-1 {
dml.WriteString(colDml) dml.WriteString(colDml + ", ")
dml.WriteString(", ")
} else { } else {
dml.WriteString(colDml) dml.WriteString(colDml + " ")
dml.WriteString(" ")
} }
} }
@@ -177,8 +145,7 @@ func (t Table) GetUpdateDML() (string, error) {
if i != 0 { if i != 0 {
dml.WriteString(" AND ") dml.WriteString(" AND ")
} }
dml.WriteString(pkCol) dml.WriteString(pkCol + " = ?")
dml.WriteString(" = ?")
} }
return dml.String(), nil return dml.String(), nil
@@ -186,21 +153,17 @@ func (t Table) GetUpdateDML() (string, error) {
func (t Table) GetDeleteDML(count int) (string, error) { func (t Table) GetDeleteDML(count int) (string, error) {
var dml strings.Builder var dml strings.Builder
dml.WriteString("DELETE FROM ") dml.WriteString("DELETE FROM " + t.Name + " WHERE ")
dml.WriteString(t.name)
dml.WriteString(" WHERE ")
for _, col := range t.columns { for _, col := range t.Columns {
modifiers := col.Modifiers modifiers := col.Modifiers
_, ok := modifiers["pk"] _, ok := modifiers["pk"]
if ok { if ok {
if count > 1 { if count > 1 {
dml.WriteString(col.Name) dml.WriteString(col.Name + " IN (")
dml.WriteString(" IN (")
} else { } else {
dml.WriteString(col.Name) dml.WriteString(col.Name + " = ")
dml.WriteString(" = ")
} }
} }
} }
@@ -219,33 +182,8 @@ func (t Table) GetDeleteDML(count int) (string, error) {
return dml.String(), nil return dml.String(), nil
} }
func (t Table) GetOrderByDML(ordering ...OrderBy) (string, error) {
var dml strings.Builder
dml.WriteString(" ORDER BY")
for _, orderBy := range ordering {
col, err := t.getColumnByField(orderBy.Field)
if err != nil {
return "", err
}
dml.WriteString(" ")
dml.WriteString(col.Name)
dml.WriteString(" ")
dml.WriteString(orderBy.Direction)
}
return dml.String(), nil
}
func (t Table) getColumnByField(fieldName string) (Column, error) {
for _, col := range t.columns {
if col.FieldName == fieldName {
return col, nil
}
}
return Column{}, errors.New("No column for field " + fieldName + " in table " + t.name)
}
func (t Table) IsPkAuto() bool { func (t Table) IsPkAuto() bool {
for _, constr := range t.constraints { for _, constr := range t.Constraints {
if constr.Type != "pk" { if constr.Type != "pk" {
continue continue
} }
+5 -5
View File
@@ -118,7 +118,7 @@ func TestInsertAndUpdate(t *testing.T) {
return return
} }
selectExec, err := exec.NewSelect[Test](orm) selectExec, err := exec.CreateSelect[Test](orm)
if err != nil { if err != nil {
log.LogError("TestInsertMultipleAndSelectWithParam setup failed: %s", err) log.LogError("TestInsertMultipleAndSelectWithParam setup failed: %s", err)
t.Fail() t.Fail()
@@ -207,7 +207,7 @@ func TestInsertAndDelete(t *testing.T) {
return return
} }
selectExec, err := exec.NewSelect[Test](orm) selectExec, err := exec.CreateSelect[Test](orm)
if err != nil { if err != nil {
log.LogError("TestInsertAndDelete setup failed: %s", err) log.LogError("TestInsertAndDelete setup failed: %s", err)
t.Fail() t.Fail()
@@ -263,7 +263,7 @@ func TestBoolInsertAndSelectSingle(t *testing.T) {
return return
} }
selectExec, err := exec.NewSelect[TestWithBool](orm) selectExec, err := exec.CreateSelect[TestWithBool](orm)
if err != nil { if err != nil {
log.LogError("TestBoolInsertAndSelectSingle setup failed: %s", err) log.LogError("TestBoolInsertAndSelectSingle setup failed: %s", err)
t.Fail() t.Fail()
@@ -317,7 +317,7 @@ func TestTimeInsertAndSelectSingle(t *testing.T) {
return return
} }
selectExec, err := exec.NewSelect[TestWithTime](orm) selectExec, err := exec.CreateSelect[TestWithTime](orm)
if err != nil { if err != nil {
log.LogError("TestTimeInsertAndSelectSingle setup failed: %s", err) log.LogError("TestTimeInsertAndSelectSingle setup failed: %s", err)
t.Fail() t.Fail()
@@ -423,7 +423,7 @@ func TestTransactionRollback(t *testing.T) {
return return
} }
selectExec, err := exec.NewSelect[Test](orm) selectExec, err := exec.CreateSelect[Test](orm)
if err != nil { if err != nil {
log.LogError("TestTransactionRollback WHEN failed: %s", err) log.LogError("TestTransactionRollback WHEN failed: %s", err)
t.Fail() t.Fail()
-7
View File
@@ -56,13 +56,6 @@ type TestWithTime struct {
TimeField int64 `sql:"nn"` TimeField int64 `sql:"nn"`
} }
type TestWithJsonStructTag struct {
ID int `json:"id" sql:"pk"`
Int64Field int64 `json:"int64Field" sql:"nn"`
IntField int `json:"intField" sql:"nn"`
StringField string `json:"stringField" sql:"nn"`
}
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
log.SetupLogs("Info") log.SetupLogs("Info")
-20
View File
@@ -113,23 +113,3 @@ func TestParseCompositeFk(t *testing.T) {
t.Fail() t.Fail()
} }
} }
func TestParseStructWithJsonTag(t *testing.T) {
// GIVEN
orm := simpleorm.NewORM(TestWithJsonStructTag{})
// WHEN
ddl, err := orm.CreateSchema()
// THEN
if err != nil {
log.LogError("Failed to parse schema! %s", err)
t.Fail()
}
expectedDdl := "CREATE TABLE IF NOT EXISTS TEST_WITH_JSON_STRUCT_TAG (ID INTEGER, INT64_FIELD BIGINT NOT NULL, INT_FIELD INTEGER NOT NULL, STRING_FIELD TEXT NOT NULL, CONSTRAINT pk_test_with_json_struct_tag PRIMARY KEY(ID));"
if ddl != expectedDdl {
log.LogError("Incorrect DDL.\nExpected\n%s\nActual\n%s", expectedDdl, ddl)
log.LogError("\nExpected size: %s\nActual size: %s", strconv.Itoa(len(expectedDdl)), strconv.Itoa(len(ddl)))
t.Fail()
}
log.LogInfo("Test finished!")
}
+39 -132
View File
@@ -4,9 +4,7 @@ import (
"strconv" "strconv"
"testing" "testing"
simpleorm "git.gdulai.com/gdulai/simpleorm"
"git.gdulai.com/gdulai/simpleorm/exec" "git.gdulai.com/gdulai/simpleorm/exec"
"git.gdulai.com/gdulai/simpleorm/schema"
log "gitlab.com/gdulai/simpleloglvl" log "gitlab.com/gdulai/simpleloglvl"
) )
@@ -16,7 +14,7 @@ func TestSelectEmpty(t *testing.T) {
defer cleanUp("test.db", conn) defer cleanUp("test.db", conn)
// WHEN // WHEN
selectExec, err := exec.NewSelect[Test](orm) selectExec, err := exec.CreateSelect[Test](orm)
// THEN // THEN
if err != nil { if err != nil {
@@ -55,7 +53,7 @@ func TestSelectSingle(t *testing.T) {
return return
} }
selectExec, err := exec.NewSelect[Test](orm) selectExec, err := exec.CreateSelect[Test](orm)
if err != nil { if err != nil {
log.LogError("TestInsertAndSelectSingle setup failed: %s", err) log.LogError("TestInsertAndSelectSingle setup failed: %s", err)
t.Fail() t.Fail()
@@ -121,7 +119,7 @@ func TestSelectWithCompositePk(t *testing.T) {
return return
} }
selectExec, err := exec.NewSelect[TestWithCompositePk](orm) selectExec, err := exec.CreateSelect[TestWithCompositePk](orm)
if err != nil { if err != nil {
log.LogError("TestInsertSelectWithCompositePk setup failed: %s", err) log.LogError("TestInsertSelectWithCompositePk setup failed: %s", err)
t.Fail() t.Fail()
@@ -182,7 +180,7 @@ func TestSelectWithParam(t *testing.T) {
return return
} }
selectExec, err := exec.NewSelect[Test](orm) selectExec, err := exec.CreateSelect[Test](orm)
if err != nil { if err != nil {
log.LogError("TestInsertMultipleAndSelectWithParam setup failed: %s", err) log.LogError("TestInsertMultipleAndSelectWithParam setup failed: %s", err)
t.Fail() t.Fail()
@@ -255,7 +253,7 @@ func TestSelectWithLimitAndOffset(t *testing.T) {
} }
// WHEN // WHEN
selectExec, err := exec.NewSelect[Test](orm) selectExec, err := exec.CreateSelect[Test](orm)
if err != nil { if err != nil {
log.LogError("TestSelectWithLimitAndOffset failed: %s", err) log.LogError("TestSelectWithLimitAndOffset failed: %s", err)
t.Fail() t.Fail()
@@ -278,142 +276,51 @@ func TestSelectWithLimitAndOffset(t *testing.T) {
} }
} }
func TestSelectOrderByDesc(t *testing.T) { func TestSelectOrderBy(t *testing.T) {
// GIVEN // GIVEN
orm, conn := testSetup() orm, conn := testSetup()
defer cleanUp("test.db", conn) defer cleanUp("test.db", conn)
err := orderBySetup(conn, orm) testEntites := []Test{}
for i := 0; i < 1000; i++ {
testEntites = append(testEntites, Test{Int64Field: -1, IntField: i, StringField: "Entity " + strconv.Itoa(i)})
}
insertExec, err := exec.NewInsert[Test](orm, testEntites...)
if err != nil { if err != nil {
log.LogError("TestSelectOrderByAsc setup failed: %s", err) log.LogError("TestSelectWithLimitAndOffset setup failed: %s", err)
t.Fail() t.Fail()
return return
} }
// WHEN
selectExec, err := exec.NewSelect[Test](orm)
if err != nil {
log.LogError("TestSelectOrderByDesc failed: %s", err)
t.Fail()
return
}
selectExec.OrderBy(schema.OrderBy{Field: "StringField", Direction: "DESC"})
err = selectExec.Execute(conn)
if err != nil {
log.LogError("TestSelectOrderByDesc failed: %s", err)
t.Fail()
return
}
// THEN
var resultStr string
for _, obj := range selectExec.Results() {
resultStr += obj.StringField
}
if resultStr != "EDCBA" {
log.LogError("TestSelectOrderByDesc failed, epxected: EDCBA actual: %s", resultStr)
t.Fail()
}
}
func TestSelectOrderByAsc(t *testing.T) {
// GIVEN
orm, conn := testSetup()
defer cleanUp("test.db", conn)
err := orderBySetup(conn, orm)
if err != nil {
log.LogError("TestSelectOrderByAsc setup failed: %s", err)
t.Fail()
return
}
// WHEN
selectExec, err := exec.NewSelect[Test](orm)
if err != nil {
log.LogError("TestSelectOrderByAsc failed: %s", err)
t.Fail()
return
}
selectExec.OrderBy(schema.OrderBy{Field: "StringField", Direction: "ASC"})
err = selectExec.Execute(conn)
if err != nil {
log.LogError("TestSelectOrderByAsc failed: %s", err)
t.Fail()
return
}
// THEN
var resultStr string
for _, obj := range selectExec.Results() {
resultStr += obj.StringField
}
if resultStr != "ABCDE" {
log.LogError("TestSelectOrderByAsc failed, epxected: ABCDE actual: %s", resultStr)
t.Fail()
}
}
func TestSelectOrderByAscWithLimitAndOffset(t *testing.T) {
// GIVEN
orm, conn := testSetup()
defer cleanUp("test.db", conn)
err := orderBySetup(conn, orm)
if err != nil {
log.LogError("TestSelectOrderByAsc setup failed: %s", err)
t.Fail()
return
}
// WHEN
selectExec, err := exec.NewSelect[Test](orm)
if err != nil {
log.LogError("TestSelectOrderByAsc failed: %s", err)
t.Fail()
return
}
selectExec.OrderBy(schema.OrderBy{Field: "StringField", Direction: "ASC"}).Limit(3).Offset(0)
err = selectExec.Execute(conn)
if err != nil {
log.LogError("TestSelectOrderByAsc failed: %s", err)
t.Fail()
return
}
// THEN
var resultStr string
for _, obj := range selectExec.Results() {
resultStr += obj.StringField
}
if resultStr != "ABC" {
log.LogError("TestSelectOrderByAsc failed, epxected: ABC actual: %s", resultStr)
t.Fail()
}
}
func orderBySetup(conn *simpleorm.DBConnection, orm *simpleorm.ORM) error {
insertExec, err := exec.NewInsert[Test](orm,
Test{Int64Field: -1, IntField: 1, StringField: "C"},
Test{Int64Field: -1, IntField: 1, StringField: "D"},
Test{Int64Field: -1, IntField: 1, StringField: "E"},
Test{Int64Field: -1, IntField: 1, StringField: "A"},
Test{Int64Field: -1, IntField: 1, StringField: "B"},
)
if err != nil {
return err
}
err = insertExec.Execute(conn) err = insertExec.Execute(conn)
if err != nil { if err != nil {
return err log.LogError("TestSelectWithLimitAndOffset setup failed: %s", err)
t.Fail()
return
}
// WHEN
selectExec, err := exec.CreateSelect[Test](orm)
if err != nil {
log.LogError("TestSelectWithLimitAndOffset failed: %s", err)
t.Fail()
return
}
selectExec.OrderBy(exec.OrderBy{Column: "StringField", Direction: "ASC"})
err = selectExec.Execute(conn)
if err != nil {
log.LogError("TestSelectWithLimitAndOffset failed: %s", err)
t.Fail()
return
} }
return nil // THEN
if len(selectExec.Results()) != 100 {
log.LogError("TestSelectWithLimitAndOffset expected result size 100, actual: %s", len(selectExec.Results()))
t.Fail()
}
} }