Make linter happy and update dependencies.
Some checks failed
continuous-integration/drone/push Build is failing
Some checks failed
continuous-integration/drone/push Build is failing
This commit is contained in:
@@ -32,14 +32,14 @@ import (
|
||||
const FlatFileDialect = "flatfiles"
|
||||
|
||||
var (
|
||||
c *context.Context
|
||||
f *FlatFiles
|
||||
ctx *context.Context
|
||||
flf *FlatFiles
|
||||
)
|
||||
|
||||
func New(cc *context.Context) {
|
||||
c = cc
|
||||
// nolint:exhaustivestruct
|
||||
f = &FlatFiles{}
|
||||
ctx = cc
|
||||
// nolint:exhaustruct
|
||||
flf = &FlatFiles{}
|
||||
|
||||
c.Database.RegisterDialect(dialectinterface.Interface(Handler{}))
|
||||
ctx.Database.RegisterDialect(dialectinterface.Interface(Handler{}))
|
||||
}
|
||||
|
@@ -49,7 +49,7 @@ func (ff *FlatFiles) DeletePaste(pasteID int) error {
|
||||
// Delete from disk.
|
||||
err := os.Remove(filepath.Join(ff.path, "pastes", strconv.Itoa(pasteID)+".json"))
|
||||
if err != nil {
|
||||
c.Logger.Error().Err(err).Msg("Failed to delete paste!")
|
||||
ctx.Logger.Error().Err(err).Msg("Failed to delete paste!")
|
||||
|
||||
// nolint:wrapcheck
|
||||
return err
|
||||
@@ -83,25 +83,25 @@ func (ff *FlatFiles) GetDatabaseConnection() *sql.DB {
|
||||
func (ff *FlatFiles) GetPaste(pasteID int) (*structs.Paste, error) {
|
||||
ff.writeMutex.Lock()
|
||||
pastePath := filepath.Join(ff.path, "pastes", strconv.Itoa(pasteID)+".json")
|
||||
c.Logger.Debug().Str("path", pastePath).Msg("Trying to load paste data")
|
||||
ctx.Logger.Debug().Str("path", pastePath).Msg("Trying to load paste data")
|
||||
|
||||
pasteInBytes, err := ioutil.ReadFile(pastePath)
|
||||
if err != nil {
|
||||
c.Logger.Debug().Err(err).Msg("Failed to read paste from storage")
|
||||
ctx.Logger.Debug().Err(err).Msg("Failed to read paste from storage")
|
||||
|
||||
// nolint:wrapcheck
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c.Logger.Debug().Int("paste bytes", len(pasteInBytes)).Msg("Loaded paste")
|
||||
ctx.Logger.Debug().Int("paste bytes", len(pasteInBytes)).Msg("Loaded paste")
|
||||
ff.writeMutex.Unlock()
|
||||
|
||||
// nolint:exhaustivestruct
|
||||
// nolint:exhaustruct
|
||||
paste := &structs.Paste{}
|
||||
|
||||
err1 := json.Unmarshal(pasteInBytes, paste)
|
||||
if err1 != nil {
|
||||
c.Logger.Error().Err(err1).Msgf("Failed to parse paste")
|
||||
ctx.Logger.Error().Err(err1).Msgf("Failed to parse paste")
|
||||
|
||||
// nolint:wrapcheck
|
||||
return nil, err1
|
||||
@@ -114,7 +114,7 @@ func (ff *FlatFiles) GetPagedPastes(page int) ([]structs.Paste, error) {
|
||||
// Pagination.
|
||||
startPagination := 0
|
||||
if page > 1 {
|
||||
startPagination = (page - 1) * c.Config.Pastes.Pagination
|
||||
startPagination = (page - 1) * ctx.Config.Pastes.Pagination
|
||||
}
|
||||
|
||||
// Iteration one - get only public pastes.
|
||||
@@ -130,38 +130,38 @@ func (ff *FlatFiles) GetPagedPastes(page int) ([]structs.Paste, error) {
|
||||
pastesData := make([]structs.Paste, 0)
|
||||
|
||||
for idx, paste := range publicPastes {
|
||||
if len(pastesData) == c.Config.Pastes.Pagination {
|
||||
if len(pastesData) == ctx.Config.Pastes.Pagination {
|
||||
break
|
||||
}
|
||||
|
||||
if idx < startPagination {
|
||||
c.Logger.Debug().Int("paste index", idx).Msg("Paste isn't in pagination query: too low index")
|
||||
ctx.Logger.Debug().Int("paste index", idx).Msg("Paste isn't in pagination query: too low index")
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if (idx-1 >= startPagination && page > 1 && idx > startPagination+((page-1)*c.Config.Pastes.Pagination)) || (idx-1 >= startPagination && page == 1 && idx > startPagination+(page*c.Config.Pastes.Pagination)) {
|
||||
c.Logger.Debug().Int("paste index", idx).Msg("Paste isn't in pagination query: too high index")
|
||||
if (idx-1 >= startPagination && page > 1 && idx > startPagination+((page-1)*ctx.Config.Pastes.Pagination)) || (idx-1 >= startPagination && page == 1 && idx > startPagination+(page*ctx.Config.Pastes.Pagination)) {
|
||||
ctx.Logger.Debug().Int("paste index", idx).Msg("Paste isn't in pagination query: too high index")
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
c.Logger.Debug().Int("ID", paste.ID).Int("index", idx).Msg("Getting paste data")
|
||||
ctx.Logger.Debug().Int("ID", paste.ID).Int("index", idx).Msg("Getting paste data")
|
||||
|
||||
// Get paste data.
|
||||
// nolint:exhaustivestruct
|
||||
// nolint:exhaustruct
|
||||
pasteData := &structs.Paste{}
|
||||
|
||||
pasteRawData, err := ioutil.ReadFile(filepath.Join(ff.path, "pastes", strconv.Itoa(paste.ID)+".json"))
|
||||
if err != nil {
|
||||
c.Logger.Error().Err(err).Msg("Failed to read paste data")
|
||||
ctx.Logger.Error().Err(err).Msg("Failed to read paste data")
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
err1 := json.Unmarshal(pasteRawData, pasteData)
|
||||
if err1 != nil {
|
||||
c.Logger.Error().Err(err1).Msg("Failed to parse paste data")
|
||||
ctx.Logger.Error().Err(err1).Msg("Failed to parse paste data")
|
||||
|
||||
continue
|
||||
}
|
||||
@@ -185,9 +185,9 @@ func (ff *FlatFiles) GetPastesPages() int {
|
||||
ff.writeMutex.Unlock()
|
||||
|
||||
// Calculate pages.
|
||||
pages := len(publicPastes) / c.Config.Pastes.Pagination
|
||||
pages := len(publicPastes) / ctx.Config.Pastes.Pagination
|
||||
// Check if we have any remainder. Add 1 to pages count if so.
|
||||
if len(publicPastes)%c.Config.Pastes.Pagination > 0 {
|
||||
if len(publicPastes)%ctx.Config.Pastes.Pagination > 0 {
|
||||
pages++
|
||||
}
|
||||
|
||||
@@ -195,14 +195,14 @@ func (ff *FlatFiles) GetPastesPages() int {
|
||||
}
|
||||
|
||||
func (ff *FlatFiles) Initialize() {
|
||||
c.Logger.Info().Msg("Initializing flatfiles storage...")
|
||||
ctx.Logger.Info().Msg("Initializing flatfiles storage...")
|
||||
|
||||
path := c.Config.Database.Path
|
||||
path := ctx.Config.Database.Path
|
||||
// Get proper paste file path.
|
||||
if strings.Contains(c.Config.Database.Path, "~") {
|
||||
if strings.Contains(ctx.Config.Database.Path, "~") {
|
||||
curUser, err := user.Current()
|
||||
if err != nil {
|
||||
c.Logger.Error().Msg("Failed to get current user. Will replace '~' for '/' in storage path!")
|
||||
ctx.Logger.Error().Msg("Failed to get current user. Will replace '~' for '/' in storage path!")
|
||||
|
||||
path = strings.Replace(path, "~", "/", -1)
|
||||
}
|
||||
@@ -213,40 +213,40 @@ func (ff *FlatFiles) Initialize() {
|
||||
path, _ = filepath.Abs(path)
|
||||
ff.path = path
|
||||
|
||||
c.Logger.Debug().Msgf("Storage path is now: %s", ff.path)
|
||||
ctx.Logger.Debug().Msgf("Storage path is now: %s", ff.path)
|
||||
|
||||
// Create directory if necessary.
|
||||
if _, err := os.Stat(ff.path); err != nil {
|
||||
c.Logger.Debug().Str("directory", ff.path).Msg("Directory does not exist, creating...")
|
||||
ctx.Logger.Debug().Str("directory", ff.path).Msg("Directory does not exist, creating...")
|
||||
_ = os.MkdirAll(ff.path, os.ModePerm)
|
||||
} else {
|
||||
c.Logger.Debug().Str("directory", ff.path).Msg("Directory already exists")
|
||||
ctx.Logger.Debug().Str("directory", ff.path).Msg("Directory already exists")
|
||||
}
|
||||
|
||||
// Create directory for pastes.
|
||||
if _, err := os.Stat(filepath.Join(ff.path, "pastes")); err != nil {
|
||||
c.Logger.Debug().Str("directory", ff.path).Msg("Directory does not exist, creating...")
|
||||
ctx.Logger.Debug().Str("directory", ff.path).Msg("Directory does not exist, creating...")
|
||||
_ = os.MkdirAll(filepath.Join(ff.path, "pastes"), os.ModePerm)
|
||||
} else {
|
||||
c.Logger.Debug().Str("directory", ff.path).Msg("Directory already exists")
|
||||
ctx.Logger.Debug().Str("directory", ff.path).Msg("Directory already exists")
|
||||
}
|
||||
|
||||
// Load pastes index.
|
||||
ff.pastesIndex = []Index{}
|
||||
if _, err := os.Stat(filepath.Join(ff.path, "pastes", "index.json")); err != nil {
|
||||
c.Logger.Warn().Msg("Pastes index file does not exist, will create new one")
|
||||
ctx.Logger.Warn().Msg("Pastes index file does not exist, will create new one")
|
||||
} else {
|
||||
indexData, err := ioutil.ReadFile(filepath.Join(ff.path, "pastes", "index.json"))
|
||||
if err != nil {
|
||||
c.Logger.Fatal().Msg("Failed to read contents of index file!")
|
||||
ctx.Logger.Fatal().Msg("Failed to read contents of index file!")
|
||||
}
|
||||
|
||||
err1 := json.Unmarshal(indexData, &ff.pastesIndex)
|
||||
if err1 != nil {
|
||||
c.Logger.Error().Err(err1).Msg("Failed to parse index file contents from JSON into internal structure. Will create new index file. All of your previous pastes will became unavailable.")
|
||||
ctx.Logger.Error().Err(err1).Msg("Failed to parse index file contents from JSON into internal structure. Will create new index file. All of your previous pastes will became unavailable.")
|
||||
}
|
||||
|
||||
c.Logger.Debug().Int("pastes count", len(ff.pastesIndex)).Msg("Parsed pastes index")
|
||||
ctx.Logger.Debug().Int("pastes count", len(ff.pastesIndex)).Msg("Parsed pastes index")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,7 +257,7 @@ func (ff *FlatFiles) SavePaste(paste *structs.Paste) (int64, error) {
|
||||
pasteID := len(filesOnDisk) + 1
|
||||
paste.ID = pasteID
|
||||
|
||||
c.Logger.Debug().Int("new paste ID", pasteID).Msg("Writing paste to disk")
|
||||
ctx.Logger.Debug().Int("new paste ID", pasteID).Msg("Writing paste to disk")
|
||||
|
||||
data, err := json.Marshal(paste)
|
||||
if err != nil {
|
||||
@@ -276,7 +276,7 @@ func (ff *FlatFiles) SavePaste(paste *structs.Paste) (int64, error) {
|
||||
}
|
||||
|
||||
// Add it to cache.
|
||||
// nolint:exhaustivestruct
|
||||
// nolint:exhaustruct
|
||||
indexData := Index{}
|
||||
indexData.ID = pasteID
|
||||
indexData.Private = paste.Private
|
||||
@@ -287,18 +287,18 @@ func (ff *FlatFiles) SavePaste(paste *structs.Paste) (int64, error) {
|
||||
}
|
||||
|
||||
func (ff *FlatFiles) Shutdown() {
|
||||
c.Logger.Info().Msg("Saving indexes...")
|
||||
ctx.Logger.Info().Msg("Saving indexes...")
|
||||
|
||||
indexData, err := json.Marshal(ff.pastesIndex)
|
||||
if err != nil {
|
||||
c.Logger.Error().Err(err).Msg("Failed to encode index data into JSON")
|
||||
ctx.Logger.Error().Err(err).Msg("Failed to encode index data into JSON")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err1 := ioutil.WriteFile(filepath.Join(ff.path, "pastes", "index.json"), indexData, 0o600)
|
||||
if err1 != nil {
|
||||
c.Logger.Error().Err(err1).Msg("Failed to write index data to file. Pretty sure that you've lost your pastes.")
|
||||
ctx.Logger.Error().Err(err1).Msg("Failed to write index data to file. Pretty sure that you've lost your pastes.")
|
||||
|
||||
return
|
||||
}
|
||||
|
@@ -33,33 +33,33 @@ import (
|
||||
type Handler struct{}
|
||||
|
||||
func (dbh Handler) DeletePaste(pasteID int) error {
|
||||
return f.DeletePaste(pasteID)
|
||||
return flf.DeletePaste(pasteID)
|
||||
}
|
||||
|
||||
func (dbh Handler) GetDatabaseConnection() *sql.DB {
|
||||
return f.GetDatabaseConnection()
|
||||
return flf.GetDatabaseConnection()
|
||||
}
|
||||
|
||||
func (dbh Handler) GetPaste(pasteID int) (*structs.Paste, error) {
|
||||
return f.GetPaste(pasteID)
|
||||
return flf.GetPaste(pasteID)
|
||||
}
|
||||
|
||||
func (dbh Handler) GetPagedPastes(page int) ([]structs.Paste, error) {
|
||||
return f.GetPagedPastes(page)
|
||||
return flf.GetPagedPastes(page)
|
||||
}
|
||||
|
||||
func (dbh Handler) GetPastesPages() int {
|
||||
return f.GetPastesPages()
|
||||
return flf.GetPastesPages()
|
||||
}
|
||||
|
||||
func (dbh Handler) Initialize() {
|
||||
f.Initialize()
|
||||
flf.Initialize()
|
||||
}
|
||||
|
||||
func (dbh Handler) SavePaste(p *structs.Paste) (int64, error) {
|
||||
return f.SavePaste(p)
|
||||
return flf.SavePaste(p)
|
||||
}
|
||||
|
||||
func (dbh Handler) Shutdown() {
|
||||
f.Shutdown()
|
||||
flf.Shutdown()
|
||||
}
|
||||
|
@@ -30,14 +30,14 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
c *context.Context
|
||||
d *Database
|
||||
ctx *context.Context
|
||||
dbAdapter *Database
|
||||
)
|
||||
|
||||
func New(cc *context.Context) {
|
||||
c = cc
|
||||
// nolint:exhaustivestruct
|
||||
d = &Database{}
|
||||
ctx = cc
|
||||
// nolint:exhaustruct
|
||||
dbAdapter = &Database{}
|
||||
|
||||
c.Database.RegisterDialect(dialectinterface.Interface(Handler{}))
|
||||
ctx.Database.RegisterDialect(dialectinterface.Interface(Handler{}))
|
||||
}
|
||||
|
@@ -33,33 +33,33 @@ import (
|
||||
type Handler struct{}
|
||||
|
||||
func (dbh Handler) DeletePaste(pasteID int) error {
|
||||
return d.DeletePaste(pasteID)
|
||||
return dbAdapter.DeletePaste(pasteID)
|
||||
}
|
||||
|
||||
func (dbh Handler) GetDatabaseConnection() *sql.DB {
|
||||
return d.GetDatabaseConnection()
|
||||
return dbAdapter.GetDatabaseConnection()
|
||||
}
|
||||
|
||||
func (dbh Handler) GetPaste(pasteID int) (*structs.Paste, error) {
|
||||
return d.GetPaste(pasteID)
|
||||
return dbAdapter.GetPaste(pasteID)
|
||||
}
|
||||
|
||||
func (dbh Handler) GetPagedPastes(page int) ([]structs.Paste, error) {
|
||||
return d.GetPagedPastes(page)
|
||||
return dbAdapter.GetPagedPastes(page)
|
||||
}
|
||||
|
||||
func (dbh Handler) GetPastesPages() int {
|
||||
return d.GetPastesPages()
|
||||
return dbAdapter.GetPastesPages()
|
||||
}
|
||||
|
||||
func (dbh Handler) Initialize() {
|
||||
d.Initialize()
|
||||
dbAdapter.Initialize()
|
||||
}
|
||||
|
||||
func (dbh Handler) SavePaste(p *structs.Paste) (int64, error) {
|
||||
return d.SavePaste(p)
|
||||
return dbAdapter.SavePaste(p)
|
||||
}
|
||||
|
||||
func (dbh Handler) Shutdown() {
|
||||
d.Shutdown()
|
||||
dbAdapter.Shutdown()
|
||||
}
|
||||
|
@@ -29,16 +29,16 @@ import (
|
||||
"go.dev.pztrn.name/fastpastebin/internal/context"
|
||||
)
|
||||
|
||||
var c *context.Context
|
||||
var ctx *context.Context
|
||||
|
||||
// New initializes migrations.
|
||||
func New(cc *context.Context) {
|
||||
c = cc
|
||||
ctx = cc
|
||||
}
|
||||
|
||||
// Migrate launching migrations.
|
||||
func Migrate() {
|
||||
c.Logger.Info().Msg("Migrating database...")
|
||||
ctx.Logger.Info().Msg("Migrating database...")
|
||||
|
||||
_ = goose.SetDialect("mysql")
|
||||
goose.AddNamedMigration("1_initial.go", InitialUp, nil)
|
||||
@@ -47,13 +47,13 @@ func Migrate() {
|
||||
goose.AddNamedMigration("4_passworded_pastes.go", PasswordedPastesUp, PasswordedPastesDown)
|
||||
// Add new migrations BEFORE this message.
|
||||
|
||||
dbConn := c.Database.GetDatabaseConnection()
|
||||
dbConn := ctx.Database.GetDatabaseConnection()
|
||||
if dbConn != nil {
|
||||
err := goose.Up(dbConn, ".")
|
||||
if err != nil {
|
||||
c.Logger.Panic().Msgf("Failed to migrate database to latest version: %s", err.Error())
|
||||
ctx.Logger.Panic().Msgf("Failed to migrate database to latest version: %s", err.Error())
|
||||
}
|
||||
} else {
|
||||
c.Logger.Warn().Msg("Current database dialect isn't supporting migrations, skipping")
|
||||
ctx.Logger.Warn().Msg("Current database dialect isn't supporting migrations, skipping")
|
||||
}
|
||||
}
|
||||
|
@@ -80,7 +80,7 @@ func (db *Database) GetDatabaseConnection() *sql.DB {
|
||||
func (db *Database) GetPaste(pasteID int) (*structs.Paste, error) {
|
||||
db.check()
|
||||
|
||||
// nolint:exhaustivestruct
|
||||
// nolint:exhaustruct
|
||||
paste := &structs.Paste{}
|
||||
|
||||
err := db.db.Get(paste, db.db.Rebind("SELECT * FROM `pastes` WHERE id=?"), pasteID)
|
||||
@@ -103,10 +103,10 @@ func (db *Database) GetPagedPastes(page int) ([]structs.Paste, error) {
|
||||
// Pagination.
|
||||
startPagination := 0
|
||||
if page > 1 {
|
||||
startPagination = (page - 1) * c.Config.Pastes.Pagination
|
||||
startPagination = (page - 1) * ctx.Config.Pastes.Pagination
|
||||
}
|
||||
|
||||
err := db.db.Select(&pastesRaw, db.db.Rebind("SELECT * FROM `pastes` WHERE private != true ORDER BY id DESC LIMIT ? OFFSET ?"), c.Config.Pastes.Pagination, startPagination)
|
||||
err := db.db.Select(&pastesRaw, db.db.Rebind("SELECT * FROM `pastes` WHERE private != true ORDER BY id DESC LIMIT ? OFFSET ?"), ctx.Config.Pastes.Pagination, startPagination)
|
||||
if err != nil {
|
||||
// nolint:wrapcheck
|
||||
return nil, err
|
||||
@@ -142,9 +142,9 @@ func (db *Database) GetPastesPages() int {
|
||||
}
|
||||
|
||||
// Calculate pages.
|
||||
pages := len(pastes) / c.Config.Pastes.Pagination
|
||||
pages := len(pastes) / ctx.Config.Pastes.Pagination
|
||||
// Check if we have any remainder. Add 1 to pages count if so.
|
||||
if len(pastes)%c.Config.Pastes.Pagination > 0 {
|
||||
if len(pastes)%ctx.Config.Pastes.Pagination > 0 {
|
||||
pages++
|
||||
}
|
||||
|
||||
@@ -153,23 +153,23 @@ func (db *Database) GetPastesPages() int {
|
||||
|
||||
// Initialize initializes MySQL/MariaDB connection.
|
||||
func (db *Database) Initialize() {
|
||||
c.Logger.Info().Msg("Initializing database connection...")
|
||||
ctx.Logger.Info().Msg("Initializing database connection...")
|
||||
|
||||
// There might be only user, without password. MySQL/MariaDB driver
|
||||
// in DSN wants "user" or "user:password", "user:" is invalid.
|
||||
var userpass string
|
||||
if c.Config.Database.Password == "" {
|
||||
userpass = c.Config.Database.Username
|
||||
if ctx.Config.Database.Password == "" {
|
||||
userpass = ctx.Config.Database.Username
|
||||
} else {
|
||||
userpass = c.Config.Database.Username + ":" + c.Config.Database.Password
|
||||
userpass = ctx.Config.Database.Username + ":" + ctx.Config.Database.Password
|
||||
}
|
||||
|
||||
dbConnString := fmt.Sprintf("%s@tcp(%s:%s)/%s?parseTime=true&collation=utf8mb4_unicode_ci&charset=utf8mb4", userpass, c.Config.Database.Address, c.Config.Database.Port, c.Config.Database.Database)
|
||||
c.Logger.Debug().Str("DSN", dbConnString).Msgf("Database connection string composed")
|
||||
dbConnString := fmt.Sprintf("%s@tcp(%s:%s)/%s?parseTime=true&collation=utf8mb4_unicode_ci&charset=utf8mb4", userpass, ctx.Config.Database.Address, ctx.Config.Database.Port, ctx.Config.Database.Database)
|
||||
ctx.Logger.Debug().Str("DSN", dbConnString).Msgf("Database connection string composed")
|
||||
|
||||
dbConn, err := sqlx.Connect("mysql", dbConnString)
|
||||
if err != nil {
|
||||
c.Logger.Error().Err(err).Msg("Failed to connect to database")
|
||||
ctx.Logger.Error().Err(err).Msg("Failed to connect to database")
|
||||
|
||||
return
|
||||
}
|
||||
@@ -177,12 +177,12 @@ func (db *Database) Initialize() {
|
||||
// Force UTC for current connection.
|
||||
_ = dbConn.MustExec("SET @@session.time_zone='+00:00';")
|
||||
|
||||
c.Logger.Info().Msg("Database connection established")
|
||||
ctx.Logger.Info().Msg("Database connection established")
|
||||
|
||||
db.db = dbConn
|
||||
|
||||
// Perform migrations.
|
||||
migrations.New(c)
|
||||
migrations.New(ctx)
|
||||
migrations.Migrate()
|
||||
}
|
||||
|
||||
@@ -208,7 +208,7 @@ func (db *Database) Shutdown() {
|
||||
if db.db != nil {
|
||||
err := db.db.Close()
|
||||
if err != nil {
|
||||
c.Logger.Error().Err(err).Msg("Failed to close database connection")
|
||||
ctx.Logger.Error().Err(err).Msg("Failed to close database connection")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -30,14 +30,14 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
c *context.Context
|
||||
d *Database
|
||||
ctx *context.Context
|
||||
dbAdapter *Database
|
||||
)
|
||||
|
||||
func New(cc *context.Context) {
|
||||
c = cc
|
||||
// nolint:exhaustivestruct
|
||||
d = &Database{}
|
||||
ctx = cc
|
||||
// nolint:exhaustruct
|
||||
dbAdapter = &Database{}
|
||||
|
||||
c.Database.RegisterDialect(dialectinterface.Interface(Handler{}))
|
||||
ctx.Database.RegisterDialect(dialectinterface.Interface(Handler{}))
|
||||
}
|
||||
|
@@ -33,33 +33,33 @@ import (
|
||||
type Handler struct{}
|
||||
|
||||
func (dbh Handler) DeletePaste(pasteID int) error {
|
||||
return d.DeletePaste(pasteID)
|
||||
return dbAdapter.DeletePaste(pasteID)
|
||||
}
|
||||
|
||||
func (dbh Handler) GetDatabaseConnection() *sql.DB {
|
||||
return d.GetDatabaseConnection()
|
||||
return dbAdapter.GetDatabaseConnection()
|
||||
}
|
||||
|
||||
func (dbh Handler) GetPaste(pasteID int) (*structs.Paste, error) {
|
||||
return d.GetPaste(pasteID)
|
||||
return dbAdapter.GetPaste(pasteID)
|
||||
}
|
||||
|
||||
func (dbh Handler) GetPagedPastes(page int) ([]structs.Paste, error) {
|
||||
return d.GetPagedPastes(page)
|
||||
return dbAdapter.GetPagedPastes(page)
|
||||
}
|
||||
|
||||
func (dbh Handler) GetPastesPages() int {
|
||||
return d.GetPastesPages()
|
||||
return dbAdapter.GetPastesPages()
|
||||
}
|
||||
|
||||
func (dbh Handler) Initialize() {
|
||||
d.Initialize()
|
||||
dbAdapter.Initialize()
|
||||
}
|
||||
|
||||
func (dbh Handler) SavePaste(p *structs.Paste) (int64, error) {
|
||||
return d.SavePaste(p)
|
||||
return dbAdapter.SavePaste(p)
|
||||
}
|
||||
|
||||
func (dbh Handler) Shutdown() {
|
||||
d.Shutdown()
|
||||
dbAdapter.Shutdown()
|
||||
}
|
||||
|
@@ -29,16 +29,16 @@ import (
|
||||
"go.dev.pztrn.name/fastpastebin/internal/context"
|
||||
)
|
||||
|
||||
var c *context.Context
|
||||
var ctx *context.Context
|
||||
|
||||
// New initializes migrations.
|
||||
func New(cc *context.Context) {
|
||||
c = cc
|
||||
ctx = cc
|
||||
}
|
||||
|
||||
// Migrate launching migrations.
|
||||
func Migrate() {
|
||||
c.Logger.Info().Msg("Migrating database...")
|
||||
ctx.Logger.Info().Msg("Migrating database...")
|
||||
|
||||
_ = goose.SetDialect("postgres")
|
||||
goose.AddNamedMigration("1_initial.go", InitialUp, nil)
|
||||
@@ -47,14 +47,14 @@ func Migrate() {
|
||||
goose.AddNamedMigration("4_passworded_pastes.go", PasswordedPastesUp, PasswordedPastesDown)
|
||||
// Add new migrations BEFORE this message.
|
||||
|
||||
dbConn := c.Database.GetDatabaseConnection()
|
||||
dbConn := ctx.Database.GetDatabaseConnection()
|
||||
if dbConn != nil {
|
||||
err := goose.Up(dbConn, ".")
|
||||
if err != nil {
|
||||
c.Logger.Info().Msgf("%+v", err)
|
||||
c.Logger.Panic().Msgf("Failed to migrate database to latest version: %s", err.Error())
|
||||
ctx.Logger.Info().Msgf("%+v", err)
|
||||
ctx.Logger.Panic().Msgf("Failed to migrate database to latest version: %s", err.Error())
|
||||
}
|
||||
} else {
|
||||
c.Logger.Warn().Msg("Current database dialect isn't supporting migrations, skipping")
|
||||
ctx.Logger.Warn().Msg("Current database dialect isn't supporting migrations, skipping")
|
||||
}
|
||||
}
|
||||
|
@@ -28,6 +28,7 @@ package postgresql
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
// PostgreSQL driver.
|
||||
@@ -83,7 +84,7 @@ func (db *Database) GetDatabaseConnection() *sql.DB {
|
||||
func (db *Database) GetPaste(pasteID int) (*structs.Paste, error) {
|
||||
db.check()
|
||||
|
||||
// nolint:exhaustivestruct
|
||||
// nolint:exhaustruct
|
||||
paste := &structs.Paste{}
|
||||
|
||||
err := db.db.Get(paste, db.db.Rebind("SELECT * FROM pastes WHERE id=$1"), pasteID)
|
||||
@@ -113,10 +114,10 @@ func (db *Database) GetPagedPastes(page int) ([]structs.Paste, error) {
|
||||
// Pagination.
|
||||
startPagination := 0
|
||||
if page > 1 {
|
||||
startPagination = (page - 1) * c.Config.Pastes.Pagination
|
||||
startPagination = (page - 1) * ctx.Config.Pastes.Pagination
|
||||
}
|
||||
|
||||
err := db.db.Select(&pastesRaw, db.db.Rebind("SELECT * FROM pastes WHERE private != true ORDER BY id DESC LIMIT $1 OFFSET $2"), c.Config.Pastes.Pagination, startPagination)
|
||||
err := db.db.Select(&pastesRaw, db.db.Rebind("SELECT * FROM pastes WHERE private != true ORDER BY id DESC LIMIT $1 OFFSET $2"), ctx.Config.Pastes.Pagination, startPagination)
|
||||
if err != nil {
|
||||
// nolint:wrapcheck
|
||||
return nil, err
|
||||
@@ -158,9 +159,9 @@ func (db *Database) GetPastesPages() int {
|
||||
}
|
||||
|
||||
// Calculate pages.
|
||||
pages := len(pastes) / c.Config.Pastes.Pagination
|
||||
pages := len(pastes) / ctx.Config.Pastes.Pagination
|
||||
// Check if we have any remainder. Add 1 to pages count if so.
|
||||
if len(pastes)%c.Config.Pastes.Pagination > 0 {
|
||||
if len(pastes)%ctx.Config.Pastes.Pagination > 0 {
|
||||
pages++
|
||||
}
|
||||
|
||||
@@ -169,31 +170,31 @@ func (db *Database) GetPastesPages() int {
|
||||
|
||||
// Initialize initializes MySQL/MariaDB connection.
|
||||
func (db *Database) Initialize() {
|
||||
c.Logger.Info().Msg("Initializing database connection...")
|
||||
ctx.Logger.Info().Msg("Initializing database connection...")
|
||||
|
||||
var userpass string
|
||||
if c.Config.Database.Password == "" {
|
||||
userpass = c.Config.Database.Username
|
||||
if ctx.Config.Database.Password == "" {
|
||||
userpass = ctx.Config.Database.Username
|
||||
} else {
|
||||
userpass = c.Config.Database.Username + ":" + c.Config.Database.Password
|
||||
userpass = ctx.Config.Database.Username + ":" + ctx.Config.Database.Password
|
||||
}
|
||||
|
||||
dbConnString := fmt.Sprintf("postgres://%s@%s:%s/%s?connect_timeout=10&fallback_application_name=fastpastebin&sslmode=disable", userpass, c.Config.Database.Address, c.Config.Database.Port, c.Config.Database.Database)
|
||||
c.Logger.Debug().Str("DSN", dbConnString).Msg("Database connection string composed")
|
||||
dbConnString := fmt.Sprintf("postgres://%s@%s/%s?connect_timeout=10&fallback_application_name=fastpastebin&sslmode=disable", userpass, net.JoinHostPort(ctx.Config.Database.Address, ctx.Config.Database.Port), ctx.Config.Database.Database)
|
||||
ctx.Logger.Debug().Str("DSN", dbConnString).Msg("Database connection string composed")
|
||||
|
||||
dbConn, err := sqlx.Connect("postgres", dbConnString)
|
||||
if err != nil {
|
||||
c.Logger.Error().Err(err).Msg("Failed to connect to database")
|
||||
ctx.Logger.Error().Err(err).Msg("Failed to connect to database")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
c.Logger.Info().Msg("Database connection established")
|
||||
ctx.Logger.Info().Msg("Database connection established")
|
||||
|
||||
db.db = dbConn
|
||||
|
||||
// Perform migrations.
|
||||
migrations.New(c)
|
||||
migrations.New(ctx)
|
||||
migrations.Migrate()
|
||||
}
|
||||
|
||||
@@ -206,22 +207,22 @@ func (db *Database) SavePaste(paste *structs.Paste) (int64, error) {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var id int64
|
||||
var newPasteID int64
|
||||
|
||||
err = stmt.Get(&id, paste)
|
||||
err = stmt.Get(&newPasteID, paste)
|
||||
if err != nil {
|
||||
// nolint:wrapcheck
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return id, nil
|
||||
return newPasteID, nil
|
||||
}
|
||||
|
||||
func (db *Database) Shutdown() {
|
||||
if db.db != nil {
|
||||
err := db.db.Close()
|
||||
if err != nil {
|
||||
c.Logger.Error().Err(err).Msg("Failed to close database connection")
|
||||
ctx.Logger.Error().Err(err).Msg("Failed to close database connection")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user