db.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package db
  2. import (
  3. "errors"
  4. "sync"
  5. "github.com/jinzhu/gorm"
  6. _ "github.com/lib/pq"
  7. _ "github.com/mattn/go-sqlite3"
  8. )
  9. const (
  10. SQLITE_DRIVER = "sqlite3"
  11. POSTGRES_DRIVER = "postgres"
  12. )
  13. type DB interface {
  14. Hello() string
  15. Orm() *gorm.DB
  16. Mutex() *sync.Mutex
  17. Insert(obj interface{}) error
  18. Get(objs interface{}, where map[string]interface{}, order string, limit uint64, offset uint64, deleted bool) error
  19. Update(obj interface{}, para map[string]interface{}) error
  20. Delete(obj interface{}, para map[string]interface{}) error
  21. GetMeta(name interface{}) (interface{}, error)
  22. GetTables() (interface{}, error)
  23. }
  24. //support databes 'sqlite3','postgres'
  25. func Open(driver string, args ...interface{}) (DB, error) {
  26. if driver == "" {
  27. return nil, errors.New("Invalid driver name.")
  28. }
  29. d, err := gorm.Open(driver, args...)
  30. if err != nil {
  31. return nil, err
  32. }
  33. var db DB
  34. switch driver {
  35. case SQLITE_DRIVER:
  36. db = Sqlite{orm: d, mutex: &sync.Mutex{}}
  37. case POSTGRES_DRIVER:
  38. db = Postgres{orm: d, mutex: &sync.Mutex{}}
  39. default:
  40. return nil, errors.New("Unknown database driver")
  41. }
  42. return db, nil
  43. }