Create Engine

Create Engine

When using xorm, you can create one or more ORM engines in one application. XORM supports two kinds of engines, Engine and EngineGroup. An engine could operate one database and an engine group could handle Master/Slave situations. Both kinds of engines have similar APIs, so that you can easily change from one to another. We also provide an EngineInterface to do that.

One app could create one or more engines. One engine could handle one database. You can invoke xorm.NewEngine to do that. For example:

  1. import (
  2. _ "github.com/go-sql-driver/mysql"
  3. "xorm.io/xorm"
  4. )
  5. var engine *xorm.Engine
  6. func main() {
  7. var err error
  8. engine, err = xorm.NewEngine("mysql", "root:[email protected]/test?charset=utf8")
  9. }

or

  1. import (
  2. _ "github.com/mattn/go-sqlite3"
  3. "xorm.io/xorm"
  4. )
  5. var engines []*xorm.Engine
  6. func main() {
  7. for i:=0; i < 10; i++ {
  8. engine, err := xorm.NewEngine("sqlite3", fmt.Sprintf("./test%d.db", i))
  9. engines = append(engines, engine)
  10. }
  11. }

You can create many engines for different databases. Generally, you just need to create only one engine. Engine supports run on go routines.

When you want to manually close the engine, call engine.Close. Generally, we don’t need to do this, because engine will be closed automatically when application exits.

xorm supports drivers as below:

NewEngine’s parameters are the same as sql.Open. So you should read the driver’s document for parameter’s usage.

After engine is created, you can do some settings.

Logs

  • engine.ShowSQL(true), Shows SQL statement on standard output or your io.Writer;
  • engine.Logger().SetLevel(log.LOG_DEBUG), Shows debug and other infomations;

If you want to record infomations with another method: use engine.SetLogger() as io.Writer:

  1. f, err := os.Create("sql.log")
  2. if err != nil {
  3. println(err.Error())
  4. return
  5. }
  6. engine.SetLogger(log.NewSimpleLogger(f))

Logs also support recording to syslog, for example:

  1. logWriter, err := syslog.New(syslog.LOG_DEBUG, "rest-xorm-example")
  2. if err != nil {
  3. log.Fatalf("Fail to create xorm system logger: %v\n", err)
  4. }
  5. logger := log.NewSimpleLogger(logWriter)
  6. logger.ShowSQL(true)
  7. engine.SetLogger(logger)

Connections pool

Engine provides DB connections pool settings.

  • Use engine.SetMaxIdleConns() to set idle connections.
  • Use engine.SetMaxOpenConns() to set Max connections. This methods support only Go 1.2+.
  • Use engine.SetConnMaxLifetime() to set Max life time. This methods support only Go 1.6+.