Beispiel #1
0
func SetEngine() (err error) {
	switch DbCfg.Type {
	case "mysql":
		orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
			DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name))
	case "postgres":
		orm, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s",
			DbCfg.User, DbCfg.Pwd, DbCfg.Name, DbCfg.SslMode))
	case "sqlite3":
		os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
		orm, err = xorm.NewEngine("sqlite3", DbCfg.Path)
	default:
		return fmt.Errorf("Unknown database type: %s", DbCfg.Type)
	}
	if err != nil {
		return fmt.Errorf("models.init(fail to conntect database): %v", err)
	}

	// WARNNING: for serv command, MUST remove the output to os.stdout,
	// so use log file to instead print to stdout.
	execDir, _ := base.ExecDir()
	logPath := execDir + "/log/xorm.log"
	os.MkdirAll(path.Dir(logPath), os.ModePerm)

	f, err := os.Create(logPath)
	if err != nil {
		return fmt.Errorf("models.init(fail to create xorm.log): %v", err)
	}
	orm.Logger = f

	orm.ShowSQL = true
	orm.ShowDebug = true
	orm.ShowErr = true
	return nil
}
Beispiel #2
0
func setEngine() {
	var err error
	switch DbCfg.Type {
	case "mysql":
		orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@%s/%s?charset=utf8",
			DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name))
	case "postgres":
		orm, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s",
			DbCfg.User, DbCfg.Pwd, DbCfg.Name, DbCfg.SslMode))
	case "sqlite3":
		os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
		orm, err = xorm.NewEngine("sqlite3", DbCfg.Path)
	default:
		fmt.Printf("Unknown database type: %s\n", DbCfg.Type)
		os.Exit(2)
	}
	if err != nil {
		fmt.Printf("models.init(fail to conntect database): %v\n", err)
		os.Exit(2)
	}

	// WARNNING: for serv command, MUST remove the output to os.stdout,
	// so use log file to instead print to stdout.

	//x.ShowDebug = true
	//orm.ShowErr = true
	f, err := os.Create("xorm.log")
	if err != nil {
		fmt.Printf("models.init(fail to create xorm.log): %v\n", err)
		os.Exit(2)
	}
	orm.Logger = f
	orm.ShowSQL = true
}
Beispiel #3
0
func XConDb() (*xorm.Engine, error) {
	switch {
	case dbtype == "sqlite":
		return xorm.NewEngine("sqlite3", DbName)

	case dbtype == "mysql":
		return xorm.NewEngine("mysql", "user=mysql password=jn!@#9^&* dbname=mysql")

	case dbtype == "pgsql":
		return xorm.NewEngine("postgres", "user=postgres password=jn!@#$%^&* dbname=pgsql sslmode=disable")
	}
	return nil, errors.New("尚未设定数据库连接")
}
Beispiel #4
0
func ConDb() (*xorm.Engine, error) {
	switch {
	case dbtype == "sqlite":
		return xorm.NewEngine("sqlite3", "./data/sqlite.db")

	case dbtype == "mysql":
		return xorm.NewEngine("mysql", "user=mysql password=jn!@#9^&* dbname=mysql")

	case dbtype == "pgsql":
		// "user=postgres password=jn!@#$%^&* dbname=pgsql sslmode=disable maxcons=10 persist=true"
		//return xorm.NewEngine("postgres", "host=110.76.39.205 user=postgres password=LhS88root dbname=pgsql sslmode=disable")
		return xorm.NewEngine("postgres", "user=postgres password=LhS88root dbname=mzr sslmode=disable")
	}
	return nil, errors.New("尚未设定数据库连接")
}
Beispiel #5
0
//设置数据库
func SetDB() {
	path, _ := filepath.Abs("")
	c, _ := config.ReadDefault(fmt.Sprintf("%s/admin/conf/databases.conf", path))

	driver, _ := c.String("database", "db.driver")
	dbname, _ := c.String("database", "db.dbname")
	user, _ := c.String("database", "db.user")
	password, _ := c.String("database", "db.password")
	host, _ := c.String("database", "db.host")
	//prefix, _ := c.String("database", "db.prefix")

	//数据库链接
	var err error
	Engine, err = xorm.NewEngine(driver, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", user, password, host, dbname))
	if err != nil {
		revel.WARN.Printf("错误: %v", err)
	}

	//缓存方式是存放到内存中,缓存struct的记录数为1000条
	//cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
	//Engine.SetDefaultCacher(cacher)

	//控制台打印SQL语句
	//Engine.ShowSQL = true

	//控制台打印调试信息
	//Engine.ShowDebug = true

	//控制台打印错误信息
	//Engine.ShowErr = true

	//控制台打印警告信息
	//Engine.ShowWarn = true
}
Beispiel #6
0
func ConnectDb() (*xorm.Engine, error) {
	fmt.Println("database type: " + dbtype)
	switch {
	case dbtype == "sqlite":
		return xorm.NewEngine("sqlite3", dbname)

	case dbtype == "mysql":
		return xorm.NewEngine("mysql", fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v",
			dbuser, dbpassword, dbhost, dbport, dbname, dbcharset))

	case dbtype == "pgsql":
		return xorm.NewEngine("postgres", fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v",
			dbuser, dbpassword, dbhost, dbport, dbname, dbcharset))
	}
	return nil, errors.New("No database found!")
}
Beispiel #7
0
func setEngine() {
	dbName := utils.Cfg.MustValue("db", "name")
	dbPwd := utils.Cfg.MustValue("db", "pwd_"+runtime.GOOS)

	if runtime.GOOS == "darwin" {
		u, err := user.Current()
		if err != nil {
			beego.Critical("models.init -> fail to get user:"******"db", "pwd_"+runtime.GOOS+"_"+u.Username)
	}

	var err error
	x, err = xorm.NewEngine("mysql", fmt.Sprintf("%v:%v@%v/%v?charset=utf8",
		utils.Cfg.MustValue("db", "user"), dbPwd,
		utils.Cfg.MustValue("db", "host"), dbName))
	if err != nil {
		beego.Critical("models.init -> fail to conntect database:", err.Error())
		os.Exit(2)
	}

	if beego.RunMode != "pro" {
		x.ShowDebug = true
		x.ShowErr = true
		//x.ShowSQL = true
	}

	beego.Trace("Initialized database ->", dbName)
}
Beispiel #8
0
Datei: xo.go Projekt: rose312/mzr
func ConDb() *xorm.Engine {

	/*
		engine, _ = xorm.NewEngine("sqlite3", "./test.db")
	*/
	engine, _ = xorm.NewEngine("postgres", "user=postgres password=jn!@#$%^&* dbname=pgsql sslmode=disable")
	return engine
}
Beispiel #9
0
// should be call before pacakge called
func InitDB(driver, dataSource string) (err error) {
	x, err = xorm.NewEngine(driver, dataSource)
	if err != nil {
		return
	}
	// create tables
	return x.Sync(new(Project), new(File))
}
Beispiel #10
0
func InitOrm() *xorm.Engine {
	LoadDBConfig()
	orm, err := xorm.NewEngine("postgres", fmt.Sprintf("user=%s dbname=%s sslmode=%s",
		DBConfig.User, DBConfig.Name, DBConfig.SslMode))
	if err != nil {
		panic(err)
	}
	return orm
}
Beispiel #11
0
func NewTestEngine(x *xorm.Engine) (err error) {
	switch DbCfg.Type {
	case "mysql":
		x, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
			DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name))
	case "postgres":
		x, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s",
			DbCfg.User, DbCfg.Pwd, DbCfg.Name, DbCfg.SslMode))
	// case "sqlite3":
	// 	os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
	// 	x, err = xorm.NewEngine("sqlite3", DbCfg.Path)
	default:
		return fmt.Errorf("Unknown database type: %s", DbCfg.Type)
	}
	if err != nil {
		return fmt.Errorf("models.init(fail to conntect database): %v", err)
	}

	return x.Sync(new(User), new(PublicKey), new(Repository), new(Watch),
		new(Action), new(Access), new(Issue), new(Comment))
}
func SetupDb() (engine *xorm.Engine) {
	var (
		err error
	)

	if engine, err = xorm.NewEngine("sqlite3", "/tmp/tmp.db"); err != nil {
		panic(err)
	}

	if err = engine.Sync(new(User)); err != nil {
		panic(err)
	}

	return engine
}
Beispiel #13
0
func (s *ServerType) init() {

	s.DB, err = xorm.NewEngine("mysql", s.MYSQL_DSN)
	if err != nil {
		panic(err)
	}
	s.DB.ShowSQL = s.MYSQL_DEBUG

	if s.PHP_CLI == "" {
		s.PHP_CLI = DEFAULT_PHP_CLI
	}

	if s.LogFile != "" {
		logFile, err := os.OpenFile(s.LogFile, os.O_RDWR|os.O_CREATE, 0666)
		if err != nil {
			panic(err)
		}
		log.SetOutput(logFile)
	}

	//worker_num为0表示不启用PHP引擎
	if s.PHP_WORKER_NUM != 0 {

		if s.PHP_TPL_DIR == "" {
			s.PHP_TPL_DIR = s.Root + "/static/template/"
		}

		//php模板引擎
		s.PHP = php.NewEngine(s.PHP_WORKER_NUM, s.PHP_CLI, s.PHP_TPL_DIR)
		//设置PHP的运行路径
		s.PHP.RunDir = s.Root
		//初始化
		s.PHP.Init()

		go s.PHP.EngineLoop()
	}

	go Session_CheckExpire()

	//默认
	if s.DefaultAction == "" {
		s.DefaultAction = "index"
	}
	if s.DefaultController == "" {
		s.DefaultController = "Base"
	}
	s.Charset = "utf-8"
}
Beispiel #14
0
func init() {
	st := NewSuite("xorm")
	st.InitF = func() {
		st.AddBenchmark("Insert", 2000*ORM_MULTI, XormInsert)
		st.AddBenchmark("MultiInsert 100 row", 500*ORM_MULTI, XormInsertMulti)
		st.AddBenchmark("Update", 2000*ORM_MULTI, XormUpdate)
		st.AddBenchmark("Read", 4000*ORM_MULTI, XormRead)
		st.AddBenchmark("MultiRead limit 100", 2000*ORM_MULTI, XormReadSlice)

		engine, _ := xorm.NewEngine("mysql", ORM_SOURCE)

		engine.SetMaxIdleConns(ORM_MAX_IDLE)
		engine.SetMaxConns(ORM_MAX_CONN)

		xo = engine.NewSession()
	}
}
Beispiel #15
0
func init() {
	var err error
	orm, err = xorm.NewEngine("sqlite3", "./test.db")
	if err != nil {
		fmt.Println(err)
	}

	orm.ShowSQL = true
	orm.ShowDebug = true

	err = orm.Sync(&User{}, &Repository{})
	if err != nil {
		fmt.Println(err)
	}

	base.RepoRootPath = "test"
}
Beispiel #16
0
func Init() {
	var found bool
	var driver string
	if driver, found = r.Config.String("db.driver"); !found {
		r.ERROR.Fatal("No db.driver found.")
	}
	var spec string
	if spec, found = r.Config.String("db.spec"); !found {
		spec = calcSpec()
	}
	r.INFO.Printf("Connecting to mysql at %v", spec)
	engine, err := xorm.NewEngine(driver, spec)
	if err != nil {
		panic(err)
	}
	Engine = engine
}
Beispiel #17
0
func init() {
	LoadModelsConfig()
	NewEngine()

	var err error
	orm, err = xorm.NewEngine("sqlite3", "./test.db")
	if err != nil {
		fmt.Println(err)
	}

	orm.ShowSQL = true
	orm.ShowDebug = true

	err = orm.Sync(&User{}, &Repo{})
	if err != nil {
		fmt.Println(err)
	}

	root = "test"
}
Beispiel #18
0
func setEngine() {
	dbName := utils.Cfg.MustValue("db", "name")
	dbPwd := utils.Cfg.MustValue("db", "pwd")

	var err error
	x, err = xorm.NewEngine("mysql", fmt.Sprintf("%v:%v@%v/%v?charset=utf8",
		utils.Cfg.MustValue("db", "user"), dbPwd,
		utils.Cfg.MustValue("db", "host"), dbName))
	if err != nil {
		log.Fatalf("models.init -> fail to conntect database: %v", err)
	}

	if beego.RunMode != "pro" {
		// x.ShowDebug = true
		x.ShowErr = true
		//x.ShowSQL = true
	}

	beego.Trace("Initialized database ->", dbName)
}
func main() {
	var err error
	baseDirectory, err = findRoot()
	checkErr(err)

	fmt.Println("base directory =", baseDirectory)
	dbPath := fmt.Sprintf("%s/news.db", []byte(baseDirectory))
	engine, err = xorm.NewEngine(xorm.SQLITE, dbPath)
	if err != nil {
		return
	}
	defer engine.Close()
	engine.ShowSQL = true

	go Crawl(engine)

	router := new(RegexpHandler)

	re, err := regexp.Compile("/css/*")
	checkErr(err)
	dir := fmt.Sprintf("%s/static/", []byte(baseDirectory))
	router.Handler(re, http.FileServer(http.Dir(dir)))

	re, err = regexp.Compile("/js/*")
	checkErr(err)
	router.Handler(re, http.FileServer(http.Dir(dir)))

	re, err = regexp.Compile("/article")
	checkErr(err)
	router.HandleFunc(re, ViewArticle)

	re, err = regexp.Compile("/*")
	checkErr(err)
	router.HandleFunc(re, ListArticles)

	err = http.ListenAndServe(":8080", router)
	checkErr(err)

}
Beispiel #20
0
func postgresEngine() (*xorm.Engine, error) {
	return xorm.NewEngine("postgres", "dbname=xorm_test sslmode=disable")
}
Beispiel #21
0
func main() {
	f := "cache.db"
	os.Remove(f)

	Orm, err := xorm.NewEngine("sqlite3", f)
	if err != nil {
		fmt.Println(err)
		return
	}
	Orm.ShowSQL = true
	cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
	Orm.SetDefaultCacher(cacher)

	err = Orm.CreateTables(&User{})
	if err != nil {
		fmt.Println(err)
		return
	}

	_, err = Orm.Insert(&User{Name: "xlw"})
	if err != nil {
		fmt.Println(err)
		return
	}

	users := make([]User, 0)
	err = Orm.Find(&users)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("users:", users)

	users2 := make([]User, 0)

	err = Orm.Find(&users2)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("users2:", users2)

	users3 := make([]User, 0)

	err = Orm.Find(&users3)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("users3:", users3)

	user4 := new(User)
	has, err := Orm.Id(1).Get(user4)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("user4:", has, user4)

	user4.Name = "xiaolunwen"
	_, err = Orm.Id(1).Update(user4)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("user4:", user4)

	user5 := new(User)
	has, err = Orm.Id(1).Get(user5)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("user5:", has, user5)

	_, err = Orm.Id(1).Delete(new(User))
	if err != nil {
		fmt.Println(err)
		return
	}

	for {
		user6 := new(User)
		has, err = Orm.Id(1).Get(user6)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println("user6:", has, user6)
	}
}
Beispiel #22
0
func runReverse(cmd *Command, args []string) {
	num := checkFlags(cmd.Flags, args, printReversePrompt)
	if num == -1 {
		return
	}
	args = args[num:]

	if len(args) < 3 {
		fmt.Println("params error, please see xorm help reverse")
		return
	}

	var isMultiFile bool = true
	if use, ok := cmd.Flags["-s"]; ok {
		isMultiFile = !use
	}

	curPath, err := os.Getwd()
	if err != nil {
		fmt.Println(curPath)
		return
	}

	var genDir string
	var model string
	if len(args) == 4 {

		genDir, err = filepath.Abs(args[3])
		if err != nil {
			fmt.Println(err)
			return
		}
		model = path.Base(genDir)
	} else {
		model = "model"
		genDir = path.Join(curPath, model)
	}

	dir, err := filepath.Abs(args[2])
	if err != nil {
		logging.Error("%v", err)
		return
	}

	if !dirExists(dir) {
		logging.Error("Template %v path is not exist", dir)
		return
	}

	var langTmpl LangTmpl
	var ok bool
	var lang string = "go"

	cfgPath := path.Join(dir, "config")
	info, err := os.Stat(cfgPath)
	var configs map[string]string
	if err == nil && !info.IsDir() {
		configs = loadConfig(cfgPath)
		if l, ok := configs["lang"]; ok {
			lang = l
		}
		if j, ok := configs["genJson"]; ok {
			genJson, err = strconv.ParseBool(j)
		}
	}

	if langTmpl, ok = langTmpls[lang]; !ok {
		fmt.Println("Unsupported programing language", lang)
		return
	}

	os.MkdirAll(genDir, os.ModePerm)

	Orm, err := xorm.NewEngine(args[0], args[1])
	if err != nil {
		logging.Error("%v", err)
		return
	}

	tables, err := Orm.DBMetas()
	if err != nil {
		logging.Error("%v", err)
		return
	}

	filepath.Walk(dir, func(f string, info os.FileInfo, err error) error {
		if info.IsDir() {
			return nil
		}

		if info.Name() == "config" {
			return nil
		}

		bs, err := ioutil.ReadFile(f)
		if err != nil {
			logging.Error("%v", err)
			return err
		}

		t := template.New(f)
		t.Funcs(langTmpl.Funcs)

		tmpl, err := t.Parse(string(bs))
		if err != nil {
			logging.Error("%v", err)
			return err
		}

		var w *os.File
		fileName := info.Name()
		newFileName := fileName[:len(fileName)-4]
		ext := path.Ext(newFileName)

		if !isMultiFile {
			w, err = os.OpenFile(path.Join(genDir, newFileName), os.O_RDWR|os.O_CREATE, 0600)
			if err != nil {
				logging.Error("%v", err)
				return err
			}

			imports := langTmpl.GenImports(tables)

			tbls := make([]*xorm.Table, 0)
			for _, table := range tables {
				tbls = append(tbls, table)
			}

			newbytes := bytes.NewBufferString("")

			t := &Tmpl{Tables: tbls, Imports: imports, Model: model}
			err = tmpl.Execute(newbytes, t)
			if err != nil {
				logging.Error("%v", err)
				return err
			}

			tplcontent, err := ioutil.ReadAll(newbytes)
			if err != nil {
				logging.Error("%v", err)
				return err
			}
			var source string
			if langTmpl.Formater != nil {
				source, err = langTmpl.Formater(string(tplcontent))
				if err != nil {
					logging.Error("%v", err)
					return err
				}
			} else {
				source = string(tplcontent)
			}

			w.WriteString(source)
			w.Close()
		} else {
			for _, table := range tables {
				// imports
				tbs := []*xorm.Table{table}
				imports := langTmpl.GenImports(tbs)

				w, err := os.OpenFile(path.Join(genDir, unTitle(mapper.Table2Obj(table.Name))+ext), os.O_RDWR|os.O_CREATE, 0600)
				if err != nil {
					logging.Error("%v", err)
					return err
				}

				newbytes := bytes.NewBufferString("")

				t := &Tmpl{Tables: tbs, Imports: imports, Model: model}
				err = tmpl.Execute(newbytes, t)
				if err != nil {
					logging.Error("%v", err)
					return err
				}

				tplcontent, err := ioutil.ReadAll(newbytes)
				if err != nil {
					logging.Error("%v", err)
					return err
				}
				var source string
				if langTmpl.Formater != nil {
					source, err = langTmpl.Formater(string(tplcontent))
					if err != nil {
						logging.Error("%v-%v", err, string(tplcontent))
						return err
					}
				} else {
					source = string(tplcontent)
				}

				w.WriteString(source)
				w.Close()
			}
		}

		return nil
	})

}
Beispiel #23
0
func sqliteEngine() (*xorm.Engine, error) {
	os.Remove("./test.db")
	return xorm.NewEngine("sqlite3", "./goroutine.db")
}
Beispiel #24
0
func mysqlEngine() (*xorm.Engine, error) {
	return xorm.NewEngine("mysql", "root:@/test?charset=utf8")
}
Beispiel #25
0
func main() {
	//runtime.GOMAXPROCS(2)

	// load config
	var err error
	cfg, err := config.Load("config.ini")
	if err != nil {
		fmt.Println(err)
		return
	}

	cfgs := cfg.Map()

	// create Orm
	var orm *xorm.Engine
	orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%v:%v@%v/%v?charset=utf8",
		cfgs["dbuser"], cfgs["dbpasswd"], cfgs["dbhost"], cfgs["dbname"]))
	if err != nil {
		fmt.Println(err)
		return
	}
	orm.ShowSQL, _ = cfg.GetBool("showSql")
	orm.ShowDebug, _ = cfg.GetBool("showDebug")

	err = orm.Sync(&User{}, &Question{},
		&QuestionFollow{}, &UserFollow{}, &Answer{}, &AnswerUp{},
		&QuestionComment{}, &AnswerComment{}, &Tag{}, &QuestionTag{},
		&Message{}, &Topic{}, &QuestionTopic{}, &TopicFollow{}, &News{})

	if err != nil {
		fmt.Println(err)
		return
	}

	server := xweb.MainServer()
	app := xweb.RootApp()
	app.SetConfig("Orm", orm)

	if useCache, _ := cfg.GetBool("useCache"); useCache {
		server.Info("using orm cache system ...")
		cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
		orm.SetDefaultCacher(cacher)
	}

	// add actions
	xweb.AddAction(&HomeAction{})
	xweb.AutoAction(&ExerciseAction{}, &QuestionAction{}, &NewsAction{})
	xweb.AddAction(&UserAction{})

	// add login filter
	loginFilter := xweb.NewLoginFilter(app, USER_ID_TAG, "/login")
	loginFilter.AddAnonymousUrls("/", "/exercise", "/exercise/compile",
		"/news", "/login", "/about", "/register")
	app.AddFilter(loginFilter)

	// add func or var app scope
	app.AddTmplVar("AppVer", func() string {
		return "v" + APP_VER
	})

	// run the web server
	xweb.Run(fmt.Sprintf("%v:%v", cfgs["address"], cfgs["port"]))
}
Beispiel #26
0
func runShell(cmd *Command, args []string) {
	if len(args) != 2 {
		fmt.Println("params error, please see xorm help shell")
		return
	}

	var err error
	engine, err = xorm.NewEngine(args[0], args[1])
	if err != nil {
		fmt.Println(err)
		return
	}

	err = engine.Ping()
	if err != nil {
		fmt.Println(err)
		return
	}

	var scmd string
	fmt.Print("xorm$ ")
	for {
		var input string
		_, err := fmt.Scan(&input)
		if err != nil {
			fmt.Println(err)
			continue
		}
		if strings.ToLower(input) == "exit" {
			fmt.Println("bye")
			return
		}
		if !strings.HasSuffix(input, ";") {
			scmd = scmd + " " + input
			continue
		}
		scmd = scmd + " " + input
		lcmd := strings.TrimSpace(strings.ToLower(scmd))
		if strings.HasPrefix(lcmd, "select") {
			res, err := engine.Query(scmd + "\n")
			if err != nil {
				fmt.Println(err)
			} else {
				if len(res) <= 0 {
					fmt.Println("no records")
				} else {
					columns := make(map[string]int)
					for k, _ := range res[0] {
						columns[k] = len(k)
					}

					for _, m := range res {
						for k, s := range m {
							l := len(string(s))
							if l > columns[k] {
								columns[k] = l
							}
						}
					}

					var maxlen = 0
					for _, l := range columns {
						maxlen = maxlen + l + 3
					}
					maxlen = maxlen + 1

					fmt.Println(strings.Repeat("-", maxlen))
					fmt.Print("|")
					slice := make([]string, 0)
					for k, l := range columns {
						fmt.Print(" " + k + " ")
						fmt.Print(strings.Repeat(" ", l-len(k)))
						fmt.Print("|")
						slice = append(slice, k)
					}
					fmt.Print("\n")
					for _, r := range res {
						fmt.Print("|")
						for _, k := range slice {
							fmt.Print(" " + string(r[k]) + " ")
							fmt.Print(strings.Repeat(" ", columns[k]-len(string(r[k]))))
							fmt.Print("|")
						}
						fmt.Print("\n")
					}
					fmt.Println(strings.Repeat("-", maxlen))
					//fmt.Println(res)
				}
			}
		} else if lcmd == "show tables;" {
			tables, err := engine.DBMetas()
			if err != nil {
				fmt.Println(err)
			} else {

			}
		} else {
			cnt, err := engine.Exec(scmd)
			if err != nil {
				fmt.Println(err)
			} else {
				fmt.Printf("%d records changed.\n", cnt)
			}
		}
		scmd = ""
		fmt.Print("xorm$ ")
	}
}
Beispiel #27
0
func sqliteEngine() (*xorm.Engine, error) {
	f := "sync.db"
	//os.Remove(f)

	return xorm.NewEngine("sqlite3", f)
}