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

feat(errors): add unique constraint violation error #1069

Merged
merged 25 commits into from
Jan 15, 2024
Merged

Conversation

steebchen
Copy link
Owner

@steebchen steebchen commented Oct 28, 2023

Adds helper functions for one of the most commonly used errors, a unique constraint violation.

Note that different databases return slightly different metadata, which means the implementation details depend on what database you use:

user, err := db.User.CreateOne(...).Exec(cxt)
if err != nil {
	if info, err := db.IsErrUniqueConstraint(); err != nil {
		// Fields exists for Postgres and SQLite
		log.Printf("unique constraint on the fields: %s", info.Fields)

		// you can also compare it with generated field names:
		if info.Fields[0] == db.User.Name.Field() {
			// do something
		}

		// For MySQL and MongoDB, use the constraint key
		log.Printf("unique constraint on the key: %s", info.Key)
	}
}

fix #213

@nettrino
Copy link

@steebchen is this OK to be merged? would help a lot with error handling

@steebchen
Copy link
Owner Author

steebchen commented Dec 27, 2023

@nettrino Actually it would be great if you could try it using

go get github.com/steebchen/prisma-client-go@c1a00401061ebbb46e41033b620d9fafa5896204

and re-generate the client.

This PR includes some tests but it would be great for someone to actually use it and check if everything looks good. Thanks! Feel free to ping me in discord as well.

@ytsruh
Copy link

ytsruh commented Jan 10, 2024

Tested on Postgres (Neon DB) tonight and it works fine for me. Unique constraints on both BigInt & String types work as expected. Thanks for this!

@nettrino
Copy link

@steebchen Has also been running fine for me for a week or so, so this should be good to merge!

@steebchen
Copy link
Owner Author

Awesome thanks! One thing which @abelanger5 mentioned is that it would be nice if errors.As would work, which it doesn't right now. It needs some refactor though and some extra work, so I'll just merge this as is and anything else can be an extra improvement.

@steebchen steebchen merged commit eba1a7f into main Jan 15, 2024
12 checks passed
@steebchen steebchen deleted the feat/errors-uqv branch January 15, 2024 08:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Provide proper error handling for unique constraints
3 participants