database.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. _ "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. slog.Info("Running database migrations",
  28. slog.Int("current_version", currentVersion),
  29. slog.Int("latest_version", schemaVersion),
  30. )
  31. for version := currentVersion; version < schemaVersion; version++ {
  32. newVersion := version + 1
  33. tx, err := db.Begin()
  34. if err != nil {
  35. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  36. }
  37. if err := migrations[version](tx); err != nil {
  38. tx.Rollback()
  39. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  40. }
  41. if _, err := tx.Exec(`DELETE FROM schema_version`); err != nil {
  42. tx.Rollback()
  43. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  44. }
  45. if _, err := tx.Exec(`INSERT INTO schema_version (version) VALUES ($1)`, newVersion); err != nil {
  46. tx.Rollback()
  47. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  48. }
  49. if err := tx.Commit(); err != nil {
  50. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  51. }
  52. }
  53. return nil
  54. }
  55. // IsSchemaUpToDate checks if the database schema is up to date.
  56. func IsSchemaUpToDate(db *sql.DB) error {
  57. var currentVersion int
  58. db.QueryRow(`SELECT version FROM schema_version`).Scan(&currentVersion)
  59. if currentVersion < schemaVersion {
  60. return fmt.Errorf(`the database schema is not up to date: current=v%d expected=v%d`, currentVersion, schemaVersion)
  61. }
  62. return nil
  63. }