2021-12-14 02:47:04 +03:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
2022-10-02 01:01:39 +03:00
|
|
|
"fmt"
|
2021-12-14 02:47:04 +03:00
|
|
|
"github.com/emvi/logbuch"
|
|
|
|
"gorm.io/gorm"
|
2022-10-02 01:01:39 +03:00
|
|
|
"reflect"
|
2021-12-14 02:47:04 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func IsCleanDB(db *gorm.DB) bool {
|
|
|
|
if db.Dialector.Name() == "sqlite" {
|
|
|
|
var count int64
|
|
|
|
if err := db.Raw("SELECT count(*) from sqlite_master WHERE type = 'table'").Scan(&count).Error; err != nil {
|
|
|
|
logbuch.Error("failed to check if database is clean - '%v'", err)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return count == 0
|
|
|
|
}
|
|
|
|
logbuch.Warn("IsCleanDB is not yet implemented for dialect '%s'", db.Dialector.Name())
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func HasConstraints(db *gorm.DB) bool {
|
|
|
|
if db.Dialector.Name() == "sqlite" {
|
|
|
|
var count int64
|
|
|
|
if err := db.Raw("SELECT count(*) from sqlite_master WHERE sql LIKE '%CONSTRAINT%'").Scan(&count).Error; err != nil {
|
|
|
|
logbuch.Error("failed to check if database has constraints - '%v'", err)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return count != 0
|
|
|
|
}
|
|
|
|
logbuch.Warn("HasForeignKeyConstraints is not yet implemented for dialect '%s'", db.Dialector.Name())
|
|
|
|
return false
|
|
|
|
}
|
2022-10-02 01:01:39 +03:00
|
|
|
|
|
|
|
func WhereNullable(query *gorm.DB, col string, val any) *gorm.DB {
|
|
|
|
if val == nil || reflect.ValueOf(val).IsNil() {
|
|
|
|
return query.Where(fmt.Sprintf("%s is null", col))
|
|
|
|
}
|
|
|
|
return query.Where(fmt.Sprintf("%s = ?", col), val)
|
|
|
|
}
|