postgres.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package postgres
  2. import (
  3. "context"
  4. "database/sql"
  5. "log"
  6. // Import the PostgreSQL driver.
  7. _ "github.com/lib/pq"
  8. "github.com/pkg/errors"
  9. "github.com/usememos/memos/server/profile"
  10. "github.com/usememos/memos/store"
  11. )
  12. type DB struct {
  13. db *sql.DB
  14. profile *profile.Profile
  15. // Add any other fields as needed
  16. }
  17. func NewDB(profile *profile.Profile) (store.Driver, error) {
  18. if profile == nil {
  19. return nil, errors.New("profile is nil")
  20. }
  21. // Open the PostgreSQL connection
  22. db, err := sql.Open("postgres", profile.DSN)
  23. if err != nil {
  24. log.Printf("Failed to open database: %s", err)
  25. return nil, errors.Wrapf(err, "failed to open database: %s", profile.DSN)
  26. }
  27. var driver store.Driver = &DB{
  28. db: db,
  29. profile: profile,
  30. }
  31. // Return the DB struct
  32. return driver, nil
  33. }
  34. func (d *DB) GetDB() *sql.DB {
  35. return d.db
  36. }
  37. func (d *DB) Vacuum(ctx context.Context) error {
  38. tx, err := d.db.BeginTx(ctx, nil)
  39. if err != nil {
  40. return err
  41. }
  42. defer tx.Rollback()
  43. if err := vacuumMemo(ctx, tx); err != nil {
  44. return err
  45. }
  46. if err := vacuumResource(ctx, tx); err != nil {
  47. return err
  48. }
  49. if err := vacuumUserSetting(ctx, tx); err != nil {
  50. return err
  51. }
  52. if err := vacuumMemoOrganizer(ctx, tx); err != nil {
  53. return err
  54. }
  55. if err := vacuumMemoRelations(ctx, tx); err != nil {
  56. return err
  57. }
  58. if err := vacuumInbox(ctx, tx); err != nil {
  59. return err
  60. }
  61. if err := vacuumTag(ctx, tx); err != nil {
  62. // Prevent revive warning.
  63. return err
  64. }
  65. return tx.Commit()
  66. }
  67. func (*DB) GetCurrentDBSize(context.Context) (int64, error) {
  68. return 0, errors.New("unimplemented")
  69. }
  70. func (d *DB) Close() error {
  71. return d.db.Close()
  72. }