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

Parameterization in PostgreSQL queries #4514

Open
murkykiska opened this issue May 28, 2024 · 1 comment
Open

Parameterization in PostgreSQL queries #4514

murkykiska opened this issue May 28, 2024 · 1 comment

Comments

@murkykiska
Copy link

I encountered the following problem:
If there is a “where” or “limit” in queries for postgres, the following queries are built:

int number = 3;       
var users1 = connection.GetTable<User>().Where(u => u.Id > number);
--  PostgreSQL.15 PostgreSQL
DECLARE @number Integer -- Int32
SET     @number = 3

SELECT
        u."Id",
        u."Name",
        u."Email",
        u."CreatedAt"
FROM
        "User" u
WHERE
        u."Id" > :number

Such a request is not correct in syntax, i.e. when we try to execute it we get the following error: Npgsql.PostgresException: "42601: Syntax error (approximate position: "@")

A workaround was found: if you substitute a specific number/string into a linq query, then they are directly substituted into the “where”. But in real tasks, more complex data types are used (guides/dates, etc.), and this way does not work with them.

var sql = service.BuildQuery(dc =>
{   
    return
        dc.Table
            .AsSqlServer().WithNoLock()
          .Where(r => r.InstanceID == Guid.Empty)
          .OrderBy(r => r.Number)
          .Take(10);
});
--  PostgreSQL.9.2 PostgreSQL
DECLARE @Empty Uuid -- Guid
SET     @Empty = '00000000-0000-0000-0000-000000000000'::uuid
DECLARE @take Integer -- Int32
SET     @take = 10

SELECT
	"r"."RowID",	
    "r"."Number",
	"r"."InstanceID"	
FROM
	"Table" "r"
WHERE
	"r"."InstanceID" = :Empty
ORDER BY
	"r"."Number"
LIMIT :take

Is it possible to get rid of variable declarations?

Environment details

Linq To DB version: 5.4.1

Database (with version): PostgreSQL 15

ADO.NET Provider (with version): Npgsql

Operating system: Windows 11

.NET Version: .net framework 4.8, .net 6.0

@sdanyliv
Copy link
Member

Currently linq2db is not usable for building just SQL, what you see is debug information, which executes only in SQL Server. What is the implication of generating SQL queries without execution?

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

No branches or pull requests

2 participants