database.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2018 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package database // import "miniflux.app/database"
  5. import (
  6. "database/sql"
  7. "fmt"
  8. // Postgresql driver import
  9. _ "github.com/lib/pq"
  10. "miniflux.app/logger"
  11. )
  12. // NewConnectionPool configures the database connection pool.
  13. func NewConnectionPool(dsn string, minConnections, maxConnections int) (*sql.DB, error) {
  14. db, err := sql.Open("postgres", dsn)
  15. if err != nil {
  16. return nil, err
  17. }
  18. db.SetMaxOpenConns(maxConnections)
  19. db.SetMaxIdleConns(minConnections)
  20. return db, nil
  21. }
  22. // Migrate executes database migrations.
  23. func Migrate(db *sql.DB) {
  24. var currentVersion int
  25. db.QueryRow(`SELECT version FROM schema_version`).Scan(&currentVersion)
  26. fmt.Println("-> Current schema version:", currentVersion)
  27. fmt.Println("-> Latest schema version:", schemaVersion)
  28. for version := currentVersion; version < schemaVersion; version++ {
  29. newVersion := version + 1
  30. fmt.Println("* Migrating to version:", newVersion)
  31. tx, err := db.Begin()
  32. if err != nil {
  33. logger.Fatal("[Migration v%d] %v", newVersion, err)
  34. }
  35. if err := migrations[version](tx); err != nil {
  36. tx.Rollback()
  37. logger.Fatal("[Migration v%d] %v", newVersion, err)
  38. }
  39. if _, err := tx.Exec(`DELETE FROM schema_version`); err != nil {
  40. tx.Rollback()
  41. logger.Fatal("[Migration v%d] %v", newVersion, err)
  42. }
  43. if _, err := tx.Exec(`INSERT INTO schema_version (version) VALUES ($1)`, newVersion); err != nil {
  44. tx.Rollback()
  45. logger.Fatal("[Migration v%d] %v", newVersion, err)
  46. }
  47. if err := tx.Commit(); err != nil {
  48. logger.Fatal("[Migration v%d] %v", newVersion, err)
  49. }
  50. }
  51. }
  52. // IsSchemaUpToDate checks if the database schema is up to date.
  53. func IsSchemaUpToDate(db *sql.DB) error {
  54. var currentVersion int
  55. db.QueryRow(`SELECT version FROM schema_version`).Scan(&currentVersion)
  56. if currentVersion < schemaVersion {
  57. return fmt.Errorf(`the database schema is not up to date: current=v%d expected=v%d`, currentVersion, schemaVersion)
  58. }
  59. return nil
  60. }