123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- package cmd
- import (
- "database/sql"
- "fmt"
- "os"
- "strings"
- "xg_once_query/dbBase"
- "xg_once_query/setting"
- )
- func CmdInit(db *sql.DB) {
- args := os.Args[1:]
- if len(args) == 0 {
- fmt.Println("没有参数")
- //view(db)
- return
- }
- first := args[0]
- switch first {
- case "--":
- var sql string
- if len(args[1:]) == 0 {
- fmt.Println("“-”缺少映射指令")
- return
- }
- //setting.PrintSqlMap()
- //println("args[1]", args[1])
- if setting.SqlMaps[args[1]] == nil {
- fmt.Println("不存在的映射指令")
- return
- } else {
- sql = setting.SqlMaps[args[1]].(string)
- }
- sql = strings.TrimSpace(sql)
- //%s替换
- countArguments(&sql, args)
- //Limit添加
- if setting.SInfo.Limit != "0" {
- if sql[len(sql)-1] == ';' {
- index := len(sql) - 2
- sql := sql[:index+1] + " limit " + setting.SInfo.Limit
- fmt.Println("sql: ", sql)
- dbBase.DbQuery(db, sql)
- break
- }
- sql = fmt.Sprintf(sql+" limit %s", setting.SInfo.Limit)
- fmt.Println("sql: ", sql)
- }
- fmt.Println("sql: ", sql)
- dbBase.DbQuery(db, sql)
- case "-":
- sql := args[1]
- if sql == "" {
- fmt.Println("指令为空")
- break
- }
- fmt.Println("sql: ", sql)
- dbBase.DbQuery(db, sql)
- default:
- //fmt.Println("cmd = default")
- sql := args[0]
- if sql == "" {
- fmt.Println("指令为空")
- break
- }
- }
- }
- func countArguments(sql *string, args []string) {
- // 计算 %s 的出现次数
- count := strings.Count(*sql, "%s")
- switch count {
- case 0:
- break
- case 1:
- if len(args) < 3 {
- fmt.Println("缺少参数")
- return
- }
- *sql = strings.Replace(*sql, "%s", args[2], 1)
- case 2:
- if len(args) < 4 {
- fmt.Println("缺少参数")
- return
- } else {
- *sql = strings.Replace(*sql, "%s", args[2], 1)
- *sql = strings.Replace(*sql, "%s", args[3], 1)
- }
- case 3:
- if len(args) < 5 {
- fmt.Println("缺少参数")
- return
- } else {
- *sql = strings.Replace(*sql, "%s", args[2], 1)
- *sql = strings.Replace(*sql, "%s", args[3], 1)
- *sql = strings.Replace(*sql, "%s", args[4], 1)
- }
- case 4:
- if len(args) < 6 {
- fmt.Println("缺少参数")
- return
- } else {
- *sql = strings.Replace(*sql, "%s", args[2], 1)
- *sql = strings.Replace(*sql, "%s", args[3], 1)
- *sql = strings.Replace(*sql, "%s", args[4], 1)
- *sql = strings.Replace(*sql, "%s", args[5], 1)
- }
- default:
- fmt.Println("缺少参数")
- return
- }
- }
|