Is there a more advance way to handle Go Entgo postgreSQL error handling? - postgresql

So I'm developing a API using Go together with ORM package Entgo and Postgres. Is there a way to handle the errors same or similar way as they are solved in pg package where I have all needed information why query failed?
All I found in ent go are this methods but they only return bool
ent.IsNotFound(err)
ent.IsConstraintError(err)
ent.IsNotLoaded(err)
ent.IsValidationError(err)
It would be great to have something similar like pg.Error:
type Error struct {
Severity string
Code ErrorCode
Message string
Detail string
Hint string
Position string
InternalPosition string
InternalQuery string
Where string
Schema string
Table string
Column string
DataTypeName string
Constraint string
File string
Line string
Routine string
}

So I asked this same question on package repo and this is the answer I got from repo Maintainer.
Ent wraps or returns the underlying driver errors. So, you can either use type-assertion or errors.Is/errors.As helpers to extract these types.
See examples in our integration-test:
https://github.com/ent/ent/blob/60e0328/entc/integration/integration_test.go#L1845-L1858
https://github.com/ent/ent/blob/60e0328/entc/integration/integration_test.go#L423

Related

#Query - Returning primitive type or String object?

I'm facing a little problem trying to retrieve an int value or String looking for Top record or last record on my DB, depending in what I want.
Looking in Spring data documentation I found something like this:
Vaccine findTopByOrderByVaccineCodeDesc();
Which is perfectly well but is returning a Vaccine, I don't want the whole Vaccine Object, I just want for example the "vaccine code". I tried something like this:
String findTop1ByOrderByVaccineCodeDesc();
But unfortunately is wrong! It's not working. But what about this:
#Query("SELECT TOP v.vaccineCode FROM Vaccine v ORDER BY vaccineCode Desc")
String getLastRecordByVaccineCode();
I know this is syntactically wrong wrote because I'm using TOP in wrong way but I don't know how to do it.
Any advice? I really appreciate a clue how to find the answer in the documentation or how to read the doc cauze I'm no good looking in the doc.
You can use EntityManager
public String getVaccineCode {
#AutoWired
EntityManager entityManager;
String vaccineCode = (String) entityManager.createQuery("SELECT v.vaccineCode FROM Vaccine v ORDER BY vaccineCode Desc", String.class).getFirstResult());
return vaccineCode;
}

SpringData annotation(or the standard way) to use String for MongoDB ObjectId in java for manual references

I am wondering if there exists a way to map String on the java side for manual references to ObjectIds and vice-versa. For example in:
User =[{_id: ObjectId('123'),
pics_id: ObjectId('123'), ...
}, ... ]
pics_id is a manual reference to another collection. The following code:
class User{
#Id id;
#Field("pics_id") String picId;
}
stores the pics_id as String instead of ObjectId.
Is there any way to make this happen without the use of the ObjectId class instead of String? IMHO, using ObjectId in the java code would make the code look a bit strange, as some ids are string(such as fields annotated with #Id) and some are objectIds. Thank you.
With the upcoming Spring Data MongoDB 2.2 release it is possible to define the desired target type via the #Field annotation.
The type information is passed down to the conversion subsystem so that eg. a plain String can be stored as Code or ObjectId.
class User {
#Id String id;
#Field(targetType = FieldType.OBJECT_ID)
String picId;
}
Please have a look at the documentation of 2.2.0.RC1 for more details.

How to filter fields from the database in JSON response?

i am making a REST API in golang and i want to add support for filtering fields but i don't know the best way to implement that, lets say i have this structure representing an Album model
type Album struct {
ID uint64 `json:"id"`
User uint64 `json:"user"`
Name string `json:"name"`
CreatedDate time.Time `json:"createdDate"`
Privacy string `json:"privacy"`
Stars int `json:"stars"`
PicturesCount int `json:"picturesCount"`
}
and a function that returns an instance of an Album
func GetOne(id uint64, user uint64) (Album, error) {
var album Album
sql := `SELECT * FROM "album" WHERE "id" = $1 AND "user" = $2;`
err := models.DB.QueryRow(sql, id, user).Scan(
&album.ID,
&album.User,
&album.Name,
&album.CreatedDate,
&album.Privacy,
&album.Stars,
&album.PicturesCount,
)
return album, err
}
and the client was to issue a request like this
https://api.localhost.com/albums/1/?fields=id,name,privacy
obvious security issues aside, my first thought was to filter the fields in the database using something like this
func GetOne(id uint64, user uint64, fields string) {
var album Album
sql := fmt.Sprintf(`SELECT %s FROM "album" WHERE "id" = $1 AND "user" = $2;`, fields)
// i don't know what to do after this
}
and then i thought of adding omitempty tag to all the fields and setting the fields to their zero value before encoding it to JSON,
would this work?
which one is the better way?
is there a best way?
how would i go about implementing the first method?
Thank you.
For your first proposal (querying only the requested fields) there are two approaches (answering "would this work?" and "how would I go about implementing the first method?"):
Dynmaically reate a (possibly anonymous) struct and generate JSON from there using encoding/json.
Implement a wrapper that will translate the *database/sql.Rows you get back from the query into JSON.
For approach (1.), you will somehow need to create structs for any combination of attributes from your original struct. As reflect cannot create a new struct type at runtime, your only chance would be to generate them at compile time. The combinatorial explosion will bloat your binary, so do not do that.
Approach (2.) is to be handled with caution and can only be a last resort. Taking the list of requested fields and writing out JSON with the values you got from DB sounds straightforward and does not involve reflection. However your solution will be (very likely) much more unstable than encoding/json.
When reading your question I too thought about using the json:"omitempty" struct tag. And I think that it is the preferable solution. It does neither involve metaprogramming nor writing your own JSON encoder, which is a good thing. Just be aware of the implications in case some fields are missing (client side maybe has to account for that). You could query for all attributes always and override the unwanted ones using reflection.
In the end, all above solutions are suboptimal, and the best solution would be to not implement that feature at all. I hope you have a solid reason to make attributes variable, and I am happy to further clarify my answer based on your explaination. However, if one of the attributes of a resource is too large, it maybe should be a sub-resource.

String from DB is not parsing in Powershell

While fetching data from db, I am getting a string which is not getting formatted in pwoershell.
String
[{"varun":"\\","rocks":true}]
It throws below exception
System.FormatException: Input string was not in a correct format.
My guess is that you're using it with the -f operator as format string? In this case you'll have to escape { and } as {{ and }} respectively because those are used for placeholders in the format string (e.g. {0}).
Also please provide more details next time, such as the complete error message (it says where it occurs, for example) and the code where it happens.

Unable to use Variable in XPath in Eclipse - Selenium

I need to pass values from excel sheet ( stored in variable api ) to XPATH in eclipse (java - Selenium).
I tried several options but none works. Please guide.
Here is my line of code.
String appcode = //input[contains(#id,'app') and contains(#type,'text') and ancestor::div[contains(#id, '+api+')]]
When i hardcode the value of api as below it works.
String appcode="//input[contains(#id,'app') and contains(#type,'text') and ancestor::div[contains(#id, 'setmember')]]";
Isnt it this easy?
Appreciate your help
pk
you probably did not end the String constructor properly. Try this:
String appcode = "//input[contains(#id,'app') and contains(#type,'text') and ancestor::div[contains(#id, '" +api+" ')]]";
My assumption is, that api variable is type String
you can use \" so you would have something like
String appcode ="//input[contains(#id,\" "+[VARIABLE]+ " \")[..] ";