package db
|
|
import (
|
"errors"
|
"fmt"
|
"os"
|
"os/exec"
|
"path/filepath"
|
"strings"
|
"sync"
|
)
|
|
var Dbconn *Conn
|
var sy sync.Mutex
|
|
func init() {
|
GetConn()
|
}
|
|
// get Conn of db for do execute.
|
func GetConn() error {
|
var err error
|
path, err := GetCurrentPath()
|
if err != nil {
|
return errors.New("get current path error")
|
}
|
|
filepath := fmt.Sprintf("%stest.db", path)
|
fmt.Println("self: ========>", filepath)
|
db, err := New(filepath, "", false)
|
if err != nil {
|
fmt.Println("new db database: ", err)
|
return err
|
}
|
Dbconn, err = db.Connect()
|
if err != nil {
|
fmt.Println("new db conn error; ", err)
|
return err
|
}
|
return nil
|
}
|
|
//bak dbdata.
|
func BakDbFile() (string, error) {
|
|
path, err := GetCurrentPath()
|
if err != nil {
|
return "", errors.New("get current path error")
|
}
|
|
filepath := fmt.Sprintf("%stmptest.db", path)
|
db, err := New(filepath, "", false)
|
if err != nil {
|
fmt.Println("new db database: ", err)
|
return "", err
|
}
|
|
tmpconn, err := db.Connect()
|
if err != nil {
|
fmt.Println("new db conn error; ", err)
|
return "", err
|
}
|
defer tmpconn.Close()
|
|
err = Dbconn.Backup(tmpconn)
|
if err != nil {
|
return "", err
|
}
|
return filepath, nil
|
}
|
|
// do exet when get querystring.
|
func DoExecute(executestring []string) ([]*Result, error) {
|
sy.Lock()
|
defer sy.Unlock()
|
allResults, err := Dbconn.Execute(executestring, false, false)
|
if err != nil {
|
fmt.Println("execute error!", err)
|
return nil, err
|
}
|
return allResults, nil
|
}
|
|
// get current path
|
func GetCurrentPath() (string, error) {
|
file, err := exec.LookPath(os.Args[0])
|
if err != nil {
|
return "", err
|
}
|
path, err := filepath.Abs(file)
|
if err != nil {
|
return "", err
|
}
|
i := strings.LastIndex(path, "/")
|
if i < 0 {
|
i = strings.LastIndex(path, "\\")
|
}
|
if i < 0 {
|
return "", errors.New(`error: Can't find "/" or "\".`)
|
}
|
return string(path[0 : i+1]), nil
|
}
|
|
func Dumpdb() {
|
|
var b strings.Builder
|
if err := Dbconn.Dump(&b); err != nil {
|
fmt.Println("dump file ", err.Error())
|
}
|
fmt.Printf("%T\n", b)
|
}
|