Repository navigation
Description
I've written a blog post detailing the context for this, go read it.
Summary of benefits:
- Parsing the PostgreSQL SQL dialect isn’t trivial. For example, we must avoid manipulating string literals, which may contain semicolons or text that looks like placeholders. Of course, Npgsql doesn’t include a full SQL parser - that would be very hard to do - but rather a very small parser that knows the absolute minimum in order to perform its job. Now, we haven’t had any bugs recently, but I’m sure that if I really dove in there, I could produce cases where the parser mistakenly identifies a placeholder or semicolon where it shouldn’t, or vice versa. It’s an inherently unsafe situation.
- Beyond correctness, both parsing and producing the rewritten SQL is work, which can hurt performance. The longer the SQL query and the more parameters it has, the more overhead this process adds to query execution. Nobody wants that.
- When managing a parameter collection (e.g. NpgsqlParameterCollection), we have to maintain an internal dictionary that indexes parameters by their name. If we didn’t have to handle names, the collection would become a simple list - this is more efficient.
Subtasks:
- Implement support for positional parameters #3852
- Implementation of the ADO.NET batching API #3860
- Implement AppContext-switch mode to disable SQL parsing/rewriting #3920
- Report positional parameters in DataSourceInformation #4028
https://github.com/dotnet/corefx/issues/3688 discussed the same issue on a general ADO.NET level, if that issue receives attention this one is no longer necessary.
ADO.NET currently "supports" batching multiple SQL statements into a single DbCommand by packing them into the command's CommandText, delimited by semicolons (INSERT ... ; INSERT ...). In PostgreSQL's case, to support this Npgsql must parse the CommandText to find the semicolons, and break up the text into several PostgreSQL protocol messages.
Having Npgsql parse SQL is clearly problematic. SQL (and it's PostgreSQL variant) is a complex language, with non-trivial quoting and escaping, and we've had issues in the past where the SQL parser had issues. An ADO.NET provider should be as minimal and "pass-through" as possible, and not perform such a complex task.
Npgsql already maintains (and even exposes) a non-standard NpgsqlStatement class, which represents a single SQL statement within a multistatement command. In 3.0 NpgsqlStatement instances can be accessed after executing the command to access rows affected, for example. We could allow users to populate NpgsqlCommand's with NpgsqlStatements, providing a structured API for creating multistatement commands rather than the current semicolon-delimited method.
A second issue is parameters. In ADO.NET the parameter list is set on the command, which means that parameters are global to all statements. However, in the PostgreSQL protocol things don't work that way - each statement is completely separate and has its own parameter set (in the Bind message). Npgsql 3.0 works around this problem by again, parsing the SQL, figuring out which statement references which parameter, and sending each statement with its own parameters.
The solution here would be to have a parameter list on each NpgsqlStatement, allowing the user to manually specify parameters on a per-statement basis.
An example of what this API would look like:
using (var cmd = new NpgsqlCommand
{
Connection = conn,
Statements =
{
new NpgsqlStatement("INSERT INTO data (first_name, last_name) VALUES ($1, $2)") {
Parameters =
{
new NpgsqlParameter { Value = "John" },
new NpgsqlParameter { Value = "Doe" }
}
},
new NpgsqlStatement("INSERT INTO data (first_name, last_name) VALUES ($1, $2)") {
Parameters =
{
new NpgsqlParameter { Value = "Alice" },
new NpgsqlParameter { Value = "Doe" }
}
}
}
})
{
cmd.ExecuteNonQuery();
}Some notes:
- In order to truly stop parsing the SQL, users would also have to switch to PostgreSQL's parameter placeholders, which are positional ($1, $2) rather than names (@myParam).
- For single-statement commands, the command-level CommandText and parameter list can still be used.
- It should be impossible to mix both command-level parameters and statement-level parameters.
- This should obviously be an opt-in option
- Port the EF6 and EFCore providers to use this API
Activity
Emill commentedon Apr 24, 2016
It could be an opt-in feature, but I still think you should be able to feed in a semicolon-separated query since that is quite standard and if you have a sql script file you want to execute, you don't want to split it up yourself.
PostgreSQL's lexer is very seldom updated with breaking changes (https://github.com/postgres/postgres/commits/master/src/backend/parser/scan.l) so it shouldn't be that hard to keep in sync with it. I also don't think there is a particular slowdown having to parse the query - it's just a linear pass over it.
The biggest current issue as I see it are the parameters how they can be cross-referenced in different statements.
I'm pretty sure MySQL also parses the query and splits it up the same way as Npgsql.
roji commentedon Apr 24, 2016
I've been thinking about this a while, the recent trigger for me was #946. BTW, as I was fixing that I noticed that the IsParamNameChar method was using a lookup table ParamNameCharTable which was typed as Array, meaning that each GetValue() call on it implies a boxing operation... So this very small operation caused useless heap allocation operations! I admit it's just a programming error that's easily fixed though.
Regardless, I agree with most of what you say @Emill. It should definitely be opt-in and I'm not considering removing the "query parse/rewrite" mode entirely, just allow users a way to do it "cleanly" if they want to. It's more a matter of making things minimal and correct, and I'm sure there are still some bugs hidden in the SQL parser which will come up as more people use Npgsql in new ways.
I think the parameter cross-reference issue can be handled the way I proposed - it should be up to the user to create each NpgsqlStatement along with its parameter list. This would correspond exactly to the way protocol messages are structured - each statement has it's Parse (for SQL) and Bind (for parameters).
BTW Are you sure the MySQL driver actually parses the query, or does it deliver it to the backend which does the parsing? Note that the PostgreSQL simple query protocol also supports delivering messages with semicolons (and this is how Npgsql 2.x did non-prepared statements) - but not the extended protocol which is necessary for parameters, prepared statements etc. Also, does the MySQL driver do parameter placeholder replacing in addition to semicolon detection? All this stuff really seems outside of what an ADO.NET driver is supposed to do, at least IMHO.
Emill commentedon Apr 24, 2016
Ok the IsParamNameChar could be optimized as you say... I think that implementation has been there for quite some time.
Regarding MySql, if you download the source code at https://dev.mysql.com/downloads/connector/net/6.9.html you can see their tokenizer in Source/MySql.Data/common/MySqlTokenizer.cs which seems to be used when running statements. It finds all the parameters but it doesn't seem to split on ;
roji commentedon Apr 24, 2016
OK.
Don't worry, this whole thing is just something that's bothering me, it's definitely not for anytime soon.
[-]New batching API that doesn't parse the query text[/-][+]New raw SQL mode where Npgsql doesn't parse the SQL[/+]MarkusSintonen commentedon Jul 18, 2016
Hi @roji
Could we get the possibility in the new API to use (execute) the NpgsqlStatement without wrapping them first in NpgsqlCommands. For example:
Then the ExecuteXXX functions would be also available for NpgsqlStatement (also with Prepare and so on). Most of the protocol message writing code would be then moved inside NpgsqlStatement and NpgsqlCommand would only contain batch executing and raw SQL parsing logic.
Wrapping the NpgsqlStatements always into the NpgsqlCommands seems quite verbose when only single statements are used. Of course when executing multiple staments as a batch then they could be wrapped inside NpgsqlCommand as suggested by @roji here. Therefore the NpgsqlCommand would be only used to execute batched statements and for backward compatibility with SQL (but requiring raw SQL parsing). NpgsqlStatements could be directly used as the recomended way to interact with PostgreSQL to avoid the raw SQL parsing step. NpgsqlStatements could be also prepared and persisted directly to the server as discussed in PRs #1084 and #1204 for low latency applications (not requiring SQL parsing at each Prepare() call)
roji commentedon Jul 18, 2016
You can check on work-in-progress on this at https://github.com/roji/Npgsql/tree/raw-sql. It's still in pretty early stages so probably no need to point out errors yet. I'll probably continue working on this in the near future.
I agree. The problem is that I'd like to avoid an additional connection string parameter that would activate the raw SQL mode. In my current WIP this is already implemented - NpgsqlCommand has an internal RawSqlMode flag which is set depending on which property is set. If the user sets CommandText, RawSqlMode is set to false. If the user modifies Statements in any way, RawSqlMode is set to true. I'm happy with this, except that the constructor
NpgsqlCommand(string text, NpsqlConnection conn)is already taken and modifies the command text. I'll probably provide an additional constructor accepting a bool flag:NpgsqlCommand(string text, NpgsqlConnection conn, bool rawSqlMode)which would solve this problem.I don't think this is going to be possible. NpgsqlCommand is a fundamental part of the ADO.NET API and I don't intend on providing a way for executing an NpgsqlStatement with wrapping it in an NpgsqlCommand. A lot of the logic currently in NpgsqlCommand would also have to be duplicated into NpgsqlStatement - prepare logic, message sending logic... Allowing an execution path which bypasses NpgsqlCommand would be a very invasive change and would move us farther away from standard ADO.NET behavior.
It's also odd and problematic for NpgsqlCommands to be required for batched statements, and at the same time to always do SQL parsing. What if I want to do raw SQL (bypass parsing) but still want batches? The user should be able to choose between raw SQL mode or parsed mode regardless of whether they're executing one statement or a batch.
In any case, I don't really see any reason to go down this path - there's no harm in always having an NpgsqlCommand which wraps 1 or more NpgsqlCommand. In fact, this is how things have worked internally since Npgsql 3.0 (i.e. this is the output from the SQL parsing phase). As I said above, the API should make it easier (i.e. less verbose) to manage handle the single-statement case, but that shouldn't affect the actual architecture in such a drastic way.
MarkusSintonen commentedon Jul 18, 2016
I would buy
NpgsqlCommand(string text, NpgsqlConnection conn, bool rawSqlMode):). How about also an additional property that the user can use (not internal) in NpgsqlCommand e.g. UseRawSql = trueI also dislike the idea of a new connection string parameter.
roji commentedon Jul 18, 2016
@MarkusSintonen I think I have an even better solution - simply add NpgsqlRawCommand. This would inherit from NpgsqlCommand but be raw-SQL-only. Thus you'd use
new NpgsqlRawCommand("SomeSql", conn)just like the normal NpgsqlCommand, but without the SQL parsing.Aside from being simpler, and no more verbose than regular NpgsqlCommand (except for batched statements), it would also allow us to throw an exception if
NpgsqlRawCommand.Parametersis set - in raw SQL mode parameters must be set on the statement, not on the command. It would also simplify things internally because there will no longer be a need to intelligently detect whether raw SQL mode should be on or not, based on the last modification of CommandText/Statements.MarkusSintonen commentedon Jul 18, 2016
Cool, that sounds really good! You were actually reading my mind since I was just writing a follow up suggesting almost the same thing.
How about if users tries to add named NpgsqlParameter to the NpgsqlRawCommand, probably some exception should be thrown? Or should the NpgsqlRawCommand only allow some new type of parametrization (NpgsqlRawParameter?) that does not allow namings.
What did you mean on Parameters can not be modified in NpgsqlRawCommand? This does not work?:
roji commentedon Jul 18, 2016
Regarding named parameters, it's true that names are meanless for raw SQL mode, since PostgreSQL's parameters are positional. However, that doesn't seem like a strong-enough reason to create a wholly separate NpgsqlRawParameter - NpgsqlRawCommand can simply ignore the names.
Regarding modifying Parameters directly on NpgsqlRawCommand (your code sample). For commands with multiple statements, this makes no sense - in the PostgreSQL protocol each statement is sent with its own set of parameters, there's no concept of a "command" (or batch of statements) which has a shared list of parameters, referred to from individual statements. However, in order to again simplify the API and keep it terse, we could allow setting parameters on the command as long as there's only a single statement. In that case, the command's parameter list will be used as the single statement's list. However, if the command has multiple statements and its Parameters list is non-empty, an exception should be thrown ("set your parameters on your statement instead").
This seems to provide an API that is almost identical to the regular ADO.NET API, while still allowing structured batching of statements, which is great. I'll probably complete this in the coming days.
MarkusSintonen commentedon Jul 18, 2016
Ok, sounds good. Now I got it what you ment previously with .Parameters throwing exception when set with batched commands.
6 remaining items
Implement raw SQL mode for prepared, non-batched commands
Implement raw SQL mode for prepared, non-batched commands
Implement raw SQL mode for prepared, non-batched commands (take 2) (#…