go-gorp/gorp

Avoid creating duplicate unique indexes

lieut-data opened this issue · 0 comments

Most methods on DbMap are idempotent, checking to ensure that duplicate resources aren't being created (or effecting changes that are safe to apply multiple times), but SetUniqueTogether will duplicate unique indexes each time it is called with the same parameters. For example,

package main

import (
	"database/sql"
	"fmt"

	"github.com/go-gorp/gorp"
	_ "github.com/mattn/go-sqlite3"
)

type Emoji struct {
	Id       string `json:"id"`
	Name     string `json:"name"`
	DeleteAt int64  `json:"delete_at"`
}

func main() {
	db, _ := sql.Open("sqlite3", ":memory:")
	dbMap := &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}

	table := dbMap.AddTableWithName(Emoji{}, "Emoji")
	table.SetKeys(false, "Id")
	table.ColMap("Id").SetMaxSize(26)
	table.ColMap("Name").SetMaxSize(64)

	table.SetUniqueTogether("Name", "DeleteAt")
	table.SetUniqueTogether("Name", "DeleteAt")

	fmt.Print(table.SqlForCreate(false))
}

results in:

create table "Emoji" ("Id" varchar(26) not null primary key, "Name" varchar(64), "DeleteAt" integer, unique ("Name", "DeleteAt"), unique ("Name", "DeleteAt")) ;