Skip to content

Commit

Permalink
change order in which sync statements are executed (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
NickDubelman authored Oct 7, 2024
1 parent 78f6e4c commit 35df459
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,15 +119,16 @@ func (t table) syncTarget(

tableName := t.config.Table

var inserts []sq.InsertBuilder
var updates []sq.UpdateBuilder
var deletes []sq.DeleteBuilder

// Iterate over source rows and perform INSERTs or UPDATEs as needed
for key, val := range sourceMap {
// If the key doesn't exist in targetMap, then we need to INSERT
if _, ok := targetMap[key]; !ok {
insert := sq.Insert(tableName).Columns(t.columns...).Values(val...)

if _, err := insert.RunWith(t.DB).Exec(); err != nil {
return "", false, err
}
inserts = append(inserts, insert)
} else {
// If the key exists in targetMap, then we need to check if there is a diff

Expand Down Expand Up @@ -156,9 +157,7 @@ func (t table) syncTarget(
update = update.Set(col, val[i])
}

if _, err := update.RunWith(t.DB).Exec(); err != nil {
return "", false, err
}
updates = append(updates, update)
}
}

Expand All @@ -168,11 +167,28 @@ func (t table) syncTarget(
Delete(tableName).
Where(key.whereClause(t.primaryKeys, t.primaryKeyIndices))

deletes = append(deletes, delete)
}

// Actually execute the statements (DELETEs -> UPDATEs -> INSERTs)
for _, delete := range deletes {
if _, err := delete.RunWith(t.DB).Exec(); err != nil {
return "", false, err
}
}

for _, update := range updates {
if _, err := update.RunWith(t.DB).Exec(); err != nil {
return "", false, err
}
}

for _, insert := range inserts {
if _, err := insert.RunWith(t.DB).Exec(); err != nil {
return "", false, err
}
}

return targetChecksum, true, nil
}

Expand Down

0 comments on commit 35df459

Please sign in to comment.