Giter VIP home page Giter VIP logo

sqlingo's People

Contributors

lqs avatar lqvito avatar varushsu avatar zjc17 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sqlingo's Issues

BUG

var members []*DtbMemberModel

	_, err = db.Select(DtbMember.GetFields()).From(tDtbMember).FetchAll(&members)

	if err != nil {
		panic(err)
	}

会报错 panic: Error 1241: Operand should contain 1 column(s),原因是生成的sql 带括号,导致报错,sql如下:

SELECT (`id`, `username`, `password`, `api_token`, `remember_token`, `created_at`, `updated_at`, `organization_id`) FROM `dtb_member`

使用下面的替换 select中字段可正常

var fields []interface{}
	
	for _, name := range DtbMember.GetFields() {
		fields = append(fields, name)
	}

db.Select(fields...)

或者

db.Select(DtbMember.GetFields()).From(tDtbMember) 替换成 db.SelectFrom

Null handling

Trying out sqlingo this afternoon on a mysql database with lots of nulls and sqlingo complains:

"read C:\users\ed\gostuff\sqlingotest\generated\sqlingo\jake2.dsl.go: unexpected NUL in input"

Looks like a nice tool set. Is it not built to handle nulls?

Error generated DSL

Errors:

undefined: ufloat64

Generated sample code:

type SampleModel struct {
    Id             uint32
    DoubleValue    ufloat64
}
Field is not a type

Generated sample code:

type Field interface {
    Expression
    GetTable() Table
}

DB: MariaDB 10.x

error in generating code...

D:\Projects\GoProjects*>sqlingo-gen-mysql root:flipped199@/lover-bind >model/user2.go
Generating user
panic: 4:14: expected ';', found '-'

goroutine 1 [running]:
main.main()
C:/Users/Administrator/go/pkg/mod/github.com/lqs/[email protected]/sqlingo-gen-mysql/main.go:12 +0xf1

D:\Projects\GoProjects*>

ddl is ok.

改进意见

业务里有几个特殊地方,需要用到db.query,垮了几个表最终查询到数据并不是一个实际表,比如

Table A
akey  avalue

Table B
bkey  bvalue
type Item struct {
		Akey    string
		AValue  string
		BKey    string
		BValue  string
		Querytime time.Time
	}
	
	var items []Item

	rows, _ := db.Query(`select total.*, now() as querytime from (select akey, avalue,bkey, bvalue from table_a join table_b) total`)

	for rows.Next() {
		var i Item
		rows.Scan(&i)
		
		items = append(items,i)
	}
	
	//....

这种情况很麻烦啊,又没办法用fetchAll 或者 fetchAllAsMap

mysql sql return
image

A transaction innovation plan.

type Database interface {
	GetDB() *sql.DB

	BeginTx(ctx context.Context, opts *sql.TxOptions, f func(tx Transaction) error) error
	// todo
        // Begin() (Database, error)
	// SavePoint(name string) error
	// RollbackTo(name string) error
	// Rollback() error
        // Commit() error

	Query(sql string) (Cursor, error)
	QueryContext(ctx context.Context, sqlString string) (Cursor, error)
	Execute(sql string) (sql.Result, error)
	ExecuteContext(ctx context.Context, sql string) (sql.Result, error)
	SetLogger(logger func(sql string, durationNano int64))
	SetRetryPolicy(retryPolicy func(err error) bool)
	EnableCallerInfo(enableCallerInfo bool)
	SetInterceptor(interceptor InterceptorFunc)

	Select(fields ...interface{}) selectWithFields
	SelectDistinct(fields ...interface{}) selectWithFields
	SelectFrom(tables ...Table) selectWithTables
	InsertInto(table Table) insertWithTable
	ReplaceInto(table Table) insertWithTable
	Update(table Table) updateWithSet
	DeleteFrom(table Table) deleteWithTable
}

What do you think of use those function instead of BeginTx? Or any suggestion else?
It's a graceful way for me.

The ability to use this library in existing code

Hello.
Please add the ability to use this library in existing code, without opening a connection to the database, but using the existing one.

For example:

var db *sql.DB // already existing connection
sq := sqlingo.Use("mysql", db)

If I understand correctly, this fix should suffice:

func Use(driverName string, sqlDB *sql.DB) Database {
	return &database{
		dialect: getDialectFromDriverName(driverName),
		db:      sqlDB,
	}
}

I want to add a Cache-function, Currently like this, is there any other simplified way

I want to add a Cache-function, Currently like this, is there any other simplified way

var foundCachedErr = errors.New("FoundCachedErr")

	db.SetInterceptor(func(ctx context.Context, sql string, invoker sqlingo.InvokerFunc) error {
		var v = ctx.Value("name").(string)

		if cache.Instance().Exists(v) {
			return foundCachedErr
		}

		return invoker(ctx, sql)
	})

	var member DtbMemberModel
	var cacheName = "DtbMember:ID:1"

	ctx := context.WithValue(context.Background(), "name", cacheName)

	ok, err := db.SelectFrom(DtbMember).Where(
		sqlingo.And(
			DtbMember.Id.Equals(1),
		),
	).WithContext(ctx).FetchFirst(&member)

	if errors.Is(err, foundCachedErr) {
		cache.Instance().Get(cacheName)
		// ....
		// return
	}

	if err != nil {
		panic(err)
	}

	// ....

	spew.Dump(ok)
	spew.Dump(member)

support prepared arguments

SELECT ...... WHERE "Order"."id" in (1,2,3) AND ("Order"."name" LIKE 'Can%' OR "Order"."price" > 15)

to

SELECT ...... WHERE "Order"."id" in (?,?,?) AND ("Order"."name" LIKE ? OR "Order"."price" > ?)

By the way, this is a very good project!

Need to insert comment or fragment in sql

Such as select name from user /* shard_id=1 */ where name like 'can%', the shard_id comment is to tell the database proxy how to route to the sharded database.

Suggest: db.SelectFrom(User).AddFrag(Frag("/* shard_id=1 */").BeforeWhere()).Where(...)....

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.