### Install Goquent Package Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Use 'go get' to install the Goquent library into your project. ```bash go get github.com/alimm/goquent ``` -------------------------------- ### Complete Goquent Publishing Example Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_2.md A comprehensive example demonstrating the entire process from initializing the repository and committing changes to tagging the release and performing a manual fetch. Includes a `sed` command to ensure the module path is correctly set. ```bash # 1. Change module path to your GitHub username sed -i 's/github.com/alimmughanil/github.com/alimmughanil/g' go.mod USE gh commands check in mvp context7 # 2. Commit & push git init git add . git branch -M main git commit -m "Initial release of goquent - Laravel-like ORM for Go" git remote add origin https://github.com/alimmughanil/goquent.git git push -u origin main # 3. Tag release git tag v0.1.0 git push origin v0.1.0 # 4. Manual fetch (instant) curl https://proxy.golang.org/github.com/alimmughanil/goquent/@v/v0.1.0.info # 5. Open in browser # https://pkg.go.dev/github.com/alimmughanil/goquent ``` -------------------------------- ### Install Database Drivers Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Install the necessary GORM database drivers for your chosen database system. ```bash # For SQLite go get gorm.io/driver/sqlite # For MySQL go get gorm.io/driver/mysql # For PostgreSQL go get gorm.io/driver/postgres # For SQL Server go get gorm.io/driver/sqlserver ``` -------------------------------- ### Begin a Transaction Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Start a new database transaction using `Begin`. This returns a `Querier` interface that can be used for operations within the transaction. ```go func (q *Query) Begin(opts ...*sql.TxOptions) (contracts.Querier, error) { tx := q.db.Begin(opts...) if tx.Error != nil { return nil, tx.Error } return newQuery(tx), nil } ``` -------------------------------- ### Install Goquent ORM Source: https://github.com/alimmughanil/goquent/blob/main/README.md Install the Goquent ORM package using go get. You will also need to install a database driver. ```bash go get github.com/alimmughanil/goquent ``` ```bash # For SQLite go get gorm.io/driver/sqlite # For MySQL go get gorm.io/driver/mysql # For PostgreSQL go get gorm.io/driver/postgres ``` -------------------------------- ### Integrate Goquent with Gin Source: https://github.com/alimmughanil/goquent/blob/main/README.md Example of integrating Goquent with the Gin web framework. Demonstrates handling GET requests with pagination. ```go package main import ( "strconv" "github.com/gin-gonic/gin" "github.com/alimmughanil/goquent" "gorm.io/driver/sqlite" ) func main() { goquent.Init(sqlite.Open("app.db")) goquent.Instance().AutoMigrate(&User{}) r := gin.Default() r.GET("/users", func(c *gin.Context) { page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) perPage, _ := strconv.Atoi(c.DefaultQuery("per_page", "10")) var users []User paginator, err := goquent.Query().ForPage(page, perPage).Paginate(perPage, &users) if err != nil { c.JSON(500, gin.H{"error": err.Error()}); return } c.JSON(200, paginator.ToMap()) }) r.Run(":8080") } ``` -------------------------------- ### Initialize Goquent with Configuration Object Source: https://github.com/alimmughanil/goquent/blob/main/docs/structures/overview.md Initialize Goquent using a ConnectionConfig object for more detailed setup, including driver, DSN, and log level. ```go goquent.InitWithConfig(&contracts.ConnectionConfig{ Driver: "postgres", DSN: "host=localhost user=db pass=db dbname=test port=5432", LogLevel: 4, // 1: Silent, 2: Error, 3: Warn, 4: Info }) ``` -------------------------------- ### Explain SQL Query Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Use `Explain` to get the execution plan for the generated SQL query. This helps in optimizing query performance. ```go func (q *Query) Explain() (string, error) { var result string err := q.db.Raw("EXPLAIN " + q.ToSQL()).Scan(&result).Error return result, err } ``` -------------------------------- ### Integrate Goquent with Fiber (v3) Source: https://github.com/alimmughanil/goquent/blob/main/README.md Example of integrating Goquent with the Fiber web framework. Demonstrates handling GET requests with pagination. ```go package main import ( "log" "github.com/gofiber/fiber/v3" "github.com/alimmughanil/goquent" "gorm.io/driver/sqlite" ) func main() { goquent.Init(sqlite.Open("app.db")) goquent.Instance().AutoMigrate(&User{}) app := fiber.New() app.Get("/users", func(c fiber.Ctx) error { var users []User // Pagination built-in! page := c.QueryInt("page", 1) perPage := c.QueryInt("per_page", 10) paginator, err := goquent.Query().ForPage(page, perPage).Paginate(perPage, &users) if err != nil { return c.Status(500).JSON(fiber.Map{"error": err.Error()}) } return c.JSON(paginator.ToMap()) }) log.Fatal(app.Listen(":3000")) } ``` -------------------------------- ### Manually Fetch to pkg.go.dev Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_2.md Instantly fetch your module to pkg.go.dev by running the 'go get' command with specific proxy and module settings. This bypasses the automatic indexing wait time. ```bash GOPROXY=https://proxy.golang.org GO111MODULE=on go get github.com/alimmughanil/goquent@v0.1.0 ``` -------------------------------- ### Get Singleton Database Instance Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Retrieves the globally initialized singleton database instance. Panics if the database has not been initialized. ```APIDOC ## Instance ### Description Returns the singleton `*DB` instance. It panics if `Init()` or `InitWithConfig()` has not been called prior to this. ### Signature `func Instance() *DB` ### Returns - `*DB`: The singleton database instance. ### Panics - If the database has not been initialized. ``` -------------------------------- ### Gin Web Server with Goquent Integration Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md This Go code sets up a Gin web server and integrates Goquent for database operations. It includes endpoints for creating, reading, updating, deleting, searching, and paginating user data, as well as handling transactions. Ensure Goquent is initialized and models are migrated before starting the server. ```go package main import ( "net/http" "strconv" "github.com/gin-gonic/gin" "github.com/alimm/goquent" "github.com/alimm/goquent/contracts" "github.com/alimm/goquent/examples/gin/models" "gorm.io/driver/sqlite" ) func main() { goquent.Init(sqlite.Open("gin_app.db")) goquent.Instance().AutoMigrate( &models.User{}, &models.Post{}, &models.Profile{}, &models.Comment{}, &models.Role{}, ) r := gin.Default() r.GET("/users", func(c *gin.Context) { page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) perPage, _ := strconv.Atoi(c.DefaultQuery("per_page", "10")) var users []models.User paginator, err := goquent.Query().With("Profile", "Posts").OrderBy("created_at", "desc").ForPage(page, perPage).Paginate(perPage, &users) if err != nil { c.JSON(500, gin.H{"error": err.Error()}); return } c.JSON(200, paginator.ToMap()) }) r.GET("/users/:id", func(c *gin.Context) { var user models.User if err := goquent.Query().With("Profile", "Posts.Comments", "Roles").First(&user, c.Param("id")); err != nil { c.JSON(404, gin.H{"error": "User not found"}); return } c.JSON(200, user) }) r.POST("/users", func(c *gin.Context) { var user models.User if err := c.ShouldBindJSON(&user); err != nil { c.JSON(400, gin.H{"error": err.Error()}); return } if err := goquent.Query().Create(&user); err != nil { c.JSON(500, gin.H{"error": err.Error()}); return } c.JSON(201, user) }) r.PUT("/users/:id", func(c *gin.Context) { var user models.User if err := goquent.Query().First(&user, c.Param("id")); err != nil { c.JSON(404, gin.H{"error": "User not found"}); return } var updates models.User c.ShouldBindJSON(&updates) goquent.Query().Model(&user).Updates(&updates) c.JSON(200, user) }) r.DELETE("/users/:id", func(c *gin.Context) { var user models.User goquent.Query().First(&user, c.Param("id")) goquent.Query().Delete(&user) c.JSON(200, gin.H{"message": "User deleted"}) }) r.GET("/users/search", func(c *gin.Context) { q := goquent.Query() if name := c.Query("name"); name != "" { q = q.Where("name LIKE ?", "%"+name+"%") } if email := c.Query("email"); email != "" { q = q.Where("email LIKE ?", "%"+email+"%") } var users []models.User q.Find(&users) c.JSON(200, users) }) r.GET("/users/adults", func(c *gin.Context) { var users []models.User goquent.Query().Scopes(models.AdultScope, models.ActiveScope).Find(&users) c.JSON(200, users) }) r.POST("/transfer", func(c *gin.Context) { err := goquent.Transaction(func(tx contracts.Querier) error { return nil }) if err != nil { c.JSON(500, gin.H{"error": err.Error()}); return } c.JSON(200, gin.H{"message": "Success"}) }) r.Run(":8080") } ``` -------------------------------- ### Get User Statistics (Count and Average Age) Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Performs database aggregations to count the total number of users and calculate the average age of all users. ```go // GET /users/stats (Aggregation) app.Get("/users/stats", func(c fiber.Ctx) error { var total int64 var avgAge float64 goquent.Query().Model(&models.User{}).Count(&total) goquent.Query().Model(&models.User{}).Avg("age", &avgAge) return c.JSON(fiber.Map{"total_users": total, "average_age": avgAge}) }) ``` -------------------------------- ### Date and Time Utility Functions Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Provides functions for getting the current time, today's date (midnight), yesterday's date, and tomorrow's date. ```go func Now() time.Time { return time.Now() } func Today() time.Time { now := time.Now() return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) } func Yesterday() time.Time { return Today().AddDate(0, 0, -1) } func Tomorrow() time.Time { return Today().AddDate(0, 0, 1) } ``` -------------------------------- ### Goquent Project File Structure Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Overview of the directory and file layout for the Goquent project. This structure organizes source code, examples, and tests. ```text goquent/ ├── go.mod # Module definition ├── README.md # Documentation ├── IMPLEMENTATION_PLAN.md # This file │ ├── contracts/ │ └── orm.go # Interface contracts (Querier, Paginator, etc) │ db.go # Entry point, singleton, multi-connection query.go # Core query builder (80+ methods) model.go # Base Model, SoftDeletes, Timestamps paginator.go # Pagination (Offset, Simple, Cursor) helper.go # Utilities & error helpers │ ├── examples/ │ ├── fiber/ │ │ ├── main.go # Complete Fiber API example │ │ └── models/ │ │ └── user.go # Models with relationships │ └── gin/ │ ├── main.go # Complete Gin API example │ └── models/ │ └── user.go # Same models (framework agnostic) │ └── tests/ └── query_test.go # Unit tests ``` -------------------------------- ### Get Users with Scopes (Adults and Active) Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Retrieves users that satisfy multiple conditions defined by scopes, such as being an adult and active. Requires predefined scopes in the models. ```go // GET /users/adults (Scopes) app.Get("/users/adults", func(c fiber.Ctx) error { var users []models.User goquent.Query().Scopes(models.AdultScope, models.ActiveScope).Find(&users) return c.JSON(users) }) ``` -------------------------------- ### Pagination with Limit and Offset in Goquent Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Control the number of records returned and their starting position using `Limit`, `Offset`, and `ForPage`. `ForPage` is a convenience method for calculating offset based on page number and items per page. ```Go func (q *Query) Limit(limit int) contracts.Querier { q.db = q.db.Limit(limit) return q } ``` ```Go func (q *Query) Offset(offset int) contracts.Querier { q.db = q.db.Offset(offset) return q } ``` ```Go func (q *Query) ForPage(page, perPage int) contracts.Querier { q.db = q.db.Offset((page - 1) * perPage).Limit(perPage) return q } ``` -------------------------------- ### Query Execution Methods in Goquent Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Execute queries and retrieve results. Methods include fetching single records (`First`, `FirstOrCreate`, `FirstOrNew`), multiple records (`Find`, `Get`), specific columns (`Pluck`, `Value`), and aggregate functions (`Count`, `Max`, `Min`, `Avg`, `Sum`). ```Go func (q *Query) First(dest interface{}, conds ...interface{}) error { return q.db.First(dest, conds...).Error } ``` ```Go func (q *Query) FirstOrCreate(dest interface{}, conds ...interface{}) error { return q.db.FirstOrCreate(dest, conds...).Error } ``` ```Go func (q *Query) FirstOrNew(dest interface{}, conds ...interface{}) error { return q.db.FirstOrInit(dest, conds...).Error } ``` ```Go func (q *Query) Find(dest interface{}, conds ...interface{}) error { return q.db.Find(dest, conds...).Error } ``` ```Go func (q *Query) Get(dest interface{}) error { return q.db.Find(dest).Error } ``` ```Go func (q *Query) Pluck(column string, dest interface{}) error { return q.db.Pluck(column, dest).Error } ``` ```Go func (q *Query) Value(column string, dest interface{}) error { return q.db.Select(column).Row().Scan(dest) } ``` ```Go func (q *Query) Count(count *int64) error { return q.db.Count(count).Error } ``` ```Go func (q *Query) Max(column string, dest interface{}) error { return q.db.Select("MAX(" + column + ")").Row().Scan(dest) } ``` ```Go func (q *Query) Min(column string, dest interface{}) error { return q.db.Select("MIN(" + column + ")").Row().Scan(dest) } ``` ```Go func (q *Query) Avg(column string, dest interface{}) error { return q.db.Select("AVG(" + column + ")").Row().Scan(dest) } ``` ```Go func (q *Query) Sum(column string, dest interface{}) error { return q.db.Select("SUM(" + column + ")").Row().Scan(dest) } ``` -------------------------------- ### Get Paginated Users Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Fetches a paginated list of users, ordered by creation date in descending order. Supports query parameters for page number and items per page. ```go // GET /users app.Get("/users", func(c fiber.Ctx) error { page := c.QueryInt("page", 1) perPage := c.QueryInt("per_page", 10) var users []models.User paginator, err := goquent.Query().With("Profile", "Posts").OrderBy("created_at", "desc").ForPage(page, perPage).Paginate(perPage, &users) if err != nil { return c.Status(500).JSON(fiber.Map{"error": err.Error()}) } return c.JSON(paginator.ToMap()) }) ``` -------------------------------- ### Get User by ID with Relations Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Retrieves a single user by their ID, including their profile, posts, comments on posts, and roles. Handles user not found errors. ```go // GET /users/:id app.Get("/users/:id", func(c fiber.Ctx) error { var user models.User err := goquent.Query().With("Profile", "Posts.Comments", "Roles").First(&user, c.Params("id")) if err != nil { if goquent.IsNotFoundError(err) { return c.Status(404).JSON(fiber.Map{"error": "User not found"}) } return c.Status(500).JSON(fiber.Map{"error": err.Error()}) } return c.JSON(user) }) ``` -------------------------------- ### Initialize and Push to GitHub Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_2.md Initialize a new Git repository, add files, commit, set the remote origin, and push to the main branch. Ensure the module name in go.mod matches the GitHub repository URL. ```bash # Replace with your GitHub username git init git add . git commit -m "Initial release" git remote add origin https://github.com/alimmughanil/goquent.git git push -u origin main ``` ```go module github.com/alimmughanil/goquent ``` -------------------------------- ### Initialize Goquent with Simple Configuration Source: https://github.com/alimmughanil/goquent/blob/main/docs/structures/overview.md Initialize the global Goquent singleton in main.go before making queries. Pass a GORM dialector and optionally auto-migrate models. ```go import ( "github.com/alimmughanil/goquent" "gorm.io/driver/sqlite" // or mysql, postgres ) func main() { // Pass a GORM dialector err := goquent.Init(sqlite.Open("app.db")) // Auto-migrate models goquent.Instance().AutoMigrate(&User{}) } ``` -------------------------------- ### Limit & Offset Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Methods for controlling the number of records returned and their starting position. ```APIDOC ## Limit and Offset Methods ### Description Methods to control pagination and the number of results. ### Methods - `Limit(limit int) contracts.Querier`: Sets the maximum number of records to retrieve. - `Offset(offset int) contracts.Querier`: Sets the number of records to skip from the beginning. - `ForPage(page int, perPage int) contracts.Querier`: Calculates and applies offset and limit for a specific page. ``` -------------------------------- ### Initialize Goquent DB with Configuration Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Initializes the Goquent database instance using a provided connection configuration. Supports multiple drivers like SQLite, MySQL, PostgreSQL, and SQL Server. Configures connection pooling and logging levels. ```go package goquent import ( "context" "database/sql" "fmt" "sync" "time" "gorm.io/driver/mysql" "gorm.io/driver/postgres" "gorm.io/driver/sqlite" "gorm.io/driver/sqlserver" "gorm.io/gorm" "gorm.io/gorm/logger" "github.com/alimm/goquent/contracts" ) var ( instance *DB once sync.Once ) type DB struct { gormDB *gorm.DB config *contracts.ConnectionConfig query *Query connections map[string]*gorm.DB mu sync.RWMutex } func Open(dialector gorm.Dialector, opts ...gorm.Option) (*DB, error) { db := &DB{connections: make(map[string]*gorm.DB)} gormDB, err := gorm.Open(dialector, opts...) if err != nil { return nil, fmt.Errorf("failed to open database: %w", err) } db.gormDB = gormDB db.query = newQuery(gormDB) return db, nil } func Init(dialector gorm.Dialector, opts ...gorm.Option) error { var err error once.Do(func() { instance, err = Open(dialector, opts...) }) return err } func InitWithConfig(config *contracts.ConnectionConfig) error { var dialector gorm.Dialector var logLevel logger.LogLevel switch config.LogLevel { case 1: logLevel = logger.Silent case 2: logLevel = logger.Error case 3: logLevel = logger.Warn default: logLevel = logger.Info } sswitch config.Driver { case "sqlite", "sqlite3": dialector = sqlite.Open(config.DSN) case "mysql": dialector = mysql.Open(config.DSN) case "postgres", "postgresql": dialector = postgres.Open(config.DSN) case "sqlserver", "mssql": dialector = sqlserver.Open(config.DSN) default: return fmt.Errorf("unsupported driver: %s", config.Driver) } db, err := Open(dialector, &gorm.Config{Logger: logger.Default.LogMode(logLevel)}) if err != nil { return err } sqlDB, err := db.gormDB.DB() if err != nil { return err } if config.MaxOpenConns > 0 { sqlDB.SetMaxOpenConns(config.MaxOpenConns) } if config.MaxIdleConns > 0 { sqlDB.SetMaxIdleConns(config.MaxIdleConns) } if config.ConnMaxLifetime > 0 { sqlDB.SetConnMaxLifetime(time.Duration(config.ConnMaxLifetime) * time.Second) } if config.ConnMaxIdleTime > 0 { sqlDB.SetConnMaxIdleTime(time.Duration(config.ConnMaxIdleTime) * time.Second) } instance = db return nil } func Instance() *DB { if instance == nil { panic("goquent: database not initialized. Call Init() first") } return instance } func IsInitialized() bool { return instance != nil } func Query() contracts.Querier { return Instance().Query() } func (db *DB) Query() contracts.Querier { return newQuery(db.gormDB) } func (db *DB) GormDB() *gorm.DB { return db.gormDB } func (db *DB) AddConnection(name string, dialector gorm.Dialector, opts ...gorm.Option) error { db.mu.Lock() defer db.mu.Unlock() gormDB, err := gorm.Open(dialector, opts...) if err != nil { return fmt.Errorf("failed to open connection %s: %w", name, err) } db.connections[name] = gormDB return nil } func (db *DB) Connection(name string) contracts.Querier { db.mu.RLock() defer db.mu.RUnlock() gormDB, ok := db.connections[name] if !ok { panic(fmt.Sprintf("goquent: connection %s not found", name)) } return newQuery(gormDB) } func (db *DB) Close() error { sqlDB, err := db.gormDB.DB() if err != nil { return err } return sqlDB.Close() } func (db *DB) Ping() error { sqlDB, err := db.gormDB.DB() if err != nil { return err } return sqlDB.Ping() } func (db *DB) Stats() sql.DBStats { sqlDB, err := db.gormDB.DB() if err != nil { return sql.DBStats{} } return sqlDB.Stats() } func (db *DB) AutoMigrate(dst ...interface{}) error { return db.gormDB.AutoMigrate(dst...) } func (db *DB) SetLogger(l logger.Interface) { db.gormDB.Logger = l } func Transaction(fc func(tx contracts.Querier) error, opts ...*sql.TxOptions) error { return Instance().Transaction(fc, opts...) } func (db *DB) Transaction(fc func(tx contracts.Querier) error, opts ...*sql.TxOptions) error { return db.gormDB.Transaction(func(tx *gorm.DB) error { return fc(newQuery(tx)) }, opts...) } func WithContext(ctx context.Context) contracts.Querier { return Instance().Query().WithContext(ctx) } ``` -------------------------------- ### Get SQL Statement Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md The `ToSQL` method returns the generated SQL statement for the current query. This is useful for debugging or logging. ```go func (q *Query) ToSQL() string { stmt := q.db.Statement return stmt.SQL.String() } ``` -------------------------------- ### Add pkg.go.dev Badge to README Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_2.md Include a badge in your README file that links directly to your module's documentation on pkg.go.dev. This provides a quick reference for users. ```markdown [![Go Reference](https://pkg.go.dev/badge/github.com/alimmughanil/goquent.svg)](https://pkg.go.dev/github.com/alimmughanil/goquent) ``` -------------------------------- ### Initialize Database with Connection Configuration Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Initializes the database connection using a detailed `ConnectionConfig` struct, allowing for driver selection, DSN, log level, and connection pool settings. ```APIDOC ## InitWithConfig ### Description Initializes the global singleton database instance using a `contracts.ConnectionConfig`. This method supports various database drivers (sqlite, mysql, postgres, sqlserver) and configures connection pooling and logging. ### Signature `func InitWithConfig(config *contracts.ConnectionConfig) error` ### Parameters - `config` (*contracts.ConnectionConfig): A struct containing database connection details like Driver, DSN, LogLevel, MaxOpenConns, etc. ### Returns - `error`: An error if the driver is unsupported or the connection fails. ``` -------------------------------- ### Perform Database Transaction Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Executes a block of database operations within a transaction. Ensures atomicity, where all operations succeed or none are applied. The provided example is a placeholder. ```go // POST /transfer (Transaction) app.Post("/transfer", func(c fiber.Ctx) error { err := goquent.Transaction(func(tx contracts.Querier) error { // Transaction logic return nil }) if err != nil { return c.Status(500).JSON(fiber.Map{"error": err.Error()}) } return c.JSON(fiber.Map{"message": "Success"}) }) ``` -------------------------------- ### Go: Test CRUD Operations with Goquent Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Demonstrates creating, reading, updating, and deleting user records using Goquent's Query interface. Ensure the database is initialized and models are migrated before running. ```go package tests import ( testify "github.com/stretchr/testify/assert" "github.com/alimm/goquent" "gorm.io/driver/sqlite" "testing" ) type TestUser struct { goquent.Model Name string Email string `gorm:"unique"` Age int } func TestCRUD(t *testing.T) { goquent.Init(sqlite.Open(":memory:")) goquent.Instance().AutoMigrate(&TestUser{}) // Create user := TestUser{Name: "John", Email: "john@test.com", Age: 25} err := goquent.Query().Create(&user) assert.NoError(t, err) assert.NotZero(t, user.ID) // Read var found TestUser err = goquent.Query().First(&found, user.ID) assert.NoError(t, err) assert.Equal(t, "John", found.Name) // Update err = goquent.Query().Model(&found).Update("age", 26) assert.NoError(t, err) // Delete err = goquent.Query().Delete(&found) assert.NoError(t, err) } ``` -------------------------------- ### Initialize Singleton Database Instance Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Initializes the global singleton instance of the database connection. This should be called once during application startup. ```APIDOC ## Init ### Description Initializes the global singleton instance of the database connection using the provided GORM dialector and options. This function uses `sync.Once` to ensure it's only executed once. ### Signature `func Init(dialector gorm.Dialector, opts ...gorm.Option) error` ### Parameters - `dialector` (gorm.Dialector): The database driver and connection string. - `opts` ([]gorm.Option): Optional GORM configuration settings. ### Returns - `error`: An error if the initialization fails. ``` -------------------------------- ### Initialize Goquent Connection Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Initialize the Goquent database connection using either a simple method with a DSN or a detailed configuration object. ```go package main import ( "github.com/alimm/goquent" "gorm.io/driver/sqlite" ) func main() { // Simple initialization err := goquent.Init(sqlite.Open("app.db")) if err != nil { panic(err) } // Or with config goquent.InitWithConfig(&goquent.ConnectionConfig{ Driver: "sqlite", DSN: "app.db", MaxOpenConns: 10, MaxIdleConns: 5, ConnMaxLifetime: 3600, LogLevel: 4, // Info }) } ``` -------------------------------- ### Tag with Semantic Version Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_2.md Tag the first release using semantic versioning (e.g., v0.1.0) and push the tag to the remote repository. pkg.go.dev only recognizes semver tags. ```bash # Tag first release git tag v0.1.0 git push origin v0.1.0 ``` -------------------------------- ### Add WHERE BETWEEN Clause Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Use `WhereBetween` to filter records where a column's value falls within a specified range (inclusive). Provide the column name and the start and end values. ```go func (q *Query) WhereBetween(column string, start, end interface{}) contracts.Querier { q.db = q.db.Where(column+" BETWEEN ? AND ?", start, end) return q } ``` -------------------------------- ### Initialize Goquent Database Connection Source: https://github.com/alimmughanil/goquent/blob/main/README.md Initialize the database connection using Init() before making any queries. This should be done once during application startup. AutoMigrate can be used to create database tables based on your models. ```go package main import ( "log" "github.com/alimmughanil/goquent" "gorm.io/driver/sqlite" ) func main() { err := goquent.Init(sqlite.Open("app.db")) if err != nil { log.Fatal("Failed to initialize database:", err) } // Automatically migrate your models goquent.Instance().AutoMigrate(&User{}) } ``` -------------------------------- ### ConnectionConfig Struct Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Configuration options for establishing a database connection. ```APIDOC ## ConnectionConfig Struct ### Fields - **Driver (string)**: The database driver to use (e.g., "mysql", "postgres"). - **DSN (string)**: The Data Source Name for the connection. - **MaxOpenConns (int)**: The maximum number of open connections. - **MaxIdleConns (int)**: The maximum number of idle connections. - **ConnMaxLifetime (int)**: The maximum lifetime of a connection in seconds. - **ConnMaxIdleTime (int)**: The maximum idle time of a connection in seconds. - **LogLevel (int)**: The log level for database operations. ``` -------------------------------- ### Create Records in Batches Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Use `CreateInBatches` for efficient insertion of multiple records. Specify the number of records per batch. ```go func (q *Query) CreateInBatches(value interface{}, batchSize int) error { return q.db.CreateInBatches(value, batchSize).Error } ``` -------------------------------- ### Simple Pagination Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Use `SimplePaginate` for basic pagination where only the next page's records are fetched. It's more efficient if you don't need the total count upfront. ```go func (q *Query) SimplePaginate(pageSize int, dest interface{}) (contracts.Paginator, error) { page := 1 if err := q.db.Offset((page - 1) * pageSize).Limit(pageSize + 1).Find(dest).Error; err != nil { return nil, err } return NewSimplePaginator(dest, pageSize, page), nil } ``` -------------------------------- ### Standard Paginator Implementation Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Implements a standard paginator with total item count, current page, and per-page settings. Provides methods for navigating pages and generating URLs. ```go package goquent import ( "fmt" "math" "github.com/alimm/goquent/contracts" ) type paginator struct { items interface{} total int64 perPage int currentPage int } func NewPaginator(items interface{}, total int64, perPage, currentPage int) contracts.Paginator { if currentPage < 1 { currentPage = 1 } return &paginator{items: items, total: total, perPage: perPage, currentPage: currentPage} } func (p *paginator) Items() interface{} { return p.items } func (p *paginator) Total() int64 { return p.total } func (p *paginator) PerPage() int { return p.perPage } func (p *paginator) CurrentPage() int { return p.currentPage } func (p *paginator) LastPage() int { if p.perPage == 0 { return 1 } return int(math.Ceil(float64(p.total) / float64(p.perPage))) } func (p *paginator) HasMorePages() bool { return p.currentPage < p.LastPage() } func (p *paginator) NextPageURL() *string { if !p.HasMorePages() { return nil } url := fmt.Sprintf("?page=%d&per_page=%d", p.currentPage+1, p.perPage) return &url } func (p *paginator) PreviousPageURL() *string { if p.currentPage <= 1 { return nil } url := fmt.Sprintf("?page=%d&per_page=%d", p.currentPage-1, p.perPage) return &url } func (p *paginator) Links() []contracts.PageLink { links := make([]contracts.PageLink, 0) lastPage := p.LastPage() prevURL := p.PreviousPageURL() links = append(links, contracts.PageLink{URL: prevURL, Label: "« Previous", Active: false}) for i := 1; i <= lastPage; i++ { url := fmt.Sprintf("?page=%d&per_page=%d", i, p.perPage) links = append(links, contracts.PageLink{URL: &url, Label: fmt.Sprintf("%d", i), Active: i == p.currentPage}) } nextURL := p.NextPageURL() links = append(links, contracts.PageLink{URL: nextURL, Label: "Next »", Active: false}) return links } func (p *paginator) ToMap() map[string]interface{} { return map[string]interface{}{ "data": p.items, "total": p.total, "per_page": p.perPage, "current_page": p.currentPage, "last_page": p.LastPage(), "from": (p.currentPage-1)*p.perPage + 1, "to": min(int64(p.currentPage*p.perPage), p.total), "links": p.Links(), "next_page_url": p.NextPageURL(), "prev_page_url": p.PreviousPageURL(), } } ``` -------------------------------- ### Perform CRUD Operations Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Demonstrates basic Create, Read, Update, and Delete operations using the Goquent Query Builder. ```go // Create user := User{Name: "John", Email: "john@example.com"} goquent.Query().Create(&user) // Read var users []User goquent.Query().Where("active", true).Find(&users) // Update goquent.Query().Model(&user).Update("name", "John Doe") // Delete goquent.Query().Delete(&user) ``` -------------------------------- ### Cursor-Based Pagination Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Implement cursor pagination with `CursorPaginate`. This method is efficient for large datasets and allows for forward/backward navigation using cursors. ```go func (q *Query) CursorPaginate(perPage int, dest interface{}) (contracts.CursorPaginator, error) { if err := q.db.Limit(perPage + 1).Find(dest).Error; err != nil { return nil, err } return NewCursorPaginator(dest, perPage), nil } ``` -------------------------------- ### WithContext() Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Creates a query builder that uses the provided context, operating on the global singleton instance. ```APIDOC ## WithContext ### Description Returns a `contracts.Querier` that is associated with the given `context.Context`. This allows for context-aware database operations, such as timeouts or cancellation, using the global singleton instance. ### Signature `func WithContext(ctx context.Context) contracts.Querier` ### Parameters - `ctx` (context.Context): The context to associate with the query. ### Returns - `contracts.Querier`: A query interface bound to the provided context. ``` -------------------------------- ### Process Records in Chunks (Default Size) Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md The `Each` method is a convenience wrapper around `Chunk` that processes records in batches of 1000. ```go func (q *Query) Each(fc func(rows contracts.Rows) error) error { return q.Chunk(1000, fc) } ``` -------------------------------- ### Select Specific Columns Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Use the `Select` method to specify which columns to retrieve from the database. This can improve performance by reducing the amount of data transferred. ```go func (q *Query) Select(columns ...string) contracts.Querier { q.db = q.db.Select(columns) return q } ``` -------------------------------- ### Simple Paginator Implementation Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Implements a simplified paginator that does not track the total number of items or last page. Useful when total count is unknown or not needed. ```go type simplePaginator struct { items interface{} perPage int currentPage int hasMore bool } func NewSimplePaginator(items interface{}, perPage, currentPage int) contracts.Paginator { return &simplePaginator{items: items, perPage: perPage, currentPage: currentPage, hasMore: false} } func (p *simplePaginator) Items() interface{} { return p.items } func (p *simplePaginator) Total() int64 { return -1 } func (p *simplePaginator) PerPage() int { return p.perPage } func (p *simplePaginator) CurrentPage() int { return p.currentPage } func (p *simplePaginator) LastPage() int { return -1 } func (p *simplePaginator) HasMorePages() bool { return p.hasMore } func (p *simplePaginator) NextPageURL() *string { return nil } func (p *simplePaginator) PreviousPageURL() *string { return nil } func (p *simplePaginator) Links() []contracts.PageLink { return nil } func (p *simplePaginator) ToMap() map[string]interface{} { return map[string]interface{}{"data": p.items, "per_page": p.perPage, "current_page": p.currentPage, "has_more": p.hasMore} } ``` -------------------------------- ### Create a New User Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Creates a new user record in the database. Handles request body binding and checks for duplicate email errors. ```go // POST /users app.Post("/users", func(c fiber.Ctx) error { var user models.User if err := c.Bind().Body(&user); err != nil { return c.Status(400).JSON(fiber.Map{"error": err.Error()}) } if err := goquent.Query().Create(&user); err != nil { if goquent.IsDuplicateKeyError(err) { return c.Status(409).JSON(fiber.Map{"error": "Email already exists"}) } return c.Status(500).JSON(fiber.Map{"error": err.Error()}) } return c.Status(201).JSON(user) }) ``` -------------------------------- ### Create a Single Record Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Use the `Create` method to insert a single record into the database. Ensure the value is a pointer to a struct. ```go func (q *Query) Create(value interface{}) error { return q.db.Create(value).Error } ``` -------------------------------- ### Initialize Goquent and Migrate Models Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Initializes the Goquent ORM with a SQLite database and performs automatic migrations for defined models. Ensure the database file path is correct. ```go package main import ( "log" "github.com/gofiber/fiber/v3" "github.com/alimm/goquent" "github.com/alimm/goquent/contracts" "github.com/alimm/goquent/examples/fiber/models" "gorm.io/driver/sqlite" ) func main() { err := goquent.Init(sqlite.Open("fiber_app.db")) if err != nil { log.Fatal("Failed to initialize database:", err) } goquent.Instance().AutoMigrate( &models.User{}, &models.Post{}, &models.Profile{}, &models.Comment{}, &models.Role{}, ) app := fiber.New() // ... rest of the application } ``` -------------------------------- ### Create a Savepoint Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Create a `SavePoint` within a transaction. This allows for partial rollback to a specific point without aborting the entire transaction. ```go func (q *Query) SavePoint(name string) error { return q.db.SavePoint(name).Error } ``` -------------------------------- ### Open Database Connection Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Opens a new database connection using a specified GORM dialector and options. This is a foundational step for interacting with the database. ```APIDOC ## Open ### Description Opens a new database connection using a specified GORM dialector and options. ### Signature `func Open(dialector gorm.Dialector, opts ...gorm.Option) (*DB, error)` ### Parameters - `dialector` (gorm.Dialector): The database driver and connection string. - `opts` ([]gorm.Option): Optional GORM configuration settings. ### Returns - `*DB`: A pointer to the initialized DB struct. - `error`: An error if the connection fails. ``` -------------------------------- ### DB.AutoMigrate() Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Performs automatic database schema migration for the given Go structs. ```APIDOC ## DB.AutoMigrate() ### Description Automatically migrates the database schema based on the provided Go struct types. This is useful for creating or updating tables. ### Signature `func (db *DB) AutoMigrate(dst ...interface{}) error` ### Parameters - `dst` ([]interface{}): A variadic list of Go struct types to migrate. ### Returns - `error`: An error if the migration process fails. ``` -------------------------------- ### Update to a New Version Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_2.md Commit changes, tag a new version using semantic versioning, and push the tag to update your module on pkg.go.dev. The update typically occurs automatically within minutes. ```bash # Fix bug or add feature git add . git commit -m "Add transaction support" # Tag new version git tag v0.2.0 git push origin v0.2.0 ``` -------------------------------- ### DB.GormDB() Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Provides direct access to the underlying GORM DB instance. ```APIDOC ## DB.GormDB() ### Description Returns the underlying `*gorm.DB` instance managed by the `DB` struct. This allows for using GORM's specific features not directly exposed by Goquent. ### Signature `func (db *DB) GormDB() *gorm.DB` ### Returns - `*gorm.DB`: The underlying GORM database object. ``` -------------------------------- ### Cursor Paginator Implementation Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Implements a cursor-based paginator, useful for infinite scrolling or when stable pagination is required across changing datasets. It uses cursors instead of page numbers. ```go type cursorPaginator struct { items interface{} perPage int nextCursor *string prevCursor *string hasMore bool } func NewCursorPaginator(items interface{}, perPage int) contracts.CursorPaginator { return &cursorPaginator{items: items, perPage: perPage} } func (p *cursorPaginator) Items() interface{} { return p.items } func (p *cursorPaginator) PerPage() int { return p.perPage } func (p *cursorPaginator) NextCursor() *string { return p.nextCursor } func (p *cursorPaginator) PreviousCursor() *string { return p.prevCursor } func (p *cursorPaginator) HasMorePages() bool { return p.hasMore } func (p *cursorPaginator) HasPages() bool { return true } ``` -------------------------------- ### GORM Expression and Raw SQL Execution Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Helper functions to create GORM expressions and execute raw SQL queries. The Raw function requires the database instance to be initialized. ```go func Expr(expr string, args ...interface{}) interface{} { return gorm.Expr(expr, args...) } func Raw(sql string, values ...interface{}) *gorm.DB { if instance == nil { panic("goquent: database not initialized") } return instance.gormDB.Raw(sql, values...) } ``` -------------------------------- ### Scopes and Raw SQL Execution in Goquent Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Apply predefined query scopes or execute raw SQL statements. Scopes allow for reusable query logic, while `Raw` enables direct SQL execution with parameter binding. ```Go func (q *Query) Scopes(funcs ...contracts.ScopeFunc) contracts.Querier { gormScopes := make([]func(*gorm.DB) *gorm.DB, len(funcs)) for i, f := range funcs { gormScopes[i] = func(db *gorm.DB) *gorm.DB { qCopy := &Query{db: db} result := f(qCopy) if result != nil { return result.(*Query).db } return db } } q.db = q.db.Scopes(gormScopes...) return q } ``` ```Go func (q *Query) Raw(sql string, values ...interface{}) contracts.Querier { q.db = q.db.Raw(sql, values...) return q } ``` -------------------------------- ### Check Initialization Status Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Checks if the Goquent database instance has been initialized. ```APIDOC ## IsInitialized ### Description Checks whether the global database instance has been initialized. ### Signature `func IsInitialized() bool` ### Returns - `bool`: `true` if the database is initialized, `false` otherwise. ``` -------------------------------- ### Select Columns with Raw SQL Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Use `SelectRaw` to select columns using raw SQL expressions. This allows for more complex selections, including functions and subqueries. ```go func (q *Query) SelectRaw(raw string, args ...interface{}) contracts.Querier { q.db = q.db.Select(raw, args...) return q } ``` -------------------------------- ### Add Basic WHERE Clause Source: https://github.com/alimmughanil/goquent/blob/main/docs/plans/phase_1.md Use the `Where` method to add a standard WHERE clause to your query. It accepts a query string and optional arguments for parameter binding. ```go func (q *Query) Where(query interface{}, args ...interface{}) contracts.Querier { q.db = q.db.Where(query, args...) return q } ```