Ejemplo n.º 1
0
func initDb() {
	var err error
	Engine, err = xorm.NewEngine("mysql", mysql_dsn)

	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}

	tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, "pk_")
	Engine.SetTableMapper(tbMapper)

	Engine.ShowSQL = true   //则会在控制台打印出生成的SQL语句;
	Engine.ShowDebug = true //则会在控制台打印调试信息;
	Engine.ShowErr = true   //则会在控制台打印错误信息;
	Engine.ShowWarn = true  //则会在控制台打印警告信息;

	f, err := os.Create("sql.log")
	if err != nil {
		println("error:")
		println(err.Error())
		return
	}
	defer f.Close()
	Engine.Logger = xorm.NewSimpleLogger(f)
	//	fmt.Println(Engine)
}
Ejemplo n.º 2
0
func OpenDb(dbConf DbConf) *xorm.Engine {

	engine, err := xorm.NewEngine(DbUrl(dbConf))
	if err != nil {
		log.Println(err)
	}
	//sql log
	engine.ShowSQL = dbConf.ShowSql
	engine.ShowErr = true
	engine.ShowWarn = true

	engine.SetMaxIdleConns(dbConf.MaxIdleConns)
	engine.SetMaxOpenConns(dbConf.MaxOpenConns)

	dbLog, err = os.Create("logs/db.log")
	if err != nil {
		log.Println("err:", err)
	}
	engine.Logger = xorm.NewSimpleLogger(dbLog)
	//init tx
	dbx.InitTx(engine)

	db = engine
	return engine
}
Ejemplo n.º 3
0
func init() {
	// 创建 ORM 引擎与数据库
	var err error
	x, err = xorm.NewEngine("sqlite3", "./bank.db")
	if err != nil {
		log.Fatalf("Fail to create engine: %v\n", err)
	}

	// 同步结构体与数据表
	if err = x.Sync(new(Account)); err != nil {
		log.Fatalf("Fail to sync database: %v\n", err)
	}

	// 记录日志
	f, err := os.Create("sql.log")
	if err != nil {
		log.Fatalf("Fail to create log file: %v\n", err)
		return
	}
	x.Logger = xorm.NewSimpleLogger(f)
	x.ShowSQL = true

	// 设置默认 LRU 缓存
	cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
	x.SetDefaultCacher(cacher)
}
Ejemplo n.º 4
0
func SetEngine() (*xorm.Engine, error) {

	if engine, err := ConDb(); err != nil {

		return nil, err
	} else {

		engine.ShowInfo = false
		engine.ShowSQL = true   //true则会在控制台打印出生成的SQL语句;
		engine.ShowDebug = true //true则会在控制台打印调试信息;
		engine.ShowWarn = true  //true则会在控制台打印警告信息;
		engine.Logger.SetLevel(core.LOG_OFF)

		cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 10000)
		engine.SetDefaultCacher(cacher)
		//engine.TZLocation = time.Local

		if f, err := os.Create("./logs/xorm.log"); err != nil {
			panic(fmt.Sprintf("Create Xorm Logs Error :%v", err))
		} else {
			engine.Logger = xorm.NewSimpleLogger(f)
		}

		return engine, err
	}
}
Ejemplo n.º 5
0
func SetEngine(engine *xorm.Engine, enableLog bool) (err error) {
	x = engine
	dialect = migrator.NewDialect(x.DriverName())

	migrator := migrator.NewMigrator(x)
	migrator.LogLevel = 2
	migrations.AddMigrations(migrator)

	if err := migrator.Start(); err != nil {
		return fmt.Errorf("Sqlstore::Migration failed err: %v\n", err)
	}

	if enableLog {
		logPath := path.Join("/tmp", "xorm.log")
		os.MkdirAll(path.Dir(logPath), os.ModePerm)
		f, err := os.Create(logPath)
		if err != nil {
			return fmt.Errorf("sqlstore.init(fail to create xorm.log): %v", err)
		}
		x.SetLogger(xorm.NewSimpleLogger(f))
		x.ShowSQL(true)
	}

	return nil
}
Ejemplo n.º 6
0
func CreateEngine(cfg *config.Config) (engine *xorm.Engine, err error) {
	x, err = getEngine(cfg)
	if err != nil {
		return nil, fmt.Errorf("Fail to connect to database: %v", err)
	}

	if cfg.Database.LogPath != "" {
		logPath := path.Join(cfg.Database.LogPath, "xorm.log")
		os.MkdirAll(path.Dir(logPath), os.ModePerm)

		file, err := os.Create(logPath)
		if err != nil {
			return nil, fmt.Errorf("Fail to create xorm.log file: %v", err)
		}
		x.SetLogger(xorm.NewSimpleLogger(file))
	}

	x.ShowDebug = cfg.Database.ShowDebug
	x.ShowInfo = cfg.Database.ShowInfo
	x.ShowSQL = cfg.Database.ShowSQL
	x.ShowWarn = cfg.Database.ShowWarn
	x.ShowErr = cfg.Database.ShowErr

	// 如果有其他orm相关设置, 请直接设置即可

	return x, nil
}
Ejemplo n.º 7
0
func SetEngine() (err error) {
	x, err = getEngine()
	if err != nil {
		return fmt.Errorf("Fail to connect to database: %v", err)
	}

	x.SetMapper(core.GonicMapper{})

	// WARNING: for serv command, MUST remove the output to os.stdout,
	// so use log file to instead print to stdout.
	logPath := path.Join( /*setting.LogRootPath*/ "log", "xorm.log")
	os.MkdirAll(path.Dir(logPath), os.ModePerm)

	f, err := os.Create(logPath)
	if err != nil {
		return fmt.Errorf("Fail to create xorm.log: %v", err)
	}
	x.SetLogger(xorm.NewSimpleLogger(f))

	x.ShowSQL = true
	x.ShowInfo = true
	x.ShowDebug = true
	x.ShowErr = true
	x.ShowWarn = true
	return nil
}
Ejemplo n.º 8
0
func SetEngine(engine *xorm.Engine, enableLog bool) (err error) {
	x = engine
	dialect = migrator.NewDialect(x.DriverName())

	migrator := migrator.NewMigrator(x)
	migrator.LogLevel = log.INFO
	migrations.AddMigrations(migrator)

	if err := migrator.Start(); err != nil {
		return fmt.Errorf("Sqlstore::Migration failed err: %v\n", err)
	}

	if enableLog {
		logPath := path.Join(setting.LogsPath, "xorm.log")
		os.MkdirAll(path.Dir(logPath), os.ModePerm)

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

		if setting.Env == setting.DEV {
			x.ShowSQL = false
			x.ShowInfo = false
			x.ShowDebug = false
			x.ShowErr = true
			x.ShowWarn = true
		}
	}

	return nil
}
Ejemplo n.º 9
0
Archivo: models.go Proyecto: hzmnet/api
func newEngine(conf setting.DataBaseConfig) (*xorm.Engine, error) {
	cnnstr := ""
	switch conf.TYPE {
	case "mysql":
		if conf.HOST[0] == '/' { // looks like a unix socket
			cnnstr = fmt.Sprintf("%s:%s@unix(%s)/%s?charset=utf8",
				conf.USER, conf.PASSWD, conf.HOST, conf.DB)
		} else {
			cnnstr = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
				conf.USER, conf.PASSWD, conf.HOST, conf.DB)
		}
	case "postgres":
		var host, port = "127.0.0.1", "5432"
		fields := strings.Split(conf.HOST, ":")
		if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
			host = fields[0]
		}
		if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
			port = fields[1]
		}
		cnnstr = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
			conf.USER, conf.PASSWD, host, port, conf.DB, conf.SSL_MODE)
	case "sqlite3":
		os.MkdirAll(path.Dir(conf.PATH), os.ModePerm)
		cnnstr = "file:" + conf.PATH + "?cache=shared&mode=rwc"
	default:
		return nil, fmt.Errorf("Unknown database type: %s", conf.TYPE)
	}
	x, err := xorm.NewEngine(conf.TYPE, cnnstr)
	if err != nil {
		return nil, err
	}
	// 连接池的空闲数大小
	x.SetMaxIdleConns(conf.MaxIdle)
	// 最大打开连接数
	x.SetMaxOpenConns(conf.MaxOpen)

	x.ShowSQL = true
	// 则会在控制台打印出生成的SQL语句;
	x.ShowDebug = true
	// 则会在控制台打印调试信息;
	x.ShowErr = true
	// 则会在控制台打印错误信息;
	x.ShowWarn = true
	// 则会在控制台打印警告信息;

	logpath, _ := filepath.Abs(conf.LogPath)
	os.MkdirAll(path.Dir(logpath), os.ModePerm)
	// 日志
	f, err := os.Create(logpath)
	if err != nil {
		log.Error(4, "create xorm log file failed %v", err)
		return nil, err
	}
	// defer f.Close()
	x.Logger = xorm.NewSimpleLogger(f)
	return x, nil
}
Ejemplo n.º 10
0
func init() {
	var err error
	mysqlEngine, err = xorm.NewEngine("mysql", "dasea:dasea@/dasea?charset=utf8")
	logger := xorm.NewSimpleLogger(os.Stdout)
	logger.SetLevel(core.LOG_OFF)
	mysqlEngine.SetLogger(logger)
	if err != nil {
		panic(err)
	}
}
Ejemplo n.º 11
0
func init() {
	//获取服务器数据库相关信息
	dbhost, _ := conf.Cfg.GetValue("db", "db_host")
	dbport, _ := conf.Cfg.GetValue("db", "db_port")
	dbuser, _ := conf.Cfg.GetValue("db", "db_user")
	dbpass, _ := conf.Cfg.GetValue("db", "db_pass")
	dbname, _ := conf.Cfg.GetValue("db", "db_name")
	dbIdle, _ := conf.Cfg.Int("db", "db_max_idle_conn")
	dbConn, _ := conf.Cfg.Int("db", "db_max_open_conn")

	dburl := dbuser + ":" + dbpass + "@tcp(" + dbhost + ":" + dbport + ")/" + dbname + "?charset=utf8"

	engine, err := xorm.NewEngine("mysql", dburl)
	if err != nil {
		log.Fatalf("数据库连接失败:%s", err)
	}

	//连接池空闲数和最大连接数
	engine.SetMaxIdleConns(dbIdle)
	engine.SetMaxOpenConns(dbConn)

	//engine.Ping测试数据库连接
	if err = engine.Ping(); err != nil {
		log.Fatalf("数据库连接失败:%s", err)
		os.Exit(1)
	}
	//同步数据结构
	engine.Sync2(new(User))

	runmode, _ := conf.Cfg.GetValue("", "runmode")
	if !strings.EqualFold(runmode, "dev") {
		// 输出sql到log
		var filelog string
		filelog = "log/xorm-sql-" + strings.Split(time.Now().String(), " ")[0] + ".log"
		f, err := os.OpenFile(filelog, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			log.Fatalf("日志文件建立失败:%s", err)
			os.Exit(1)
		}
		engine.Logger = xorm.NewSimpleLogger(f)
	}

	//读取配置文件,设置xorm日志状态
	showSQL, _ := conf.Cfg.GetValue("xorm", "showSql")
	showDebug, _ := conf.Cfg.GetValue("xorm", "showDebug")
	showError, _ := conf.Cfg.GetValue("xorm", "showError")
	showWarn, _ := conf.Cfg.GetValue("xorm", "showWarn")

	engine.ShowSQL = strings.EqualFold(showSQL, "true")
	engine.ShowDebug = strings.EqualFold(showDebug, "true")
	engine.ShowErr = strings.EqualFold(showError, "true")
	engine.ShowWarn = strings.EqualFold(showWarn, "true")

	Xorm = engine
}
Ejemplo n.º 12
0
Archivo: xorm.go Proyecto: ryancsq/test
func main() {
	var err error
	engine, err = xorm.NewEngine("mysql", "root:123456@tcp(192.168.1.172:3306)/jc_test")

	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}

	tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, "pk_")
	engine.SetTableMapper(tbMapper)

	engine.ShowSQL = true   //则会在控制台打印出生成的SQL语句;
	engine.ShowDebug = true //则会在控制台打印调试信息;
	engine.ShowErr = true   //则会在控制台打印错误信息;
	engine.ShowWarn = true  //则会在控制台打印警告信息;
	fmt.Println(err)
	//	fmt.Println(engine.DBMetas())

	//	sql := "show tables"
	//results, err := engine.Query(sql)
	//fmt.Println(results)
	//fmt.Println(err)

	f, err := os.Create("sql.log")
	if err != nil {
		println(err.Error())
		return
	}
	defer f.Close()
	engine.Logger = xorm.NewSimpleLogger(f)
	var odds_url = "http://odds.500.com/fenxi/yazhi-TTT.shtml"

	a := time.Now().Unix() - 86400
	fmt.Println(a)

	yesday := time.Unix(a, 0).Format("2006-01-02")

	schs := make([]Schedule, 0)
	engine.Distinct("schedule_fid", "schedule_no", "schedule_date").Where("schedule_date = ?", yesday).Find(&schs)
	//fmt.Println(schs)
	for _, sch_info := range schs {
		fmt.Println(sch_info.ScheduleFid)
		fid := fmt.Sprintf("%d", sch_info.ScheduleFid)
		schedule_no := sch_info.ScheduleNo
		schedule_date := sch_info.ScheduleDate
		schedule_odds_url := strings.Replace(odds_url, "TTT", fid, -1)
		fmt.Println(schedule_odds_url)

		res := ParseOddUrl(schedule_odds_url, fid, schedule_no, schedule_date)
		fmt.Println(res)

	}

}
Ejemplo n.º 13
0
func (s *Store) SetLogFile(path string) error {
	if path == "" {
		return nil
	}
	f, e := os.Create(path)
	if e != nil {
		return e
	}
	s.eng.Logger = xorm.NewSimpleLogger(f)
	s.eng.ShowSQL = true
	return nil
}
Ejemplo n.º 14
0
// We cannot initialize xorm.Engine in init() function because Opts are
// initialized in init function, and we cannot guarentee that Opts must be
// initialized before any other init functions. So we intialize engine in main.
// We must call meta.InitEngine in main before using it.
func InitEngine(t string, hosts []string) {
	var err error
	//currently we only use one host, we will switch to using
	//2 alternatively in the future
	Engine, err = xorm.NewEngine(t, hosts[0])
	logger := xorm.NewSimpleLogger(os.Stdout)
	logger.SetLevel(core.LOG_OFF)
	Engine.SetLogger(logger)
	if err != nil {
		panic(err)
	}
}
Ejemplo n.º 15
0
func SetEngine() *xorm.Engine {
	Log.Info("db initializing...")
	var err error
	server := Cfg.MustValue("db", "server", "127.0.0.1")
	username := Cfg.MustValue("db", "username", "root")
	password := Cfg.MustValue("db", "password", "pass")
	dbName := Cfg.MustValue("db", "db_name", "go_display")
	orm, err = xorm.NewEngine("mysql", username+":"+password+"@tcp("+server+":3306)/"+dbName+"?charset=utf8")
	PanicIf(err)
	orm.TZLocation = time.Local
	orm.ShowSQL = Cfg.MustBool("db", "show_sql", false)
	orm.Logger = xorm.NewSimpleLogger(Log.GetWriter())
	return orm
}
Ejemplo n.º 16
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":
		var host, port = "127.0.0.1", "5432"
		fields := strings.Split(DbCfg.Host, ":")
		if len(fields) > 0 {
			host = fields[0]
		}
		if len(fields) > 1 {
			port = fields[1]
		}
		orm, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
			DbCfg.User, DbCfg.Pwd, host, port, 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 = xorm.NewSimpleLogger(f)

	orm.ShowSQL = true
	orm.ShowDebug = true
	orm.ShowErr = true
	return nil
}
Ejemplo n.º 17
0
func main() {
	router := httprouter.New()
	router.ServeFiles("/js/*filepath", http.Dir("public/js"))
	router.ServeFiles("/css/*filepath", http.Dir("public/css"))
	router.ServeFiles("/bower_components/*filepath", http.Dir("public/bower_components"))
	router.GET("/", Index)
	router.GET("/user", UserGetHandler)
	router.POST("/user", UserPostHandler)

	// REST API for sfver
	router.GET("/sfvers", SfversGetHandler)
	router.POST("/sfvers", SfversPostHandler)

	go sfvTaskSchedule()

	var err error
	Engine, err = xorm.NewEngine("mysql", "test:1234@/sfver?charset=utf8")
	if err != nil {
		log.Fatal("database err:", err)
	}
	Engine.ShowDebug = true
	Engine.ShowErr = true
	Engine.ShowWarn = true
	Engine.ShowSQL = true
	f, err := os.Create("sql.log")
	if err != nil {
		log.Fatal("sql log create failed", err)
	}
	defer f.Close()
	Engine.Logger = xorm.NewSimpleLogger(f)

	err = Engine.Sync2(new(sfv.Sfver))
	if err != nil {
		log.Fatal("database sync failed", err)
	}
	// Engine.DropTables("sfver")
	sfverService = sfv.DefaultSfvService(Engine)
	log.Println("Listening at 8080 ...")
	log.Fatal(http.ListenAndServe(":8080", router))
}
Ejemplo n.º 18
0
Archivo: conf.go Proyecto: ohko/gmdd
func init() {
	// read configure
	Conf = ReadConf()

	// setup xorm
	var err error
	if DB, err = xorm.NewEngine(Conf["DB"], Conf["DSN"]); err != nil {
		panic(err.Error())
	}

	// set table prefix
	tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, Conf["PREFIX"])
	DB.SetTableMapper(tbMapper)

	// record sql
	DB.ShowSQL = true
	f, err := os.Create("sql.log")
	if err != nil {
		panic(err.Error())
	}
	DB.Logger = xorm.NewSimpleLogger(f)
}
Ejemplo n.º 19
0
func InitDb() {
	err := util.InitConf()
	if err != nil {
		return
	}
	err = initDb()

	if err != nil {
		log.Fatalf("Fail to create engine %v.", err)
	}

	engine.ShowSQL = false   //则会在控制台打印出生成的SQL语句
	engine.ShowDebug = false //则会在控制台打印调试信息;
	engine.ShowErr = true    //则会在控制台打印错误信息;
	engine.ShowWarn = false  //则会在控制台打印警告信息;

	f, err := os.Create("./logs/sql.log")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer f.Close()
	engine.Logger = xorm.NewSimpleLogger(f)
}
Ejemplo n.º 20
0
func SetEngine() (err error) {
	x, err = getEngine()
	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.
	logPath := path.Join(setting.LogRootPath, "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)
	}
	x.Logger = xorm.NewSimpleLogger(f)

	x.ShowSQL = true
	x.ShowInfo = true
	x.ShowDebug = true
	x.ShowErr = true
	x.ShowWarn = true
	return nil
}