100% type-safe ORM for Go (Golang) with code generation and MySQL, PostgreSQL, Sqlite3, SQL Server support. GORM under the hood.

Overview

go-queryset GoDoc Go Report Card Codacy Badge Maintainability Build Status Coverage Status

100% type-safe ORM for Go (Golang) with code generation and MySQL, PostgreSQL, Sqlite3, SQL Server support. GORM under the hood.

Contents

Installation

go get -u github.com/jirfag/go-queryset/cmd/goqueryset

Usage

Define models

Imagine you have model User in your models.go file:

type User struct {
	gorm.Model
	Rating      int
	RatingMarks int
}

Now transform it by adding comments for query set generation:

//go:generate goqueryset -in models.go

// User struct represent user model. Next line (gen:qs) is needed to autogenerate UserQuerySet.
// gen:qs
type User struct {
	gorm.Model
	Rating      int
	RatingMarks int
}

Take a look at line // gen:qs. It's a necessary line to enable querysets for this struct. You can put it at any line in struct's doc-comment.

Then execute next shell command:

go generate ./...

And you will get file autogenerated_models.go in the same directory (and package) as models.go.

In this autogenerated file you will find a lot of autogenerated typesafe methods like these:

func (qs UserQuerySet) CreatedAtGte(createdAt time.Time) UserQuerySet {
	return qs.w(qs.db.Where("created_at >= ?", createdAt))
}

func (qs UserQuerySet) RatingGt(rating int) UserQuerySet {
	return qs.w(qs.db.Where("rating > ?", rating))
}

func (qs UserQuerySet) IDEq(ID uint) UserQuerySet {
	return qs.w(qs.db.Where("id = ?", ID))
}

func (qs UserQuerySet) DeletedAtIsNull() UserQuerySet {
	return qs.w(qs.db.Where("deleted_at IS NULL"))
}

func (o *User) Delete(db *gorm.DB) error {
	return db.Delete(o).Error
}

func (qs UserQuerySet) OrderAscByCreatedAt() UserQuerySet {
	return qs.w(qs.db.Order("created_at ASC"))
}

See full autogenerated file here.

Now you can use this queryset for creating/reading/updating/deleting. Let's take a look at these operations.

Relation with GORM

You can embed and not embed gorm.Model into your model (e.g. if you don't need DeletedAt field), but you must use *gorm.DB to properly work. Don't worry if you don't use GORM yet, it's easy to create *gorm.DB:

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

func getGormDB() *gorm.DB {
	db, err := gorm.Open("mysql", "user:[email protected]/dbname?charset=utf8&parseTime=True&loc=Local")
	// ...
}

If you already use another ORM or raw sql.DB, you can reuse your sql.DB object (to reuse connections pool):

	var sqlDB *sql.DB = getSQLDBFromAnotherORM()
	var gormDB *gorm.DB
	gormDB, err = gorm.Open("mysql", sqlDB)

Create

u := User{
	Rating: 5,
	RatingMarks: 0,
}
err := u.Create(getGormDB())

Under the hood Create method just calls db.Create(&u).

Select

It's the most powerful feature of query set. Let's execute some queries:

Select all users

var users []User
err := NewUserQuerySet(getGormDB()).All(&users)
if err == gorm.ErrRecordNotFound {
	// no records were found
}

It generates this SQL request for MySQL:

SELECT * FROM `users` WHERE `users`.deleted_at IS NULL

deleted_at filtering is added by GORM (soft-delete), to disable it use Unscoped.

Select one user

var user User
err := NewUserQuerySet(getGormDB()).One(&user)

Select N users with highest rating

var users []User
err := NewUserQuerySet(getGormDB()).
	RatingMarksGte(minMarks).
	OrderDescByRating().
	Limit(N).
	All(&users)

Select users registered today

In this example we will define custom method on generated UserQuerySet for later reuse in multiple functions:

func (qs UserQuerySet) RegisteredToday() UserQuerySet {
	// autogenerated typesafe method CreatedAtGte(time.Time)
	return qs.CreatedAtGte(getTodayBegin())
}

...
var users []User
err := NewUserQuerySet(getGormDB()).
	RegisteredToday().
	OrderDescByCreatedAt().
	Limit(N).
	All(&users)

Select specific fields

By default all fields are fetched using the * field selector. using the select methd it is possible to limit the SQL statement to fetch specific fields:

var users []User
err := NewUserQuerySet(getGormDB()).Select(UserDBSchema.ID, UserDBSchema.Rating).All(&users)
if err == gorm.ErrRecordNotFound {
	// no records were found
}

It generates this SQL request for MySQL:

SELECT id, rating FROM `users` WHERE `users`.deleted_at IS NULL

Update

Update one record by primary key

u := User{
	Model: gorm.Model{
		ID: uint(7),
	},
	Rating: 1,
}
err := u.Update(getGormDB(), UserDBSchema.Rating)

Goqueryset generates DB names for struct fields into UserDBSchema variable. In this example we used UserDBSchema.Rating.

And this code generates next SQL:

UPDATE `users` SET `rating` = ? WHERE `users`.deleted_at IS NULL AND `users`.`id` = ?

Update multiple record or without model object

Sometimes we don't have model object or we are updating multiple rows in DB. For these cases there is another typesafe interface:

err := NewUserQuerySet(getGormDB()).
	RatingLt(1).
	GetUpdater().
	SetRatingMarks(0).
	Update()
UPDATE `users` SET `rating_marks` = ? WHERE `users`.deleted_at IS NULL AND ((rating < ?))

UpdateNum

This method makes the same sql queries as Update() method, except return values: it returns number of affected rows and error

num, err := NewUserQuerySet(getGormDB()).
	RatingLt(1).
	GetUpdater().
	SetRatingMarks(0).
	UpdateNum()
UPDATE `users` SET `rating_marks` = ? WHERE `users`.deleted_at IS NULL AND ((rating < ?))

Delete

Delete one record by primary key

u := User{
	Model: gorm.Model{
		ID: uint(7),
	},
}
err := u.Delete(getGormDB())

Delete multiple records

err := NewUserQuerySet(getGormDB()).
	RatingMarksEq(0).
	Delete()

Full list of generated methods

QuerySet methods - func (qs {StructName}QuerySet)

  • create new queryset: New{StructName}QuerySet(db *gorm.DB)
func NewUserQuerySet(db *gorm.DB) UserQuerySet
  • filter by field (where)

    • all field types
      • Equals: {FieldName}(Eq|Ne)(arg {FieldType})
       func (qs UserQuerySet) RatingEq(rating int) UserQuerySet
      • In: {FieldName}(Not)In(arg {FieldType}, argsRest ...{FieldType})
       func (qs UserQuerySet) NameIn(name string, nameRest ...string) UserQuerySet {}
       func (qs UserQuerySet) NameNotIn(name string, nameRest ...string) UserQuerySet {}
      • Order(Asc|Desc)By{FieldName}()
       func (qs UserQuerySet) OrderDescByRating() UserQuerySet
    • numeric types (int, int64, uint etc + time.Time):
      • {FieldName}(Lt|Lte|Gt|Gte)(arg {FieldType)
       func (qs UserQuerySet) RatingGt(rating int) UserQuerySet
    • string types (string):
      • {FieldName}(Like/Notlike)(arg {FieldType)
       func (qs UserQuerySet) NameLike(name string) UserQuerySet
    • pointer fields: {FieldName}IsNull(), {FieldName}IsNotNull()
     func (qs UserQuerySet) ProfileIsNull() UserQuerySet {}
     func (qs UserQuerySet) ProfileIsNotNull() UserQuerySet {}
  • preload related object (for structs fields or pointers to structs fields): Preload{FieldName}() For struct

     	type User struct {
     		profile *Profile
     	}

    will be generated:

     func (qs UserQuerySet) PreloadProfile() UserQuerySet

    Preload functions call gorm.Preload to preload related object.

  • selectors

    • Select all objects, return gorm.ErrRecordNotFound if no records
     func (qs UserQuerySet) All(users *[]User) error
    • Select one object, return gorm.ErrRecordNotFound if no records
     func (qs UserQuerySet) One(user *User) error
  • Limit

func (qs UserQuerySet) Limit(limit int) UserQuerySet
  • get updater (for update + where, based on current queryset):
func (qs UserQuerySet) GetUpdater() UserUpdater
  • delete with conditions from current queryset: Delete()
func (qs UserQuerySet) Delete() error
  • Aggregations
    • Count
     func (qs UserQuerySet) Count() (int, error)

Object methods - func (u *User)

  • create object
func (o *User) Create(db *gorm.DB) error
  • delete object by PK
func (o *User) Delete(db *gorm.DB) error
  • update object by PK
func (o *User) Update(db *gorm.DB, fields ...userDBSchemaField) error

Pay attention that field names are automatically generated into variable

type userDBSchemaField string

// UserDBSchema stores db field names of User
var UserDBSchema = struct {
	ID          userDBSchemaField
	CreatedAt   userDBSchemaField
	UpdatedAt   userDBSchemaField
	DeletedAt   userDBSchemaField
	Rating      userDBSchemaField
	RatingMarks userDBSchemaField
}{

	ID:          userDBSchemaField("id"),
	CreatedAt:   userDBSchemaField("created_at"),
	UpdatedAt:   userDBSchemaField("updated_at"),
	DeletedAt:   userDBSchemaField("deleted_at"),
	Rating:      userDBSchemaField("rating"),
	RatingMarks: userDBSchemaField("rating_marks"),
}

And they are typed, so you won't have string-misprint error.

Updater methods - func (u UserUpdater)

  • set field: Set{FieldName}
func (u UserUpdater) SetCreatedAt(createdAt time.Time) UserUpdater
  • execute update: Update()
func (u UserUpdater) Update() error

Golang version

Golang >= 1.8 is required. Tested on go 1.8, 1.9 versions by Travis CI

Why?

Why not just use GORM?

I like GORM: it's the best ORM for golang, it has fantastic documentation, but as a Golang developers team lead I can point out some troubles with it:

  1. GORM isn't typesafe: it's so easy to spend 1 hour trying to execute simple Update. GORM gets all arguments as interface{} and in the case of invalid GORM usage you won't get error: you will get invalid SQL, no SQL (!) and error == nil etc. It's easy to get SELECT * FROM t WHERE string_field == 1 SQL in production without type safety.
  2. GORM is difficult for beginners because of unclear interface{} interfaces: one can't easily find which arguments to pass to GORM methods.

Why not another ORM?

Type-safety, like with GORM.

Why not any ORM?

I didn't see any ORM that properly handles code duplication. GORM is the best with Scopes support, but even it's far from ideal. E.g. we have GORM and next typical code:

type User struct {
	gorm.Model
	Rating      int
	RatingMarks int
}

func GetUsersWithMaxRating(limit int) ([]User, error) {
	var users []User
	if err := getGormDB().Order("rating DESC").Limit(limit).Find(&users).Error; err != nil {
		return nil, err
	}
	return users, nil
}

func GetUsersRegisteredToday(limit int) ([]User, error) {
	var users []User
	today := getTodayBegin()
	err := getGormDB().Where("created_at >= ?", today).Limit(limit).Find(&users).Error
	if err != nil {
		return nil, err
	}
	return users, nil
}

At one moment PM asks us to implement new function, returning list of users registered today AND sorted by rating. Copy-paste way is to add Order("rating DESC") to GetUsersRegisteredToday. But it leads to typical copy-paste troubles: when we change rating calculation logics (e.g. to .Where("rating_marks >= ?", 10).Order("rating DESC")) we must change it in two places.

How to solve it? First idea is to make reusable functions:

func queryUsersWithMaxRating(db *gorm.DB, limit int) *gorm.DB {
	return db.Order("rating DESC").Limit(limit)
}

func queryUsersRegisteredToday(db *gorm.DB, limit int) *gorm.DB {
	today := getTodayBegin()
	return db.Where("created_at >= ?", today).Limit(limit)
}

func GetUsersWithMaxRating(limit int) ([]User, error) {
	var users []User
	if err := queryUsersWithMaxRating(getGormDB(), limit).Find(&users).Error; err != nil {
		return nil, err
	}
	return users, nil
}

func GetUsersRegisteredToday(limit int) ([]User, error) {
	var users []User
	if err := queryUsersRegisteredToday(getGormDB(), limit).Find(&users).Error; err != nil {
		return nil, err
	}
	return users, nil
}

func GetUsersRegisteredTodayWithMaxRating(limit int) ([]User, error) {
	var users []User
	err := queryUsersWithMaxRating(queryUsersRegisteredToday(getGormDB(), limit), limit).
		Find(&users).Error
	if err != nil {
		return nil, err
	}
	return users, nil
}

We can use GORM Scopes to improve how it looks:

func queryUsersWithMaxRating(db *gorm.DB) *gorm.DB {
	return db.Order("rating DESC")
}

func queryUsersRegisteredToday(db *gorm.DB) *gorm.DB {
	return db.Where("created_at >= ?", getTodayBegin())
}

func GetUsersRegisteredTodayWithMaxRating(limit int) ([]User, error) {
	var users []User
	err := getGormDB().
		Scopes(queryUsersWithMaxRating, queryUsersRegisteredToday).
		Limit(limit).
		Find(&users).Error
	if err != nil {
		return nil, err
	}
	return users, nil
}

Looks nice, but we loosed ability to parametrize our reusable GORM queries (scopes): they must have only one argument of type *gorm.DB. It means that we must move out Limit from them (let's say we get it from user). If we need to implement query QueryUsersRegisteredAfter(db *gorm.DB, t time.Time) - we can't do it.

Now compare it with go-queryset solution:

// UserQuerySet is an autogenerated struct with a lot of typesafe methods.
// We can define any methods on it because it's in the same package
func (qs UserQuerySet) WithMaxRating(minMarks int) UserQuerySet {
	return qs.RatingMarksGte(minMarks).OrderDescByRating()
}

func (qs UserQuerySet) RegisteredToday() UserQuerySet {
	// autogenerated typesafe method CreatedAtGte(time.Time)
	return qs.CreatedAtGte(getTodayBegin())
}

// now we can parametrize it
const minRatingMarks = 10

func GetUsersWithMaxRating(limit int) ([]User, error) {
	var users []User
	err := NewUserQuerySet(getGormDB()).
		WithMaxRating(minRatingMarks). // reuse our method
		Limit(limit).                  // autogenerated typesafe method Limit(int)
		All(&users)                    // autogenerated typesafe method All(*[]User)
	if err != nil {
		return nil, err
	}
	return users, nil
}

func GetUsersRegisteredToday(limit int) ([]User, error) {
	var users []User
	err := NewUserQuerySet(getGormDB()).
		RegisteredToday(). // reuse our method
		Limit(limit).      // autogenerated typesafe method Limit(int)
		All(&users)        // autogenerated typesafe method All(*[]User)
	if err != nil {
		return nil, err
	}
	return users, nil
}

func GetUsersRegisteredTodayWithMaxRating(limit int) ([]User, error) {
	var users []User
	err := NewUserQuerySet(getGormDB()).
		RegisteredToday().             // reuse our method
		WithMaxRating(minRatingMarks). // reuse our method
		Limit(limit).
		All(&users) // autogenerated typesafe method All(*[]User)
	if err != nil {
		return nil, err
	}
	return users, nil
}

Why not raw SQL queries?

No type-safety, a lot of boilerplate code.

Why not go-kallax?

  1. It works only with PostgreSQL. Go-queryset supports mysql, postgresql, sqlite, mssql etc (all that gorm supports).
  2. Lacks simplier model updating interface

How it relates to another languages ORMs

QuerySet pattern is similar to:

Features

  • 100% typesafe: there is no one method with interface{} arguments.
  • QuerySet pattern allows to reuse queries by defining custom methods on it.
  • Supports all DBMS that GORM supports: MySQL, PostgreSQL, Sqlite3, SQL Server.
  • Supports creating, selecting, updating, deleting of objects.

Limitations

  • Joins aren't supported
  • Struct tags aren't supported

Performance

Runtime

Performance is similar to GORM performance. GORM uses reflection and it may be slow, so why don't we generate raw SQL code?

  1. Despite the fact GORM uses reflection, it's the most popular ORM for golang. There are really few tasks where you are CPU-bound while working with DB, usually you are CPU-bound in machine with DB and network/disk bound on machine with golang server.
  2. Premature optimization is the root of all evil.
  3. Go-queryset is fully compatible with GORM.
  4. Code generation is used here not to speedup things, but to create nice interfaces.
  5. The main purpose of go-queryset isn't speed, but usage convenience.

Code generation

Code generation is fast:

  1. We parse AST of needed file and find needed structs.
  2. We load package and parse it by go/types
  3. We don't use reflect module for parsing, because it's slow
Issues
  • NotIn QuerySet function

    NotIn QuerySet function

    this function StatusNotIn(status types.TXStatus, statusRest ...types.TXStatus)

    has to be used like this: StatusNotIn(types.CompletedTXStatuses[0], types.CompletedTXStatuses[1:]...)

    as for me, better way is StatusNotIn(types.CompletedTXStatuses...)

    enhancement 
    opened by grechkin-pogrebnyakov 10
  • Added support for supplying the fields to query in the select statement

    Added support for supplying the fields to query in the select statement

    Example usage: 'NewUserQuerySet(db).Select(UserDBSchema.Name, UserDBSchema.Email).All(&users)' This will fetch only the 'name' and 'email' fields for all users, instead of fetching all the fields in the table.

    opened by ghost 4
  • Missing Private Fields

    Missing Private Fields

    This system is excellent. However, all private fields are ignored. This is probably a good decision in general but I think that if the gorm struct tag Column is present then even private fields should be generated for.

    opened by Nokel81 3
  • vgo/go mod support

    vgo/go mod support

    Thanks for this great package. I noticed that since I moved my project to go modules, the generation stopped working.

    The issue appears to be with packages created outside the $GOPATH. Is there planned support for this?

    opened by Azuka 3
  • can't generate query sets on Windows

    can't generate query sets on Windows

    My ENV: go version go1.9.2 windows/amd64

    My Code Path:

    E:\GOPATH\src\test\models.go

    My question : To excute go generate ./... got a failure info : can't generate query sets: can't parse file models.go to get structs: can't load types for file models.go in package "./." But in Desktop dictionary path “test/models.go” to excute go generate ./... was successful !

    The code :

    import "github.com/jinzhu/gorm"
    
    //go:generate goqueryset -in models.go
    // User struct represent user model. Next line (gen:qs) is needed to autogenerate UserQuerySet.
    // gen:qs
    type User struct {
    	gorm.Model
    	Rating      int
    	RatingMarks int
    }
    
    bug 
    opened by JermineHu 3
  • go-queryset ignores custom column tag

    go-queryset ignores custom column tag

    Sample:

    Value int `gorm:"column:someprefix_value"`
    

    will result in:

    func (qs QuerySet) ValueEq(value int) QuerySet {
           return qs.w(qs.db.Where("value = ?", value))
    }
    
    opened by to6ka 3
  • Interesting Generation Error

    Interesting Generation Error

    First off, awesome job on this package, I was really impressed with the api it generated so much so we started migrating our GORM queries across to use this package instead.

    So the issue is I have an Enum that is imported from another package. This seems to work fine on other code generations we have. However, when I generated code using go-queryset I got an unexpected result.

    The struct // gen:qs is above looks like this:

    type Example struct {
    
    	PriceID int64
    
    	Currency forex.Currency
    
            ....
    }
    

    The Generated code for currency looks like this:

    // CurrencyEq is an autogenerated method
    // nolint: dupl
    func (qs ExampleQuerySet) CurrencyEq(currency v1.Currency) ExampleQuerySet {
    	return qs.w(qs.db.Where("currency = ?", currency))
    }
    
    // CurrencyGt is an autogenerated method
    // nolint: dupl
    func (qs ExampleQuerySet) CurrencyGt(currency v1.Currency) ExampleQuerySet {
    	return qs.w(qs.db.Where("currency > ?", currency))
    }
    
    ....
    

    The error is that the generated code has placed v1 as the package selector and not the actual package name forex.

    This is non-blocking for me as It's very easy to fix up manually. However, this would suggest that the code generation is picking up v1 from the file path? The import is like so: import "go.company.com/internal-files/companyapi/forex/v1".

    Happy to help look into this problem but I thought I'd raise it first just in case something like this has occurred else where.

    opened by chrisfentiman 3
  • Missing packages on generate

    Missing packages on generate

    When I run go generate ./... using the latest master code. I get a file called autogenerated_***.go just like the readme states it should. The problem is that it is importing a package called base "github.com/jirfag/go-queryset/queryset/base" which doesn't seem to exist.

    It also misses the packages "time" and "fmt"

    Any ideas?

    opened by iain17 3
  • queryset.go: added getDBObject method

    queryset.go: added getDBObject method

    • This method returns DB object w.r.t queryset used to call it.
    • The returned object can further be used to call gorm related property for many to many relation.
    opened by rajatgpt1521 2
  • Queryset Preload Methods Repeat Keys

    Queryset Preload Methods Repeat Keys

    When writing a Query that involves preloading a foreign-key object (for example: DBModel.NewObjectQuerySet(DBConn).PrimaryKeyEq(pk).PreloadNestedObject()), the Nested Objects are fetched in a query that has a WHERE clause with all the foreign-key IDs.

    The problem arises when said Nested Objects are the same for multiple instances of Object (a many-to-one relationship); the underlying query repeats the key. For example:

    | Object PK | Nested Object FK | | --------- | ---------------- | | 1 | 1 | | 2 | 2 | | 3 | 1 | | 4 | 1 | | 5 | 1 |

    Results in the following query when using PreloadNestedObject():

    SELECT * FROM NestedObject WHERE pk IN (1, 1, 1, 1, 2);

    This massively slows down the underlying queries when fetching fairly average resultsets (tens of seconds every 30000 simple records).

    wontfix 
    opened by DazedNConfused- 2
  • Fields list in selects

    Fields list in selects

    Now it generates:

    // One is used to retrieve one result. It returns gorm.ErrRecordNotFound
    // if nothing was fetched
    func (qs PaymentQuerySet) One(ret *Payment) error {
     return qs.db.First(ret).Error
    }
    

    If would be awesome if it was this like:

    // One is used to retrieve one result. It returns gorm.ErrRecordNotFound
    // if nothing was fetched
    func (qs PaymentQuerySet) One(ret *Payment, fields ...paymentDBSchemaField) error {
     if (len(fields) != 0) {
      qs = qs.w(qs.db.Select(fields...))
     }
     return qs.db.First(ret).Error
    }
    
    enhancement 
    opened by grechkin-pogrebnyakov 2
  • A question regarding the logic of the Select methods (All in particular)

    A question regarding the logic of the Select methods (All in particular)

    @jirfag great project and I am glad I found it even though this late.

    I have one question though. With respect to code readability, does it make sense to copy gorm's way of accepting a result pointer as an argument?

    What I mean is the following. Every QuerySet instance has one of these methods:

    func (qs UserQuerySet) All(ret *[]User) error {
    	return qs.db.Find(ret).Error
    }
    

    I allowed myself to insert a second method that looks one idea cleaner if you are coming from other languages:

    func (qs UserQuerySet) AllRet() ([]User, error) {
    	var ret []User
    	err := qs.db.Find(&ret).Error
    	return ret, err
    }
    

    Since I don't want to make false claims, I also wrote a quick benchmark testing each and every method with the same conditions (10000 mock users benching for 5s). Here are the results:

    BenchmarkUserSelectAll-8   	      361764	     14977 ns/op	    6154 B/op	     100 allocs/op
    BenchmarkUserSelectAllRet-8   368132	     14634 ns/op	    6153 B/op	     100 allocs/op
    

    Without going as far as to claim that my method is faster, I'd just say they are on par with one another. What was then the motivation to follow the result pointer approach? Could we make an improvement proposal in the future?

    opened by preslavrachev 0
  • GORM 2.0 compliance

    GORM 2.0 compliance

    Any plans to make the generator GORM 2.0 compliant soon?

    Perhaps I might be all wrong here (or just plain optimistic), but at glance, it does not seem to be quite a big deal - here's the simplest patch I could think of (neither unit tests nor examples fixed yet):

    diff --git a/go.mod b/go.mod
    index 7fd83ac..9071c01 100644
    --- a/go.mod
    +++ b/go.mod
    @@ -7,8 +7,6 @@ require (
     	github.com/go-sql-driver/mysql v0.0.0-20170822214809-26471af196a1 // indirect
     	github.com/gofrs/uuid v3.2.0+incompatible // indirect
     	github.com/jinzhu/gorm v1.9.2
    -	github.com/jinzhu/inflection v0.0.0-20170102125226-1c35d901db3d // indirect
    -	github.com/jinzhu/now v1.0.0 // indirect
     	github.com/lib/pq v1.0.0 // indirect
     	github.com/mattn/go-sqlite3 v1.10.0 // indirect
     	github.com/pkg/errors v0.8.1
    @@ -16,6 +14,7 @@ require (
     	golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 // indirect
     	golang.org/x/tools v0.0.0-20190226205152-f727befe758c
     	gopkg.in/DATA-DOG/go-sqlmock.v1 v1.2.0
    +	gorm.io/gorm v1.20.8
     )
     
     go 1.13
    diff --git a/go.sum b/go.sum
    index 7f4f78c..84deb88 100644
    --- a/go.sum
    +++ b/go.sum
    @@ -53,8 +53,12 @@ github.com/jinzhu/gorm v1.9.2 h1:lCvgEaqe/HVE+tjAR2mt4HbbHAZsQOv3XAZiEZV37iw=
     github.com/jinzhu/gorm v1.9.2/go.mod h1:Vla75njaFJ8clLU1W44h34PjIkijhjHIYnZxMqCdxqo=
     github.com/jinzhu/inflection v0.0.0-20170102125226-1c35d901db3d h1:jRQLvyVGL+iVtDElaEIDdKwpPqUIZJfzkNLV34htpEc=
     github.com/jinzhu/inflection v0.0.0-20170102125226-1c35d901db3d/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
    +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
    +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
     github.com/jinzhu/now v1.0.0 h1:6WV8LvwPpDhKjo5U9O6b4+xdG/jTXNPwlDme/MTo8Ns=
     github.com/jinzhu/now v1.0.0/go.mod h1:oHTiXerJ20+SfYcrdlBO7rzZRJWGwSTQ0iUY2jI6Gfc=
    +github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E=
    +github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
     github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
     github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
     github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
    @@ -166,6 +170,8 @@ gopkg.in/DATA-DOG/go-sqlmock.v1 v1.2.0/go.mod h1:OdE7CF6DbADk7lN8LIKRzRJTTZXIjtW
     gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
     gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
     gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
    +gorm.io/gorm v1.20.8 h1:iToaOdZgjNvlc44NFkxfLa3U9q63qwaxt0FdNCiwOMs=
    +gorm.io/gorm v1.20.8/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
     grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o=
     honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
     honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
    diff --git a/internal/queryset/field/field.go b/internal/queryset/field/field.go
    index 0b7e344..75ad6ed 100644
    --- a/internal/queryset/field/field.go
    +++ b/internal/queryset/field/field.go
    @@ -1,12 +1,11 @@
     package field
     
     import (
    +	"bytes"
     	"fmt"
     	"go/types"
     	"reflect"
     	"strings"
    -
    -	"github.com/jinzhu/gorm"
     )
     
     type BaseInfo struct {
    @@ -99,7 +98,7 @@ func (g InfoGenerator) GenFieldInfo(f Field) *Info {
     		return nil
     	}
     
    -	dbName := gorm.ToDBName(f.Name())
    +	dbName := toDBName(f.Name()) // Equvalent to old: gorm.ToDBName(f.Name())
     	if dbColName := tagSetting["COLUMN"]; dbColName != "" {
     		dbName = dbColName
     	}
    @@ -162,3 +161,52 @@ func (g InfoGenerator) GenFieldInfo(f Field) *Info {
     		return nil
     	}
     }
    +
    +func toDBName(name string) string {
    +	const (
    +		lower = false
    +		upper = true
    +	)
    +
    +	if name == "" {
    +		return ""
    +	}
    +
    +	var (
    +		value                                    = name // commonInitialismsReplacer.Replace(name)
    +		buf                                      = bytes.NewBufferString("")
    +		lastCase, currCase, nextCase, nextNumber bool
    +	)
    +
    +	for i, v := range value[:len(value)-1] {
    +		nextCase = bool(value[i+1] >= 'A' && value[i+1] <= 'Z')
    +		nextNumber = bool(value[i+1] >= '0' && value[i+1] <= '9')
    +
    +		if i > 0 {
    +			if currCase == upper {
    +				if lastCase == upper && (nextCase == upper || nextNumber == upper) {
    +					buf.WriteRune(v)
    +				} else {
    +					if value[i-1] != '_' && value[i+1] != '_' {
    +						buf.WriteRune('_')
    +					}
    +					buf.WriteRune(v)
    +				}
    +			} else {
    +				buf.WriteRune(v)
    +				if i == len(value)-2 && (nextCase == upper && nextNumber == lower) {
    +					buf.WriteRune('_')
    +				}
    +			}
    +		} else {
    +			currCase = upper
    +			buf.WriteRune(v)
    +		}
    +		lastCase = currCase
    +		currCase = nextCase
    +	}
    +
    +	buf.WriteByte(value[len(value)-1])
    +
    +	return strings.ToLower(buf.String())
    +}
    diff --git a/internal/queryset/generator/generator.go b/internal/queryset/generator/generator.go
    index a0bf12f..f817eb0 100644
    --- a/internal/queryset/generator/generator.go
    +++ b/internal/queryset/generator/generator.go
    @@ -59,7 +59,7 @@ import (
     	"strings"
     	"time"
     
    -	"github.com/jinzhu/gorm"
    +	"gorm.io/jgorm"
     )
     `
     
    diff --git a/internal/queryset/methods/queryset.go b/internal/queryset/methods/queryset.go
    index b42395b..bb8f2af 100644
    --- a/internal/queryset/methods/queryset.go
    +++ b/internal/queryset/methods/queryset.go
    @@ -353,8 +353,8 @@ func NewCountMethod(qsTypeName string) CountMethod {
     	return CountMethod{
     		baseQuerySetMethod: newBaseQuerySetMethod(qsTypeName),
     		namedMethod:        newNamedMethod("Count"),
    -		constRetMethod:     newConstRetMethod("(int, error)"),
    -		constBodyMethod: newConstBodyMethod(`var count int
    +		constRetMethod:     newConstRetMethod("(int64, error)"),
    +		constBodyMethod: newConstBodyMethod(`var count int64
     			err := %s.Count(&count).Error
     			return count, err`, qsDbName),
     	}
    

    Any thoughts in this regard so far? Thanks. Regards

    opened by vladica-stojic-estv 1
  • Added emplty line between package string and header comment

    Added emplty line between package string and header comment

    Currently, the comment // Code generated by go-queryset. DO NOT EDIT. is inserted right before the package ... line. This causes the comment to be considered package documentation. Adding an empty line between the two makes it so, that this string is no longer package documentation.

    I would argue that this is preferable, as the comment is only relevant for the one file and not the whole package and, as such, should not be package documentation.

    opened by LogicalOverflow 1
  • Object Mapper design/functionality?

    Object Mapper design/functionality?

    Hi, Thank you for the effort you have put into this project and making it available as open source.

    I'm new to Go and am looking for an Object Mapper library in Golang - I'm struggling to see past the sytax right now - hence this question.

    Essentially Object Mapper approach builds on the lessons learned from the AvtiveRecord and DataMapper patterns/conventions, as well as the implementation lessons from like named project.

    Something with the design and functionality of rom-rb.

    Does your library a Object Mapper type functionality?
    If not would you kind enough to share the name of any OM libraries that your know of in Goland?

    opened by bbros-dev 0
  • Support preload for struct slice

    Support preload for struct slice

    GORM's preload can also be used for a struct slice. This patch makes it possible to generate methods for it.

    This PR will be in conflict with #54. If it's merged before this, I'll rebase this onto master.

    opened by tchssk 1
Owner
Denis Isaev
Senior Engineering Manager at Yandex.Taxi. Author of golangci-lint.
Denis Isaev
Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle, Moved to https://gitea.com/xorm/xorm

xorm HAS BEEN MOVED TO https://gitea.com/xorm/xorm . THIS REPOSITORY WILL NOT BE UPDATED ANY MORE. 中文 Xorm is a simple and powerful ORM for Go. Featur

null 6.5k May 11, 2022
Using-orm-with-db - Trying to use ORM to work with PostgreSQL

Using ORM with db This repo contains the training (rough) code, and possibly not

Pavel V 2 Jan 6, 2022
beedb is a go ORM,support database/sql interface,pq/mysql/sqlite

Beedb ❗ IMPORTANT: Beedb is being deprecated in favor of Beego.orm ❗ Beedb is an ORM for Go. It lets you map Go structs to tables in a database. It's

astaxie 709 Mar 8, 2022
Golang mysql orm, a personal learning project, dedicated to easy use of mysql

golang mysql orm 个人学习项目, 一个易于使用的mysql-orm mapping struct to mysql table golang结构

magacy 1 Dec 30, 2021
A better ORM for Go, based on non-empty interfaces and code generation.

reform A better ORM for Go and database/sql. It uses non-empty interfaces, code generation (go generate), and initialization-time reflection as oppose

null 1.3k May 14, 2022
A better ORM for Go, based on non-empty interfaces and code generation.

A better ORM for Go and database/sql. It uses non-empty interfaces, code generation (go generate), and initialization-time reflection as opposed to interface{}, type system sidestepping, and runtime reflection. It will be kept simple.

null 1.2k May 12, 2022
Golang ORM with focus on PostgreSQL features and performance

go-pg is in a maintenance mode and only critical issues are addressed. New development happens in Bun repo which offers similar functionality but works with PostgreSQL, MySQL, and SQLite.

null 5.1k May 10, 2022
Gorm-sharding - High performance table sharding plugin for Gorm

Gorm Sharding This project has moved to Gorm offical organization: https://githu

Longbridge 57 May 13, 2022
Api-project - Api project with Golang, Gorm, Gorilla-Mux, Postgresql

TECHNOLOGIES GOLANG 1.14 GORM GORILLA-MUX POSTGRESQL API's PATHS For Product Ser

Mustafa Enes Tepe 3 Feb 26, 2022
SQL mapper ORM framework for Golang

SQL mapper ORM framework for Golang English 中文 Please read the documentation website carefully when using the tutorial. DOC Powerful Features High Per

null 0 Dec 8, 2021
Mybatis for golang - SQL mapper ORM framework

SQL mapper ORM framework for Golang English 中文 Please read the documentation website carefully when using the tutorial. DOC Powerful Features High Per

Tim 2 Mar 20, 2022
Simple and performant ORM for sql.DB

Simple and performant ORM for sql.DB Main features are: Works with PostgreSQL, MySQL, SQLite. Selecting into a map, struct, slice of maps/structs/vars

Uptrace 894 May 14, 2022
Crud - A mysql crud code generate tool from table DDL sql file

crud is a mysql crud code generate tool 中文文档 Getting Started Overview Crud is a

null 14 Apr 26, 2022
An orm library support nGQL for Golang

norm An ORM library support nGQL for Golang. Overview Build insert nGQL by struct / map (Support vertex, edge). Parse Nebula execute result to struct

Zhihu 65 May 9, 2022
A simple wrapper around sql.DB to help with structs. Not quite an ORM.

go-modeldb A simple wrapper around sql.DB to help with structs. Not quite an ORM. Philosophy: Don't make an ORM Example: // Setup require "modeldb" db

Jae Kwon 17 Nov 16, 2019
CURD using go fiber - gorm - mysql

GO Fiber - CRUD - GORM - Mysql Folder Structure - database | database config |- migration | migration config - middleware | mid

Muhammad Hizbullah 7 Apr 25, 2022
A code generator base on GORM

GORM/GEN The code generator base on GORM, aims to be developer friendly. Overview CRUD or DIY query method code generation Auto migration from databas

null 842 May 10, 2022
Go tool for generating sql scanners, sql statements and other helper functions

sqlgen generates SQL statements and database helper functions from your Go structs. It can be used in place of a simple ORM or hand-written SQL. See t

drone.io 182 Jan 3, 2022
golang orm

korm golang orm, 一个简单易用的orm, 支持嵌套事务 安装 go get github.com/wdaglb/korm go get github.com/go-sql-driver/mysql 支持数据库 mysql https://github.com/go-sql-driv

null 6 Oct 11, 2021