/orc8r/cloud/go/sqorc/open.go

https://github.com/facebookincubator/magma · Go · 46 lines · 23 code · 5 blank · 18 comment · 5 complexity · e2d2e0ade972ea11121a9b38aca66426 MD5 · raw file

  1. /*
  2. Copyright 2020 The Magma Authors.
  3. This source code is licensed under the BSD-style license found in the
  4. LICENSE file in the root directory of this source tree.
  5. Unless required by applicable law or agreed to in writing, software
  6. distributed under the License is distributed on an "AS IS" BASIS,
  7. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. See the License for the specific language governing permissions and
  9. limitations under the License.
  10. */
  11. package sqorc
  12. import (
  13. "database/sql"
  14. "strings"
  15. _ "github.com/go-sql-driver/mysql"
  16. _ "github.com/lib/pq"
  17. _ "github.com/mattn/go-sqlite3"
  18. )
  19. const (
  20. MariaDriver = "mysql"
  21. PostgresDriver = "postgres"
  22. SQLiteDriver = "sqlite3"
  23. )
  24. // Open is a wrapper for sql.Open which sets the max open connections to 1
  25. // for in memory sqlite3 dbs. In memory sqlite3 creates a new database
  26. // on each connection, so the number of open connections must be limited
  27. // to 1 for thread safety. Otherwise, there is a race condition between
  28. // threads using a cached connection to the original database or opening
  29. // a new connection to a new database.
  30. func Open(driver string, source string) (*sql.DB, error) {
  31. db, err := sql.Open(driver, source)
  32. if err != nil {
  33. return nil, err
  34. }
  35. if driver == SQLiteDriver && strings.Contains(source, ":memory:") {
  36. db.SetMaxOpenConns(1)
  37. }
  38. return db, nil
  39. }