2025-01-20 17:20:04 +01:00
|
|
|
/*
|
|
|
|
Copyright 2025 Peter Kurfer.
|
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2024-12-13 09:09:14 +01:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"iter"
|
|
|
|
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
|
|
|
|
supabasev1alpha1 "code.icb4dc0.de/prskr/supabase-operator/api/v1alpha1"
|
2025-01-05 11:42:15 +01:00
|
|
|
"code.icb4dc0.de/prskr/supabase-operator/assets/migrations"
|
2024-12-13 09:09:14 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type Migrator struct {
|
|
|
|
Conn *pgx.Conn
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m Migrator) ApplyAll(ctx context.Context, status supabasev1alpha1.MigrationStatus, seq iter.Seq2[migrations.Script, error]) (appliedSomething bool, err error) {
|
|
|
|
for s, err := range seq {
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if status.IsApplied(s.FileName) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := m.Apply(ctx, s.Content); err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
appliedSomething = true
|
|
|
|
status.Record(s.FileName)
|
|
|
|
}
|
|
|
|
|
|
|
|
return appliedSomething, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m Migrator) Apply(ctx context.Context, script string) error {
|
|
|
|
tx, err := m.Conn.BeginTx(ctx, pgx.TxOptions{})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = tx.Exec(ctx, script)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Join(err, tx.Rollback(ctx))
|
|
|
|
}
|
|
|
|
|
|
|
|
return tx.Commit(ctx)
|
|
|
|
}
|