From 2f2f6e1ffeb6e65cbcbe959d69d350e28596ea48 Mon Sep 17 00:00:00 2001 From: wenzi1 Date: Wed, 11 Mar 2020 00:29:25 +0800 Subject: [PATCH] add Tables and TableFields method --- database/gdb/gdb_driver_sqlite.go | 41 +++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/database/gdb/gdb_driver_sqlite.go b/database/gdb/gdb_driver_sqlite.go index e23442316..5e7f9ac34 100644 --- a/database/gdb/gdb_driver_sqlite.go +++ b/database/gdb/gdb_driver_sqlite.go @@ -12,8 +12,10 @@ package gdb import ( "database/sql" + "fmt" "github.com/gogf/gf/internal/intlog" "github.com/gogf/gf/text/gstr" + "strings" ) // DriverSqlite is the driver for sqlite database. @@ -59,17 +61,52 @@ func (d *DriverSqlite) HandleSqlBeforeCommit(link Link, sql string, args []inter // Tables retrieves and returns the tables of current schema. // It's mainly used in cli tool chain for automatically generating the models. -// TODO func (d *DriverSqlite) Tables(schema ...string) (tables []string, err error) { + var result Result + + result, err = d.DB.DoGetAll(nil, `SELECT NAME FROM SQLITE_MASTER WHERE TYPE='table' ORDER BY NAME`) + if err != nil { + return + } + for _, m := range result { + for _, v := range m { + tables = append(tables, v.String()) + } + } return } // TableFields retrieves and returns the fields information of specified table of current schema. -// TODO func (d *DriverSqlite) TableFields(table string, schema ...string) (fields map[string]*TableField, err error) { table = gstr.Trim(table) if gstr.Contains(table, " ") { panic("function TableFields supports only single table operations") } + + checkSchema := d.DB.GetSchema() + if len(schema) > 0 && schema[0] != "" { + checkSchema = schema[0] + } + v := d.DB.GetCache().GetOrSetFunc( + fmt.Sprintf(`sqlite_table_fields_%s_%s`, table, checkSchema), func() interface{} { + var result Result + + result, err = d.DB.DoGetAll(nil, fmt.Sprintf(`PRAGMA TABLE_INFO(%s)`, table)) + if err != nil { + return nil + } + fields = make(map[string]*TableField) + for i, m := range result { + fields[strings.ToLower(m["name"].String())] = &TableField{ + Index: i, + Name: strings.ToLower(m["name"].String()), + Type: strings.ToLower(m["type"].String()), + } + } + return fields + }, 0) + if err == nil { + fields = v.(map[string]*TableField) + } return }