main.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package main
  2. import (
  3. _ "github.com/mattn/go-sqlite3"
  4. "github.com/go-xorm/xorm"
  5. "os"
  6. "fmt"
  7. "github.com/go-xorm/core"
  8. "github.com/davecgh/go-spew/spew"
  9. )
  10. type User struct {
  11. Id int64
  12. Name string `xorm:"varchar(25) not null unique 'usr_name'"`
  13. }
  14. type Article struct {
  15. Id int64
  16. Title string `xorm:"varchar(25) not null unique 'art_title'"`
  17. }
  18. func configureOrm(orm *xorm.Engine) {
  19. // Show SQL statement on standard output
  20. orm.ShowSQL = true
  21. // Show debug infomation on standard output
  22. orm.ShowDebug = true
  23. // Show error infomation on standard output;
  24. orm.ShowErr = true
  25. // Show warnning information on standard output;
  26. orm.ShowWarn = true
  27. // TODO Show which info ?
  28. orm.ShowInfo = true
  29. f, err := os.Create("sql.log")
  30. if err != nil {
  31. println(err.Error())
  32. return
  33. }
  34. orm.Logger = xorm.NewSimpleLogger(f)
  35. orm.SetMaxIdleConns(1)
  36. orm.SetMaxOpenConns(10)
  37. // Set mapper: GonicMapper, SameMapper, SnakeMapper (default).
  38. orm.SetMapper(core.SnakeMapper{})
  39. }
  40. func addData(orm *xorm.Engine) {
  41. u1 := new(User)
  42. u1.Name = "FGM";
  43. x, err := orm.Insert(u1)
  44. if err != nil {
  45. fmt.Println(err)
  46. os.Exit(3)
  47. }
  48. spew.Dump(x, u1)
  49. }
  50. func check(e error) {
  51. if e != nil {
  52. panic(e)
  53. }
  54. }
  55. func main() {
  56. orm, err := xorm.NewEngine("sqlite3", "./test.db")
  57. if err != nil {
  58. panic(err)
  59. os.Exit(1)
  60. }
  61. fmt.Println("ORM loaded")
  62. configureOrm(orm)
  63. err = orm.Sync(new(User), new(Article))
  64. if err != nil {
  65. panic(err)
  66. os.Exit(2)
  67. }
  68. fmt.Println("ORM synced")
  69. addData(orm)
  70. orm.Close()
  71. }