Add CommandType support to SqlProgram
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.
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 |
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.