Quickstart

Init Project

First, use go mod init to initialize the project and add GoooQo by:

go get -u github.com/doytowin/goooqo

Then, initialize the database connection and transaction manager as follows:

package main

import (
	"database/sql"
	"github.com/doytowin/goooqo/rdb"
	_ "github.com/mattn/go-sqlite3"
)

func main() {
	db, _ := sql.Open("sqlite3", "./test.db")

	tm := rdb.NewTransactionManager(db)

	//...
}

Build DataAccess

Suppose we have the following user table in test.db:

We define an entity object and a query object for the table:

user.go
package main

import (
	. "github.com/doytowin/goooqo"
)

type UserEntity struct {
	Int64Id
	Name  *string `json:"name"`
	Score *int    `json:"score"`
	Memo  *string `json:"memo"`
}

func (u UserEntity) GetTableName() string {
	return "t_user"
}

type UserQuery struct {
	PageQuery
	ScoreLt   *int
	MemoStart *string
	// ...
}

The fields of the entity object correspond to the columns of the table, and the fields of the query object are based on the query conditions of the requirements.

Then we define a userDataAccess to access the table:

userDataAccess := rdb.NewTxDataAccess[UserEntity](tm)

userQuery := UserQuery{PageQuery: PageQuery{PageSize: P(10)}, ScoreLt: P(80)}
userEntities, err := userDataAccess.Query(ctx, userQuery)

This will generate and execute the following SQL:

SELECT id, name, score, memo FROM t_user WHERE score < ? LIMIT 10 OFFSET 0

Last updated