github.com/uber/kraken@v0.1.4/localdb/database.go (about)

     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  
    16  import (
    17  	"fmt"
    18  
    19  	_ "github.com/uber/kraken/localdb/migrations" // Add migrations.
    20  	"github.com/uber/kraken/utils/osutil"
    21  
    22  	"github.com/jmoiron/sqlx"
    23  	_ "github.com/mattn/go-sqlite3" // SQL driver.
    24  	"github.com/pressly/goose"
    25  )
    26  
    27  // New creates a new locally embedded SQLite database.
    28  func New(config Config) (*sqlx.DB, error) {
    29  	if err := osutil.EnsureFilePresent(config.Source, 0775); err != nil {
    30  		return nil, fmt.Errorf("ensure db source present: %s", err)
    31  	}
    32  	db, err := sqlx.Open("sqlite3", config.Source)
    33  	if err != nil {
    34  		return nil, fmt.Errorf("open sqlite3: %s", err)
    35  	}
    36  	// SQLite has concurrency issues where queries result in error if more than
    37  	// one connection is accessing a table.
    38  	db.SetMaxOpenConns(1)
    39  	if err := goose.SetDialect("sqlite3"); err != nil {
    40  		return nil, fmt.Errorf("set dialect as sqlite3: %s", err)
    41  	}
    42  	if err := goose.Up(db.DB, "."); err != nil {
    43  		return nil, fmt.Errorf("perform db migration: %s", err)
    44  	}
    45  	return db, nil
    46  }