jet icon indicating copy to clipboard operation
jet copied to clipboard

Generate table indexes

Open amanbolat opened this issue 2 years ago • 3 comments
trafficstars

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.

amanbolat avatar Mar 06 '23 10:03 amanbolat

Hi @amanbolat, Could you share a pseudo code how you intended to use them.

go-jet avatar Mar 07 '23 17:03 go-jet

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
}

amanbolat avatar Mar 08 '23 06:03 amanbolat

Aha, I see. It makes sense.

go-jet avatar Mar 10 '23 12:03 go-jet