How to construct subquery in the form of SELECT * FROM (<subquery>) ORDER BY column;? - go

I am using gorm to interact with a postgres database. I'm trying to ORDER BY a query that uses DISTINCT ON and this question documents how it's not that easy to do that. So I need to end up with a query in the form of
SELECT * FROM (<subquery>) ORDER BY column;
At first glance it looks like I need to use db.QueryExpr() to turn the query I have into an expression and build another query around it. However it doesn't seem gorm has an easy way to directly specify the FROM clause. I tried using db.Model(expr) or db.Table(fmt.Sprint(expr)) but Model seems to be completely ignored and fmt.Sprint(expr) doesn't return exactly what I thought. Expressions contain a few private variables. If I could turn the original query into a completely parsed string then I could use db.Table(query) but I'm not sure if I can generate the query as a string without running it.
If I have a fully built gorm query, how can I wrap it in another query to do the ORDER BY I'm trying to do?

If you want to write raw SQL (including one that has a SQL subquery) that will be executed and the results added to an object using gorm, you can use the .Raw() and .Scan() methods:
query := `
SELECT sub.*
FROM (<subquery>) sub
ORDER BY sub.column;`
db.Raw(query).Scan(&result)
You pass a pointer reference to an object to .Scan() that is structured like the resulting rows, very similarly to how you would use .First(). .Raw() can also have data added to the query using ? in the query and adding the values as comma separated inputs to the function:
query := `
SELECT sub.*
FROM (<subquery>) sub
WHERE
sub.column1 = ?
AND sub.column2 = ?
ORDER BY sub.column;`
db.Raw(query, val1, val2).Scan(&result)
For more information on how to use the SQL builder, .Raw(), and .Scan() take a look at the examples in the documentation: http://gorm.io/advanced.html#sql-builder

Related

How to search an array element in SurrealDB

I'm trying to perform a query that evaluates if an array includes or contains a specif value or set of values.
SELECT * FROM table
WHERE data = ['value_a']
https://surrealdb.com/docs/surrealql/statements/select
I've read the documentation and try several queries, but I didn't find any function or way to create this query.
I've read the official documentation and performed several queries based on the examples, but nothing have worked.
https://surrealdb.com/docs/surrealql/statements/select
My expected behaviour is:
Matches a specific value or set of values like these examples in SQL relational database.
https://www.w3schools.com/sql/sql_in.asp
There is a CONTAINS operator :
https://surrealdb.com/docs/surrealql/operators#contains
The Query should be like:
SELECT * FROM table WHERE data CONTAINS 'value_a'

Using aliased expression used in select clause into my order by clause for a criteria query

I have a requirement which is somewhat similar to this. My API supports a filter where there is more than 8 filter parameter. So, I want to create a query dynamically based on the filter parameter passed. I am using CriteriaBuilder to create a dynamic query.
Now, I am able to create dynamic queries successfully but the issue comes when the user wants to sort on an aggregate functions. In my query, I have 4 aggregate (count) function. So to support sorting on these columns, I just use the expression of this aggregate function but what I want is to use the alias of this expression
Repeating the expression in select and order by doesn't seem right to me. So, is there a solution/workaround to the problem. I want to declare the expression alias once and use it in both select and order by clause and if required in my group by clause in future
You probably need to build a custom projection class, you can find a decent and easy one, SQLProjectionWithAliasSupport in https://hibernate.atlassian.net/browse/HHH-2952 (from Sergey Pulyaev)
If then one wants to support also sub criteria, things get more complicate

Laravel Query Builder, selectRaw or select and raw

What's the difference between:
DB::table('some_table')
->selectRaw('COUNT(*) AS result')
->get();
and:
DB::select(DB::raw("
SELECT COUNT(*) AS result
FROM some_table"));
In the documentation https://laravel.com/docs/5.6/queries they advert about using raw()due SQL Injection, but it's the same with selectRaw?
The end result of both is the same i.e but there are some difference:
The first one:
DB::table('some_table')
->selectRaw('COUNT(*) AS result')
->get();
Returns a collection of PHP objects,
You can call collections method fluently on the result
It is cleaner.
While the second:
DB::select(DB::raw("
SELECT COUNT(*) AS result
FROM some_table"
));
Returns an array of Php object.
Although they have similarities: the raw query string.
Those two examples yield the same result, although with different result data types.
Using raw queries can indeed be an attack vector if you don't escape values used within the query (especially those coming from user input).
However that can be mitigated very easily by using bindings passed as the second parameter of any raw query method, as showcased in the same documentation (selectRaw accepts a second parameter as an array of bindings, as well as other raw methods from the Query Builder such as whereRaw, etc). Actually at the begining of the docs page you referenced, the second paragraph also states the following:
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
So as long as you're careful and make sure any parameters are passed as bindings and not concatenated as plain values within the raw query string you should be safe.

Dynamic linq: passing entire query as string

Looking at Dynamic Linq, it's possible to use strings to define the key parts of the query. My question is, is it possible to pass the entire query in as a string?
ie: var foo = "from..."
LINQ stands for "Language INtegrated Queries" - it's compiled with the rest of the code, not parsed on the run. You can use Microsoft.CSharp.CSharpCodeProvider to compile your query on the run - but you will have to know in advance what local objects you want to send to the query.
That's not possible in dynamic LINQ -- dynamic LINQ only replaces specific pieces of the query. You can use ExecuteQuery on the data context in LINQ to SQL or SqlQuery on a DbSet<T>, though, to execute specific SQL commands.

Dynamic Query using Linq To SQL According Multiple Fields

Hi Experts
I have a special question About dynamic Linq to Sql.
Consider we want to search in a table according two fields*(LetterNo(string) and LetterDate(Datetime))*
.OK the problem is user can enter on of that fields or even both.
I searched in the internet and found "Linq.Dynamic" library in ScottGu weblog.but in that library if we want to use SqlParameter in exported command we should use #0 and param for that.problem is I don't know how many fields user entered.
I want use one query for that and no external tool like "Linq Kit PredicateBuilder".
If I create my query string Manually(and execute using ExecuteCommand) then I will abdicate SqlParameter and risk of Sql Injenction growing up.
How Can do that?
thanks
I suspect you are wanting to do something like the following:
IQueryable<Letter> query = context.Letters;
if (!string.IsNullOrEmpty(LetterNo))
query = query.Where(letter => letter.LetterNo == LetterNo);
If (LetterDate.HasValue)
query = query.Where(letter => letter.LetterDate == LetterDate);
When you execute query, it will combine the necessary expressions and issue a single query to the database based on the user's input.

Resources