CoreLibraries icon indicating copy to clipboard operation
CoreLibraries copied to clipboard

Add CommandType support to SqlProgram

Open thargy opened this issue 9 years ago • 2 comments

SqlProgram needs to be enhanced to support more command types than Stored Procedures. In particular, we should support CommandType.Text to allow execution of dynamic, parameterized scripts. At the same time, we might consider CommandType.TableDirect, though it is not a core driver for this enhancement.

thargy avatar Apr 05 '17 12:04 thargy

Something to consider when we add text execution is validation. This can be achieved by parsing the T-SQL first to ensure it is actually valid SQL, but then we would need to validate the objects referenced and any parameters it contains.

We should utilise sp-describe-undeclared-parameters-transact-sql as this reports any syntax errors, along with any missing (undeclared) parameters.

This would need to be executed against the database upon SqlProgram Validation for CommandType.Text. We could do something similar when doing CommandType.TableDirect as it will be converted to CommandType.Text under the hood.

Example usage: Valid SQL:

EXEC sp_describe_undeclared_parameters
@tsql = N'SELECT object_id, name, type_desc FROM sys.Indexes;'

Output:
Nothing

Invalid SQL:

EXEC sp_describe_undeclared_parameters
@tsql = N'SELECT object_id, name, type_desc FROM sys.InvalidTable;'

Output:
Msg 208, Level 16, State 1, Line 23
Invalid object name 'sys.InvalidTable'.
Msg 11501, Level 16, State 2, Line 23
The batch could not be analyzed because of compile errors.

Declared Parameter:

EXEC sp_describe_undeclared_parameters
@tsql = N'SELECT object_id, name, type_desc FROM sys.Indexes WHERE name = @Name;',
@params = N'@Name nvarchar(128)'

Output:
Nothing

Undeclared Parameter:

EXEC sp_describe_undeclared_parameters
@tsql = N'SELECT object_id, name, type_desc FROM sys.Indexes WHERE name = @Name;'

Output (partial):

parameter_ordinal name suggested_system_type_id suggested_system_type_name suggested_max_length suggested_precision suggested_scale suggested_user_type_id suggested_user_type_database suggested_user_type_schema suggested_user_type_name
1 @Name 231 nvarchar(128) 256 0 0 256 CampingCaravanClub_Release sys sysname

josh-green avatar Apr 18 '17 13:04 josh-green

This is really useful, however, as we can't guarantee to have all scripts available once at startup, then the overhead of round-tripping a validation step to the DB is probably not viable. In reality, the main thing we need to find are Identifiers, for disambiguation when combining batches (in #45), even better would be if we could figure out automatically what Identifiers are correctly initialised or specified. However, for now, we can validate that supplied parameters are used/referenced within a script, and potentially rename them when creating batches.

thargy avatar Apr 18 '17 14:04 thargy