EntityFramework.SqlServer Adapter interface to make working with instances of or easier. Implementing types wrap instances of DbGeography/DbGeometry and allow them to be consumed in a common way. This interface is implemented by wrapping types for two reasons: 1. The DbGeography/DbGeometry classes cannot directly implement internal interfaces because their members are virtual (behavior is not guaranteed). 2. The wrapping types ensure that instances of IDbSpatialValue handle the s thrown by any unimplemented members of derived DbGeography/DbGeometry types that correspond to the properties and methods declared in the interface. An execution strategy that doesn't affect the execution but will throw a more helpful exception if a transient failure is detected. Returns an instance of that wraps the specified value. IDbSpatialValue members are guaranteed not to throw the s caused by unimplemented members of their wrapped values. The geography instance to wrap An instance of that wraps the specified geography value Returns an instance of that wraps the specified value. IDbSpatialValue members are guaranteed not to throw the s caused by unimplemented members of their wrapped values. The geometry instance to wrap An instance of that wraps the specified geometry value Strongly-typed and parameterized string resources. A string like "The argument '{0}' cannot be null, empty or contain only white space." A string like "The provider returned null for the informationType '{0}'." A string like "The underlying provider does not support the type '{0}'." A string like "There is no store type corresponding to the conceptual side type '{0}' of primitive type '{1}'." A string like "The provider manifest given is not of type '{0}'." A string like "Internal .NET Framework Data Provider error {0}." A string like "Spatial readers can only be produced from readers of type SqlDataReader. A reader of type {0} was provided." A string like "Expected a geography value, found a value of type {0}." A string like "Expected a geometry value, found a value of type {0}." A string like "The connection is not of type '{0}'." A string like "Store-generated keys are only supported for identity columns. More than one key column is marked as server generated in table '{0}'." A string like "Store-generated keys are only supported for identity columns. Key column '{0}' has type '{1}', which is not a valid type for an identity column." A string like "The expression '{0}' is of an unsupported type. " A string like "The DATEPART argument to the '{0}.{1}' function must be a literal string." A string like "'{0}' is not a valid value for the DATEPART argument in the '{1}.{2}' function." A string like "Constant expressions of type {0} with a value of NaN are not supported by SQL Server." A string like "Constant expressions of type {0} with a value of {1}.PositiveInfinity are not supported by SQL Server." A string like "Constant expressions of type {0} with a value of {1}.NegativeInfinity are not supported by SQL Server." A string like "There is no store type that maps to the EDM type '{0}' on versions of SQL Server earlier than SQL Server 2008." A string like "The EDM function '{0}' is not supported on versions of SQL Server earlier than SQL Server 2008." A string like "The specified provider value is not compatible with this spatial services implementation. A value is required of type '{0}'." A string like "The specified DbGeography value could not be converted to a SQL Server compatible value." A string like "The specified DbGeometry value could not be converted to a SQL Server compatible value." A string like "Could not determine storage version; a valid storage connection or a version hint is required." A string like "Spatial types and functions are only supported by SQL Server 2008 or later." A string like "Spatial types and functions are not available for this provider because the assembly 'Microsoft.SqlServer.Types' version 10 or higher could not be found. " A string like "The database creation succeeded, but the creation of the database objects failed. The consequent attempt to drop the database also failed. See InnerException for details." A string like "See InnerExceptions for details." A string like "Unable to complete operation. The supplied SqlConnection does not specify an initial catalog or AttachDBFileName." A string like "Unable to delete the database. There is no database that corresponds to the given AttachDBFileName." A string like "A connection to the specified database could not be opened. See InnerException for details. However, there is a database registered with the server that corresponds to the given AttachDbFileName." A string like "This operation requires a connection to the 'master' database. Unable to create a connection to the 'master' database because the original database connection has been opened and credentials have been removed from the connection string. Supply an unopened connection." A string like "The execution of this query requires the APPLY operator, which is not supported in versions of SQL Server earlier than SQL Server 2005." A string like "Functions listed in the provider manifest that are attributed as NiladicFunction='true' cannot have parameter declarations." A string like "Parameters as arguments to a TOP sub-clause and a LIMIT sub-clause in a query, or a LimitExpression in a command tree, are not supported in versions of SQL Server earlier than SQL Server 2005." A string like "Parameters as arguments to a SKIP sub-clause in a query, or a SkipExpression in a command tree, are not supported in versions of SQL Server earlier than SQL Server 2005." A string like "The specified DbWellKnownGeographyValue does not contain either Well-Known Text or Well-Known Binary." A string like "The specified DbWellKnownGeometryValue does not contain either Well-Known Text or Well-Known Binary." A string like "A Spatial Reference System Identifier (SRID) value could not be retrieved from the specified DbGeography value." A string like "The specified DbGeography value did not provide either Well-Known Binary or Well-Known Text." A string like "A Spatial Reference System Identifier (SRID) value could not be retrieved from the specified DbGeometry value." A string like "The specified DbGeometry value did not provide either Well-Known Binary or Well-Known Text." A string like "An exception has been raised that is likely due to a transient failure. If you are connecting to a SQL Azure database consider using the SQL Azure executionStrategy, see SqlAzureDbConfiguration." Strongly-typed and parameterized exception factory. The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method. The exception that is thrown when the author has yet to implement the logic at this point in the program. This can act as an exception based TODO tag. The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality. AutoGenerated resource class. Usage: string s = EntityRes.GetString(EntityRes.MyIdenfitier); A class derived from this class can be placed in the same assembly as a class derived from to enable the SQL Azure retry policy for it. Initializes a new instance of and sets as the default execution strategy. Adds an factory method for a particular server name. The order in which the factories are added is important. The last one takes precedence. A function that returns a new instance of an execution strategy. A string that will be matched against the server name in the connection string. null will match anything. An that uses the and . A that detects the exceptions caused by SQL Azure transient failures. Appends raw SQL into the string builder. Raw SQL string to append into the string builder. Appends new line for visual formatting or for ending a comment. Append raw SQL into the string builder with formatting options and invariant culture formatting. A composite format string. An array of objects to format. Initializes a new instance of A function that returns a new instance of an execution strategy. A string that will be matched against the server name in the connection string. null will match anything. Used for wrapping a boolean value as an object. Class generating SQL for a DML command tree. Determine whether we should use a generated values variable to return server generated values. This is true when we're attempting to insert a row where the primary key is server generated but is not an integer type (and therefore can't be used with scope_identity()). It is also true where there is a compound server generated key. Generates SQL fragment returning server-generated values. Requires: translator knows about member values so that we can figure out how to construct the key predicate. Sample SQL: select IdentityValue from dbo.MyTable where @@ROWCOUNT > 0 and IdentityValue = scope_identity() or select TimestampValue from dbo.MyTable where @@ROWCOUNT > 0 and Id = 1 Note that we filter on rowcount to ensure no rows are returned if no rows were modified. On SQL Server 2005 and up, we have an additional syntax used for non integer return types: declare @generatedValues table(ID uniqueidentifier) insert dbo.MyTable output ID into @generated_values values (...); select ID from @generatedValues as g join dbo.MyTable as t on g.ID = t.ID where @@ROWCOUNT > 0; Builder containing command text Modification command tree Type of table. Translator used to produce DML SQL statement for the tree Returning expression. If null, the method returns immediately without producing a SELECT statement. Lightweight expression translator for DML expression trees, which have constrained scope and support. Initialize a new expression translator populating the given string builder with command text. Command text builder and command tree must not be null. Command text with which to populate commands Command tree generating SQL Indicates whether the translator should preserve member values while compiling t-SQL (only needed for server generation) Call this method to register a property value pair so the translator "remembers" the values for members of the row being modified. These values can then be used to form a predicate for server-generation (based on the key of the row) DbExpression containing the column reference (property expression). DbExpression containing the value of the column. Used to create an instance of for a specific SQL Types assembly such that it can be used for converting EF spatial types backed by one version to those backed by the version actually in use in this app domain. For testing. Returns the highest available version of the Microsoft.SqlServer.Types assembly that could be located using Assembly.Load; may return null if no version of the assembly could be found. This class is a simple utility class that determines the SQL Server version from the connection. Get the SqlVersion from the connection. Returns one of Sql8, Sql9, Sql10, Sql11 The passed connection must be open current sql connection Sql Version for the current connection This is a wrapper for that allows a mock implementation to be used. Uses a stack to non-recursively traverse a given tree structure and retrieve the leaf nodes. The node that represents the root of the tree. Expressions not of this kind are considered leaves. A function that traverses the tree by retrieving the immediate descendants of a (non-leaf) node. An enumerable containing the leaf nodes. Represents the sql fragment for any node in the query tree. The nodes in a query tree produce various kinds of sql A select statement. A reference to an extent. (symbol) A raw string. We have this interface to allow for a common return type for the methods in the expression visitor Add the endd of translation, the sql fragments are converted into real strings. Write the string represented by this fragment into the stream. The stream that collects the strings. Context information used for renaming. The global lists are used to generated new names without collisions. A Join symbol is a special kind of Symbol. It has to carry additional information ColumnList for the list of columns in the select clause if this symbol represents a sql select statement. This is set by . ExtentList is the list of extents in the select clause. FlattenedExtentList - if the Join has multiple extents flattened at the top level, we need this information to ensure that extent aliases are renamed correctly in NameToExtent has all the extents in ExtentList as a dictionary. This is used by to flatten record accesses. IsNestedJoin - is used to determine whether a JoinSymbol is an ordinary join symbol, or one that has a corresponding SqlSelectStatement. All the lists are set exactly once, and then used for lookups/enumerated. This class represents an extent/nested select statement, or a column. The important fields are Name, Type and NewName. NewName starts off the same as Name, and is then modified as necessary. The rest are used by special symbols. e.g. NeedsRenaming is used by columns to indicate that a new name must be picked for the column in the second phase of translation. IsUnnest is used by symbols for a collection expression used as a from clause. This allows to add the column list after the alias. Used to track the columns originating from this Symbol when it is used in as a from extent in a SqlSelectStatement with a Join or as a From Extent in a Join Symbol. Used to track the output columns of a SqlSelectStatement it represents Use this constructor if the symbol represents a SqlStatement for which the output columns need to be tracked. Write this symbol out as a string for sql. This is just the new name of the symbol (which could be the same as the old name). We rename columns here if necessary. Represents a column in a select list that should be printed only if it is later used. Such columns get added by . The SymbolUsageManager associated with the OptionalColumn has the information whether the column has been used based on its symbol. Append to the "fragment" representing this column Writes that fragment that represents the optional column if the usage manager says it is used. The Sql8ConformanceChecker walks a DbExpression tree and determines whether it should be rewritten in order to be translated to SQL appropriate for SQL Server 2000. The tree should be rewritten if it contains any of the following expressions: Also, it throws if it determines that the tree can not be translated into SQL appropriate for SQL Server 2000. This happens if: The tree contains The tree contains with property Limit of type The tree contains with property Count of type The visitor only checks for expressions for which the support differs between SQL Server 2000 and SQL Server 2005, but does not check/throw for expressions that are not supported for both providers. Implementation note: In the cases when the visitor encounters an expression that requires rewrite, it still needs to walk its structure in case something below it is not supported and needs to throw. The entry point True if the tree needs to be rewriten, false otherwise Default Constructor Default handling for DbUnaryExpression-derived classes. Simply visits its argument The DbUnaryExpression to visit Default handling for DbBinaryExpression-derived classes. Visits both arguments. The DbBinaryExpression to visit Walks the structure DbExpressionBinding handler Used as handler for expressions Used as handler for SortClauses Helper method for iterating a list Handing for list of s. Handing for list of s. Handing for list of s. Handling for list of s. Called when an of an otherwise unrecognized type is encountered. The expression Always thrown if this method is called, since it indicates that is of an unsupported type The DbAndExpression that is being visited. Not supported on SQL Server 2000. The DbApplyExpression that is being visited. Always Default handling for DbArithmeticExpression. Visits all arguments. The DbArithmeticExpression that is being visited. Walks the strucutre The DbCaseExpression that is being visited. The DbCastExpression that is being visited. The DbComparisonExpression that is being visited. Returns false The DbConstantExpression that is being visited. Walks the structure The DbCrossJoinExpression that is being visited. The DeRefExpression that is being visited. The DbDistinctExpression that is being visited. The DbElementExpression that is being visited. The DbEntityRefExpression that is being visited. Returns true, the tree needs to be rewritten. The DbExceptExpression that is being visited. Walks the structure The DbFilterExpression that is being visited. Visits the arguments The DbFunctionExpression that is being visited. Visits the arguments and lambda body The DbLambdaExpression that is being visited. Walks the structure The DbExpression that is being visited. Returns true. The DbIntersectExpression that is being visited. The DbIsEmptyExpression that is being visited. The DbIsNullExpression that is being visited. The DbIsOfExpression that is being visited. Walks the structure The DbJoinExpression that is being visited. Walks the structure The DbLikeExpression that is being visited. Walks the structure expression.Limit is DbParameterReferenceExpression Walks the arguments The DbNewInstanceExpression that is being visited. The DbNotExpression that is being visited. Returns false The DbNullExpression that is being visited. false The DbOfTypeExpression that is being visited. The DbOrExpression that is being visited. The DbInExpression that is being visited. Returns false The DbParameterReferenceExpression that is being visited. Walks the structure The DbProjectExpression that is being visited. Returns false The DbPropertyExpression that is being visited. Walks the structure The DbQuantifierExpression that is being visited. The DbRefExpression that is being visited. The DbRefKeyExpression that is being visited. Walks the structure The DbRelationshipNavigationExpression that is being visited. Returns false; The DbScanExpression that is being visited. Resturns true expression.Count is DbParameterReferenceExpression Walks the structure The DbSortExpression that is being visited. The DbTreatExpression that is being visited. The DbUnionAllExpression that is being visited. Returns false The DbVariableReferenceExpression that is being visited. false Used for Rewrites an expression tree to make it suitable for translation to SQL appropriate for SQL Server 2000 In particular, it replaces expressions that are not directly supported on SQL Server 2000 with alternative translations. The following expressions are translated: The other expressions are copied unmodified. The new expression belongs to a new query command tree. The only entry point. Rewrites the given tree by replacing expressions that are not directly supported on SQL Server 2000 with alterntive translations. The tree to rewrite The new tree Private Constructor. Logicaly, translates to: SELECT Y.x1, Y.x2, ..., Y.xn FROM ( SELECT X.x1, X.x2, ..., X.xn, FROM input AS X EXCEPT SELECT TOP(count) Z.x1, Z.x2, ..., Z.xn FROM input AS Z ORDER BY sk1, sk2, ... ) AS Y ORDER BY sk1, sk2, ... Here, input refers to the input of the , and count to the count property of the . The implementation of EXCEPT is non-duplicate eliminating, and does equality comparison only over the equality comparable columns of the input. This corresponds to the following expression tree: SORT | NON-DISTINCT EXCEPT (specially translated, | | - Left: clone of input | - Right: | Limit | | - Limit: Count | - Input | Sort | input This method is invoked when tranforming and by doing comparison over all input columns. This method is used for translating and , and for translating the "Except" part of . into the follwoing expression: A INTERSECT B, A EXCEPT B (DISTINCT) | FILTER | | - Input: A | - Predicate:(NOT) | ANY | | - Input: B | - Predicate: (B.b1 = A.a1 or (B.b1 is null and A.a1 is null)) AND (B.b2 = A.a2 or (B.b2 is null and A.a2 is null)) AND ... AND (B.bn = A.an or (B.bn is null and A.an is null))) Here, A corresponds to right and B to left. (NOT) is present when transforming Except for the purpose of translating or . (DISTINCT) is present when transforming for the purpose of translating or . For , the input to ANY is caped with project which projects out only the columns represented in the sortExpressionsOverLeft list and only these are used in the predicate. This is because we want to support skip over input with non-equal comarable columns and we have no way to recognize these. note that this list gets destroyed by this method Adds the flattened properties on the input to the flattenedProperties list. Helper method for Removes all pairs of property expressions from list1 and list2, for which the property expression in list1 does not have a 'matching' property expression in list2. The lists list1 and list2 are known to not create duplicate, and the purpose of the sortList is just for this method. Thus, to optimize the match process, we remove the seen property expressions from the sort list in when iterating both list simultaneously. Helper method for Checks whether expr has a 'match' in the given list of property expressions. If it does, the matching expression is removed form the list, to speed up future matching. Determines whether two expressions match. They match if they are of the shape expr1 -> DbPropertyExpression(... (DbPropertyExpression(DbVariableReferenceExpression(expr1BindingVariableName), nameX), ..., name1) expr1 -> DbPropertyExpression(... (DbPropertyExpression(DbVariableReferenceExpression(expr2BindingVariableName), nameX), ..., name1), i.e. if they only differ in the name of the binding. Helper method for Creates a over the given inputBinding that projects out the given flattenedProperties. and updates the flattenedProperties to be over the newly created project. An over the newly created This class is like StringBuilder. While traversing the tree for the first time, we do not know all the strings that need to be appended e.g. things that need to be renamed, nested select statements etc. So, we use a builder that can collect all kinds of sql fragments. Add an object to the list - we do not verify that it is a proper sql fragment since this is an internal method. This is to pretty print the SQL. The writer needs to know about new lines so that it can add the right amount of indentation at the beginning of lines. We delegate the writing of the fragment to the appropriate type. Whether the builder is empty. This is used by the to determine whether a sql statement can be reused. Enacapsulates the logic required to translate function calls represented as instances of DbFunctionExpression into SQL. There are several special cases that modify how the translation should proceed. These include: - 'Special' canonical functions, for which the function name or arguments differ between the EDM canonical function and the SQL function - 'Special' server functions, which are similar to the 'special' canonical functions but sourced by the SQL Server provider manifest - Niladic functions, which require the parentheses that would usually follow the function name to be omitted - Spatial canonical functions, which must translate to a static method call, instance method call, or instance property access against one of the built-in spatial CLR UDTs (geography/geometry). All special store functions and their handlers All special non-aggregate canonical functions and their handlers Initalizes the mapping from functions to TSql operators for all functions that translate to TSql operators Initalizes the mapping from names of canonical function for date/time addition to corresponding dateparts Initalizes the mapping from names of canonical function for date/time difference to corresponding dateparts Initalizes the mapping from names of canonical function that represent static geography methods to their corresponding static method name, qualified with the 'geography::' prefix. Initalizes the mapping from names of canonical function that represent geography instance properties to their corresponding store property name. Initalizes the mapping of canonical function name to instance method name for geography instance functions that differ in name from the sql server equivalent. Initalizes the mapping from names of canonical function that represent static geometry methods to their corresponding static method name, qualified with the 'geometry::' prefix. Initalizes the mapping from names of canonical function that represent geometry instance properties to their corresponding store property name. Initalizes the mapping of canonical function name to instance method name for geometry instance functions that differ in name from the sql server equivalent. Determines whether the given function is a store function that requires special handling Determines whether the given function is a canonical function that requires special handling Determines whether the given function is a canonical function the translates to a spatial (geography/geometry) property access or method call. Default handling for functions. Translates them to FunctionName(arg1, arg2, ..., argn) Default handling for functions with a given name. Translates them to FunctionName(arg1, arg2, ..., argn) Default handling for functions with a given name and given return value cast. Translates them to CAST(FunctionName(arg1, arg2, ..., argn) AS returnType) Default handling on function arguments. Appends the list of arguments to the given result If the function is niladic it does not append anything, otherwise it appends (arg1, arg2, .., argn) Handler for functions that need to be translated to different store function based on version Handler for special build in functions Handler for special canonical functions Dispatches the special function processing to the appropriate handler Handles functions that are translated into TSQL operators. The given function should have one or two arguments. Functions with one arguemnt are translated into op arg Functions with two arguments are translated into arg0 op arg1 Also, the arguments can be optionaly enclosed in parethesis Whether the arguments should be enclosed in parethesis Handles special case in which datapart 'type' parameter is present. all the functions handles here have *only* the 1st parameter as datepart. datepart value is passed along the QP as string and has to be expanded as TSQL keyword. Handler for canonical functions for extracting date parts. For example: Year(date) -> DATEPART( year, date) Handler for canonical funcitons for GetTotalOffsetMinutes. GetTotalOffsetMinutes(e) --> Datepart(tzoffset, e) Handler for turning a canonical function into DATEPART Results in DATEPART(datepart, e) Handler for the canonical function CurrentDateTime For Sql8 and Sql9: CurrentDateTime() -> GetDate() For Sql10: CurrentDateTime() -> SysDateTime() Handler for the canonical function CurrentUtcDateTime For Sql8 and Sql9: CurrentUtcDateTime() -> GetUtcDate() For Sql10: CurrentUtcDateTime() -> SysUtcDateTime() Handler for the canonical function CurrentDateTimeOffset For Sql8 and Sql9: throw For Sql10: CurrentDateTimeOffset() -> SysDateTimeOffset() See for exact translation Pre Katmai creates datetime. On Katmai creates datetime2. See for exact translation Pre Katmai not supported. On Katmai creates datetimeoffset. See for exact translation Pre Katmai not supported. On Katmai creates time. Helper for all date and time types creating functions. The given expression is in general trainslated into: CONVERT(@typename, [datePart] + [timePart] + [timeZonePart], 121), where the datePart and the timeZonePart are optional Only on Katmai, if a date part is present it is wrapped with a call for adding years as shown below. The individual parts are translated as: Date part: PRE KATMAI: convert(varchar(255), @year) + '-' + convert(varchar(255), @month) + '-' + convert(varchar(255), @day) KATMAI: DateAdd(year, @year-1, covert(@typename, '0001' + '-' + convert(varchar(255), @month) + '-' + convert(varchar(255), @day) + [possibly time ], 121) Time part: PRE KATMAI: convert(varchar(255), @hour)+ ':' + convert(varchar(255), @minute)+ ':' + str(@second, 6, 3) KATMAI: convert(varchar(255), @hour)+ ':' + convert(varchar(255), @minute)+ ':' + str(@second, 10, 7) Time zone part: (case when @tzoffset >= 0 then '+' else '-' end) + convert(varchar(255), ABS(@tzoffset)/60) + ':' + convert(varchar(255), ABS(@tzoffset)%60) Helper method that wrapps the given expession with a conver to varchar(255) TruncateTime(DateTime X) PreKatmai: TRUNCATETIME(X) => CONVERT(DATETIME, CONVERT(VARCHAR(255), expression, 102), 102) Katmai: TRUNCATETIME(X) => CONVERT(DATETIME2, CONVERT(VARCHAR(255), expression, 102), 102) TruncateTime(DateTimeOffset X) TRUNCATETIME(X) => CONVERT(datetimeoffset, CONVERT(VARCHAR(255), expression, 102) + ' 00:00:00 ' + Right(convert(varchar(255), @arg, 121), 6), 102) Handler for date addition functions supported only starting from Katmai Handler for all date/time addition canonical functions. Translation, e.g. AddYears(datetime, number) => DATEADD(year, number, datetime) Hanndler for date differencing functions supported only starting from Katmai Handler for all date/time addition canonical functions. Translation, e.g. DiffYears(datetime, number) => DATEDIFF(year, number, datetime) Function rename IndexOf -> CHARINDEX Function rename NewGuid -> NEWID Function rename Length -> LEN Round(numericExpression) -> Round(numericExpression, 0); Round(numericExpression, digits) -> Round(numericExpression, digits); Truncate(numericExpression) -> Round(numericExpression, 0, 1); (does not exist as canonical function yet) Truncate(numericExpression, digits) -> Round(numericExpression, digits, 1); Common handler for the canonical functions ROUND and TRUNCATE Handle the canonical function Abs(). TRIM(string) -> LTRIM(RTRIM(string)) Function rename ToLower -> LOWER Function rename ToUpper -> UPPER Function to translate the StartsWith, EndsWith and Contains canonical functions to LIKE expression in T-SQL and also add the trailing ESCAPE '~' when escaping of the search string for the LIKE expression has occurred Handler for Contains. Wraps the normal translation with a case statement CONTAINS(arg0, arg1) => arg0 LIKE '%arg1%' Handler for StartsWith. Wraps the normal translation with a case statement STARTSWITH(arg0, arg1) => arg0 LIKE 'arg1%' Handler for EndsWith. Wraps the normal translation with a case statement ENDSWITH(arg0, arg1) => arg0 LIKE '%arg1' Turns a predicate into a statement returning a bit PREDICATE => CASE WHEN (PREDICATE) THEN CAST(1 AS BIT) WHEN (NOT (PREDICATE)) CAST (O AS BIT) END The predicate is produced by the given predicateTranslator. Writes the function name to the given SqlBuilder. Is this a Store function (ie) does it have the builtinAttribute specified and it is not a canonical function? determines if the function requires the return type be enforeced by use of a cast expression determines if the function requires the return type be enforeced by use of a cast expression determines if the function requires the return type be enforeced by use of a cast expression determines if the function requires the return type be enforeced by use of a cast expression Determines if the function requires the return type be enforced by use of a cast expression Translates the command object into a SQL string that can be executed on SQL Server 2000 and SQL Server 2005. The translation is implemented as a visitor over the query tree. It makes a single pass over the tree, collecting the sql fragments for the various nodes in the tree . The major operations are Select statement minimization. Multiple nodes in the query tree that can be part of a single SQL select statement are merged. e.g. a Filter node that is the input of a Project node can typically share the same SQL statement. Alpha-renaming. As a result of the statement minimization above, there could be name collisions when using correlated subqueries Filter( b = Project( c.x c = Extent(foo) ) exists ( Filter( c = Extent(foo) b.x = c.x ) ) ) The first Filter, Project and Extent will share the same SQL select statement. The alias for the Project i.e. b, will be replaced with c. If the alias c for the Filter within the exists clause is not renamed, we will get c.x = c.x, which is incorrect. Instead, the alias c within the second filter should be renamed to c1, to give c.x = c1.x i.e. b is renamed to c, and c is renamed to c1. Join flattening. In the query tree, a list of join nodes is typically represented as a tree of Join nodes, each with 2 children. e.g. a = Join(InnerJoin b = Join(CrossJoin c = Extent(foo) d = Extent(foo) ) e = Extent(foo) on b.c.x = e.x ) If translated directly, this will be translated to FROM ( SELECT c.*, d.* FROM foo as c CROSS JOIN foo as d) as b INNER JOIN foo as e on b.x' = e.x It would be better to translate this as FROM foo as c CROSS JOIN foo as d INNER JOIN foo as e on c.x = e.x This allows the optimizer to choose an appropriate join ordering for evaluation. Select * and column renaming. In the example above, we noticed that in some cases we add SELECT * FROM ... to complete the SQL statement. i.e. there is no explicit PROJECT list. In this case, we enumerate all the columns available in the FROM clause This is particularly problematic in the case of Join trees, since the columns from the extents joined might have the same name - this is illegal. To solve this problem, we will have to rename columns if they are part of a SELECT * for a JOIN node - we do not need renaming in any other situation. . Renaming issues. When rows or columns are renamed, we produce names that are unique globally with respect to the query. The names are derived from the original names, with an integer as a suffix. e.g. CustomerId will be renamed to CustomerId1, CustomerId2 etc. Since the names generated are globally unique, they will not conflict when the columns of a JOIN SELECT statement are joined with another JOIN. Record flattening. SQL server does not have the concept of records. However, a join statement produces records. We have to flatten the record accesses into a simple alias.column form. Building the SQL. There are 2 phases Traverse the tree, producing a sql builder Write the SqlBuilder into a string, renaming the aliases and columns as needed. In the first phase, we traverse the tree. We cannot generate the SQL string right away, since The WHERE clause has to be visited before the from clause. extent aliases and column aliases need to be renamed. To minimize renaming collisions, all the names used must be known, before any renaming choice is made. To defer the renaming choices, we use symbols . These are renamed in the second phase. Since visitor methods cannot transfer information to child nodes through parameters, we use some global stacks, A stack for the current SQL select statement. This is needed by to create a list of free variables used by a select statement. This is needed for alias renaming. A stack for the join context. When visiting an extent, we need to know whether we are inside a join or not. If we are inside a join, we do not create a new SELECT statement. Global state. To enable renaming, we maintain The set of all extent aliases used. The set of all parameter names. The set of all column names that may need to be renamed. Finally, we have a symbol table to lookup variable references. All references to the same extent have the same symbol. Sql select statement sharing. Each of the relational operator nodes Project Filter GroupBy Sort/OrderBy can add its non-input (e.g. project, predicate, sort order etc.) to the SQL statement for the input, or create a new SQL statement. If it chooses to reuse the input's SQL statement, we play the following symbol table trick to accomplish renaming. The symbol table entry for the alias of the current node points to the symbol for the input in the input's SQL statement. Project(b.x b = Filter( c = Extent(foo) c.x = 5) ) The Extent node creates a new SqlSelectStatement. This is added to the symbol table by the Filter as {c, Symbol(c)}. Thus, c.x is resolved to Symbol(c).x. Looking at the project node, we add {b, Symbol(c)} to the symbol table if the SQL statement is reused, and {b, Symbol(b)}, if there is no reuse. Thus, b.x is resolved to Symbol(c).x if there is reuse, and to Symbol(b).x if there is no reuse. Every relational node has to pass its SELECT statement to its children This allows them (DbVariableReferenceExpression eventually) to update the list of outer extents (free variables) used by this select statement. Nested joins and extents need to know whether they should create a new Select statement, or reuse the parent's. This flag indicates whether the parent is a join or not. VariableReferenceExpressions are allowed only as children of DbPropertyExpression or MethodExpression. The cheapest way to ensure this is to set the following property in DbVariableReferenceExpression and reset it in the allowed parent expressions. Maintain the list of (string) DbParameterReferenceExpressions that should be compensated, viz. forced to non-unicode format. A parameter is added to the list if it is being compared to a non-unicode store column and none of its other usages in the query tree, disqualify it (For example - if the parameter is also being projected or compared to a unicode column) The goal of the compensation is to have the store index picked up by the server. String constants are also compensated and the decision is local, unlike parameters. Set and reset in DbComparisonExpression and DbLikeExpression visit methods. Maintains global state information that the children of these nodes are candidates for compensation. Set when it is is safe to ignore the unicode/non-unicode aspect. See for an example. The current SQL Server version Basic constructor. server version General purpose static function that can be called from System.Data assembly Server version command tree Parameters to add to the command tree corresponding to constants in the command tree. Used only in ModificationCommandTrees. CommandType for generated command. The string representing the SQL to be executed. Translate a command tree to a SQL string. The input tree could be translated to either a SQL SELECT statement or a SELECT expression. This choice is made based on the return type of the expression CollectionType => select statement non collection type => select expression The string representing the SQL to be executed. Convert the SQL fragments to a string. We have to setup the Stream for writing. A string representing the SQL to be executed. Translate(left) AND Translate(right) A . An apply is just like a join, so it shares the common join processing in A . For binary expressions, we delegate to . We handle the other expressions directly. A If the ELSE clause is null, we do not write it out. A The parser generates Not(Equals(...)) for <>. A . Checks if the arguments of the input Comparison or Like expression are candidates for compensation. If yes, sets global state variable - _forceNonUnicode. DBComparisonExpression or DbLikeExpression The grammar for the pattern that we are looking for is - Pattern := Target OP Source | Source OP Target OP := Like | In | Comparison Source := Non-unicode DbPropertyExpression Target := Target FUNC Target | DbConstantExpression | DBParameterExpression FUNC := CONCAT | RTRIM | LTRIM | TRIM | SUBSTRING | TOLOWER | TOUPPER | REVERSE | REPLACE Matches the non-terminal symbol "target" in above grammar. Determines if the expression represents a non-unicode string column(char/varchar store type) Determines if the expression represents a string constant or parameter with the facet, unicode=null. Generate tsql for a constant. Avoid the explicit cast (if possible) when the isCastOptional parameter is set the constant expression can we avoid the CAST the tsql fragment Helper method for A double value If a value of positive or negative infinity, or is specified Helper method for A single value If a value of positive or negative infinity, or is specified Helper function for Appends the given constant value to the result either 'as is' or wrapped with a cast to the given type. We do not pass constants as parameters. A . Strings are wrapped in single quotes and escaped. Numbers are written literally. The DISTINCT has to be added to the beginning of SqlSelectStatement.Select, but it might be too late for that. So, we use a flag on SqlSelectStatement instead, and add the "DISTINCT" in the second phase. A An element expression returns a scalar - so it is translated to ( Select ... ) Only concrete expression types will be visited. If we are in a Join context, returns a with the extent name, otherwise, a new with the From field set. Gets escaped TSql identifier describing this entity set. The bodies of , , , are similar. Each does the following. Visit the input expression Determine if the input's SQL statement can be reused, or a new one must be created. Create a new symbol table scope Push the Sql statement onto a stack, so that children can update the free variable list. Visit the non-input expression. Cleanup A Lambda functions are not supported. The functions supported are: Canonical Functions - We recognize these by their dataspace, it is DataSpace.CSpace Store Functions - We recognize these by the BuiltInAttribute and not being Canonical User-defined Functions - All the rest We handle Canonical and Store functions the same way: If they are in the list of functions that need special handling, we invoke the appropriate handler, otherwise we translate them to FunctionName(arg1, arg2, ..., argn). We translate user-defined functions to NamespaceName.FunctionName(arg1, arg2, ..., argn). A for general details. We modify both the GroupBy and the Select fields of the SqlSelectStatement. GroupBy gets just the keys without aliases, and Select gets the keys and the aggregates with aliases. Sql Server does not support arbitrarily complex expressions inside aggregates, and requires keys to have reference to the input scope, so in some cases we create a nested query in which we alias the arguments to the aggregates. The exact limitations of Sql Server are: If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression (SQLBUDT #488741) Sql Server cannot perform an aggregate function on an expression containing an aggregate or a subquery. (SQLBUDT #504600) Sql Server requries each GROUP BY expression (key) to contain at least one column that is not an outer reference. (SQLBUDT #616523) Aggregates on the right side of an APPLY cannot reference columns from the left side. (SQLBUDT #617683) The default translation, without inner query is: SELECT kexp1 AS key1, kexp2 AS key2,... kexpn AS keyn, aggf1(aexpr1) AS agg1, .. aggfn(aexprn) AS aggn FROM input AS a GROUP BY kexp1, kexp2, .. kexpn When we inject an innner query, the equivalent translation is: SELECT key1 AS key1, key2 AS key2, .. keyn AS keys, aggf1(agg1) AS agg1, aggfn(aggn) AS aggn FROM ( SELECT kexp1 AS key1, kexp2 AS key2,... kexpn AS keyn, aexpr1 AS agg1, .. aexprn AS aggn FROM input AS a ) as a GROUP BY key1, key2, keyn A Not(IsEmpty) has to be handled specially, so we delegate to . A . [NOT] EXISTS( ... ) Not(IsNull) is handled specially, so we delegate to A IS [NOT] NULL No error is raised if the store cannot support this. A A . A . A Translates to TOP expression. For Sql8, limit can only be a constant expression A DbNewInstanceExpression is allowed as a child of DbProjectExpression only. If anyone else is the parent, we throw. We also perform special casing for collections - where we could convert them into Unions for the actual implementation. The Not expression may cause the translation of its child to change. These children are NOT(Not(x)) becomes x NOT EXISTS becomes EXISTS IS NULL becomes IS NOT NULL = becomes <> A A Visit a DbOrExpression and consider the subexpressions for whether to generate OR conditions or an IN clause. DbOrExpression to be visited A fragment of SQL generated Visits a DbInExpression and generates the corresponding SQL fragment. A that specifies the expression to be visited. A that specifies the generated SQL fragment. Determine if a DbOrExpression can be optimized into one or more IN clauses and generate an ISqlFragment if it is possible. DbOrExpression to attempt translation upon Fragment of SQL generated True if an IN clause is possible and sqlFragment has been generated, false otherwise Determines if a DbExpression is a valid key for the purposes of generating an In clause optimization. DbExpression to consider True if the expression can be used as a key, false otherwise Looks at both sides of a DbBinaryExpression to consider if either side is a valid candidate to be a key and if so adds it to the KeyToListMap as a key with the other side as the value. DbBinaryExpression to consider KeyToListMap to add the sides of the binary expression to True if the expression was added, false otherwise Attempts to build a KeyToListMap containing valid references and the appropriate value equality tests associated with each so that they can be optimized into IN clauses. Calls itself recursively to consider additional OR branches. DbExpression representing the branch to evaluate KeyToListMap to which to add references and value equality tests encountered True if this branch contained just equality tests or further OR branches, false otherwise This method handles the DBParameterReference expressions. If the parameter is in a part of the tree, which matches our criteria for forcing to non-unicode, then we add it to the list of candidate parameters. If the parameter occurs in a different usage scenario, then disqualify it from being forced to non-unicode. A for the general ideas. A This method handles record flattening, which works as follows. consider an expression Prop(y, Prop(x, Prop(d, Prop(c, Prop(b, Var(a))))) where a,b,c are joins, d is an extent and x and y are fields. b has been flattened into a, and has its own SELECT statement. c has been flattened into b. d has been flattened into c. We visit the instance, so we reach Var(a) first. This gives us a (join)symbol. Symbol(a).b gives us a join symbol, with a SELECT statement i.e. Symbol(b). From this point on , we need to remember Symbol(b) as the source alias, and then try to find the column. So, we use a SymbolPair. We have reached the end when the symbol no longer points to a join symbol. A if we have not reached the first Join node that has a SELECT statement. A if we have seen the JoinNode, and it has a SELECT statement. A with {Input}.propertyName otherwise. Any(input, x) => Exists(Filter(input,x)) All(input, x) => Not Exists(Filter(input, not(x)) For Sql9 it translates to: SELECT Y.x1, Y.x2, ..., Y.xn FROM ( SELECT X.x1, X.x2, ..., X.xn, row_number() OVER (ORDER BY sk1, sk2, ...) AS [row_number] FROM input as X ) as Y WHERE Y.[row_number] > count ORDER BY sk1, sk2, ... A A A This code is shared by and Since the left and right expression may not be Sql select statements, we must wrap them up to look like SQL select statements. This method determines whether an extent from an outer scope(free variable) is used in the CurrentSelectStatement. An extent in an outer scope, if its symbol is not in the FromExtents of the CurrentSelectStatement. A . Aggregates are not visited by the normal visitor walk. The aggregate go be translated The translated aggregate argument Dump out an expression - optionally wrap it with parantheses if possible Handler for inline binary expressions. Produces left op right. For associative operations does flattening. Puts parenthesis around the arguments if needed. Creates a flat list of the associative arguments. For example, for ((A1 + (A2 - A3)) + A4) it will create A1, (A2 - A3), A4 Only 'unfolds' the given arguments that are of the given expression kind. Helper method for FlattenAssociativeExpression. Creates a flat list of the associative arguments and appends to the given argument list. For example, for ((A1 + (A2 - A3)) + A4) it will add A1, (A2 - A3), A4 to the list. Only 'unfolds' the given expression if it is of the given expression kind. Private handler for comparison expressions - almost identical to VisitBinaryExpression. We special case constants, so that we don't emit unnecessary casts the comparison op the left-side expression the right-side expression This is called by the relational nodes. It does the following If the input is not a SqlSelectStatement, it assumes that the input is a collection expression, and creates a new SqlSelectStatement A and the main fromSymbol for this select statement. Was the parent a DbNotExpression? Translate a NewInstance(Element(X)) expression into "select top(1) * from X" Was the parent a DbNotExpression? This handles the processing of join expressions. The extents on a left spine are flattened, while joins not on the left spine give rise to new nested sub queries. Joins work differently from the rest of the visiting, in that the parent (i.e. the join node) creates the SqlSelectStatement for the children to use. The "parameter" IsInJoinContext indicates whether a child extent should add its stuff to the existing SqlSelectStatement, or create a new SqlSelectStatement By passing true, we ask the children to add themselves to the parent join, by passing false, we ask the children to create new Select statements for themselves. This method is called from and . A This is called from . This is responsible for maintaining the symbol table after visiting a child of a join expression. The child's sql statement may need to be completed. The child's result could be one of The same as the parent's - this is treated specially. A sql select statement, which may need to be completed An extent - just copy it to the from clause Anything else (from a collection-valued expression) - unnest and copy it. If the input was a Join, we need to create a new join symbol, otherwise, we create a normal symbol. We then call AddFromSymbol to add the AS clause, and update the symbol table. If the child's result was the same as the parent's, we have to clean up the list of symbols in the FromExtents list, since this contains symbols from the children of both the parent and the child. The happens when the child visited is a Join, and is the leftmost child of the parent. We assume that this is only called as a child of a Project. This replaces , since we do not allow DbNewInstanceExpression as a child of any node other than DbProjectExpression. We write out the translation of each of the columns in the record. A Handler for set operations It generates left separator right. Only for SQL 8.0 it may need to create a new select statement above the set operation if the left child's output columns got renamed Add the column names from the referenced extent/join to the select statement. If the symbol is a JoinSymbol, we recursively visit all the extents, halting at real extents and JoinSymbols that have an associated SqlSelectStatement. The column names for a real extent can be derived from its type. The column names for a Join Select statement can be got from the list of columns that was created when the Join's select statement was created. We do the following for each column. Add the SQL string for each column to the SELECT clause Add the column to the list of columns - so that it can become part of the "type" of a JoinSymbol Check if the column name collides with a previous column added to the same select statement. Flag both the columns for renaming if true. Add the column to a name lookup dictionary for collision detection. The select statement that started off as SELECT * The symbol containing the type information for the columns to be added. Columns that have been added to the Select statement. This is created in . A dictionary of the columns above. Creates an optional column and registers the corresponding symbol with the optionalColumnUsageManager it has not already been registered. Helper method for AddColumns. Adds a column with the given column name to the Select list of the given select statement. The select statement to whose SELECT part the column should be added The symbol from which the column to be added originated Columns that have been added to the Select statement. This is created in . A dictionary of the columns above. The name of the column to be added. Expands Select * to "select the_list_of_columns" If the columns are taken from an extent, they are written as {original_column_name AS Symbol(original_column)} to allow renaming. If the columns are taken from a Join, they are written as just {original_column_name}, since there cannot be a name collision. We concatenate the columns from each of the inputs to the select statement. Since the inputs may be joins that are flattened, we need to recurse. The inputs are inferred from the symbols in FromExtents. This method is called after the input to a relational node is visited. and There are 2 scenarios The fromSymbol is new i.e. the select statement has just been created, or a join extent has been added. The fromSymbol is old i.e. we are reusing a select statement. If we are not reusing the select statement, we have to complete the FROM clause with the alias -- if the input was an extent FROM = [SchemaName].[TableName] -- if the input was a Project FROM = (SELECT ... FROM ... WHERE ...) These become -- if the input was an extent FROM = [SchemaName].[TableName] AS alias -- if the input was a Project FROM = (SELECT ... FROM ... WHERE ...) AS alias and look like valid FROM clauses. Finally, we have to add the alias to the global list of aliases used, and also to the current symbol table. The alias to be used. Translates a list of SortClauses. Used in the translation of OrderBy The SqlBuilder to which the sort keys should be appended This is called after a relational node's input has been visited, and the input's sql statement cannot be reused. When the input's sql statement cannot be reused, we create a new sql statement, with the old one as the from clause of the new statement. The old statement must be completed i.e. if it has an empty select list, the list of columns must be projected out. If the old statement being completed has a join symbol as its from extent, the new statement must have a clone of the join symbol as its extent. We cannot reuse the old symbol, but the new select statement must behave as though it is working over the "join" record. A new select statement, with the old one as the from clause. Before we embed a string literal in a SQL string, we should convert all ' to '', and enclose the whole string in single quotes. The escaped sql string. Returns the sql primitive/native type name. It will include size, precision or scale depending on type information present in the type facets Handles the expression represending DbLimitExpression.Limit and DbSkipExpression.Count. If it is a constant expression, it simply does to string thus avoiding casting it to the specific value (which would be done if is called) This is used to determine if a particular expression is an Apply operation. This is only the case when the DbExpressionKind is CrossApply or OuterApply. This is used to determine if a particular expression is a Join operation. This is true for DbCrossJoinExpression and DbJoinExpression, the latter of which may have one of several different ExpressionKinds. This is used to determine if a calling expression needs to place round brackets around the translation of the expression e. Constants, parameters and properties do not require brackets, everything else does. true, if the expression needs brackets Determine if the owner expression can add its unique sql to the input's SqlSelectStatement The SqlSelectStatement of the input to the relational node. The kind of the expression node(not the input's) We use the normal box quotes for SQL server. We do not deal with ANSI quotes i.e. double quotes. Simply calls with addDefaultColumns set to true and markAllDefaultColumnsAsUsed set to false. This is called from and nodes which require a select statement as an argument e.g. , . SqlGenerator needs its child to have a proper alias if the child is just an extent or a join. The normal relational nodes result in complete valid SQL statements. For the rest, we need to treat them as there was a dummy -- originally {expression} -- change that to SELECT * FROM {expression} as c DbLimitExpression needs to start the statement but not add the default columns This method is called by and This is passed from in the All(...) case. If the sql fragment for an input expression is not a SqlSelect statement or other acceptable form (e.g. an extent as a SqlBuilder), we need to wrap it in a form acceptable in a FROM clause. These are primarily the The set operation expressions - union all, intersect, except TVFs, which are conceptually similar to tables Helper method for the Group By visitor Returns true if at least one of the aggregates in the given list has an argument that is not a and is not a over , either potentially capped with a This is really due to the following two limitations of Sql Server: If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression (SQLBUDT #488741) Sql Server cannot perform an aggregate function on an expression containing an aggregate or a subquery. (SQLBUDT #504600) Potentially, we could furhter optimize this. Returns true if the given expression is not a or a over a referencing the given inputVarRefName, either potentially capped with a . Helper method for the Group By visitor Returns true if at least one of the expressions in the given list is not over referencing the given inputVarRefName potentially capped with a . This is really due to the following limitation: Sql Server requires each GROUP BY expression (key) to contain at least one column that is not an outer reference. (SQLBUDT #616523) Potentially, we could further optimize this. Returns true if the given expression is not over referencing the given inputVarRefName potentially capped with a . This is really due to the following limitation: Sql Server requires each GROUP BY expression (key) to contain at least one column that is not an outer reference. (SQLBUDT #616523) Potentially, we could further optimize this. Helper method for processing Group By keys and aggregates. Returns true if the given expression is not a (and allowConstants is specified)or a over a referencing the given inputVarRefName, either potentially capped with a . Throws not supported exception if the server is pre-katmai Throws not supported exception if the server is pre-katmai The top of the stack Determine if the parent is a join. Required by the KeyToListMap to allow certain DbExpression subclasses to be used as a key which is not normally possible given their lack of Equals and GetHashCode implementations for testing object value equality. Compare two DbExpressions to see if they are equal for the purposes of our key management. We only support DbPropertyExpression, DbParameterReferenceExpression, VariableReferenceExpression and DbCastExpression types. Everything else will fail to be considered equal. First DbExpression to consider for equality Second DbExpression to consider for equality True if the types are allowed and equal, false otherwise Calculates a hashcode for a given number of DbExpression subclasses to allow the KeyToListMap to efficiently and reliably locate existing keys. DbExpression to calculate a hashcode for Integer containing the hashcode This class is used for building the SELECT clause of a Sql Statement It is used to gather information about required and optional columns and whether TOP and DISTINCT should be specified. The underlying SqlBuilder is used for gathering the required columns. The list of OptionalColumns is used for gathering the optional columns. Whether a given OptionalColumn should be written is known only after the entire command tree has been processed. The IsDistinct property indicates that we want distinct columns. This is given out of band, since the input expression to the select clause may already have some columns projected out, and we use append-only SqlBuilders. The DISTINCT is inserted when we finally write the object into a string. Also, we have a Top property, which is non-null if the number of results should be limited to certain number. It is given out of band for the same reasons as DISTINCT. Writes the string representing the Select statement: SELECT (DISTINCT) (TOP topClause) (optionalColumns) (requiredColumns) If Distinct is specified or this is part of a top most statement all optional columns are marked as used. Optional columns are only written if marked as used. In addition, if no required columns are specified and no optional columns are marked as used, the first optional column is written. Writes the optional columns that are used. If this is the topmost statement or distict is specifed as part of the same statement all optoinal columns are written. Whether at least one column got written Do we need to add a DISTINCT at the beginning of the SELECT Whether any columns have been specified. A SqlSelectStatement represents a canonical SQL SELECT statement. It has fields for the 5 main clauses SELECT FROM WHERE GROUP BY ORDER BY We do not have HAVING, since the CQT does not have such a node. Each of the fields is a SqlBuilder, so we can keep appending SQL strings or other fragments to build up the clause. The FromExtents contains the list of inputs in use for the select statement. There is usually just one element in this - Select statements for joins may temporarily have more than one. If the select statement is created by a Join node, we maintain a list of all the extents that have been flattened in the join in AllJoinExtents in J(j1= J(a,b), c) FromExtents has 2 nodes JoinSymbol(name=j1, ...) and Symbol(name=c) AllJoinExtents has 3 nodes Symbol(name=a), Symbol(name=b), Symbol(name=c) If any expression in the non-FROM clause refers to an extent in a higher scope, we add that extent to the OuterExtents list. This list denotes the list of extent aliases that may collide with the aliases used in this select statement. It is set by . An extent is an outer extent if it is not one of the FromExtents. Write out a SQL select statement as a string. We have to Check whether the aliases extents we use in this statement have to be renamed. We first create a list of all the aliases used by the outer extents. For each of the FromExtents( or AllJoinExtents if it is non-null), rename it if it collides with the previous list. Write each of the clauses (if it exists) as a string Whether the columns ouput by this sql statement were renamed from what given in the command tree. A dictionary of output columns This extends StringWriter primarily to add the ability to add an indent to each line that is written out. Reset atBeginningofLine if we detect the newline string. Add as many tabs as the value of indent if we are at the beginning of a line. The number of tabs to be added at the beginning of each new line. The SymbolPair exists to solve the record flattening problem. Consider a property expression D(v, "j3.j2.j1.a.x") where v is a VarRef, j1, j2, j3 are joins, a is an extent and x is a columns. This has to be translated eventually into {j'}.{x'} The source field represents the outermost SqlStatement representing a join expression (say j2) - this is always a Join symbol. The column field keeps moving from one join symbol to the next, until it stops at a non-join symbol. This is returned by , but never makes it into a SqlBuilder. The symbol table is quite primitive - it is a stack with a new entry for each scope. Lookups search from the top of the stack to the bottom, until an entry is found. The symbols are of the following kinds represents tables (extents/nested selects/unnests) represents Join nodes columns. Symbols represent names to be resolved, or things to be renamed. Tracks the usage of symbols. When registering a symbol with the usage manager if an input symbol is specified, than the usage of the two is 'connected' - if one ever gets marked as used, the other one becomes 'used' too. TopClause represents the a TOP expression in a SqlSelectStatement. It has a count property, which indicates how many TOP rows should be selected and a boolen WithTies property. Creates a TopClause with the given topCount and withTies. Creates a TopClause with the given topCount and withTies. Write out the TOP part of sql select statement It basically writes TOP (X) [WITH TIES]. The brackets around X are ommited for Sql8. Do we need to add a WITH_TIES to the top statement How many top rows should be selected. The Provider Manifest for SQL Server Maximum size of SQL Server unicode Initializes a new instance of the class. A token used to infer the capabilities of the store. Function to detect wildcard characters %, _, [ and ^ and escape them with a preceding ~ This escaping is used when StartsWith, EndsWith and Contains canonical and CLR functions are translated to their equivalent LIKE expression NOTE: This code has been copied from LinqToSql Original input as specified by the user escape the escape character ~ regardless whether wildcard characters were encountered true if the escaping was performed, false if no escaping was required The escaped string that can be used as pattern in a LIKE expression Providers should override this to return information specific to their provider. This method should never return null. The name of the information to be retrieved. An XmlReader at the begining of the information requested. This method takes a type and a set of facets and returns the best mapped equivalent type in EDM. A TypeUsage encapsulating a store type and a set of facets A TypeUsage encapsulating an EDM type and a set of facets This method takes a type and a set of facets and returns the best mapped equivalent type in SQL Server, taking the store version into consideration. A TypeUsage encapsulating an EDM type and a set of facets A TypeUsage encapsulating a store type and a set of facets Returns true, SqlClient supports escaping strings to be used as arguments to like The escape character is '~' The character '~' True Escapes the wildcard characters and the escape character in the given argument. Equivalent to the argument, with the wildcard characters and the escape character escaped Returns a boolean that specifies whether the corresponding provider can handle expression trees containing instances of DbInExpression. The Sql provider handles instances of DbInExpression. true. The DbProviderServices implementation for the SqlClient provider for SQL Server. Private constructor to ensure only Singleton instance is created. Singleton object Create a Command Definition object, given the connection and command tree provider manifest that was determined from metadata command tree for the statement an executable command definition object Create a SqlCommand object, given the provider manifest and command tree provider manifest command tree for the statement a command object Creates a SqlParameter given a name, type, and direction Validates that the specified value is compatible with SqlParameter and if not, attempts to return an appropriate value that is. Currently only spatial values (DbGeography/DbGeometry) may not be directly usable with SqlParameter. For these types, an instance of the corresponding SQL Server CLR spatial UDT will be manufactured based on the spatial data contained in . If is an instance of DbGeography/DbGeometry that was read from SQL Server by this provider, then the wrapped CLR UDT value is available via the ProviderValue property (see SqlSpatialServices for the full conversion process from instances of DbGeography/DbGeometry to instances of the CLR SqlGeography/SqlGeometry UDTs) Determines SqlDbType for the given primitive type. Extracts facet information as well. Determines preferred value for SqlParameter.Size. Returns null where there is no preference. Returns SqlParameter.Precision where the type facet exists. Otherwise, returns null or the maximum available precision to avoid truncation (which can occur for output parameters). Returns SqlParameter.Precision where the type facet exists. Otherwise, returns null. Returns SqlParameter.Scale where the type facet exists. Otherwise, returns null. Chooses the appropriate SqlDbType for the given string type. Chooses the appropriate SqlDbType for the given binary type. Create the database and the database objects. If initial catalog is not specified, but AttachDBFilename is specified, we generate a random database name based on the AttachDBFilename. Note: this causes pollution of the db, as when the connection string is later used, the mdf will get attached under a different name. However if we try to replicate the name under which it would be attached, the following scenario would fail: The file does not exist, but registered with database. The user calls: If (DatabaseExists) DeleteDatabase CreateDatabase For further details on the behavior when AttachDBFilename is specified see Dev10# 188936 Get the Ldf name given the Mdf full name Generates database name based on the given mdfFileName. The logic is replicated from System.Web.DataAccess.SqlConnectionHelper Get the full mdf file name given the attachDBFile value from the connection string Determines whether the database for the given connection exists. There are three cases: 1. Initial Catalog = X, AttachDBFilename = null: (SELECT Count(*) FROM sys.databases WHERE [name]= X) > 0 2. Initial Catalog = X, AttachDBFilename = F: if (SELECT Count(*) FROM sys.databases WHERE [name]= X) > true, if not, try to open the connection and then return (SELECT Count(*) FROM sys.databases WHERE [name]= X) > 0 3. Initial Catalog = null, AttachDBFilename = F: Try to open the connection. If that succeeds the result is true, otherwise if the there are no databases corresponding to the given file return false, otherwise throw. Note: We open the connection to cover the scenario when the mdf exists, but is not attached. Given that opening the connection would auto-attach it, it would not be appropriate to return false in this case. Also note that checking for the existence of the file does not work for a remote server. (Dev11 #290487) For further details on the behavior when AttachDBFilename is specified see Dev10# 188936 Delete the database for the given connection. There are three cases: 1. If Initial Catalog is specified (X) drop database X 2. Else if AttachDBFilename is specified (F) drop all the databases corresponding to F if none throw 3. If niether the catalog not the file name is specified - throw Note that directly deleting the files does not work for a remote server. However, even for not attached databases the current logic would work assuming the user does: if (DatabaseExists) DeleteDatabase The Singleton instance of the SqlProviderServices type. Requires that the given connection is of type T. Returns the connection or throws. SqlClient specific implementation of Builds and compiles the Expression equivalent of the following: (BinaryReader r) => { var result = new SpatialType(); result.Read(r); return r; } The construct/read pattern is preferred over casting the result of calling GetValue on the DataReader, because constructing the value directly allows client code to specify the type, rather than SqlClient using the server-specified assembly qualified type name from TDS to try to locate the correct type on the client. SqlTypesAssembly allows for late binding to the capabilities of a specific version of the Microsoft.SqlServer.Types assembly For testing. This enumeration describes the current SQL Server version. SQL Server 8 (2000). SQL Server 9 (2005). SQL Server 10 (2008). SQL Server 11 (2012).