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. )
  11. // NewConnectionPool configures the database connection pool.
  12. func NewConnectionPool(dsn string, minConnections, maxConnections int) (*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. return db, nil
  20. }
  21. // Migrate executes database migrations.
  22. func Migrate(db *sql.DB) error {
  23. var currentVersion int
  24. db.QueryRow(`SELECT version FROM schema_version`).Scan(&currentVersion)
  25. fmt.Println("-> Current schema version:", currentVersion)
  26. fmt.Println("-> Latest schema version:", schemaVersion)
  27. for version := currentVersion; version < schemaVersion; version++ {
  28. newVersion := version + 1
  29. fmt.Println("* Migrating to version:", newVersion)
  30. tx, err := db.Begin()
  31. if err != nil {
  32. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  33. }
  34. if err := migrations[version](tx); err != nil {
  35. tx.Rollback()
  36. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  37. }
  38. if _, err := tx.Exec(`DELETE FROM schema_version`); err != nil {
  39. tx.Rollback()
  40. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  41. }
  42. if _, err := tx.Exec(`INSERT INTO schema_version (version) VALUES ($1)`, newVersion); err != nil {
  43. tx.Rollback()
  44. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  45. }
  46. if err := tx.Commit(); err != nil {
  47. return fmt.Errorf("[Migration v%d] %v", newVersion, err)
  48. }
  49. }
  50. return nil
  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. }