lqs / sqlingo Goto Github PK
View Code? Open in Web Editor NEW💥 A lightweight DSL & ORM which helps you to write SQL in Go.
License: MIT License
💥 A lightweight DSL & ORM which helps you to write SQL in Go.
License: MIT License
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
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?
delete need limit like update, select.
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
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
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.
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
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)
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!
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(...)...
.
How can i add logrus for sqlingo
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.