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

Generate table indexes #220

Open
amanbolat opened this issue Mar 6, 2023 · 3 comments
Open

Generate table indexes #220

amanbolat opened this issue Mar 6, 2023 · 3 comments

Comments

@amanbolat
Copy link

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.

@go-jet
Copy link
Owner

go-jet commented Mar 7, 2023

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

@amanbolat
Copy link
Author

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
}

@go-jet
Copy link
Owner

go-jet commented Mar 10, 2023

Aha, I see. It makes sense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants