jet
jet copied to clipboard
Generate table indexes
Is your feature request related to a problem? Please describe. I have a few tables with unique indexes and I use a function to check the error against its error code and constraint name, which is the index name.
Describe the solution you'd like Would be nice to have indexes generated for every table.
Hi @amanbolat, Could you share a pseudo code how you intended to use them.
Hi @go-jet.
Let's say I generated a code for the table users:
type usersTable struct {
postgres.Table
//Columns
ID postgres.ColumnString
Name postgres.ColumnString
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
//Indexes
UserNameKeyIndex postgres.Index
}
Assume that we have Index interface somewhere in go-jet library:
type Index interface {
Name() string
}
At last, I have a function that will create a user in DB:
func (s *Store) CreateUser(ctx context.Context, user User) error {
// skipped
// Check for duplicate
stmt := table.User.INSERT(table.User.AllColumns).MODEL(user)
res, err := stmt.ExecContext(ctx, s.dbConn)
// pkgpostgres.DuplicateErrorCode = 23505
if IsErrorCode(err, pkgpostgres.DuplicateErrorCode, table.User.UserNameKeyIndex.Name()) {
return ErrDuplicateUserName
} else if err != nil {
return err
}
// skipped
}
Code for IsErrorCode:
func IsErrorCode(err error, code string, constraintName *string) bool {
if err == nil {
return false
}
if code == "" {
return false
}
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) {
return false
}
if pgErr.Code != code {
return false
}
if constraintName != nil && *constraintName != pgErr.ConstraintName {
return false
}
return true
}
Aha, I see. It makes sense.