surrealdb / surrealdb.go

SurrealDB SDK for Golang
https://surrealdb.com
Apache License 2.0
231 stars 62 forks source link

Add function to check error on unique index. #74

Open pof3 opened 1 year ago

pof3 commented 1 year ago

Just as the os module provides users with the os.IsNotExist function to test if the error was generated by trying to open a non existent file, regardless of its name, this commit adds the same functionality to check if the error comes from trying to insert data to a table with an unique index. This example, which is in the test generated for the function, shows its behavior:

...
err1 := errors.New("sending request failed for method 'create': There was a problem with the database: Database index `userNameIdx` already contains 'Mark', with record `user:⟨2⟩`")
err2 := errors.New("sending request failed for method 'create': There was a problem with the database: Database index \"''``\" already contains '\\', with record `user:⟨{ foo = []}⟩`")
err3 := errors.New("sending request failed for method 'create': There was a problem with the database: Database index `userNameIdx` THIS MUST NOT PASS, with record `user:⟨2⟩`")
err4 := errors.New(" Database index `uniqueBlob` already contains { date: 'today', location: 'London' }, with record `foo:2`")
err5 := errors.New(" database index `uniqueBlob` already contains { date: 'today', location: 'London' }, with record `foo:2`")
err6 := errors.New("Database record `foo:1` already exists")

fmt.Println(IsDuplicateUniqueIdx(err1))
fmt.Println(IsDuplicateUniqueIdx(err2))
fmt.Println(IsDuplicateUniqueIdx(err3))
fmt.Println(IsDuplicateUniqueIdx(err4))
fmt.Println(IsDuplicateUniqueIdx(err5))
fmt.Println(IsDuplicateUniqueIdx(err6))
...

Will print:

true
true
false
true
false
false
pof3 commented 1 year ago

Just re wrote the tests using testify. all of them are passing.

ElecTwix commented 1 year ago

Just re wrote the tests using testify. all of them are passing.

you can resolve the discussions has been fixed with this commit. Nice job. :+1:

pof3 commented 1 year ago

Thanks, @timpratim ! Yeah, I know regexp are not an ideal solution, in Go we'd rather use the built in functions errors.Is, errors.Unwrap, etc. Nonetheless, the current driver works on top of websockets, and no further modifications can be done without immediate effects on other drivers and stacks. As you say, returning the code error at the beginning would be a nice workaround, so we can standardize it and make the proper changes all together. This PR adds a quick way to do the job, so it might be helpful for users, and I think it wouldn't be an issue for backwards compatibility, since the underlying behaviour in future implementation will be the same as expected.

phughk commented 1 year ago

Linking this error ticket which also covers incorrect handling of error responses https://github.com/surrealdb/surrealdb.go/issues/33 Agreed with @timpratim we are happy to go ahead with regex parsing 👍