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

Support for non id primary keys #11

Merged
merged 3 commits into from
Dec 1, 2023
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
14 changes: 14 additions & 0 deletions clone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ func TestDownloadUpload(t *testing.T) {
assert.Equal(10, res[0]["id"])
assert.Equal("produces socks", res[1]["desc"])
assert.Equal("socks", res[2]["name"])
assert.Equal("socks are cool", res[3]["detail"])

// users are expected to do some cleanup, so test that it works
for _, row := range res {
Expand All @@ -29,6 +30,7 @@ func TestDownloadUpload(t *testing.T) {
assert.Equal(11, res[0]["id"])
assert.Equal(12, res[1]["id"])
assert.Equal(13, res[2]["id"])
assert.Equal(11, res[3]["company_id"])
}

func cleanup(row map[string]any) {
Expand Down Expand Up @@ -60,6 +62,10 @@ func (d testDB) SelectMatchingRows(tname string, conds map[string][]any) ([]map[
if conds["id"][0] == 23 {
return []map[string]any{{"id": 23, "desc": "produces socks"}}, nil
}
case "company_details":
if conds["company_id"][0] == 10 {
return []map[string]any{{"company_id": 10, "detail": "socks are cool"}}, nil
}
}

return nil, fmt.Errorf("no mock for %s where %#v", tname, conds)
Expand Down Expand Up @@ -99,6 +105,10 @@ func (d testDB) Insert(records ...map[string]any) error {
m["id"] = 13
continue
}
if m[datapasta.DumpTableKey] == "company_details" && m["company_id"] == 10 {
m["company_id"] = 11
continue
}
return fmt.Errorf("unexpected insert: %#v", m)
}
return nil
Expand All @@ -115,6 +125,10 @@ func (d testDB) ForeignKeys() []datapasta.ForeignKey {
BaseTable: "factory", BaseCol: "id",
ReferencingTable: "product", ReferencingCol: "factory_id",
},
{
BaseTable: "company", BaseCol: "id",
ReferencingTable: "company_details", ReferencingCol: "company_id",
},
}
}

Expand Down
15 changes: 10 additions & 5 deletions postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,10 +252,10 @@ func (db pgbatchtx) Insert(rows ...map[string]any) error {
builder := db.builder.Insert(`"` + table + `"`)
oldPK := row[pk]
if pk != "" {
builder = builder.Suffix("RETURNING " + pk)
builder = builder.Suffix("RETURNING " + pk + " as id")
builder = builder.Prefix("WITH inserted_row AS (")
builder = builder.Suffix(") INSERT INTO datapasta_clone (table_name, original_id, clone_id) SELECT ?, ?, id FROM inserted_row", table, oldPK)
delete(row, pk)
//delete(row, pk)
}

keys := make([]string, 0, len(row))
Expand All @@ -268,8 +268,11 @@ func (db pgbatchtx) Insert(rows ...map[string]any) error {
continue
}
deferred := false
foundForeign := false
for _, fk := range db.fks {

if fk.ReferencingCol == k && fk.ReferencingTable == table {
foundForeign = true
findInMap := squirrel.Expr("COALESCE((SELECT clone_id FROM datapasta_clone WHERE original_id = ? AND table_name = ?::text), ?)", v, fk.BaseTable, v)

if fk.BaseTable == table {
Expand All @@ -278,7 +281,7 @@ func (db pgbatchtx) Insert(rows ...map[string]any) error {
return fmt.Errorf("can't have self-referencing tables without primary key")
}
deferred = true
builder := db.builder.Update(`"`+table+`"`).Set(k, findInMap).Where("id=(SELECT clone_id FROM datapasta_clone WHERE original_id = ? AND table_name = ?::text)", oldPK, fk.BaseTable)
builder := db.builder.Update(`"`+table+`"`).Set(k, findInMap).Where(pk+"=(SELECT clone_id FROM datapasta_clone WHERE original_id = ? AND table_name = ?::text)", oldPK, fk.BaseTable)
sql, args, err := builder.ToSql()
if err != nil {
return fmt.Errorf(`build: %w, args: %s, sql: %s`, err, args, sql)
Expand All @@ -294,8 +297,10 @@ func (db pgbatchtx) Insert(rows ...map[string]any) error {
if deferred {
continue
}
keys = append(keys, fmt.Sprintf(`"%s"`, k))
vals = append(vals, v)
if foundForeign || k != pk {
keys = append(keys, fmt.Sprintf(`"%s"`, k))
vals = append(vals, v)
}
}

builder = builder.Columns(keys...).Values(vals...)
Expand Down
Loading