database.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. "time"
  9. // Postgresql driver import
  10. _ "github.com/lib/pq"
  11. )
  12. // NewConnectionPool configures the database connection pool.
  13. func NewConnectionPool(dsn string, minConnections, maxConnections int, connectionLifetime time.Duration) (*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. db.SetConnMaxLifetime(connectionLifetime)
  21. return db, nil
  22. }
  23. // Migrate executes database migrations.
  24. func Migrate(db *sql.DB) error {
  25. var currentVersion int
  26. db.QueryRow(`SELECT version FROM schema_version`).Scan(&currentVersion)
  27. fmt.Println("-> Current schema version:", currentVersion)
  28. fmt.Println("-> Latest schema version:", schemaVersion)
  29. for version := currentVersion; version < schemaVersion; version++ {
  30. newVersion := version + 1
  31. fmt.Println("* Migrating to version:", newVersion)
  32. tx, err := db.Begin()
  33. if err != nil {
  34. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  35. }
  36. if err := migrations[version](tx); err != nil {
  37. tx.Rollback()
  38. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  39. }
  40. if _, err := tx.Exec(`DELETE FROM schema_version`); err != nil {
  41. tx.Rollback()
  42. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  43. }
  44. if _, err := tx.Exec(`INSERT INTO schema_version (version) VALUES ($1)`, newVersion); err != nil {
  45. tx.Rollback()
  46. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  47. }
  48. if err := tx.Commit(); err != nil {
  49. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  50. }
  51. }
  52. return nil
  53. }
  54. // IsSchemaUpToDate checks if the database schema is up to date.
  55. func IsSchemaUpToDate(db *sql.DB) error {
  56. var currentVersion int
  57. db.QueryRow(`SELECT version FROM schema_version`).Scan(&currentVersion)
  58. if currentVersion < schemaVersion {
  59. return fmt.Errorf(`the database schema is not up to date: current=v%d expected=v%d`, currentVersion, schemaVersion)
  60. }
  61. return nil
  62. }