database.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package database // import "miniflux.app/v2/internal/database"
  4. import (
  5. "database/sql"
  6. "fmt"
  7. "log/slog"
  8. "time"
  9. // Postgresql driver import
  10. pq "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. driver := ""
  28. switch db.Driver().(type) {
  29. case *pq.Driver:
  30. driver = "postgresql"
  31. default:
  32. panic(fmt.Sprintf("the driver %s isn't supported", db.Driver()))
  33. }
  34. slog.Info("Running database migrations",
  35. slog.Int("current_version", currentVersion),
  36. slog.Int("latest_version", schemaVersion),
  37. )
  38. for version := currentVersion; version < schemaVersion; version++ {
  39. newVersion := version + 1
  40. tx, err := db.Begin()
  41. if err != nil {
  42. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  43. }
  44. if err := migrations[version](tx, driver); err != nil {
  45. tx.Rollback()
  46. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  47. }
  48. if _, err := tx.Exec(`DELETE FROM schema_version`); err != nil {
  49. tx.Rollback()
  50. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  51. }
  52. if _, err := tx.Exec(`INSERT INTO schema_version (version) VALUES ($1)`, newVersion); err != nil {
  53. tx.Rollback()
  54. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  55. }
  56. if err := tx.Commit(); err != nil {
  57. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  58. }
  59. }
  60. return nil
  61. }
  62. // IsSchemaUpToDate checks if the database schema is up to date.
  63. func IsSchemaUpToDate(db *sql.DB) error {
  64. var currentVersion int
  65. db.QueryRow(`SELECT version FROM schema_version`).Scan(&currentVersion)
  66. if currentVersion < schemaVersion {
  67. return fmt.Errorf(`the database schema is not up to date: current=v%d expected=v%d`, currentVersion, schemaVersion)
  68. }
  69. return nil
  70. }