/localdb/database.go

https://github.com/uber/kraken · Go · 46 lines · 26 code · 4 blank · 16 comment · 8 complexity · ffc91aa88815d4df96d54655e457af83 MD5 · raw file

  1. // Copyright (c) 2016-2019 Uber Technologies, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package localdb
  15. import (
  16. "fmt"
  17. _ "github.com/uber/kraken/localdb/migrations" // Add migrations.
  18. "github.com/uber/kraken/utils/osutil"
  19. "github.com/jmoiron/sqlx"
  20. _ "github.com/mattn/go-sqlite3" // SQL driver.
  21. "github.com/pressly/goose"
  22. )
  23. // New creates a new locally embedded SQLite database.
  24. func New(config Config) (*sqlx.DB, error) {
  25. if err := osutil.EnsureFilePresent(config.Source, 0775); err != nil {
  26. return nil, fmt.Errorf("ensure db source present: %s", err)
  27. }
  28. db, err := sqlx.Open("sqlite3", config.Source)
  29. if err != nil {
  30. return nil, fmt.Errorf("open sqlite3: %s", err)
  31. }
  32. // SQLite has concurrency issues where queries result in error if more than
  33. // one connection is accessing a table.
  34. db.SetMaxOpenConns(1)
  35. if err := goose.SetDialect("sqlite3"); err != nil {
  36. return nil, fmt.Errorf("set dialect as sqlite3: %s", err)
  37. }
  38. if err := goose.Up(db.DB, "."); err != nil {
  39. return nil, fmt.Errorf("perform db migration: %s", err)
  40. }
  41. return db, nil
  42. }