Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove transaction TableName method #3440

Merged
merged 1 commit into from
Oct 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 6 additions & 23 deletions internal/server/data/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,19 +137,6 @@ func (d *DB) Begin(ctx context.Context, opts *sql.TxOptions) (*Transaction, erro
return &Transaction{DB: tx, committed: new(atomic.Bool)}, nil
}

type WriteTxn interface {
ReadTxn
Exec(sql string, values ...interface{}) (sql.Result, error)
}

type ReadTxn interface {
DriverName() string
Query(query string, args ...any) (*sql.Rows, error)
QueryRow(query string, args ...any) *sql.Row

OrganizationID() uid.ID
}

// GormTxn is used as a shim in preparation for removing gorm.
type GormTxn interface {
WriteTxn
Expand Down Expand Up @@ -371,16 +358,12 @@ func add[T models.Modelable](tx GormTxn, model *T) error {
setOrg(tx, model)

var err error
if tx.DriverName() == "postgres" {
// failures on postgres need to be rolled back in order to
// continue using the same transaction
db.SavePoint("beforeCreate")
err = db.Create(model).Error
if err != nil {
db.RollbackTo("beforeCreate")
}
} else {
err = db.Create(model).Error
// failures on postgres need to be rolled back in order to
// continue using the same transaction
db.SavePoint("beforeCreate")
err = db.Create(model).Error
if err != nil {
db.RollbackTo("beforeCreate")
}
return handleError(err)
}
Expand Down
47 changes: 0 additions & 47 deletions internal/server/data/migrations.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import (
"strings"
"time"

"gorm.io/gorm"

"github.com/infrahq/infra/internal"
"github.com/infrahq/infra/internal/logging"
"github.com/infrahq/infra/internal/server/data/migrator"
Expand All @@ -25,9 +23,6 @@ func migrations() []*migrator.Migration {
ID: "202204281130",
Migrate: func(tx migrator.DB) error {
stmt := `ALTER TABLE settings DROP COLUMN IF EXISTS signup_enabled`
if tx.DriverName() == "sqlite" {
stmt = `ALTER TABLE settings DROP COLUMN signup_enabled`
}
_, err := tx.Exec(stmt)
return err
},
Expand All @@ -37,9 +32,6 @@ func migrations() []*migrator.Migration {
ID: "202204291613",
Migrate: func(tx migrator.DB) error {
stmt := `ALTER TABLE identities DROP COLUMN IF EXISTS kind`
if tx.DriverName() == "sqlite" {
stmt = `ALTER TABLE identities DROP COLUMN kind`
}
_, err := tx.Exec(stmt)
return err
},
Expand Down Expand Up @@ -82,54 +74,18 @@ func migrations() []*migrator.Migration {
var schemaSQL string

func initializeSchema(db migrator.DB) error {
if db.DriverName() == "sqlite" {
dataDB, ok := db.(*DB)
if !ok {
panic("unexpected DB type, remove this with gorm")
}
return autoMigrateSchema(dataDB.DB)
}

if _, err := db.Exec(schemaSQL); err != nil {
return fmt.Errorf("failed to exec sql: %w", err)
}
return nil
}

func autoMigrateSchema(db *gorm.DB) error {
tables := []interface{}{
&models.ProviderUser{},
&models.Group{},
&models.Identity{},
&models.Provider{},
&models.Grant{},
&models.Destination{},
&models.AccessKey{},
&models.Settings{},
&models.EncryptionKey{},
&models.Credential{},
&models.Organization{},
&models.PasswordResetToken{},
}

for _, table := range tables {
if err := db.AutoMigrate(table); err != nil {
return err
}
}

return nil
}

// #2294: set the provider kind on existing providers
func addKindToProviders() *migrator.Migration {
return &migrator.Migration{
ID: "202206151027",
Migrate: func(tx migrator.DB) error {
stmt := `ALTER TABLE providers ADD COLUMN IF NOT EXISTS kind text`
if tx.DriverName() == "sqlite" {
stmt = `ALTER TABLE providers ADD COLUMN kind text`
}
if _, err := tx.Exec(stmt); err != nil {
return err
}
Expand Down Expand Up @@ -248,9 +204,6 @@ func setDestinationLastSeenAt() *migrator.Migration {
}

stmt := `ALTER TABLE destinations ADD COLUMN last_seen_at timestamp with time zone`
if tx.DriverName() == "sqlite" {
stmt = `ALTER TABLE destinations ADD COLUMN last_seen_at datetime`
}
if _, err := tx.Exec(stmt); err != nil {
return err
}
Expand Down
25 changes: 0 additions & 25 deletions internal/server/data/migrator/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,6 @@ func HasTable(tx DB, name string) bool {
WHERE table_schema = CURRENT_SCHEMA()
AND table_name = ? AND table_type = 'BASE TABLE'
`
if tx.DriverName() == "sqlite" {
stmt = `SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?`
}

if err := tx.QueryRow(stmt, name).Scan(&count); err != nil {
logging.L.Warn().Err(err).Msg("failed to check if table exists")
return false
Expand All @@ -40,17 +36,6 @@ func HasColumn(tx DB, table string, column string) bool {
WHERE table_schema = CURRENT_SCHEMA()
AND table_name = ? AND column_name = ?
`

if tx.DriverName() == "sqlite" {
stmt = `
SELECT count(*)
FROM sqlite_master
WHERE type = 'table' AND name = ?
AND sql LIKE ?
`
column = "% " + column + " %"
}

if err := tx.QueryRow(stmt, table, column).Scan(&count); err != nil {
logging.L.Warn().Err(err).Msg("failed to check if column exists")
return false
Expand All @@ -69,16 +54,6 @@ func HasConstraint(tx DB, table string, constraint string) bool {
WHERE table_schema = CURRENT_SCHEMA()
AND table_name = ? AND constraint_name = ?
`
if tx.DriverName() == "sqlite" {
stmt = `
SELECT count(*)
FROM sqlite_master
WHERE type = 'table' AND tbl_name = ?
AND sql LIKE ?
`
constraint = "%CONSTRAINT `" + constraint + "`%"
}

if err := tx.QueryRow(stmt, table, constraint).Scan(&count); err != nil {
logging.L.Warn().Err(err).Msg("failed to check if constraint exists")
return false
Expand Down
3 changes: 0 additions & 3 deletions internal/server/data/migrator/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@ import (

func setupExampleTable(t *testing.T, db DB) {
t.Helper()
if db.DriverName() == "sqlite" {
t.Skip("does not work with sqlite")
}

_, _ = db.Exec("DROP TABLE example")

Expand Down
3 changes: 0 additions & 3 deletions internal/server/data/migrator/migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,6 @@ type Migration struct {
}

type DB interface {
// DriverName returns the name of the database driver.
DriverName() string

Exec(stmt string, args ...any) (sql.Result, error)
Query(query string, args ...any) (*sql.Rows, error)
QueryRow(query string, args ...any) *sql.Row
Expand Down
14 changes: 14 additions & 0 deletions internal/server/data/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,20 @@ import (
"github.com/infrahq/infra/uid"
)

// ReadTxn can perform read queries and contains metadata about the request.
type ReadTxn interface {
Query(query string, args ...any) (*sql.Rows, error)
QueryRow(query string, args ...any) *sql.Row

OrganizationID() uid.ID
}

// WriteTxn extends ReadTxn by adding write queries.
type WriteTxn interface {
ReadTxn
Exec(sql string, values ...interface{}) (sql.Result, error)
}

type Table interface {
Table() string
// Columns returns the names of the table's columns. Columns must return
Expand Down