package test // GENERATED FILE // DO NOT EDIT import ( "context" "encoding/json" "errors" "fmt" "github.com/doug-martin/goqu/v9" _ "github.com/doug-martin/goqu/v9/dialect/postgres" "github.com/doug-martin/goqu/v9/exp" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "strings" "test/crud" "time" ) type TestRepository struct { connPool *pgxpool.Pool dialect goqu.DialectWrapper } func NewTestRepository(connPool *pgxpool.Pool) *TestRepository { return &TestRepository{ connPool: connPool, dialect: goqu.Dialect("postgres"), } } func (r *TestRepository) Create(test Test) (int, error) { sql, args, err := r.dialect.Insert("test"). Prepared(true). Rows(goqu.Record{ "updated_at": time.Now(), "name": test.Name, "checked": test.Checked, "user_id": test.UserId, }). Returning("id"). ToSQL() if err != nil { crud.LogError("error creating create Test sql: %v", err) return -1, err } rows, err := r.connPool.Query(context.Background(), sql, args...) if err != nil { crud.LogError("error creating Test: %v", err) return -1, err } defer rows.Close() var id int if rows.Next() { err = rows.Scan(&id) if err != nil { crud.LogError("error scanning User: %v", err) return -1, err } } else { crud.Error("Test already exists") return -1, TestAlreadyExistsError{Test: test} } return id, nil } type TestAlreadyExistsError struct { Test Test } func (e TestAlreadyExistsError) Error() string { return fmt.Sprint("Test ", e.Test, " already exists") } func (r *TestRepository) getSelectColumns() []any { return []any{"id", "created_at", "updated_at", "name", "checked", "user_id", } } func (r *TestRepository) Read(userId int, id int) (Test, error) { crud.Debug("Getting Test by id ", id) sql, args, _ := r.dialect.From("test"). Prepared(true). Select(r.getSelectColumns()...). Where(goqu.Ex{ "id": id, "user_id": userId, }). ToSQL() rows, err := r.connPool.Query(context.Background(), sql, args...) if err != nil { crud.Error("Failed to get Test: ", err) } defer rows.Close() if rows.Next() { item, _, err := r.rowToItem(rows, false) return item, err } return Test{}, errors.New("no rows found") } type TestItemScan struct { Test RowId int Count int } func (r *TestRepository) rowToItem(rows pgx.Rows, rowId bool) (Test, int, error) { var item TestItemScan if rowId { err := rows.Scan( &item.RowId, &item.Count, &item.Id, &item.CreatedAt, &item.UpdatedAt, &item.Name, &item.Checked, &item.UserId, ) if err != nil { return Test{}, -1, err } } else { err := rows.Scan( &item.Id, &item.CreatedAt, &item.UpdatedAt, &item.Name, &item.Checked, &item.UserId, ) if err != nil { return Test{}, -1, err } } return Test{ Id: item.Id, CreatedAt: item.CreatedAt, UpdatedAt: item.UpdatedAt, Name: item.Name, Checked: item.Checked, UserId: item.UserId, }, item.Count, nil } func (r *TestRepository) Update(userId int, test Test) error { sql, args, err := r.dialect.Update("test"). Prepared(true). Set(goqu.Record{ "updated_at": time.Now(), "name": test.Name, "checked": test.Checked, "user_id": test.UserId, }). Where(goqu.Ex{ "id": test.Id, "user_id": userId, }). ToSQL() if err != nil { crud.LogError("error creating update Test sql: %v", err) return err } _, err = r.connPool.Exec(context.Background(), sql, args...) if err != nil { crud.LogError("error updating Test: %v", err) return err } return nil } func (r *TestRepository) Delete(userId int, id int) error { sql, args, err := r.dialect.Delete("test"). Prepared(true). Where(goqu.Ex{ "id": id, "user_id": userId, }). ToSQL() if err != nil { crud.LogError("error creating delete Test sql: %v", err) return err } _, err = r.connPool.Exec(context.Background(), sql, args...) if err != nil { crud.LogError("error deleting Test: %v", err) return err } return nil } type TestField string const ( TestFieldName TestField = "name" TestFieldChecked TestField = "checked" ) type TestNameFilter struct { Active bool Value string } type TestCheckedFilter struct { Active bool Value bool } type TestOrderDirection string const ( TestOrderDirectionAsc TestOrderDirection = "asc" TestOrderDirectionDesc TestOrderDirection = "desc" ) type TestReferences struct { UserId int } type TestPaginationParams struct { RowId int PageSize int OrderBy TestField OrderDirection TestOrderDirection NameFilter TestNameFilter CheckedFilter TestCheckedFilter References TestReferences } func (r *TestRepository) GetPage(params TestPaginationParams) ([]Test, int, error) { var orderByWindow exp.WindowExpression if params.OrderDirection == TestOrderDirectionAsc { orderByWindow = goqu.W().OrderBy(goqu.C(string(params.OrderBy)).Asc()) } else { orderByWindow = goqu.W().OrderBy(goqu.C(string(params.OrderBy)).Desc()) } selectColumns := []any{ goqu.ROW_NUMBER().Over(orderByWindow).As("row_id"), goqu.COUNT("*"), } selectColumns = append(selectColumns, r.getSelectColumns()...) whereExpressions := []goqu.Expression{ goqu.Ex{ "user_id": params.References.UserId, }, } whereExpressions = r.addPageFilters(params, whereExpressions) var colOrder exp.OrderedExpression if params.OrderDirection == TestOrderDirectionAsc { colOrder = goqu.C(string(params.OrderBy)).Asc() } else { colOrder = goqu.C(string(params.OrderBy)).Desc() } dialect := goqu.Dialect("postgres") innerFrom := dialect.From("test"). Prepared(true). Select(selectColumns...). Where(whereExpressions...). Order(colOrder) sql, args, _ := dialect.From(innerFrom). Prepared(true). Where(goqu.Ex{"row_id": goqu.Op{"gt": params.RowId}}). Limit(uint(params.PageSize)). ToSQL() sql = strings.Replace(sql, "COUNT(*)", "COUNT(*) over()", 1) rows, err := r.connPool.Query(context.Background(), sql, args...) if err != nil { crud.LogError("failed to run sql query: %v", err) return nil, -1, err } defer rows.Close() results := make([]Test, 0) totalCount := 0 for rows.Next() { parsed, count, err := r.rowToItem(rows, true) if err != nil { return nil, -1, err } totalCount = count results = append(results, parsed) } return results, totalCount, nil } func (r *TestRepository) addPageFilters(params TestPaginationParams, whereExpressions []goqu.Expression) []goqu.Expression { if params.NameFilter.Active { whereExpressions = append(whereExpressions, goqu.Ex{ "name": goqu.Op{"like": fmt.Sprint("%", params.NameFilter.Value, "%")}, }) } if params.CheckedFilter.Active { whereExpressions = append(whereExpressions, goqu.Ex{ "checked": params.CheckedFilter.Value, }) } return whereExpressions } func (r *TestRepository) jsonToString(jsonData any) string { bytes, err := json.Marshal(jsonData) if err != nil { return "{}" } return string(bytes) } func (r *TestRepository) FirstLetterToUpper(name string) string { return strings.ToUpper(name[:1]) + name[1:] }