database.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. "time"
  8. // Postgresql driver import
  9. _ "github.com/lib/pq"
  10. )
  11. // NewConnectionPool configures the database connection pool.
  12. func NewConnectionPool(dsn string, minConnections, maxConnections int, connectionLifetime time.Duration) (*sql.DB, error) {
  13. db, err := sql.Open("postgres", dsn)
  14. if err != nil {
  15. return nil, err
  16. }
  17. db.SetMaxOpenConns(maxConnections)
  18. db.SetMaxIdleConns(minConnections)
  19. db.SetConnMaxLifetime(connectionLifetime)
  20. return db, nil
  21. }
  22. // Migrate executes database migrations.
  23. func Migrate(db *sql.DB) error {
  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. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  34. }
  35. if err := migrations[version](tx); err != nil {
  36. tx.Rollback()
  37. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  38. }
  39. if _, err := tx.Exec(`DELETE FROM schema_version`); err != nil {
  40. tx.Rollback()
  41. return fmt.Errorf("[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. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  46. }
  47. if err := tx.Commit(); err != nil {
  48. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  49. }
  50. }
  51. return nil
  52. }
  53. // IsSchemaUpToDate checks if the database schema is up to date.
  54. func IsSchemaUpToDate(db *sql.DB) error {
  55. var currentVersion int
  56. db.QueryRow(`SELECT version FROM schema_version`).Scan(&currentVersion)
  57. if currentVersion < schemaVersion {
  58. return fmt.Errorf(`the database schema is not up to date: current=v%d expected=v%d`, currentVersion, schemaVersion)
  59. }
  60. return nil
  61. }