diff --git a/.gitignore b/.gitignore index 3743184..9b462ce 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,10 @@ +# Nuget restore +packages +project.lock.json + # Build folders bin FakesAssemblies -packages obj # Other misc build output @@ -18,3 +21,11 @@ TestResults *.GhostDoc.xml *.suo *.pd_ + +# Visual studio +.vs/ +.vscode/ + +# Build output +*.dll +*.exe \ No newline at end of file diff --git a/.vs/restore.dg b/.vs/restore.dg new file mode 100644 index 0000000..81f33f1 --- /dev/null +++ b/.vs/restore.dg @@ -0,0 +1 @@ +#:C:\Users\antho\Documents\Visual Studio 2015\Projects\elastic-db-tools\Test\ElasticScale.ShardManagement.UnitTests\ElasticScale.ShardManagement.UnitTests.Core.xproj diff --git a/ElasticDatabaseTools.sln b/ElasticDatabaseTools.sln index 0750c4e..7a5b300 100644 --- a/ElasticDatabaseTools.sln +++ b/ElasticDatabaseTools.sln @@ -1,27 +1,15 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 +# Visual Studio 15 +VisualStudioVersion = 15.0.26730.10 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElasticScale.Client", "Src\ElasticScale.Client\ElasticScale.Client.csproj", "{663D22BB-483A-46B0-A504-861C5335DAD1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.SqlDatabase.ElasticScale.Client", "Src\ElasticScale.Client\Microsoft.Azure.SqlDatabase.ElasticScale.Client.csproj", "{4C3B3EC4-5702-469E-800E-313FB27A0A2B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElasticScale.ClientTestCommon", "Test\ElasticScale.ClientTestCommon\ElasticScale.ClientTestCommon.csproj", "{13200C7C-8606-47B8-A004-570B56E3A9A8}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.SqlDatabase.ElasticScale.ClientTestCommon", "Test\ElasticScale.ClientTestCommon\Microsoft.Azure.SqlDatabase.ElasticScale.ClientTestCommon.csproj", "{9336E9E7-19BF-49AC-92E3-19FA6B98921E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElasticScale.Query.UnitTests", "Test\ElasticScale.Query.UnitTests\ElasticScale.Query.UnitTests.csproj", "{56DDEC7E-0B14-4636-B287-DB38DEC55192}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests", "Test\ElasticScale.ShardManagement.UnitTests\Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests.csproj", "{BEA6F911-BA98-462C-99AF-3B0595DE2307}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElasticScale.ShardManagement.LoadTests", "Test\ElasticScale.ShardManagement.LoadTests\ElasticScale.ShardManagement.LoadTests.csproj", "{6C6E8D75-DF7B-4841-A254-D0D54746B417}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElasticScale.ShardManagement.UnitTests", "Test\ElasticScale.ShardManagement.UnitTests\ElasticScale.ShardManagement.UnitTests.csproj", "{EA7DA8D7-6B11-4AF7-9C24-6FEEBDA7E188}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElasticScaleStarterKit", "Samples\ElasticScaleStarterKit\ElasticScaleStarterKit.csproj", "{115A0283-AC42-4D37-97F2-106D168E04D2}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EntityFrameworkCodeFirst", "Samples\EFCodeFirst\EntityFrameworkCodeFirst.csproj", "{904469F9-427C-4B9F-A30D-B63E53BEB489}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShardSqlCmd", "Samples\ShardSqlCmd\ShardSqlCmd.csproj", "{A95C04CC-3CEE-42ED-BB17-2B9850E374FB}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EntityFrameworkMultiTenant", "Samples\EFMultiTenant\EntityFrameworkMultiTenant.csproj", "{9AD1DDF3-213C-47B1-B136-733C9FFF9FD1}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElasticDapper", "Samples\Dapper\ElasticDapper.csproj", "{7B67F0A1-A5A9-477B-9B7E-FA2E16ED34DE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests", "Test\ElasticScale.Query.UnitTests\Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests.csproj", "{74CEE77F-D2C7-4B8B-9411-8F97F4E803FA}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -30,68 +18,35 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {663D22BB-483A-46B0-A504-861C5335DAD1}.Cover|Any CPU.ActiveCfg = Release|Any CPU - {663D22BB-483A-46B0-A504-861C5335DAD1}.Cover|Any CPU.Build.0 = Release|Any CPU - {663D22BB-483A-46B0-A504-861C5335DAD1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {663D22BB-483A-46B0-A504-861C5335DAD1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {663D22BB-483A-46B0-A504-861C5335DAD1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {663D22BB-483A-46B0-A504-861C5335DAD1}.Release|Any CPU.Build.0 = Release|Any CPU - {13200C7C-8606-47B8-A004-570B56E3A9A8}.Cover|Any CPU.ActiveCfg = Release|Any CPU - {13200C7C-8606-47B8-A004-570B56E3A9A8}.Cover|Any CPU.Build.0 = Release|Any CPU - {13200C7C-8606-47B8-A004-570B56E3A9A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {13200C7C-8606-47B8-A004-570B56E3A9A8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {13200C7C-8606-47B8-A004-570B56E3A9A8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {13200C7C-8606-47B8-A004-570B56E3A9A8}.Release|Any CPU.Build.0 = Release|Any CPU - {56DDEC7E-0B14-4636-B287-DB38DEC55192}.Cover|Any CPU.ActiveCfg = Release|Any CPU - {56DDEC7E-0B14-4636-B287-DB38DEC55192}.Cover|Any CPU.Build.0 = Release|Any CPU - {56DDEC7E-0B14-4636-B287-DB38DEC55192}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {56DDEC7E-0B14-4636-B287-DB38DEC55192}.Debug|Any CPU.Build.0 = Debug|Any CPU - {56DDEC7E-0B14-4636-B287-DB38DEC55192}.Release|Any CPU.ActiveCfg = Release|Any CPU - {56DDEC7E-0B14-4636-B287-DB38DEC55192}.Release|Any CPU.Build.0 = Release|Any CPU - {6C6E8D75-DF7B-4841-A254-D0D54746B417}.Cover|Any CPU.ActiveCfg = Release|Any CPU - {6C6E8D75-DF7B-4841-A254-D0D54746B417}.Cover|Any CPU.Build.0 = Release|Any CPU - {6C6E8D75-DF7B-4841-A254-D0D54746B417}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6C6E8D75-DF7B-4841-A254-D0D54746B417}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6C6E8D75-DF7B-4841-A254-D0D54746B417}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6C6E8D75-DF7B-4841-A254-D0D54746B417}.Release|Any CPU.Build.0 = Release|Any CPU - {EA7DA8D7-6B11-4AF7-9C24-6FEEBDA7E188}.Cover|Any CPU.ActiveCfg = Release|Any CPU - {EA7DA8D7-6B11-4AF7-9C24-6FEEBDA7E188}.Cover|Any CPU.Build.0 = Release|Any CPU - {EA7DA8D7-6B11-4AF7-9C24-6FEEBDA7E188}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EA7DA8D7-6B11-4AF7-9C24-6FEEBDA7E188}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EA7DA8D7-6B11-4AF7-9C24-6FEEBDA7E188}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EA7DA8D7-6B11-4AF7-9C24-6FEEBDA7E188}.Release|Any CPU.Build.0 = Release|Any CPU - {115A0283-AC42-4D37-97F2-106D168E04D2}.Cover|Any CPU.ActiveCfg = Cover|Any CPU - {115A0283-AC42-4D37-97F2-106D168E04D2}.Cover|Any CPU.Build.0 = Cover|Any CPU - {115A0283-AC42-4D37-97F2-106D168E04D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {115A0283-AC42-4D37-97F2-106D168E04D2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {115A0283-AC42-4D37-97F2-106D168E04D2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {115A0283-AC42-4D37-97F2-106D168E04D2}.Release|Any CPU.Build.0 = Release|Any CPU - {904469F9-427C-4B9F-A30D-B63E53BEB489}.Cover|Any CPU.ActiveCfg = Cover|Any CPU - {904469F9-427C-4B9F-A30D-B63E53BEB489}.Cover|Any CPU.Build.0 = Cover|Any CPU - {904469F9-427C-4B9F-A30D-B63E53BEB489}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {904469F9-427C-4B9F-A30D-B63E53BEB489}.Debug|Any CPU.Build.0 = Debug|Any CPU - {904469F9-427C-4B9F-A30D-B63E53BEB489}.Release|Any CPU.ActiveCfg = Release|Any CPU - {904469F9-427C-4B9F-A30D-B63E53BEB489}.Release|Any CPU.Build.0 = Release|Any CPU - {A95C04CC-3CEE-42ED-BB17-2B9850E374FB}.Cover|Any CPU.ActiveCfg = Cover|Any CPU - {A95C04CC-3CEE-42ED-BB17-2B9850E374FB}.Cover|Any CPU.Build.0 = Cover|Any CPU - {A95C04CC-3CEE-42ED-BB17-2B9850E374FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A95C04CC-3CEE-42ED-BB17-2B9850E374FB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A95C04CC-3CEE-42ED-BB17-2B9850E374FB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A95C04CC-3CEE-42ED-BB17-2B9850E374FB}.Release|Any CPU.Build.0 = Release|Any CPU - {9AD1DDF3-213C-47B1-B136-733C9FFF9FD1}.Cover|Any CPU.ActiveCfg = Cover|Any CPU - {9AD1DDF3-213C-47B1-B136-733C9FFF9FD1}.Cover|Any CPU.Build.0 = Cover|Any CPU - {9AD1DDF3-213C-47B1-B136-733C9FFF9FD1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9AD1DDF3-213C-47B1-B136-733C9FFF9FD1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9AD1DDF3-213C-47B1-B136-733C9FFF9FD1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9AD1DDF3-213C-47B1-B136-733C9FFF9FD1}.Release|Any CPU.Build.0 = Release|Any CPU - {7B67F0A1-A5A9-477B-9B7E-FA2E16ED34DE}.Cover|Any CPU.ActiveCfg = Cover|Any CPU - {7B67F0A1-A5A9-477B-9B7E-FA2E16ED34DE}.Cover|Any CPU.Build.0 = Cover|Any CPU - {7B67F0A1-A5A9-477B-9B7E-FA2E16ED34DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7B67F0A1-A5A9-477B-9B7E-FA2E16ED34DE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7B67F0A1-A5A9-477B-9B7E-FA2E16ED34DE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7B67F0A1-A5A9-477B-9B7E-FA2E16ED34DE}.Release|Any CPU.Build.0 = Release|Any CPU + {4C3B3EC4-5702-469E-800E-313FB27A0A2B}.Cover|Any CPU.ActiveCfg = Debug|Any CPU + {4C3B3EC4-5702-469E-800E-313FB27A0A2B}.Cover|Any CPU.Build.0 = Debug|Any CPU + {4C3B3EC4-5702-469E-800E-313FB27A0A2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4C3B3EC4-5702-469E-800E-313FB27A0A2B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4C3B3EC4-5702-469E-800E-313FB27A0A2B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4C3B3EC4-5702-469E-800E-313FB27A0A2B}.Release|Any CPU.Build.0 = Release|Any CPU + {9336E9E7-19BF-49AC-92E3-19FA6B98921E}.Cover|Any CPU.ActiveCfg = Debug|Any CPU + {9336E9E7-19BF-49AC-92E3-19FA6B98921E}.Cover|Any CPU.Build.0 = Debug|Any CPU + {9336E9E7-19BF-49AC-92E3-19FA6B98921E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9336E9E7-19BF-49AC-92E3-19FA6B98921E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9336E9E7-19BF-49AC-92E3-19FA6B98921E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9336E9E7-19BF-49AC-92E3-19FA6B98921E}.Release|Any CPU.Build.0 = Release|Any CPU + {BEA6F911-BA98-462C-99AF-3B0595DE2307}.Cover|Any CPU.ActiveCfg = Debug|Any CPU + {BEA6F911-BA98-462C-99AF-3B0595DE2307}.Cover|Any CPU.Build.0 = Debug|Any CPU + {BEA6F911-BA98-462C-99AF-3B0595DE2307}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BEA6F911-BA98-462C-99AF-3B0595DE2307}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BEA6F911-BA98-462C-99AF-3B0595DE2307}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BEA6F911-BA98-462C-99AF-3B0595DE2307}.Release|Any CPU.Build.0 = Release|Any CPU + {74CEE77F-D2C7-4B8B-9411-8F97F4E803FA}.Cover|Any CPU.ActiveCfg = Debug|Any CPU + {74CEE77F-D2C7-4B8B-9411-8F97F4E803FA}.Cover|Any CPU.Build.0 = Debug|Any CPU + {74CEE77F-D2C7-4B8B-9411-8F97F4E803FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {74CEE77F-D2C7-4B8B-9411-8F97F4E803FA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {74CEE77F-D2C7-4B8B-9411-8F97F4E803FA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {74CEE77F-D2C7-4B8B-9411-8F97F4E803FA}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {24237160-521B-4CD0-87AB-8994A5E50BE2} + EndGlobalSection EndGlobal diff --git a/Samples/CodeAnalysis.Samples.ruleset b/Samples/CodeAnalysis.Samples.ruleset index c5a5ec3..6f1910c 100644 --- a/Samples/CodeAnalysis.Samples.ruleset +++ b/Samples/CodeAnalysis.Samples.ruleset @@ -2,7 +2,7 @@ - + - + - + - - + diff --git a/Samples/Dapper/ElasticDapper.csproj b/Samples/Dapper/ElasticDapper.csproj index 6f93235..907f50c 100644 --- a/Samples/Dapper/ElasticDapper.csproj +++ b/Samples/Dapper/ElasticDapper.csproj @@ -8,7 +8,6 @@ ElasticDapper 512 - @@ -19,9 +18,9 @@ - diff --git a/Samples/EFCodeFirst/EntityFrameworkCodeFirst.csproj b/Samples/EFCodeFirst/EntityFrameworkCodeFirst.csproj index 1d1f616..71adf81 100644 --- a/Samples/EFCodeFirst/EntityFrameworkCodeFirst.csproj +++ b/Samples/EFCodeFirst/EntityFrameworkCodeFirst.csproj @@ -10,7 +10,6 @@ false - @@ -21,7 +20,7 @@ - diff --git a/Samples/EFMultiTenant/EntityFrameworkMultiTenant.csproj b/Samples/EFMultiTenant/EntityFrameworkMultiTenant.csproj index 5609fc0..81820e6 100644 --- a/Samples/EFMultiTenant/EntityFrameworkMultiTenant.csproj +++ b/Samples/EFMultiTenant/EntityFrameworkMultiTenant.csproj @@ -10,7 +10,6 @@ false - @@ -21,7 +20,7 @@ - diff --git a/Samples/ElasticScaleStarterKit/ElasticScaleStarterKit.csproj b/Samples/ElasticScaleStarterKit/ElasticScaleStarterKit.csproj index 1437371..cb5c111 100644 --- a/Samples/ElasticScaleStarterKit/ElasticScaleStarterKit.csproj +++ b/Samples/ElasticScaleStarterKit/ElasticScaleStarterKit.csproj @@ -8,7 +8,6 @@ ElasticScaleStarterKit ElasticScaleStarterKit - @@ -19,7 +18,7 @@ - diff --git a/Samples/ShardSqlCmd/ShardSqlCmd.csproj b/Samples/ShardSqlCmd/ShardSqlCmd.csproj index bd0d0ec..51ec489 100644 --- a/Samples/ShardSqlCmd/ShardSqlCmd.csproj +++ b/Samples/ShardSqlCmd/ShardSqlCmd.csproj @@ -8,7 +8,6 @@ ShardSqlCmd ShardSqlCmd - @@ -19,9 +18,9 @@ - diff --git a/Samples/build.props b/Samples/build.props deleted file mode 100644 index 1e89913..0000000 --- a/Samples/build.props +++ /dev/null @@ -1,12 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - - - $(MSBuildThisFileDirectory)CodeAnalysis.Samples.ruleset - Samples\$(RelativeOutputPath) - Test - - - diff --git a/Samples/dirs.proj b/Samples/dirs.proj deleted file mode 100644 index 869cca0..0000000 --- a/Samples/dirs.proj +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/Src/ElasticScale.Client/ElasticScale.Client.csproj b/Src/ElasticScale.Client/ElasticScale.Client.csproj deleted file mode 100644 index 4b5cee3..0000000 --- a/Src/ElasticScale.Client/ElasticScale.Client.csproj +++ /dev/null @@ -1,336 +0,0 @@ - - - - {663D22BB-483A-46B0-A504-861C5335DAD1} - Library - Properties - Microsoft.Azure.SqlDatabase.ElasticScale - Microsoft.Azure.SqlDatabase.ElasticScale.Client - $(OutDir)$(AssemblyName).xml - 512 - - - - true - full - false - $(DefineConstants);DEBUG;TRACE - prompt - 4 - - - pdbonly - true - $(DefineConstants);TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - True - True - Resources.resx - - - - - - - - - - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - True - True - Errors.resx - - - - - True - True - ReadOnlyScripts.resx - - - True - True - PerformanceCounters.resx - - - - - - - - - - - - - - - - - - True - True - Scripts.resx - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ResXFileCodeGenerator - ReadOnlyScripts.Designer.cs - - - ResXFileCodeGenerator - PerformanceCounters.Designer.cs - - - ResXFileCodeGenerator - Scripts.Designer.cs - Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement - - - ResXFileCodeGenerator - Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement - Errors.Designer.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Src/ElasticScale.Client/ElasticScale.Common/ExceptionHandling/ExceptionExtensionMethods.cs b/Src/ElasticScale.Client/ElasticScale.Common/ExceptionHandling/ExceptionExtensionMethods.cs index 23838f1..58e562a 100644 --- a/Src/ElasticScale.Client/ElasticScale.Common/ExceptionHandling/ExceptionExtensionMethods.cs +++ b/Src/ElasticScale.Client/ElasticScale.Common/ExceptionHandling/ExceptionExtensionMethods.cs @@ -2,10 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Reflection; namespace Microsoft.Azure.SqlDatabase.ElasticScale { diff --git a/Src/ElasticScale.Client/ElasticScale.Common/Logging/TraceSource/ActivityIdScope.cs b/Src/ElasticScale.Client/ElasticScale.Common/Logging/TraceSource/ActivityIdScope.cs index bea2ebd..d76443f 100644 --- a/Src/ElasticScale.Client/ElasticScale.Common/Logging/TraceSource/ActivityIdScope.cs +++ b/Src/ElasticScale.Client/ElasticScale.Common/Logging/TraceSource/ActivityIdScope.cs @@ -26,8 +26,8 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale /// public ActivityIdScope(Guid activityId) { - _previousActivityId = Trace.CorrelationManager.ActivityId; - Trace.CorrelationManager.ActivityId = activityId; + _previousActivityId = CorrelationManager.ActivityId; + CorrelationManager.ActivityId = activityId; } /// @@ -35,7 +35,39 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale /// public void Dispose() { - Trace.CorrelationManager.ActivityId = _previousActivityId; + CorrelationManager.ActivityId = _previousActivityId; } } + + internal static class CorrelationManager + { +#if NETFRAMEWORK + public static Guid ActivityId + { + get + { + return Trace.CorrelationManager.ActivityId; + } + set + { + Trace.CorrelationManager.ActivityId = value; + } + } +#else + [ThreadStatic] + private static Guid _activityId; + + public static Guid ActivityId + { + get + { + return _activityId; + } + set + { + _activityId = value; + } + } +#endif + } } diff --git a/Src/ElasticScale.Client/ElasticScale.Common/Logging/TraceSource/TraceSourceWrapper.cs b/Src/ElasticScale.Client/ElasticScale.Common/Logging/TraceSource/TraceSourceWrapper.cs index 6997fa9..c3ec97e 100644 --- a/Src/ElasticScale.Client/ElasticScale.Common/Logging/TraceSource/TraceSourceWrapper.cs +++ b/Src/ElasticScale.Client/ElasticScale.Common/Logging/TraceSource/TraceSourceWrapper.cs @@ -108,7 +108,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale } /// - /// Traces an exception and a message at the Warning trace level + /// Traces an exception and a message at the Warning trace level /// to the trace source /// /// @@ -119,7 +119,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale } /// - /// Traces an exception and a message at the Warning trace level + /// Traces an exception and a message at the Warning trace level /// to the trace source /// /// @@ -202,7 +202,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale } /// - /// Traces the message and exception at the Critical source level + /// Traces the message and exception at the Critical source level /// to the trace source /// /// @@ -213,7 +213,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale } /// - /// Traces the message and exception at the Critical source level + /// Traces the message and exception at the Critical source level /// to the trace source /// /// @@ -236,7 +236,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale /// public void TraceIn(string method, Guid activityId) { +#if NETFRAMEWORK _traceSource.TraceEvent(TraceEventType.Start, 0, "Start.{0}. ActivityId: {1}", method, activityId); +#endif } /// @@ -246,7 +248,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale /// public void TraceOut(string method, Guid activityId) { +#if NETFRAMEWORK _traceSource.TraceEvent(TraceEventType.Stop, 0, "Stop.{0}. ActivityId: {1}", method, activityId); +#endif } /// @@ -258,8 +262,10 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale /// public void TraceIn(string method, Guid activityId, string format, params object[] vars) { +#if NETFRAMEWORK string fmtMessage = string.Format(format, vars); _traceSource.TraceEvent(TraceEventType.Start, 0, "Start.{0}. {1}. ActivityId: {2}", method, fmtMessage, activityId); +#endif } /// @@ -271,10 +277,12 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale /// public void TraceOut(string method, Guid activityId, string format, params object[] vars) { +#if NETFRAMEWORK string fmtMessage = string.Format(format, vars); _traceSource.TraceEvent(TraceEventType.Stop, 0, "Stop.{0}. {1}. ActivityId: {2}", method, fmtMessage, activityId); +#endif } - #endregion +#endregion } } diff --git a/Src/ElasticScale.Client/ElasticScale.Common/Properties/Resources.Designer.cs b/Src/ElasticScale.Client/ElasticScale.Common/Properties/Resources.Designer.cs index 44fff2b..3946cc4 100644 --- a/Src/ElasticScale.Client/ElasticScale.Common/Properties/Resources.Designer.cs +++ b/Src/ElasticScale.Client/ElasticScale.Common/Properties/Resources.Designer.cs @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:4.0.30319.18033 +// Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. @@ -19,7 +19,7 @@ namespace Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling.Propertie // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { diff --git a/Src/ElasticScale.Client/Microsoft.Azure.SqlDatabase.ElasticScale.Client.csproj b/Src/ElasticScale.Client/Microsoft.Azure.SqlDatabase.ElasticScale.Client.csproj new file mode 100644 index 0000000..9c42a3b --- /dev/null +++ b/Src/ElasticScale.Client/Microsoft.Azure.SqlDatabase.ElasticScale.Client.csproj @@ -0,0 +1,53 @@ + + + + This client library allows ADO.NET developers to create applications that implement and use the pattern known as database sharding in Azure SQL Database. Sharding is a scale-out strategy that spreads data across a number of independent databases. The library includes APIs for creating and managing shard maps, routing SQL operations to the appropriate shard, and performing queries that cross many shards. To learn more about elastic database tools, check out http://azure.microsoft.com/en-us/documentation/articles/sql-database-elastic-scale-documentation-map/. + Copyright (C) Microsoft Corporation. All rights reserved. + Microsoft Azure SQL Database: Elastic Database Client Library + en-US + 2.0.0-preview2 + azure-sdk;Microsoft + net451;netstandard2.0 + Microsoft;Elastic;Scale;Azure;SQL;DB;Database;Shard;Sharding;Management;Query;azureofficial + Added support for .NET Standard 2.0. + http://go.microsoft.com/fwlink/?LinkID=288890 + https://github.com/Azure/elastic-db-tools + http://go.microsoft.com/?linkid=9862941 + true + git + https://github.com/Azure/elastic-db-tools + win;unix + Microsoft.Azure.SqlDatabase.ElasticScale + + + + + + + + + + + True + True + Errors.resx + + + True + True + PerformanceCounters.resx + + + + + + ResXFileCodeGenerator + Errors.Designer.cs + + + ResXFileCodeGenerator + PerformanceCounters.Designer.cs + + + + diff --git a/Src/ElasticScale.Client/Microsoft.Azure.SqlDatabase.ElasticScale.Client.xml b/Src/ElasticScale.Client/Microsoft.Azure.SqlDatabase.ElasticScale.Client.xml deleted file mode 100644 index ba81e9c..0000000 --- a/Src/ElasticScale.Client/Microsoft.Azure.SqlDatabase.ElasticScale.Client.xml +++ /dev/null @@ -1,17157 +0,0 @@ - - - - Microsoft.Azure.SqlDatabase.ElasticScale.Client - - - - - Shard management retrying event arguments - - - - - Initializes new instance of class. - - RetryingEventArgs from RetryPolicy.Retrying event. - - - - Gets the current retry count. - - - - - Gets the delay that indicates how long the current thread will be suspended before the next iteration is invoked. - - - - - Gets the exception that caused the retry conditions to occur. - - - - - Maximum length allowed for an ApplicationName - - - - - Adds suffix to the application name, but not exceeding certain length. - - Application provided application name. - Suffix to append to the application name. - Application name with suffix appended. - - - - Adds suffix to the application name of the provided connection string - Will not exceeding certain length of the application name. - - The original connection string. - The suffix to append. - - Modified connection string with suffix appended to application name - - - - - Mutates provided SqlConnectionStringBuilder with the application name suffix. - Returns modified SqlConnectionStringBuilder. - - The builder. - The suffix to append. - - - - - Extension methods for System.Exception. - - - - - Checks if this exception's type is the same, or a sub-class, of any of the specified types. - - This instance. - Types to be matched against. - Whether or not this exception matched any of the specified types. - - - - Handles the execution and retries of the user-initiated task. - - The result type of the user-initiated task. - - - - Provides a wrapper for a non-generic and calls into the pipeline - to retry only the generic version of the . - - - - - Wraps the non-generic into a generic . - - The task to wrap. - A that wraps the non-generic . - - - - Implements the common guard methods. - - - - - Checks a string argument to ensure that it isn't null or empty. - - The argument value to check. - The name of the argument. - The return value should be ignored. It is intended to be used only when validating arguments during instance creation (for example, when calling the base constructor). - - - - Checks an argument to ensure that it isn't null. - - The argument value to check. - The name of the argument. - The return value should be ignored. It is intended to be used only when validating arguments during instance creation (for example, when calling the base constructor). - - - - Checks an argument to ensure that its 32-bit signed value isn't negative. - - The value of the argument. - The name of the argument for diagnostic purposes. - - - - Checks an argument to ensure that its 64-bit signed value isn't negative. - - The value of the argument. - The name of the argument for diagnostic purposes. - - - - Checks an argument to ensure that its value doesn't exceed the specified ceiling baseline. - - The value of the argument. - The ceiling value of the argument. - The name of the argument for diagnostic purposes. - - - - Defines an interface that must be implemented by custom components responsible for detecting specific transient conditions. - - - - - Determines whether the specified exception represents a transient failure that can be compensated by a retry. - - The exception object to be verified. - true if the specified exception is considered as transient; otherwise, false. - - - - Contains information that is required for the event. - - - - - Initializes a new instance of the class. - - The current retry attempt count. - The delay that indicates how long the current thread will be suspended before the next iteration is invoked. - The exception that caused the retry conditions to occur. - - - - Gets the current retry count. - - - - - Gets the delay that indicates how long the current thread will be suspended before the next iteration is invoked. - - - - - Gets the exception that caused the retry conditions to occur. - - - - - The special type of exception that provides managed exit from a retry loop. The user code can use this - exception to notify the retry policy that no further retry attempts are required. - - - - - Initializes a new instance of the class with a default error message. - - - - - Initializes a new instance of the class with a specified error message. - - The message that describes the error. - - - - Initializes a new instance of the class with a reference to the inner exception - that is the cause of this exception. - - The exception that is the cause of the current exception. - - - - Initializes a new instance of the class with a specified error message and inner exception. - - The message that describes the error. - The exception that is the cause of the current exception. - - - - Provides the entry point to the retry functionality. - - - - - Sets the specified retry manager as the default retry manager. - - The retry manager. - true to throw an exception if the manager is already set; otherwise, false. Defaults to . - The singleton is already set and is true. - - - - Gets the default for the application. - - You can update the default retry manager by calling the method. - - - - Initializes a new instance of the class. - - The complete set of retry strategies. - - - - Initializes a new instance of the class with the specified retry strategies and default retry strategy name. - - The complete set of retry strategies. - The default retry strategy. - - - - Initializes a new instance of the class with the specified retry strategies and defaults. - - The complete set of retry strategies. - The default retry strategy. - The names of the default strategies for different technologies. - - - - Gets or sets the default retry strategy name. - - - - - Returns a retry policy with the specified error detection strategy and the default retry strategy defined in the configuration. - - The type that implements the interface that is responsible for detecting transient conditions. - A new retry policy with the specified error detection strategy and the default retry strategy defined in the configuration. - - - - Returns a retry policy with the specified error detection strategy and retry strategy. - - The type that implements the interface that is responsible for detecting transient conditions. - The retry strategy name, as defined in the configuration. - A new retry policy with the specified error detection strategy and the default retry strategy defined in the configuration. - - - - Returns the default retry strategy defined in the configuration. - - The retry strategy that matches the default strategy. - - - - Returns the retry strategy that matches the specified name. - - The retry strategy name. - The retry strategy that matches the specified name. - - - - Returns the retry strategy for the specified technology. - - The techonolgy to get the default retry strategy for. - The retry strategy for the specified technology. - - - - Provides the base implementation of the retry mechanism for unreliable actions and transient conditions. - - - - - Returns a default policy that performs no retries, but invokes the action only once. - - - - - Returns a default policy that implements a fixed retry interval configured with the default retry strategy. - The default retry policy treats all caught exceptions as transient errors. - - - - - Returns a default policy that implements a progressive retry interval configured with the default retry strategy. - The default retry policy treats all caught exceptions as transient errors. - - - - - Returns a default policy that implements a random exponential retry interval configured with the default retry strategy. - The default retry policy treats all caught exceptions as transient errors. - - - - - Initializes a new instance of the class with the specified number of retry attempts and parameters defining the progressive delay between retries. - - The that is responsible for detecting transient conditions. - The strategy to use for this retry policy. - - - - Initializes a new instance of the class with the specified number of retry attempts and default fixed time interval between retries. - - The that is responsible for detecting transient conditions. - The number of retry attempts. - - - - Initializes a new instance of the class with the specified number of retry attempts and fixed time interval between retries. - - The that is responsible for detecting transient conditions. - The number of retry attempts. - The interval between retries. - - - - Initializes a new instance of the class with the specified number of retry attempts and backoff parameters for calculating the exponential delay between retries. - - The that is responsible for detecting transient conditions. - The number of retry attempts. - The minimum backoff time. - The maximum backoff time. - The time value that will be used to calculate a random delta in the exponential delay between retries. - - - - Initializes a new instance of the class with the specified number of retry attempts and parameters defining the progressive delay between retries. - - The that is responsible for detecting transient conditions. - The number of retry attempts. - The initial interval that will apply for the first retry. - The incremental time value that will be used to calculate the progressive delay between retries. - - - - An instance of a callback delegate that will be invoked whenever a retry condition is encountered. - - - - - Gets the retry strategy. - - - - - Gets the instance of the error detection strategy. - - - - - Repetitively executes the specified action while it satisfies the current retry policy. - - A delegate that represents the executable action that doesn't return any results. - - - - Repetitively executes the specified action while it satisfies the current retry policy. - - The type of result expected from the executable action. - A delegate that represents the executable action that returns the result of type . - The result from the action. - - - - Repetitively executes the specified asynchronous task while it satisfies the current retry policy. - - A function that returns a started task (also known as "hot" task). - - A task that will run to completion if the original task completes successfully (either the - first time or after retrying transient failures). If the task fails with a non-transient error or - the retry limit is reached, the returned task will transition to a faulted state and the exception must be observed. - - - - - Repetitively executes the specified asynchronous task while it satisfies the current retry policy. - - A function that returns a started task (also known as "hot" task). - The token used to cancel the retry operation. This token does not cancel the execution of the asynchronous task. - - Returns a task that will run to completion if the original task completes successfully (either the - first time or after retrying transient failures). If the task fails with a non-transient error or - the retry limit is reached, the returned task will transition to a faulted state and the exception must be observed. - - - - - Repeatedly executes the specified asynchronous task while it satisfies the current retry policy. - - A function that returns a started task (also known as "hot" task). - - Returns a task that will run to completion if the original task completes successfully (either the - first time or after retrying transient failures). If the task fails with a non-transient error or - the retry limit is reached, the returned task will transition to a faulted state and the exception must be observed. - - - - - Repeatedly executes the specified asynchronous task while it satisfies the current retry policy. - - A function that returns a started task (also known as "hot" task). - The token used to cancel the retry operation. This token does not cancel the execution of the asynchronous task. - - Returns a task that will run to completion if the original task completes successfully (either the - first time or after retrying transient failures). If the task fails with a non-transient error or - the retry limit is reached, the returned task will transition to a faulted state and the exception must be observed. - - - - - Notifies the subscribers whenever a retry condition is encountered. - - The current retry attempt count. - The exception that caused the retry conditions to occur. - The delay that indicates how long the current thread will be suspended before the next iteration is invoked. - - - - Implements a strategy that ignores any transient errors. - - - - - Always returns false. - - The exception. - Always false. - - - - Implements a strategy that treats all exceptions as transient errors. - - - - - Always returns true. - - The exception. - Always true. - - - - Provides a generic version of the class. - - The type that implements the interface that is responsible for detecting transient conditions. - - - - Initializes a new instance of the class with the specified number of retry attempts and parameters defining the progressive delay between retries. - - The strategy to use for this retry policy. - - - - Initializes a new instance of the class with the specified number of retry attempts and the default fixed time interval between retries. - - The number of retry attempts. - - - - Initializes a new instance of the class with the specified number of retry attempts and a fixed time interval between retries. - - The number of retry attempts. - The interval between retries. - - - - Initializes a new instance of the class with the specified number of retry attempts and backoff parameters for calculating the exponential delay between retries. - - The number of retry attempts. - The minimum backoff time. - The maximum backoff time. - The time value that will be used to calculate a random delta in the exponential delay between retries. - - - - Initializes a new instance of the class with the specified number of retry attempts and parameters defining the progressive delay between retries. - - The number of retry attempts. - The initial interval that will apply for the first retry. - The incremental time value that will be used to calculate the progressive delay between retries. - - - - A retry strategy with backoff parameters for calculating the exponential delay between retries. - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class with the specified retry settings. - - The maximum number of retry attempts. - The minimum backoff time - The maximum backoff time. - The value that will be used to calculate a random delta in the exponential delay between retries. - - - - Initializes a new instance of the class with the specified name and retry settings. - - The name of the retry strategy. - The maximum number of retry attempts. - The minimum backoff time - The maximum backoff time. - The value that will be used to calculate a random delta in the exponential delay between retries. - - - - Initializes a new instance of the class with the specified name, retry settings, and fast retry option. - - The name of the retry strategy. - The maximum number of retry attempts. - The minimum backoff time - The maximum backoff time. - The value that will be used to calculate a random delta in the exponential delay between retries. - true to immediately retry in the first attempt; otherwise, false. The subsequent retries will remain subject to the configured retry interval. - - - - Returns the corresponding ShouldRetry delegate. - - The ShouldRetry delegate. - - - - Represents a retry strategy with a specified number of retry attempts and a default, fixed time interval between retries. - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class with the specified number of retry attempts. - - The number of retry attempts. - - - - Initializes a new instance of the class with the specified number of retry attempts and time interval. - - The number of retry attempts. - The time interval between retries. - - - - Initializes a new instance of the class with the specified number of retry attempts, time interval, and retry strategy. - - The retry strategy name. - The number of retry attempts. - The time interval between retries. - - - - Initializes a new instance of the class with the specified number of retry attempts, time interval, retry strategy, and fast start option. - - The retry strategy name. - The number of retry attempts. - The time interval between retries. - true to immediately retry in the first attempt; otherwise, false. The subsequent retries will remain subject to the configured retry interval. - - - - Returns the corresponding ShouldRetry delegate. - - The ShouldRetry delegate. - - - - A retry strategy with a specified number of retry attempts and an incremental time interval between retries. - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class with the specified retry settings. - - The number of retry attempts. - The initial interval that will apply for the first retry. - The incremental time value that will be used to calculate the progressive delay between retries. - - - - Initializes a new instance of the class with the specified name and retry settings. - - The retry strategy name. - The number of retry attempts. - The initial interval that will apply for the first retry. - The incremental time value that will be used to calculate the progressive delay between retries. - - - - Initializes a new instance of the class with the specified number of retry attempts, time interval, retry strategy, and fast start option. - - The retry strategy name. - The number of retry attempts. - The initial interval that will apply for the first retry. - The incremental time value that will be used to calculate the progressive delay between retries. - true to immediately retry in the first attempt; otherwise, false. The subsequent retries will remain subject to the configured retry interval. - - - - Returns the corresponding ShouldRetry delegate. - - The ShouldRetry delegate. - - - - Defines a callback delegate that will be invoked whenever a retry condition is encountered. - - The current retry attempt count. - The exception that caused the retry conditions to occur. - The delay that indicates how long the current thread will be suspended before the next iteration is invoked. - if a retry is allowed; otherwise, . - - - - Represents a retry strategy that determines the number of retry attempts and the interval between retries. - - - - - Represents the default number of retry attempts. - - - - - Represents the default amount of time used when calculating a random delta in the exponential delay between retries. - - - - - Represents the default maximum amount of time used when calculating the exponential delay between retries. - - - - - Represents the default minimum amount of time used when calculating the exponential delay between retries. - - - - - Represents the default interval between retries. - - - - - Represents the default time increment between retry attempts in the progressive delay policy. - - - - - Represents the default flag indicating whether the first retry attempt will be made immediately, - whereas subsequent retries will remain subject to the retry interval. - - - - - Returns a default policy that performs no retries, but invokes the action only once. - - - - - Returns a default policy that implements a fixed retry interval configured with the and parameters. - The default retry policy treats all caught exceptions as transient errors. - - - - - Returns a default policy that implements a progressive retry interval configured with the , , and parameters. - The default retry policy treats all caught exceptions as transient errors. - - - - - Returns a default policy that implements a random exponential retry interval configured with the , , , and parameters. - The default retry policy treats all caught exceptions as transient errors. - - - - - Initializes a new instance of the class. - - The name of the retry strategy. - true to immediately retry in the first attempt; otherwise, false. The subsequent retries will remain subject to the configured retry interval. - - - - Gets or sets a value indicating whether the first retry attempt will be made immediately, - whereas subsequent retries will remain subject to the retry interval. - - - - - Gets the name of the retry strategy. - - - - - Returns the corresponding ShouldRetry delegate. - - The ShouldRetry delegate. - - - - Provides the transient error detection logic for transient faults that are specific to SQL Database. - - - - - Error codes reported by the DBNETLIB module. - - - - - Determines whether the specified exception represents a transient failure that can be compensated by a retry. - - The exception object to be verified. - true if the specified exception is considered as transient; otherwise, false. - - - - Defines the possible throttling modes in SQL Database. - - - - - Corresponds to the "No Throttling" throttling mode, in which all SQL statements can be processed. - - - - - Corresponds to the "Reject Update / Insert" throttling mode, in which SQL statements such as INSERT, UPDATE, CREATE TABLE, and CREATE INDEX are rejected. - - - - - Corresponds to the "Reject All Writes" throttling mode, in which SQL statements such as INSERT, UPDATE, DELETE, CREATE, and DROP are rejected. - - - - - Corresponds to the "Reject All" throttling mode, in which all SQL statements are rejected. - - - - - Corresponds to an unknown throttling mode whereby throttling mode cannot be determined with certainty. - - - - - Defines the possible throttling types in SQL Database. - - - - - Indicates that no throttling was applied to a given resource. - - - - - Corresponds to a soft throttling type. Soft throttling is applied when machine resources such as, CPU, I/O, storage, and worker threads exceed - predefined safety thresholds despite the load balancer’s best efforts. - - - - - Corresponds to a hard throttling type. Hard throttling is applied when the machine is out of resources, for example storage space. - With hard throttling, no new connections are allowed to the databases hosted on the machine until resources are freed up. - - - - - Corresponds to an unknown throttling type in the event that the throttling type cannot be determined with certainty. - - - - - Defines the types of resources in SQL Database that may be subject to throttling conditions. - - - - - Corresponds to the "Physical Database Space" resource, which may be subject to throttling. - - - - - Corresponds to the "Physical Log File Space" resource, which may be subject to throttling. - - - - - Corresponds to the "Transaction Log Write IO Delay" resource, which may be subject to throttling. - - - - - Corresponds to the "Database Read IO Delay" resource, which may be subject to throttling. - - - - - Corresponds to the "CPU" resource, which may be subject to throttling. - - - - - Corresponds to the "Database Size" resource, which may be subject to throttling. - - - - - Corresponds to the "SQL Worker Thread Pool" resource, which may be subject to throttling. - - - - - Corresponds to an internal resource that may be subject to throttling. - - - - - Corresponds to an unknown resource type in the event that the actual resource cannot be determined with certainty. - - - - - Implements an object that holds the decoded reason code returned from SQL Database when throttling conditions are encountered. - - - - - Gets the error number that corresponds to the throttling conditions reported by SQL Database. - - - - - Maintains a collection of key/value pairs where a key is the resource type and a value is the type of throttling applied to the given resource type. - - - - - Provides a compiled regular expression used to extract the reason code from the error message. - - - - - Gets an unknown throttling condition in the event that the actual throttling condition cannot be determined. - - - - - Gets the value that reflects the throttling mode in SQL Database. - - - - - Gets a list of the resources in the SQL Database that were subject to throttling conditions. - - - - - Gets a value that indicates whether physical data file space throttling was reported by SQL Database. - - - - - Gets a value that indicates whether physical log space throttling was reported by SQL Database. - - - - - Gets a value that indicates whether transaction activity throttling was reported by SQL Database. - - - - - Gets a value that indicates whether data read activity throttling was reported by SQL Database. - - - - - Gets a value that indicates whether CPU throttling was reported by SQL Database. - - - - - Gets a value that indicates whether database size throttling was reported by SQL Database. - - - - - Gets a value that indicates whether concurrent requests throttling was reported by SQL Database. - - - - - Gets a value that indicates whether throttling conditions were not determined with certainty. - - - - - Determines throttling conditions from the specified SQL exception. - - The object that contains information relevant to an error returned by SQL Server when throttling conditions were encountered. - An instance of the object that holds the decoded reason codes returned from SQL Database when throttling conditions were encountered. - - - - Determines the throttling conditions from the specified SQL error. - - The object that contains information relevant to a warning or error returned by SQL Server. - An instance of the object that holds the decoded reason codes returned from SQL Database when throttling conditions were encountered. - - - - Determines the throttling conditions from the specified reason code. - - The reason code returned by SQL Database that contains the throttling mode and the exceeded resource types. - An instance of the object holding the decoded reason codes returned from SQL Database when encountering throttling conditions. - - - - Returns a textual representation of the current ThrottlingCondition object, including the information held with respect to throttled resources. - - A string that represents the current ThrottlingCondition object. - - - - Defines the retry behavior to use for detecting transient errors. - - - - - Retry policy that tries upto 5 times with a 1 second backoff before giving up - - - - - Initializes an instance of the class - - Function that detects transient errors given an exception. - The function needs to return true for an exception that should be treated as transient. - - - - - Gets the default retry behavior. - - - The default retry behavior has a built-in set of exceptions that are considered transient. - You may create and use a custom object in order - to treat additional exceptions as transient. - - - - - Transient error detector predicate which decides whether a given exception is transient or not. - - - - - Defines the retry policy to use when executing commands. - - - - - Retry policy that tries upto 5 times with exponential backoff before giving up - - - - - Initializes an instance of the class - - The number of retry attempts. - Minimum backoff time for exponential backoff policy. - Maximum backoff time for exponential backoff policy. - Delta backoff time for exponential backoff policy. - - - - Gets the default retry policy. - - - 5 retries at 1 second intervals. - - - - - Gets the number of retries - - - - - Gets minimum backoff time - - - - - Gets maximum backoff time - - - - - Gets value used to calculate random delta in the exponential delay between retries. - Time delta for next retry attempt is 2^(currentRetryCount - 1) * random value between 80% and 120% of DeltaBackOff - - - - - Marshals this instance into the TFH library RetryStrategy type. - - The RetryStrategy - - - - String representation of - - - - - - Provide XML serialization\deserialization services. - - - - - Serialize the members of an object of type T into SqlXml format. - - - - - - - - Deserialize the contents of a string object into an object of type T. - - - - - - - - Deserialize the contents of a SqlXml object into an object of type T. - - - - - - - - Determines whether this obj can be XML serialized. - (the reason object may fail serialization is if it contains characters considered invalid by XML standard) - - - The object. - - - This is fairly expensive check as it actually serializes and discards results, - but it's good enough for usage in tests - - - - - Utility class to set and restore the System.Diagnostics CorrelationManager - ActivityId via the using pattern - - - - - The previous activity id that was in scope - - - - - Creates an instance of the class - - - - - - Restores the previous activity id when this instance is disposed - - - - - Definition of a generic logging interface to abstract - implementation details. Includes api trace methods. - - - - - Generic pluggable logger factory for retrieving configured - logging objects - - - - - ILogFactory interface to be implemented for - each logger - - - - - Interface for exposing a logging configuration change - - - - - System.Diagnostics TraceSource implementation of the ILogger interface - - - - - The trace source instance - - - - - Creates an instance of the - - The TraceSource name - - - - Creates an instance of the - - The TraceSource name - The default TraceSource level to use - - - - Traces an informational message to the trace source - - The trace source - - - - Traces an informational message to the trace source - - The format - The args - - - - Traces a Verbose message to the trace source - - - - - - Traces a Verbose message to the trace source - - - - - - - Traces a message at the Warning level to the trace source - - - - - - Traces a message at the Warning level to the trace source - - - - - - - Traces an exception and a message at the Warning trace level - to the trace source - - - - - - - Traces an exception and a message at the Warning trace level - to the trace source - - - - - - - - Traces the message at the Error trace level to the trace source - - - - - - Traces the message at the Error trace level to the trace source - - - - - - - Traces the exception and message - at the Error level to the trace source - - - - - - - Traces the exception and message at - the Error level to the trace source - - - - - - - - Traces the message at the Critical source level to the trace source - - - - - - Traces the message at the Critical source level to the trace source - - - - - - - Traces the message and exception at the Critical source level - to the trace source - - - - - - - Traces the message and exception at the Critical source level - to the trace source - - - - - - - - Traces the entry of the method - - - - - - - Traces the exit of the method - - - - - - - Traces the entry of the method - - - - - - - - - Traces the exit of the method - - - - - - - - - Concrete implementation of ILogFactory that creates trace sources - - - - - The default source name - - - - - The source level of the default tracer - - - - - The default instance - - - - - Keeps track of various TraceSources - - - - - Initializes an instance of the class - - - - - Returns the default instance - - An instance of - - - - Creates and returns an instance of - - The name of the TraceSource - - - - - A disposable object which opts-out of disposing the inner disposable - only when instructed by the caller. - - - - - - Inner disposable object. - - - - - Constructor which takes an inner disposable object. - - - - - - Used for notifying about disposable decision on inner object. - - - - - Disposes the inner object if DoNotDispose is set to false. - - - - - Gets the inner disposable object. - - - - - Cached representation of collection of mappings within shard map. - The items consist of a single point values. - - - - - Mappings organized by Key. - - - - - Constructs the mapper, notes the key type for lookups. - - Key type. - - - - Add or update a mapping in cache. - - Storage mapping object. - Policy to use for preexisting cache entries during update. - - - - Remove a mapping object from cache. - - Storage maping object. - - - - Looks up a mapping by key. - - Key value. - Storage mapping object. - Mapping object which has the key value. - - - - Get number of point mappings cached in this mapper. - - Number of cached point mappings. - - - - Clears all the mappings in the lookup by Id table as well - as lookup by key table. - - - - - Cached representation of collection of mappings within shard map. - Derived classes implement either list or range functionality. - - - - - Constructs the mapper, notes the key type for lookups. - - Key type. - - - - Key type, usable by lookups by key in derived classes. - - - - - Add or update a mapping in cache. - - Storage mapping object. - Policy to use for preexisting cache entries during update. - - - - Remove a mapping object from cache. - - Storage maping object. - - - - Looks up a mapping by key. - - Key value. - Storage mapping object. - Mapping object which has the key value. - - - - Gets mappings dictionary size. - - Number of mappings cached in the dictionary. - - - - Clears all the mappings in the lookup by Id table. - - - - - Given current value of TTL, calculates the next TTL value in milliseconds. - - Current cached mapping object. - New TTL value. - - - - Cached representation of a single mapping. - - - - - Time to live for the cache entry. - - - - - Constructs cached representation of a mapping object. - - Storage representation of mapping. - - - - Constructs cached representation of a mapping object. - - Storage representation of mapping. - Mapping expiration time. - - - - Storage representation of the mapping. - - - - - Mapping entry creation time. - - - - - Mapping entry expiration time. - - - - - Resets the mapping entry expiration time to 0. - - - - - Whether TimeToLiveMilliseconds have elapsed - since the CreationTime - - True if they have - - - - Encapsulates extension methods for CacheMappings - - - - - Resets the mapping entry expiration time to 0 if necessary - - - - - - Base class for all objects in the cache, providing locking facilities. - - - - - Lock object. - - - - - Whether this object has already been disposed - - - - - Instantiates the underlying lock object. - - - - - Obtains a read locking scope on the object. - - Whether the read lock should be upgradable. - Read locking scope. - - - - Obtains a write locking scope on the object. - - Write locking scope. - - - - Public dispose method. - - - - - Protected vitual member of the dispose pattern. - - Call came from Dispose. - - - - Cached representation of collection of mappings within shard map. - The items consist of a ranges of key values. - - - - - Mappings organized by Key Ranges. - - - - - Constructs the mapper, notes the key type for lookups. - - Key type. - - - - Add or update a mapping in cache. - - Storage mapping object. - Policy to use for preexisting cache entries during update. - - - - Remove a mapping object from cache. - - Storage maping object. - - Q: Do we ever need to remove multiple entries from the cache which cover the same range? - A: Yes. Imagine that you have some stale mapping in the cache, user just simply performs - an AddRangeMapping operation on a subset of stale mapping range, now you should remove the - stale mapping. - - - - - Looks up a mapping by key. - - Key value. - Storage mapping object. - Mapping object which has the key value. - - - - Get number of range mappings cached in this mapper. - - Number of cached range mappings. - - - - Clears all the mappings in the lookup by Id table as well - as lookup by range table. - - - - - Performs binary search on the cached mappings and returns the - index of mapping object which contains the given key. - - Input key. - Index of range in the cache which contains the given key. - - - - Performs binary search on the cached mappings and returns the - index of mapping object whose min-value is less than and closest - to given key value. - - Input key. - Index of range in the cache which contains the given key. - - - - Performs binary search on the cached mappings and returns the - index of mapping object whose min-value is less than and closest - to given key value. - - Input key. - Index of range in the cache which contains the given key. - - - - Cached representation of shard map. - - - - - Constructs the cached shard map. - - Storage representation of shard map. - - - - Storage representation of shard map. - - - - - Mapper object. Exists only for List/Range/Hash shard maps. - - - - - Performance counter instance for this shard map. - - - - - Transfers the child cache objects to current instance from the source instance. - Useful for mantaining the cache even in case of refreshes to shard map objects. - - Source cached shard map to copy child objects from. - - - - Increment value of performance counter by 1. - - Name of performance counter to increment. - - - - Set raw value of performance counter. - - Performance counter to update. - Raw value for the counter. - This method is always called from CacheStore inside csm.GetWriteLockScope() so we do not have to - worry about multithreaded access here. - - - - Protected vitual member of the dispose pattern. - - Call came from Dispose. - - - - Cached representation of shard map manager. - - - - - Contained shard maps. Look up to be done by name. - - - - - Contained shard maps. Lookup to be done by Id. - - - - - Constructs the cached shard map manager. - - - - - Adds a shard map to the cache given storage representation. - - Storage representation of shard map. - Cached shard map object. - - - - Removes shard map from cache given the name. - - Storage representation of shard map. - - - - Finds shard map in cache given the name. - - Name of shard map. - The found shard map object. - Cached shard map object. - - - - Finds shard map in cache given the name. - - Id of shard map. - Cached shard map object. - - - - Clears the cache of shard maps. - - - - - Client side cache store. - - - - - The Tracer - - - - - Root of the cache tree. - - - - - Constructs an instance of client side cache object. - - - - - Invoked for refreshing shard map in cache from store. - - Storage representation of shard map. - - - - Invoked for deleting shard map in cache becase it no longer exists in store. - - Storage representation of shard map. - - - - Looks up a given shard map in cache based on it's name. - - Name of shard map. - The shard being searched. - - - - Invoked for refreshing mapping in cache from store. - - Storage representation of mapping. - Policy to use for preexisting cache entries during update. - - - - Invoked for deleting mapping in cache becase it no longer exists in store. - - Storage representation of mapping. - - - - Looks up a given key in given shard map. - - Storage representation of shard map. - Key value. - Mapping corresponding to or null. - - - - Invoked for updating specified performance counter for a cached shard map object. - - Storage representation of a shard map. - Performance counter to increment. - - - - Clears the cache. - - - - - Public dispose method. - - - - - Protected vitual member of the dispose pattern. - - Call came from Dispose. - - - - Policy for AddOrUpdateMapping operation. - - - - - Overwrite the mapping blindly. - - - - - Keep the original mapping but change TTL. - - - - - Representation of client side cache. - - - - - Invoked for refreshing shard map in cache from store. - - Storage representation of shard map. - - - - Invoked for deleting shard map in cache becase it no longer exists in store. - - Storage representation of shard map. - - - - Looks up a given shard map in cache based on it's name. - - Name of shard map. - The shard being searched. - - - - Invoked for refreshing mapping in cache from store. - - Storage representation of mapping. - Policy to use for preexisting cache entries during update. - - - - Invoked for deleting mapping in cache becase it no longer exists in store. - - Storage representation of mapping. - - - - Looks up a given key in given shard map. - - Storage representation of shard map. - Key value. - Mapping corresponding to or null. - - - - Increment specified perf counter. - - Storage representation of shard map. - Performance counter to increment.s - - - - Clears the cache. - - - - - Represents a cache entry for a mapping. - - - - - Store representation of mapping. - - - - - Mapping entry creation time. - - - - - Mapping entry expiration time. - - - - - Resets the mapping entry expiration time to 0. - - - - - Whether TimeToLiveMilliseconds have elapsed - since CreationTime - - - - - - Shard management performance counter names. - - - - - Structure holding performance counter creation information - - - - - Class represenging single instance of a all performance counters in shard management catagory - - - - - Initialize perf counter instance based on shard map name - - - - - - Try to increment specified performance counter by 1 for current instance. - - Counter to increment. - - - - Try to update performance counter with speficied value. - - Counter to update. - New value. - - - - Static method to recreate Shard Management performance counter catagory with given counter list. - - - - - Check if caller has permissions to create performance counter catagory. - - If caller can create performance counter catagory - - - - Check if caller has permissions to create performance counter instance - - If caller can create performance counter instance. - - - - Dispose performance counter instance - - - - - Wrapper class around PerformanceCounter to catch and trace all exceptions. - - - - - Create and wrap performance counter object. - - Counter catatory. - Instance name to create. - Counter name to create. - - - - Close performance counter, if initialized earlier. Counter will be removed when we delete instance. - - - - - Increment counter value by 1. - - - - - Set raw value of this performance counter. - - Value to set. - - - - Log exceptions using Tracer - - Method name - Custom message - Exception to trace out - - - - Dispose performance counter. - - - - - Scope for a read lock. - - - - - The lock object on which read lock is held. - - - - - Whether upgrade of read lock is possible. - - - - - Acquires the read lock. - - Lock to be acquired. - Whether the lock is upgradable. - - - - Upgrade the read lock to a write lock. - - - - - - Exits the locking scope. - - - - - Scope for a write lock. - - - - - The lock object on which read lock is held. - - - - - Acquires the write lock. - - Lock to be acquired. - - - - Exits the locking scope. - - - - - A strongly-typed resource class, for looking up localized strings, etc. - - - - - Returns the cached ResourceManager instance used by this class. - - - - - Overrides the current thread's CurrentUICulture property for all - resource lookups using this strongly typed resource class. - - - - - Looks up a localized string similar to Unsupport value '{0}' specified for parameter '{1}'.. - - - - - Looks up a localized string similar to The specified ShardRange {0} was not in the set of ShardRanges from which the local shardmap information can be rebuilt at location '{1}'.. - - - - - Looks up a localized string similar to Recovery token {0} was not recognized.. - - - - - Looks up a localized string similar to The given location '{0}' does not have the necessary storage structures present for a shard. Error occurred while performing operation '{1}'.. - - - - - Looks up a localized string similar to The SchemaInfo object already contains a {0} table by the given name of [{1}].[{2}].. - - - - - Looks up a localized string similar to Shard '{0}' provided for the given '{1}' is not associated with current shard map '{2}'. The '{3}' operations required the shard to be associated with the current shard map.. - - - - - Looks up a localized string similar to Shard '{0}' provided for the given '{1}' is not associated with current shard map manager at '{2}'. The '{3}' operations required the shard to be associated with the current shard map manager.. - - - - - Looks up a localized string similar to Shard key has maximum value which cannot be incremented. Perform the IsMax check on shard key before requesting next key.. - - - - - Looks up a localized string similar to Shard key has maximum value which cannot be represented. Perform the IsMax check on shard key before requesting a conversion.. - - - - - Looks up a localized string similar to The requested type '{0}' does not match the shard key type '{1}'.. - - - - - Looks up a localized string similar to The data type of the shard key '{0}' does not match the data type of comparand shard key '{1}'. Comparison is only supported for shard keys with same type.. - - - - - Looks up a localized string similar to The specified ShardKeyType specified is not supported. . - - - - - Looks up a localized string similar to Type not supported for shard keys.. - - - - - Looks up a localized string similar to The given value is of type '{0}' which is an unsupported shard key type.. - - - - - Looks up a localized string similar to The type of specified value does not match the type specified in the '{0}' parameter.. - - - - - Looks up a localized string similar to The length of raw value specified for the shard key ({0} bytes) does not match the expected length ({1} bytes) for the ShardKeyType ({2}) specified.. - - - - - Looks up a localized string similar to The given port number '{0}' is invalid.. - - - - - Looks up a localized string similar to The given '{0}' name is longer than the allowed length of '{1}' characters.. - - - - - Looks up a localized string similar to The given protocol value '{0}' is not supported.. - - - - - Looks up a localized string similar to Shard corresponding to location '{0}' could not be found in shard map '{1}' .. - - - - - Looks up a localized string similar to Property '{0}' must not be set in the input connection string for 'OpenConnection' operations.. - - - - - Looks up a localized string similar to Key values of type '{0}' are not supported. OpenConnectionForKey requests for the shard map '{1}' requires keys of type '{2}'.. - - - - - Looks up a localized string similar to Shard map '{0}' can not be converted to the target type {1}ShardMap<{2}>. Its actual type is {3}ShardMap<{4}>.. - - - - - Looks up a localized string similar to Shard map '{0}' is not associated with the current instance of shard map manager at '{1}'. Only shard maps that are obtained from the same 'ShardMapManager' instance can be used.. - - - - - Looks up a localized string similar to Shard map '{0}' could not be found in the shard map manager store at '{1}'.. - - - - - Looks up a localized string similar to Shard map name '{0}' is not supported. Shard map names are only allowed to contain unicode letters and digits.. - - - - - Looks up a localized string similar to Length of shard map name '{0}' exceeds the maximum allowed length of '{1}' characters.. - - - - - Looks up a localized string similar to '{0}' provided for operation '{1}' is not associated with the current shard map '{2}'. Only mappings associated with the same shard map as the given shard map can be used. Error occurred for parameter '{3}'.. - - - - - Looks up a localized string similar to '{0}' provided for operation '{1}' is not associated with the current instance of shard map manager at '{2}'. Only mappings associated with the same 'ShardMapManager' instance as the the one associated with current shard map '{3}' can be used. Error occurred for parameter '{4}'.. - - - - - Looks up a localized string similar to Mappings provided for the Merge operation belonging to shard map '{0}' differ in their Status property. Merge operation is only allowed for mappings with same values for Status.. - - - - - Looks up a localized string similar to LockId for locking the mapping referencing shard {0} with shard map name {1} has unsupported value '{2}'.. - - - - - Looks up a localized string similar to Mappings provided for the merge operation which belong to shard map '{0}' belong to different shards '{1}' and '{2}'. Merge operation is only allowed for mappings belonging to the same shard.. - - - - - Looks up a localized string similar to Mappings provided for the merge operation are not adjacent. Merge operation is only allowed for adjacent mappings.. - - - - - Looks up a localized string similar to Requested range is exactly the range for existing mapping. Operation is only allowed for proper subsets of existing range.. - - - - - Looks up a localized string similar to Requested range is not a subset of the existing range mapping.. - - - - - Looks up a localized string similar to Split point lies on the boundary or outside of the specified range mapping.. - - - - - Looks up a localized string similar to The low value {0} is greater than or equal to the high value {1}. Lower value must be less than the higher value.. - - - - - Looks up a localized string similar to The required property '{0}' must be set in the connection string.. - - - - - Looks up a localized string similar to All required parameters for operation '{0}' are not supplied. Error occurred while executing procedure '{1}' on the shard map manager database. Please verify and match library and store version.. - - - - - Looks up a localized string similar to All required parameters for operation '{0}' at shard '{1}' are not supplied. Error occurred while executing procedure '{2}' on the shard. Please verify and match library and store version.. - - - - - Looks up a localized string similar to Unable to create schema info with name '{0}' as there is already an entry with the same name.. - - - - - Looks up a localized string similar to Unable to {0} schema info with name '{1}' since there is no entry by the given name.. - - - - - Looks up a localized string similar to Shard '{0}' already exists in store for shard map '{1}'. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen when another concurrent user adds the shard to the store.. - - - - - Looks up a localized string similar to Shard '{0}' belonging to shard map '{1}' could not be found in the shard map manager database. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen when another concurrent user removes the shard from the store.. - - - - - Looks up a localized string similar to Shard '{0}' belonging to shard map '{1}' has mappings associated with it. Error occurred while executing stored procedure '{2}' for operation '{3}'. Remove all the mappings associated with the shard before attempting the operation.. - - - - - Looks up a localized string similar to Shard referecing location '{0}' already exists in store for shard map '{1}'. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen when another concurrent user has added a shard with specified location in store.. - - - - - Looks up a localized string similar to Shard '{0}' belonging to shard map '{1}' has been updated in store. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can occur if another concurrent user updates the shard. Perform a GetShard operation for the shard location to obtain the updated instance.. - - - - - Looks up a localized string similar to Shard map with name '{0}' already exists in the store. Error occurred while executing stored procedure '{1}' for operation '{2}'.. - - - - - Looks up a localized string similar to Shard map '{0}' has shards associated with it. Shard maps can only be removed if there are no shards associated with them. Error occurred while executing stored procedure '{1}' for operation '{2}'.. - - - - - Looks up a localized string similar to Shard map '{0}' does not exist in the store. Error occurred while executing stored procedure '{1}' for operation '{2}' for shard '{3}'. This can happen if another concurrent user deletes the shard map.. - - - - - Looks up a localized string similar to Shard map '{0}' does not exist on shard '{1}'. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen if another concurrent user deletes the shard map.. - - - - - Looks up a localized string similar to Data structures for shard map manager persistence already exists at the target location.. - - - - - Looks up a localized string similar to Data structures for shard map manager persistence do not exist at the target location.. - - - - - Looks up a localized string similar to Mapping referencing shard '{0}' belonging to shard map '{1}' is already locked. Error occurred while executing procedure '{2}' for operation '{3}' on the shard map manager database. This can happen if another concurrent user locks the mapping.. - - - - - Looks up a localized string similar to Mapping referencing shard '{0}' belonging to shard map '{1}' is locked and correct lock token is not provided. Error occurred while executing procedure '{2}' for operation '{3}' on the shard map manager database. This can happen if another concurrent user locks the mapping.. - - - - - Looks up a localized string similar to Mapping referencing shard '{0}' in the shard map '{1}' does not exist. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can occur if another concurrent user has already removed the mapping.. - - - - - Looks up a localized string similar to Mapping referencing shard '{0}' in the shard map '{1}' has 'Online' status. Error occurred while executing stored procedure '{2}' for operation '{3}'. Updates to a mapping involving modification of the shard location or removal require the mapping to be 'Offline'. . - - - - - Looks up a localized string similar to Mapping containing the given key value could not be located in the shard map '{0}'. Error occurred while executing stored procedure '{1}' for operation '{2}'.. - - - - - Looks up a localized string similar to Mapping referencing shard '{0}' in the shard map '{1}' cannot be added because the {2} it covers is already mapped by another mapping. Error occurred while executing stored procedure '{3}' for operation '{4}'. This can occur if another concurrent user has already added a mapping covering the given {2}.. - - - - - Looks up a localized string similar to Mapping referencing shard '{0}' belonging to shard map '{1}' could not be taken offline because all existing connections on the shard could not be terminated. Error occurred during '{2}' operation while executing stored procedure '{3}' on shard '{4}'.. - - - - - Looks up a localized string similar to Store Error: {0}. The error occurred while attempting to perform the underlying storage operation during '{1}' operation on the shard map manager database. See the inner StoreException for details.. - - - - - Looks up a localized string similar to Store Error: {0}. The error occurred while attempting to perform the underlying storage operation during '{1}' operation on shard '{2}'. See the inner StoreException for details.. - - - - - Looks up a localized string similar to Exclusive access to application resource '{0}' could not be acquired.. - - - - - Looks up a localized string similar to Exclusive access to application resource '{0}' could not be released.. - - - - - Looks up a localized string similar to Error occurred while performing store operation. See the inner SqlException for details.. - - - - - Looks up a localized string similar to Unexpected error code found while processing errors returned from the shard map manager store. This can occur because of a defect in the client library.. - - - - - Looks up a localized string similar to Unexpected error code found while processing errors returned from the shard location '{0}'. This can occur because of a defect in the client library.. - - - - - Looks up a localized string similar to Shard map manager store version '{0}' is not compatible with the version '{1}' supported by client library. Please upgrade the {2}.. - - - - - Looks up a localized string similar to Shard map manager store version '{0}' at shard '{1}' is not compatible with the version '{2}' supported by client library. Please upgrade the {3}.. - - - - - Looks up a localized string similar to Mapping referencing shard '{0}' associated with shard map '{1}' no longer exists in store. Error occurred while executing stored procedure '{2}' for operation '{3}' on the shard. This can happen if another concurrent user has deleted or modified the mapping.. - - - - - Looks up a localized string similar to The shard key value for an OpenConnection request is associated with a mapping that is marked ‘Offline’. Data containing this key value is likely being moved, and the connection is blocked to avoid data corruption. Validated connection requests for this shardlet will succeed when the mapping is back ‘Online’. Shard: '{0}'. Shard map: '{1}'. Error occurred while executing stored procedure '{3}' for operation '{2}' on the shard.. - - - - - Looks up a localized string similar to Shard '{0}' belonging to shard map '{1}' no longer exists in store. Error occurred while executing stored procedure '{2}' for operation '{3}' on the shard. This can happen if another concurrent user deletes the shard. . - - - - - Looks up a localized string similar to Shard map '{0}' associated with shard '{1}' no longer exists in store. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen if another concurrent user deletes the shard map.. - - - - - Looks up a localized string similar to Shard '{0}' belonging to shard map '{1}' has been modified in the store. Error occurred while executing stored procedure '{2}' for operation '{3}' on the shard. This can happen if another concurrent user performs modification operations on the shard or its associated mappings.. - - - - - Simple class that encapsulates an ILogger and - allows for custom tracing over an ILogger - - - - - The ILogger for the ShardMapManager - - - - - Helper to trace at the Verbose TraceLevel to the ILogger - - The logger - The component name - The method name - The formatted message - The args - - - - /// Helper to trace at the Information TraceLevel to the ILogger - - The logger - The component name - The method name - The formatted message - The args - - - - Helper to trace at the Warning TraceLevel to the ILogger - - The logger - The component name - The method name - The formatted message - The args - - - - Helper to trace at the Error TraceLevel to the ILogger - - The logger - The component name - The method name - The formatted message - The args - - - - Encapsulates various constants related to TraceSource - - - - - The TraceSource name for the ShardMapManager library - - - - - Component names to use while tracing - - - - - The ShardMapManagerFactory component name - - - - - The ShardMapManager component name - - - - - The ShardMap component name - - - - - The ListShardMap component name - - - - - The RangeShardMap component name - - - - - The DefaultShardMapper component name - - - - - The BaseShardMapper name - - - - - The ListShardMaper name - - - - - The RangeShardMapper name - - - - - The SqlStore component name - - - - - The Cache component name - - - - - The Shard Component name - - - - - The PointMapping component name - - - - - The RangeMapping component name - - - - - The performance counter component name - - - - - A strongly-typed resource class, for looking up localized strings, etc. - - - - - Returns the cached ResourceManager instance used by this class. - - - - - Overrides the current thread's CurrentUICulture property for all - resource lookups using this strongly typed resource class. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Reads from shard map manager version information table if it exists. - --------------------------------------------------------------------------------------------------- - - declare @stmt varchar(128) - if object_id(N'__ShardManagement.ShardMapManagerGlobal', N'U [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Reads from shard map manager version information table if it exists. - --------------------------------------------------------------------------------------------------- - - declare @stmt varchar(128) - if object_id(N'__ShardManagement.ShardMapManagerLocal', N'U' [rest of string was truncated]";. - - - - - A strongly-typed resource class, for looking up localized strings, etc. - - - - - Returns the cached ResourceManager instance used by this class. - - - - - Overrides the current thread's CurrentUICulture property for all - resource lookups using this strongly typed resource class. - - - - - Looks up a localized string similar to DDR operations/sec. - - - - - Looks up a localized string similar to Rate of data dependent routing (DDR) operations for this shard map. - - - - - Looks up a localized string similar to Mappings added or updated in cache/sec. - - - - - Looks up a localized string similar to Rate at which mappings are being added or updated in cache for this shard map. - - - - - Looks up a localized string similar to Cached mappings. - - - - - Looks up a localized string similar to Number of mappings cached for this shard map. - - - - - Looks up a localized string similar to Mapping lookup cache misses/sec. - - - - - Looks up a localized string similar to Rate of failed cache lookup operations for mappings in this shard map. - - - - - Looks up a localized string similar to Mapping lookup cache hits/sec. - - - - - Looks up a localized string similar to Rate of successful cache lookup operations for mappings in this shard map. - - - - - Looks up a localized string similar to Mappings removed from cache/sec. - - - - - Looks up a localized string similar to Rate at which mappings are being removed from cache for this shard map. - - - - - Looks up a localized string similar to Performance Monitor Users. - - - - - Looks up a localized string similar to Elastic Database: Shard Management. - - - - - Looks up a localized string similar to Performance counters for tracking shard management operations and caching. - - - - - Repesents a table in a database. - - - - - Table's schema name. - - - - - Table name. - - - - - Provides storage services to a client for storing\updating\retrieving schema information associated with a sharding scheme - and assigning names to individual buckets of information. The class doesn't store the association between a sharding scheme - and the metadata unit. It's the caller's responsibility to maintain the mapping. - - - - - Constructs an instance of schema info collection. - - Shard map manager object. - - - - Shard map manager object. - - - - - Adds a that is associated with the given name. - The associated data contains information concerning sharded tables and - reference tables. If you try to add a with an existing name, - a name-conflict exception will be thrown - - The name of the that - the will be associated with - Sharding schema information. - - - - Replaces the with the given name. - - The name of the whose will be replaced. - Sharding schema information. - - - - Tries to fetch the with the given name without - raising any exception if data doesn't exist. - - The name of the whose - will be fetched - The that was fetched or null if retrieval failed - true if schema info exists with given name, false otherwise. - - - - Fetches the stored with the supplied name. - - The name of the to get. - SchemaInfo object. - - - - Removes the with the given name. - - The name of the whose - will be removed - - - - Returns an enumerator that iterates through the . - - Enumerator of key-value pairs of name and objects. - - - - Returns an enumerator that iterates through this . - - Enumerator of key-value pairs of name and objects. - - - - Possible errors encountered by SchemaInfoCollection. - - - - - No exists with the given name. - - - - - A entry with the given name already exists. - - - - - An entry for the given table already exists in the object. - - - - - The exception that is thrown when an error occurs during operations related to schema info collection. - - - - - Initializes a new instance. - - - - - Initializes a new instance with a specified error message. - - Error message. - - - - Initializes a new instance with a specified formatted error message. - - The format message that describes the error. - The arguments to the format string. - - - - Initializes a new instance with a specified error message and a reference to the inner exception - that caused this exception. - - A message that describes the error. - The exception that is the cause of the current exception. - - - - Initializes a new instance with a specified formatted error message. - - Error code. - The format message that describes the error - The arguments to the format string - - - - Initializes a new instance with a specified error message and a reference to the inner exception - that is the cause of this exception. - - Error code. - A message that describes the error - The exception that is the cause of the current exception - - - - Initializes a new instance with serialized data. - - The object that holds the serialized object data - The contextual information about the source or destination - - - - Populates a SerializationInfo with the data needed to serialize the target object. - - The SerializationInfo to populate with data. - The destination (see StreamingContext) for this serialization. - - - - Error code. - - - - - Represents information about a single sharded table. - - - - - Name of the shard key column. - - - - - Initializes a new instance of the class. - - Sharded table name. - Shard key column name. - - - - Initializes a new instance of the class. - - Schema name of the sharded table. - Sharded table name. - Shard key column name. - - - - Determines whether the specified ShardedTableInfo object is equal to the current object. - - The ShardedTableInfo object to compare with the current object. - true if the specified ShardedTableInfo object is equal to the current object; otherwise, false. - - - - Overrides the Equals() method of Object class. Determines whether the specified object - is equal to the current object. - - The object to compare with the current ShardedTableInfo object. - true if the specified object is equal to the current ShardedTableInfo object; otherwise, false. - - - - Calculates the hash code for this instance. - - Hash code for the object. - - - - Represents information about a single reference table. - - - - - Initializes a new instance of the class. - - Reference table name. - - - - Initializes a new instance of the class. - - Schema name of the reference table. - Reference table name. - - - - Determines whether the specified ReferenceTableInfo object is equal to the current object. - - The ReferenceTableInfo object to compare with the current object. - true if the specified ReferenceTableInfo object is equal to the current object; otherwise, false. - - - - Overrides the Equals() method of Object class. Determines whether the specified object - is equal to the current object. - - The object to compare with the current ReferenceTableInfo object. - true if the specified object is equal to the current ReferenceTableInfo object; otherwise, false. - - - - Calculates the hash code for this instance. - - Hash code for the object. - - - - Represents information identifying the list of sharded tables and the list of reference - tables associated with a sharding scheme. Reference tables are replicated across shards. - This class is thread safe. - - - - - This is the list of sharded tables in the sharding schema along with their - sharding key column names. - - - - - EDCL v1.1.0 accidentally emitted the "ShardedTableSet" DataMember with the name "_shardedTableSet". - This DataMember allows us to easily deserialize this incorrectly named field without needing - to write custom deserialization logic. - - - - - This is the list of reference tables in the sharding scheme. - - - - - EDCL v1.1.0 accidentally emitted the "ReferenceTableSet" DataMember with the name "_referenceTableSet". - This DataMember allows us to easily deserialize this incorrectly named field without needing - to write custom deserialization logic. - - - - - Synchronization object used when adding table entries to the current - object. - - - - - Read-only list of information concerning all sharded tables. - - - - - Read-only list of information concerning all reference tables. - - - - - Initialize any non-DataMember objects post deserialization. - - - - - Initializes this instance after construction or deserialization. - - - - - Initializes a new instance of the class. - - - - - Adds information about a sharded table. - - Sharded table info. - - - - Adds information about a reference table. - - Reference table info. - - - - Removes information about a sharded table. - - Sharded table info. - - - - Removes information about a reference table. - - Reference table info. - - - - Check is either a sharded table or a reference table exists by the given name. - - Sharded or reference table info. - sharded, reference or null. - - - - - Class for mapping differences. - - - - - Type of mapping difference. Either List or Range. - - - - - Location where the mappings that differ exist. - - - - - ShardMap which has the consistency violation. - - - - - Mapping found in shard map. - - - - - Mapping found in shard. - - - - - Type of mapping difference. Useful for downcasting. - - - - - Violation associated with ListShardMap. - - - - - Violation associated with RangeShardMap. - - - - - Location where the different mappings exist. - - - - - Mapping is present in global store, but absent on the shard. - - - - - Mapping is absent in global store, but present on the shard. - - - - - Mapping present at both global store and shard. - - - - - Resolution strategy for resolving mapping differences. - - - - - Ignore the difference for now. - - - - - Use the mapping present in shard map. - - - - - Use the mapping in the shard. - - - - - Contains utility methods for performing comparisons among collections of - mappings of either list or range shard maps. - - - - - Helper function that produces a list of MappingComparisonResults from union of range boundaries in the gsmMappings and lsmMappings. - - StoreShardmap to be referenced in produced MappingComparisonResults - List of mappings from the GSM. - List of mappings from the LSM. - List of mappingcomparisonresults: one for each range arising from the union of boundaries in gsmMappings and lsmMappings. - - - - Helper function that produces a list of MappingComparisonResults from union of points in the gsmMappings and lsmMappings. - - StoreShardmap to be referenced in produced MappingComparisonResults - List of mappings from the GSM. - List of mappings from the LSM. - List of mappingcomparisonresults: one for each range arising from the union of boundaries in gsmMappings and lsmMappings. - - - - Helper function to advance mapping iterators. - - The iterator to advance. - The data type of the map key. - Output value that will contain next mapping. - Output value that will contain next range. - Output value that will contain next min key. - - - - Result of comparison b/w the given range mappings. - - - - - Instantiates a new instance of range mapping comparison result. - - Store representation of shard map. - Range being considered. - Location of mapping. - Storage representation of GSM mapping. - Storange representation of LSM mapping. - - - - Shard map to which mappings belong. - - - - - Current range. - - - - - Location of the mapping. - - - - - Mappings corresponding to current range in GSM. - - - - - Mapping corresponding to current range in LSM. - - - - - Manages various recovery related tasks for a shard map manager. It helps - resolving data corruption issues between shard map information stored - locally on the shards and in the global shard map manager database. - It also helps with certain 'oops' recovery scenarios where reconstruction - of shard maps from database backups or database copies is necessary. - - - Note that some of the recovery methods can cause unrecoverable data loss when not used - properly. It is recommend to take backups or copies of all databases that participate - in recovery operations. - - - - - Constructs an instance of the recovery manager for given shard map manager. - - Shard map manager being recovered. - - - - Cached list of inconsistencies so user can resolve without knowing the data format. - - - - - Cached list of IStoreShardMaps so user can reconstruct shards based on a token. - - - - - Cached list of ShardLocations so user can determine Shardlocation based on a token. - - - - - Reference to the associated shard map manager. - - - - - Attaches a shard to the shard map manager. Earlier versions - of mappings for the same shard map will automatically be updated - if more recent versions are found on the shard to be attached. - After attaching a shard, - should be called to check for any inconsistencies that warrant - manual conflict resolution. - - Location of the shard being attached. - - Note that this method can cause unrecoverable data loss. Make sure you have taken backups or copies - of your databases and only then proceed with great care. - - - - - Attaches a shard to the shard map manager. Earlier versions - of mappings for the same shard map will automatically be updated - if more recent versions are found on the shard to be attached. - Shard location will be upgraded to latest version of local store as part of this operation. - After attaching a shard, - should be called to check for any inconsistencies that warrant - manual conflict resolution. - - Location of the shard being attached. - Optional string to filter on the shard map name. - - Note that this method can cause unrecoverable data loss. Make sure you have taken backups or copies - of your databases and only then proceed with great care. - - - - - Detaches the given shard from the shard map manager. Mappings pointing to the - shard to be deleted will automatically be removed by this method. - - Location of the shard being detached. - - Note that this method can cause unrecoverable data loss. Make sure you have taken backups or copies - of your databases and only then proceed with great care. - - - - - Detaches the given shard from the shard map manager. Mappings pointing to the - shard to be deleted will automatically be removed by this method. - - Location of the shard being detached. - Optional string to filter on shard map name. - - Note that this method can cause unrecoverable data loss. Make sure you have taken backups or copies - of your databases and only then proceed with great care. - - - - - Returns a dictionary of range-to-location key-value pairs. The location returned is an enumerator stating - whether a given range (or point) is present only in the local shard map, only in the global shard map, or both. - Ranges not contained in either shard map cannot contain differences so those ranges are not shown. - - Recovery token returned from . - The set of ranges and their corresponding . - - This method assumes a previous call to that provides the recovery token parameter. - The result of this method is typically used in subsequent calls to resolve inconsistencies such as - or . - - - - - Retrieves shard map type, name and shard location based on the token returned from . - - Recovery token returned from . - Outputs shard map type (Range or List). - Outputs shard map name. - Outputs shard location - - - - Retrieves shard map type and name based on the token returned from . - - Recovery token returned from . - Output Shardmap type (Range or List). - Output name of shard map. - - - - Returns the shard map type of the shard map processed by . - - Recovery token returned from . - The type of shard map (list, range, etc...) corresponding to the recovery token. - - - - Returns the shard map name of the shard map processed by . - - Recovery token returned from . - The name of the shard map for the given recovery token. - - - - Returns the shard location of the local shard map processed by . - - Recovery token returned from - Location of the shard corresponding to the set of mapping differences detected in . - - - - Given a collection of shard locations, reconstructs local shard maps based - on the mapping information stored in the global shard map. The specified - shards need to be registered already in the global shard map. This method only - rebuilds mappings. It does not rebuild shard membership within the global shard map. - - Collection of shard locations. - - Note that this method can cause unrecoverable data loss. Make sure you have taken backups or copies - of your databases and only then proceed with great care. - - - - - Given a collection of shard locations, reconstructs local shard maps based - on the mapping information stored in the global shard map. The specified - shards need to be registered already in the global shard map. This method only - rebuilds mappings. It does not rebuild shard membership within the global shard map. - - Collection of shard locations. - Optional parameter to filter by shard map name. If omitted, all shard maps will be rebuilt. - - Note that this method can cause unrecoverable data loss. Make sure you have taken backups or copies - of your databases and only then proceed with great care. - - - - - Given a collection of shard locations, reconstructs the shard map manager based on mapping information - stored in the individual shards. The specified - shards need to be registered already in the global shard map. This method only - rebuilds mappings. It does not rebuild shard membership within the global shard map. - If the information in the individual shard maps is or becomes inconsistent, the behavior is undefined. - No cross shard locks are taken, so if any shards become inconsistent during the execution of this - method, the final state of the global shard map may be corrupt. - - Collection of shard locations. - - Note that this method can cause unrecoverable data loss. Make sure you have taken backups or copies - of your databases and only then proceed with great care. - - - - - Given a collection of shard locations, reconstructs the shard map manager based on mapping information - stored in the individual shards. The specified - shards need to be registered already in the global shard map. This method only - rebuilds mappings. It does not rebuild shard membership within the global shard map. - If the information in the individual shard maps is or becomes inconsistent, the behavior is undefined. - No cross shard locks are taken, so if any shards become inconsistent during the execution of this - method, the final state of the global shard map may be corrupt. - - Collection of shard locations. - Optional name of shard map. If omitted, will attempt to recover from all shard maps present on each shard. - - Note that this method can cause unrecoverable data loss. Make sure you have taken backups or copies - of your databases and only then proceed with great care. - - - - - Rebuilds a local range shard map from a list of inconsistent shard ranges - detected by and then accessed by . - The resulting local range shard map will always still be inconsistent with - the global shard map in the shard map manager database. A subsequent call to - is necessary to bring the system back to a healthy state. - - The recovery token from a previous call to . - The set of ranges to keep on the local shard when rebuilding the local shard map. - - Note that this method can cause unrecoverable data loss. Make sure you have taken backups or copies - of your databases and only then proceed with great care. - - Only shard ranges with inconsistencies can be rebuilt using this method. All ranges with no inconsistencies between - the local shard and the global shard map will be kept intact on the local shard and are not affected by this call. - Subsequent changes to the non-conflicting mappings can be made later using the regular interfaces in the shard map manager. - It is not necessary to use the recovery manager to change non-conflicting mappings. - - - - - Enumerates differences in the mappings between the global shard map manager database and the local shard - database in the specified shard location. - - Location of shard for which to detect inconsistencies. - Collection of tokens to be used for further resolution tasks (see ). - - - - Enumerates differences in the mappings between the global shard map manager database and the local shard - database in the specified shard location. - - Location of shard for which to detect inconsistencies. - Optional parameter to specify a particular shard map. - Collection of tokens to be used for further resolution tasks (see ). - - - - Selects one of the shard maps (either local or global) as a source of truth and brings - mappings on both shard maps in sync. - - Recovery token returned from . - The resolution strategy to be used for resolution. - - Note that this method can cause unrecoverable data loss. Make sure you have taken backups or copies - of your databases and only then proceed with great care. - - - - - Given a collection of shard locations, reconstructs the shard map manager based on information - stored in the individual shards. - If the information in the individual shard maps is or becomes inconsistent, behavior is undefined. - No cross shard locks are taken, so if any shards become inconsistent during the execution of this - method, the final state of the global shard map may be corrupt. - - Operation name. - Collection of shard locations. - Strategy for resolving the mapping differences. - Optional name of shard map. If omitted, will attempt to recover from all shard maps present on each shard. - - - - Attaches a shard to the shard map manager. - - Token from DetectMappingDifferences. - - - - Helper function to bring a Shard into a consistent state with a ShardMap. - - Token from DetectMappingDifferences - - - - Helper function to obtain a store shard object from given recovery token. - - Operation name. - Token from DetectMappingDifferences. - Reference to store shard map corresponding to the token. - Store shard object corresponding to given token, or null if shard map is default shard map. - - - - Recovery token generated and used by methods of the - to perform conflict detection and resolution for shard maps. - - - - - Parameterless constructor to generate a new unique token for shard map conflict detection and resolution. - - - - - Internal Guid for this token. - - - - - Converts the object to its string representation. - - String representation of the object. - - - - Calculates the hash code for this instance. - - Hash code for the object. - - - - Determines whether the specified Object is equal to the current Object. - - The object to compare with the current object. - True if the specified object is equal to the current object; otherwise, false. - - - - Performs equality comparison with another given RecoveryToken. - - RecoveryToken to compare with. - True if same locations, false otherwise. - - - - A strongly-typed resource class, for looking up localized strings, etc. - - - - - Returns the cached ResourceManager instance used by this class. - - - - - Overrides the current thread's CurrentUICulture property for all - resource lookups using this strongly typed resource class. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Schema - --------------------------------------------------------------------------------------------------- - if schema_id('__ShardManagement') is null - begin - exec sp_executesql N'create schema __ShardManagement' - end - go - - --------------------------------------- [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Schema - --------------------------------------------------------------------------------------------------- - if schema_id('__ShardManagement') is null - begin - exec sp_executesql N'create schema __ShardManagement' - end - go - - --------------------------------------- [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Stored Procedures - --------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------- - -- Recovery - --------------------------- [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Stored Procedures - --------------------------------------------------------------------------------------------------- - - --------------------------------------------------------------------------------------------------- - -- Shard Mappings - -------------------- [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Script to upgrade Global Shard Map from version 0.0 to 1.0 - --------------------------------------------------------------------------------------------------- - - -- add a column to ShardMapManagerGlobal table to hold SCH-M lock during upgrade - alter table __Sh [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Script to upgrade Global Shard Map from version 1.0 to 1.1 - --------------------------------------------------------------------------------------------------- - - -- drop ShardMapManagerGlobal table - drop table __ShardManagement.ShardMapManagerGlobal - - -- creat [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Script to upgrade Global Shard Map from version 1.1 to 1.2 - -- Fix for VSTS# 3410606 - --------------------------------------------------------------------------------------------------- - - -- drop extra objects from version 1.1 - - if object_id(N'__ShardManagement [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Script to upgrade Global Shard Map from version 1000.0 to 1000.1 - --------------------------------------------------------------------------------------------------- - - -- drop extra column from ShardMapManagerGlobal table which was added as first step to hold [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Script to upgrade Local Shard Map from version 0.0 to 1.0 - --------------------------------------------------------------------------------------------------- - - -- add a column to ShardMapManagerLocal table to hold SCH-M lock during upgrade - alter table __Shar [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Script to upgrade Local Shard Map from version 1.0 to 1.1 - --------------------------------------------------------------------------------------------------- - - -- drop ShardMapManagerLocal table - drop table __ShardManagement.ShardMapManagerLocal - - -- create S [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Script to upgrade Local Shard Map from version 1.1 to 1.2 - --------------------------------------------------------------------------------------------------- - - -- drop extra objects from version 1.1 - - if object_id(N'__ShardManagement.spUpdateShardLocal', N'P' [rest of string was truncated]";. - - - - - Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - -- Licensed under the MIT license. See LICENSE file in the project root for full license information. - - --------------------------------------------------------------------------------------------------- - -- Script to upgrade Local Shard Map from version 1000.0 to 1000.1 - --------------------------------------------------------------------------------------------------- - - -- drop extra column from ShardMapManagerLocal table which was added as first step to hold S [rest of string was truncated]";. - - - - - Represents error codes related to operations. - - - - - Successful execution. - - - - - Store already exists on target shard map manager database. - - - - - Store does not exist on target shard map manager database. - - - - - Shardmap with specified name already exists. - - - - - Shardmap with specified name not found. - - - - - Shardmap has shards associated with it. - - - - - GSM store version does not match with client library. - - - - - LSM store version does not match with client library. - - - - - All necessary parameters for GSM stored procedure are not supplied. - - - - - All necessary parameters for LSM stored procedure are not supplied. - - - - - Conversion of shard map failed. - - - - - Shard has mappings associated with it. - - - - - Shard already exists. - - - - - Shard location already exists. - - - - - Shard has been updated by concurrent user. - - - - - Given point is already associated with a mapping. - - - - - Specified range is already associated with a mapping. - - - - - Storage operation failed. - - - - - Shardmap does not exist any more. - - - - - Shard does not exist any more. - - - - - An application lock could not be acquired. - - - - - An application lock cound not be released. - - - - - An unexpected error has occurred. - - - - - Specified mapping no longer exists. - - - - - Could not locate a mapping corresponding to given key. - - - - - Specified mapping is offline. - - - - - Could not terminate connections associated with the Specified mapping. - - - - - Specified mapping is not offline which certain management operations warrant. - - - - - Specified mapping is locked and the given lock owner id does not match - the owner id in the store - - - - - Specified mapping has already been locked - - - - - Shard does not have storage structures. - - - - - Represents error categories related to Shard Management operations. - - - - - Shardmap manager factory. - - - - - Shardmap manager. - - - - - Shardmap. - - - - - List shard map. - - - - - Range shard map. - - - - - Version validation. - - - - - Recovery oriented errors. - - - - - Errors related to Schema Info Collection. - - - - - General failure category. - - - - - Representation of exceptions that occur during storage operations. - - - - - Initializes a new instance with a specified error message. - - Category of error. - Error code. - Error message. - - - - Initializes a new instance with a specified formatted error message. - - Category of error. - Error code. - The format message that describes the error - The arguments to the format string - - - - Initializes a new instance with a specified error message and a reference to the inner exception - that is the cause of this exception. - - Category of error. - Error code. - A message that describes the error - The exception that is the cause of the current exception - - - - Initializes a new instance with a specified formatted error message and a reference to the - inner exception that is the cause of this exception. - - Category of error. - Error code. - The format message that describes the error - The exception that is the cause of the current exception - The arguments to the format string - - - - Initializes a new instance with serialized data. - - The object that holds the serialized object data - The contextual information about the source or destination - - - - Populates a SerializationInfo with the data needed to serialize the target object. - - The SerializationInfo to populate with data. - The destination (see StreamingContext) for this serialization. - - - - Error category. - - - - - Error code. - - - - - Provides the transient error detection logic for transient faults that are specific to Shard map manager. - - - - - Delegate used for detecting transient faults. - - - - - Creates a new instance of transient error detection strategy for Shard map manager. - - User specified retry behavior. - - - - Determines whether the specified exception represents a transient failure that can be compensated by a retry. - - The exception object to be verified. - true if the specified exception is considered as transient; otherwise, false. - - - - Status of a mapping. - - - - - Mapping is Offline. - - - - - Mapping is Online. - - - - - Status of a shard. - - - - - Shard is Offline. - - - - - Shard is Online. - - - - - Instance of a Sql Store Connection. - - - - - Underlying SQL connection object. - - - - - Constructs an instance of Sql Store Connection. - - Type of store connection. - - - - - Type of store connection. - - - - - Open the store connection. - - - - - Asynchronously open the store connection. - - A task to await completion of the Open - - - - Open the store connection, and acquire a lock on the store. - - Lock Id. - - - - Closes the store connection. - - - - - Closes the store connection after releasing lock. - Lock Id. - - - - - Acquires a transactional scope on the connection. - - Type of transaction scope. - Transaction scope on the store connection. - - - - Disposes the object. - - - - - Performs actual Dispose of resources. - - Whether the invocation was from IDisposable.Dipose method. - - - - Acquires an application level lock on the connection which is session scoped. - - Identity of the lock. - - - - Releases an application level lock on the connection which is session scoped. - - Identity of the lock. - - - - Constructs instance of Sql Store Connection. - - - - - Constructs an instance of the factory. - - - - - Constructs a new instance of store connection. - - Type of store connection. - Connection string for store. - An unopened instance of the store connection. - - - - Constructs a new instance of user connection. - - Connection string of user. - An unopened instance of the user connection. - - - - Instance of a User Sql Store Connection. - - - - - Underlying connection. - - - - - Creates a new instance of user store connection. - - Connection string. - - - - Underlying SQL server connection. - - - - - Opens the connection. - - - - - Asynchronously opens the connection. - - Task to await completion of the Open - - - - Disposes the object. - - - - - Performs actual Dispose of resources. - - Whether the invocation was from IDisposable.Dipose method. - - - - Distributed Store operation. - - - - - Performs the store operation. - - Results of the operation. - - - - Performs the undo store operation. - - - - - Requests the derived class to provide information regarding the connections - needed for the operation. - - Information about shards involved in the operation. - - - - Performs the initial GSM operation prior to LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the initial GSM operation prior to LSM operations. - - Operation result. - - - - Performs the LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the the LSM operation on the source shard. - - Operation result. - - - - Performs the LSM operation on the target shard. - - Transaction scope. - Result of the operation. - - - - Performs the final GSM operation after the LSM operations. - - Operation result. - - - - Performs the final GSM operation after the LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the final GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the final GSM operation after the LSM operations. - - Operation result. - - - - Performs the undo of LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the undo of LSM operation on the source shard. - - Operation result. - - - - Performs the undo of GSM operation after LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the undo of GSM operation after LSM operations. - - Operation result. - - - - Returns the ShardManagementException to be thrown corresponding to a StoreException. - - Store Exception that has been raised. - SQL operation state. - ShardManagementException to be thrown. - - - - Factory for storage operation creation. - - - - - Constructs request for deploying SMM storage objects to target GSM database. - - Credentials for connection. - Retry policy. - Operation name, useful for diagnostics. - Creation mode. - target version of store to deploy, this will be used mainly for upgrade testing purposes. - The store operation. - - - - Constructs request for obtaining shard map manager object if the GSM has the SMM objects in it. - - Credentials for connection. - Retry policy. - Operation name, useful for diagnostics. - Whether to throw exception on failure or return error code. - The store operation. - - - - Constructs request for Detaching the given shard and mapping information to the GSM database. - - Shard map manager object. - Operation name. - Location to be detached. - Shard map from which shard is being detached. - The store operation. - - - - Constructs request for replacing the GSM mappings for given shard map with the input mappings. - - Shard map manager. - Operation name. - GSM Shard map. - GSM Shard. - Optional list of mappings to remove. - List of mappings to add. - The store operation. - - - - Constructs a request to add schema info to GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Schema info to add. - The store operation. - - - - Constructs a request to find schema info in GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Name of schema info to search. - The store operation. - - - - Constructs a request to get all schema info objects from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - The store operation. - - - - Constructs a request to delete schema info from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Name of schema info to delete. - The store operation. - - - - Constructs a request to update schema info to GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Schema info to update. - The store operation. - - - - Constructs request to get shard with specific location for given shard map from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map for which shard is being requested. - Location of shard being searched. - The store operation. - - - - Constructs request to get all shards for given shard map from GSM. - - Operation name, useful for diagnostics. - Shard map manager object. - Shard map for which shards are being requested. - The store operation. - - - - Constructs request to add given shard map to GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map to add. - The store operation. - - - - Constructs request to find shard map with given name from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Name of the shard map being searched. - The store operation. - - - - Constructs request to get distinct shard locations from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - The store operation. - - - - Constructs request to get all shard maps from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - The store operation. - - - - Constructs request to get all shard maps from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - The store operation. - - - - Constructs request to remove given shard map from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map to remove. - The store operation. - - - - Constructs request for obtaining mapping from GSM based on given key. - - Shard map manager. - Operation being executed. - Local shard map. - Mapping whose Id will be used. - Error category. - The store operation. - - - - Constructs request for obtaining mapping from GSM based on given key. - - Shard map manager. - Operation being executed. - Local shard map. - Key for lookup operation. - Policy for cache update. - Error category. - Whether to cache the results of the operation. - Ignore shard map not found error. - The store operation. - - - - Constructs request for obtaining all the mappings from GSM based on given shard and mappings. - - Shard map manager. - Operation being executed. - Local shard map. - Local shard. - Optional range to get mappings from. - Error category. - Whether to cache the results of the operation. - Ignore shard map not found error. - The store operation. - - - - Constructs request to lock or unlock given mappings in GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map to add. - Mapping to lock or unlock. Null means all mappings. - Lock owner. - Lock operation type. - Error category. - The store operation. - - - - Constructs a request to upgrade global store. - - Shard map manager object. - Operation name, useful for diagnostics. - Target version of store to deploy. - The store operation. - - - - Constructs request for obtaining all the shard maps and shards from an LSM. - - Operation name. - Shard map manager. - Location of the LSM. - - - - Constructs request for obtaining all the shard maps and shards from an LSM. - - Shard map manager. - Location of the LSM. - Operation name. - Local shard map. - Local shard. - Optional range to get mappings from. - Ignore shard map not found error. - - - - Constructs request for obtaining all the shard maps and shards from an LSM. - - Shard map manager. - Location of the LSM. - Operatio name. - - - - Constructs request for replacing the LSM mappings for given shard map with the input mappings. - - Shard map manager. - Location of the LSM. - Operation name. - Local shard map. - Local shard. - Optional list of ranges to minimize amount of deletions. - List of mappings to add. - - - - Constructs a request to upgrade store location. - - Shard map manager object. - Location to upgrade. - Operation name, useful for diagnostics. - Target version of store to deploy. - The store operation. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Shard map for which to add shard. - Shard to add. - The store operation. - - - - Creates request to remove shard from given shard map. - - Shard map manager object. - Shard map for which to remove shard. - Shard to remove. - The store operation. - - - - Creates request to update shard in given shard map. - - Shard map manager object. - Shard map for which to remove shard. - Shard to update. - Updated shard. - The store operation. - - - - Constructs request for attaching the given shard map and shard information to the GSM database. - - Shard map manager object. - Shard to attach - Shard Map to attach shard to. - The store operation. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Store operation code. - Shard map for which to add mapping. - Mapping to add. - The store operation. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Store operation code. - Shard map from which to remove mapping. - Mapping to add. - Id of lock owner. - The store operation. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Store operation code. - Shard map for which to update mapping. - Mapping to update. - Updated mapping. - Pattern for kill commands. - Id of lock owner. - Whether to kill open connections. - The store operation. - - - - Creates request to replace mappings within shard map. - - Shard map manager object. - Store operation code. - Shard map for which to update mapping. - Original mappings. - Target mappings mapping. - The store operation. - - - - Create operation corresponding to the information. - - ShardMapManager instance for undo operation. - Store operation information. - The store operation. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - The store operation. - - - - Creates request to remove shard from given shard map. - - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - The store operation. - - - - Creates request to update shard in given shard map. - - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - The store operation. - - - - Creates request to add a mapping in given shard map. - - Operation code. - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - Original shard Id. - The store operation. - - - - Creates request to remove a mapping in given shard map. - - Operation code. - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - Original shard Id. - The store operation. - - - - Creates request to update a mapping in given shard map. - - Operation code. - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - Original shard Id of source. - Original shard Id of target. - The store operation. - - - - Creates request to replace a set of mappings with new set in given shard map. - - Operation code. - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - Original shard Id of source. - The store operation. - - - - Represents a GSM only store operation. - - - - - Whether this is a read-only operation. - - - - - Performs the store operation. - - Results of the operation. - - - - Asynchronously performs the store operation. - - Task encapsulating results of the operation. - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Asynchronously execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Task encapsulating results of the operation. - - - - - Invalidates the cache on unsuccessful commit of the GSM operation. - - Operation result. - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the GSM operation. - - Operation result. - - - - Returns the ShardManagementException to be thrown corresponding to a StoreException. - - Store exception that has been raised. - ShardManagementException to be thrown. - - - - Represents an LSM only store operation. - - - - - Whether this is a read-only operation. - - - - - Performs the store operation. - - Results of the operation. - - - - Execute the operation against LSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the LSM operation. - - Operation result. - - - - Returns the ShardManagementException to be thrown corresponding to a StoreException. - - Store exception that has been raised. - ShardManagementException to be thrown. - - - - Operation codes identifying various store operations. - - - - - Attaches the given shard map and shard information to the GSM database and update shard location in LSM. - UndoLocalSourceExecute is not implemented for this operation because UpdateShardLocal operation is needed - irrespective of the success/error condition, it updates Shards table with correct location of the Shard. - - - - - Shard map to attach the shard. - - - - - Shard to attach. - - - - - Creates request to attach shard to given shard map. - - Shard map manager object. - Shard map for which to attach shard. - Shard to attach. - - - - Creates request to attach shard to given shard map. - - Shard map manager object. - Operation id. - State from which Undo operation starts. - Shard map for which to attach shard. - Shard to attach. - - - - Requests the derived class to provide information regarding the connections - needed for the operation. - - Information about shards involved in the operation. - - - - Performs the initial GSM operation prior to LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the initial GSM operation prior to LSM operations. - - Operation result. - - - - Performs the LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the the LSM operation on the source shard. - - Operation result. - - - - Performs the final GSM operation after the LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the final GSM operation after the LSM operations. - - Operation result. - - - - Performs the undo of LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the undo of LSM operation on the source shard. - - Operation result. - - - - Performs the undo of GSM operation after LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the undo of GSM operation after LSM operations. - - Operation result. - - - - Source location of error. - - - - - Target location of error. - - - - - Error category for store exception. - - - - - Obtains all the shard maps and shards from an LSM. - - - - - Constructs request for obtaining all the shard maps and shards from an LSM. - - Operation name. - Shard map manager. - Location of the LSM. - - - - Whether this is a read-only operation. - - - - - Execute the operation against LSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the LSM operation. - - Operation result. - - - - Detaches the given shard and corresponding mapping information to the GSM database. - - - - - Location to be detached. - - - - - Shard map from which shard is being detached. - - - - - Constructs request for Detaching the given shard and mapping information to the GSM database. - - Shard map manager object. - Operation name. - Location to be detached. - Shard map from which shard is being detached. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Obtains the mapping from the GSM based on given key. - - - - - Shard map manager instance. - - - - - Shard map for which mappings are requested. - - - - - Key being searched. - - - - - Policy for cache update. - - - - - Error category to use. - - - - - Whether to cache the results. - - - - - Ignore ShardMapNotFound error. - - - - - Constructs request for obtaining mapping from GSM based on given key. - - Shard map manager. - Operation being executed. - Local shard map. - Key for lookup operation. - Policy for cache update. - Error category. - Whether to cache the results of the operation. - Ignore shard map not found error. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Asynchronously execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Task encapsulating results of the operation. - - - - - Invalidates the cache on unsuccessful commit of the GSM operation. - - Operation result. - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the GSM operation. - - Operation result. - - - - Error category for store exception. - - - - - Obtains the mapping by Id from the GSM. - - - - - Shard map manager instance. - - - - - Shard map for which mappings are requested. - - - - - Mapping whose Id will be used. - - - - - Error category to use. - - - - - Constructs request for obtaining mapping from GSM based on given key. - - Shard map manager. - Operation being executed. - Local shard map. - Mapping whose Id will be used. - Error category. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Invalidates the cache on unsuccessful commit of the GSM operation. - - Operation result. - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the GSM operation. - - Operation result. - - - - Error category for store exception. - - - - - Obtains all the mappings from the GSM based on given shard and range. - - - - - Shard map manager instance. - - - - - Shard map for which mappings are requested. - - - - - Optional shard which has the mappings. - - - - - Optional range to get mappings for. - - - - - Error category to use. - - - - - Whether to cache the results. - - - - - Ignore ShardMapNotFound error. - - - - - Constructs request for obtaining all the mappings from GSM based on given shard and mappings. - - Shard map manager. - Operation being executed. - Local shard map. - Local shard. - Optional range to get mappings from. - Error category. - Whether to cache the results of the operation. - Ignore shard map not found error. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Invalidates the cache on unsuccessful commit of the GSM operation. - - Operation result. - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the GSM operation. - - Operation result. - - - - Error category for store exception. - - - - - Obtains all the shard maps and shards from an LSM. - - - - - Local shard map. - - - - - Local shard. - - - - - Range to get mappings from. - - - - - Ignore ShardMapNotFound error. - - - - - Constructs request for obtaining all the shard maps and shards from an LSM. - - Shard map manager. - Location of the LSM. - Operation name. - Local shard map. - Local shard. - Optional range to get mappings from. - Ignore shard map not found error. - - - - Whether this is a read-only operation. - - - - - Execute the operation against LSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the LSM operation. - - Operation result. - - - - Obtains all the shard maps and shards from an LSM. - - - - - Constructs request for obtaining all the shard maps and shards from an LSM. - - Shard map manager. - Location of the LSM. - Operatio name. - - - - Whether this is a read-only operation. - - - - - Execute the operation against LSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the LSM operation. - - Operation result. - - - - Replaces the GSM mappings for given shard map with the input mappings. - - - - - Global shard map. - - - - - Global shard. - - - - - List of mappings to remove. - - - - - List of mappings to add. - - - - - Constructs request for replacing the GSM mappings for given shard map with the input mappings. - - Shard map manager. - Operation name. - GSM Shard map. - GSM Shard. - Optional list of mappings to remove. - List of mappings to add. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Finds all mappings to be purged based on the given input ranges. - - GSM transaction scope. - Mappings which are to be removed. - - - - Replaces the LSM mappings for given shard map with the input mappings. - - - - - Local shard map. - - - - - Local shard. - - - - - List of ranges to be removed. - - - - - List of mappings to add. - - - - - Constructs request for replacing the LSM mappings for given shard map with the input mappings. - - Shard map manager. - Location of the LSM. - Operation name. - Local shard map. - Local shard. - Optional list of ranges to minimize amount of deletions. - List of mappings to add. - - - - Whether this is a read-only operation. - - - - - Execute the operation against LSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the LSM operation. - - Operation result. - - - - Finds all mappings to be purged based on the given input ranges. - - LSM transaction scope. - Mappings which are to be removed. - - - - Add schema info to GSM. - - - - - Schema info to add. - - - - - Constructs a request to add schema info to GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Schema info to add. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Gets all schema infos from GSM. - - - - - Constructs a request to get all schema info objects from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Finds schema info for given name in GSM. - - - - - Shard map name for given schema info. - - - - - Constructs a request to find schema info in GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Name of schema info to search. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Delete schema info from GSM. - - - - - Name of schema info to remove. - - - - - Constructs a request to delete schema info from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Name of schema info to delete. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Updates schema info in GSM. - - - - - Schema info to update. - - - - - Constructs a request to update schema info to GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Schema info to update. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Adds a mapping to given shard map. - - - - - Shard map for which to add the mapping. - - - - - Mapping to add. - - - - - Error category to use. - - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Store operation code. - Shard map for which to add mapping. - Mapping to add. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Operation id. - State from which Undo operation starts. - Store operation code. - Shard map for which to add mapping. - Mapping to add. - Original shard version. - - - - Requests the derived class to provide information regarding the connections - needed for the operation. - - Information about shards involved in the operation. - - - - Performs the initial GSM operation prior to LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the initial GSM operation prior to LSM operations. - - Operation result. - - - - Performs the LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the the LSM operation on the source shard. - - Operation result. - - - - Performs the final GSM operation after the LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the final GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the final GSM operation after the LSM operations. - - Operation result. - - - - Performs the undo of LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the undo of LSM operation on the source shard. - - Operation result. - - - - Performs the undo of GSM operation after LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the undo of GSM operation after LSM operations. - - Operation result. - - - - Source location of error. - - - - - Target location of error. - - - - - Error category for error. - - - - - Locks or unlocks given mappings GSM. - - - - - Shard map manager object. - - - - - Shard map to add. - - - - - Mapping to lock or unlock. - - - - - Lock owner id. - - - - - Operation type. - - - - - Error category to use. - - - - - Constructs request to lock or unlock given mappings in GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map to add. - Mapping to lock or unlock. Null means all mappings. - Lock owner. - Lock operation type. - Error category. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Performs undo of the storage operation that is pending. - - Log entry for the pending operation. - - - - Replaces existing mappings with new mappings in given shard map. - - - - - Shard map for which to perform operation. - - - - - Original mappings. - - - - - New mappings. - - - - - Creates request to replace mappings within shard map. - - Shard map manager object. - Store operation code. - Shard map for which to update mapping. - Original mappings. - Target mappings mapping. - - - - Creates request to replace mappings within shard map. - - Shard map manager object. - Operation id. - State from which Undo operation starts. - Store operation code. - Shard map for which to update mapping. - Original mappings. - Target mappings mapping. - Original shard version on source. - - - - Requests the derived class to provide information regarding the connections - needed for the operation. - - Information about shards involved in the operation. - - - - Performs the initial GSM operation prior to LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the initial GSM operation prior to LSM operations. - - Operation result. - - - - Performs the LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the the LSM operation on the source shard. - - Operation result. - - - - Performs the final GSM operation after the LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the final GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the final GSM operation after the LSM operations. - - Operation result. - - - - Performs the undo of LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the undo of LSM operation on the source shard. - - Operation result. - - - - Performs the undo of GSM operation after LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the undo of GSM operation after LSM operations. - - Operation result. - - - - Source location of error. - - - - - Target location of error. - - - - - Error category for error. - - - - - Removes a mapping from given shard map. - - - - - Shard map from which to remove the mapping. - - - - - Mapping to remove. - - - - - Lock owner. - - - - - Error category to use. - - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Store operation code. - Shard map from which to remove mapping. - Mapping to add. - Id of lock owner. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Operation id. - State from which Undo operation starts. - Store operation code. - Shard map from which to remove mapping. - Mapping to add. - Id of lock owner. - Original shard version. - - - - Requests the derived class to provide information regarding the connections - needed for the operation. - - Information about shards involved in the operation. - - - - Performs the initial GSM operation prior to LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the initial GSM operation prior to LSM operations. - - Operation result. - - - - Performs the LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the the LSM operation on the source shard. - - Operation result. - - - - Performs the final GSM operation after the LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the final GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the final GSM operation after the LSM operations. - - Operation result. - - - - Performs the undo of LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the undo of LSM operation on the source shard. - - Operation result. - - - - Performs the undo of GSM operation after LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the undo of GSM operation after LSM operations. - - Operation result. - - - - Source location of error. - - - - - Target location of error. - - - - - Error category for error. - - - - - Updates a mapping in given shard map. - - - - - Shard map for which to update the mapping. - - - - - Mapping to update. - - - - - Updated mapping. - - - - - Lock owner. - - - - - Error category to use. - - - - - Is this a shard location update operation. - - - - - Is mapping being taken offline. - - - - - Pattern for kill commands. - - - - - Does operation kill connection. - - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Store operation code. - Shard map for which to update mapping. - Mapping to update. - Updated mapping. - Pattern for kill commands. - Id of lock owner. - Whether to kill open connections. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Operation id. - State from which Undo operation starts. - Store operation code. - Shard map for which to update mapping. - Mapping to update. - Updated mapping. - Pattern for kill commands. - Id of lock owner. - Original shard version for removes. - Original shard version for adds. - Whether to kill open connections. - - - - Requests the derived class to provide information regarding the connections - needed for the operation. - - Information about shards involved in the operation. - - - - Performs the initial GSM operation prior to LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the initial GSM operation prior to LSM operations. - - Operation result. - - - - Performs the LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the the LSM operation on the source shard. - - Operation result. - - - - Performs the LSM operation on the target shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the the LSM operation on the target shard. - - Operation result. - - - - Performs the final GSM operation after the LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the final GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the final GSM operation after the LSM operations. - - Operation result. - - - - Performs the undo of LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the undo of LSM operation on the source shard. - - Operation result. - - - - Performs undo of LSM operation on the target shard. - - Transaction scope. - Result of the operation. - - - - Performs undo of LSM operation on the target shard. - - Operation result. - - - - Performs the undo of GSM operation after LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the undo of GSM operation after LSM operations. - - Operation result. - - - - Source location of error. - - - - - Target location of error. - - - - - Error category for error. - - - - - Terminates connection on the source shard object. - - - - - Adds a shard to given shard map. - - - - - Shard map for which to add the shard. - - - - - Shard to add. - - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Shard map for which to add shard. - Shard to add. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Operation id. - State from which Undo operation starts. - Shard map for which to add shard. - Shard to add. - - - - Requests the derived class to provide information regarding the connections - needed for the operation. - - Information about shards involved in the operation. - - - - Performs the initial GSM operation prior to LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the initial GSM operation prior to LSM operations. - - Operation result. - - - - Performs the LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the the LSM operation on the source shard. - - Operation result. - - - - Performs the final GSM operation after the LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the final GSM operation after the LSM operations. - - Operation result. - - - - Performs the undo of LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the undo of LSM operation on the source shard. - - Operation result. - - - - Performs the undo of GSM operation after LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the undo of GSM operation after LSM operations. - - Operation result. - - - - Source location of error. - - - - - Target location of error. - - - - - Error category for error. - - - - - Gets shard with specific location from given shard map from GSM. - - - - - Shard map manager object. - - - - - Shard map for which shard is being requested. - - - - - Location of the shard being searched. - - - - - Constructs request to get shard with specific location for given shard map from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map for which shard is being requested. - Location of shard being searched. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Gets all shards from given shard map from GSM. - - - - - Shard map manager object. - - - - - Shard map for which shards are being requested. - - - - - Constructs request to get all shards for given shard map from GSM. - - Operation name, useful for diagnostics. - Shard map manager object. - Shard map for which shards are being requested. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Adds given shard map to GSM. - - - - - Shard map manager object. - - - - - Shard map to add. - - - - - Constructs request to add given shard map to GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map to add. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the GSM operation. - - Operation result. - - - - Error category for store exception. - - - - - Deploys the SMM storage objects to the target GSM database. - - - - - Creation mode. - - - - - Target version of GSM to deploy, this will be used mainly for upgrade testing purpose. - - - - - Constructs request for deploying SMM storage objects to target GSM database. - - Credentials for connection. - Retry policy. - Operation name, useful for diagnostics. - Creation mode. - target version of store to deploy - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Gets all distinct shard locations from GSM. - - - - - Constructs request to get distinct shard locations from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Finds shard map with given name from GSM. - - - - - Shard map manager object. - - - - - Name of shard map being searched. - - - - - Constructs request to find shard map with given name from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Name of the shard map being searched. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the GSM operation. - - Result of the operation. - - - - Error category for store exception. - - - - - Obtains the shard map manager object if the GSM has the SMM objects in it. - - - - - Whether to throw exception on failure. - - - - - Constructs request for obtaining shard map manager object if the GSM has the SMM objects in it. - - Credentials for connection. - Retry policy. - Operation name, useful for diagnostics. - Whether to throw exception on failure or return error code. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Gets all shard maps from GSM. - - - - - Shard map manager object. - - - - - Constructs request to get all shard maps from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the GSM operation. - - Operation result. - - - - Error category for store exception. - - - - - Gets all shard maps from GSM. - - - - - Shard map manager object. - - - - - Constructs request to get all shard maps from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the GSM operation. - - Operation result. - - - - Error category for store exception. - - - - - Result of load operation. - - - - - Shard map from the store. - - - - - Mappings corresponding to the shard map. - - - - - Removes given shard map from GSM. - - - - - Shard map manager object. - - - - - Shard map to remove. - - - - - Constructs request to remove given shard map from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map to remove. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Invalidates the cache on unsuccessful commit of the GSM operation. - - Operation result. - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the GSM operation. - - Operation result. - - - - Error category for store exception. - - - - - Removes a shard from given shard map. - - - - - Shard map for which to remove the shard. - - - - - Shard to remove. - - - - - Creates request to remove shard from given shard map. - - Shard map manager object. - Shard map for which to remove shard. - Shard to remove. - - - - Creates request to remove shard from given shard map. - - Shard map manager object. - Operation id. - State from which Undo operation starts. - Shard map for which to remove shard. - Shard to remove. - - - - Requests the derived class to provide information regarding the connections - needed for the operation. - - Information about shards involved in the operation. - - - - Performs the initial GSM operation prior to LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the initial GSM operation prior to LSM operations. - - Operation result. - - - - Performs the LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the the LSM operation on the source shard. - - Operation result. - - - - Performs the final GSM operation after the LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the final GSM operation after the LSM operations. - - Operation result. - - - - Performs the undo of LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the undo of LSM operation on the source shard. - - Operation result. - - - - Performs the undo of GSM operation after LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the undo of GSM operation after LSM operations. - - Operation result. - - - - Source location of error. - - - - - Target location of error. - - - - - Error category for error. - - - - - Updates a shard in given shard map. - - - - - Shard map for which to update the shard. - - - - - Shard to update. - - - - - Updated shard. - - - - - Creates request to update shard in given shard map. - - Shard map manager object. - Shard map for which to remove shard. - Shard to update. - Updated shard. - - - - Creates request to update shard in given shard map. - - Shard map manager object. - Operation id. - State from which Undo operation starts. - Shard map for which to remove shard. - Shard to update. - Updated shard. - - - - Requests the derived class to provide information regarding the connections - needed for the operation. - - Information about shards involved in the operation. - - - - Performs the initial GSM operation prior to LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the initial GSM operation prior to LSM operations. - - Operation result. - - - - Performs the LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the the LSM operation on the source shard. - - Operation result. - - - - Performs the final GSM operation after the LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the final GSM operation after the LSM operations. - - Operation result. - - - - Performs the undo of LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the undo of LSM operation on the source shard. - - Operation result. - - - - Performs the undo of GSM operation after LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the undo of GSM operation after LSM operations. - - Operation result. - - - - Source location of error. - - - - - Target location of error. - - - - - Error category for error. - - - - - Provides information regarding LSM connections. - - - - - Optional source shard location. - - - - - Optional target shard location. - - - - - Performs a GSM only store operation. - - - - - GSM connection. - - - - - Credentials for connection establishment. - - - - - Retry policy. - - - - - Constructs an instance of SqlOperationGlobal. - - Credentials for connecting to SMM GSM database. - Retry policy for requests. - Operation name, useful for diagnostics. - - - - Operation name, useful for diagnostics. - - - - - Whether this is a read-only operation. - - - - - Performs the store operation. - - Results of the operation. - - - - Asynchronously performs the store operation. - - Task encapsulating the results of the operation. - - - - Disposes the object. - - - - - Performs actual Dispose of resources. - - Whether the invocation was from IDisposable.Dipose method. - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Asynchronously execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Task encapsulating results of the operation. - - - - - Invalidates the cache on unsuccessful commit of the GSM operation. - - Operation result. - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the GSM operation. - - Operation result. - - - - Returns the ShardManagementException to be thrown corresponding to a StoreException. - - Store exception that has been raised. - ShardManagementException to be thrown. - - - - Error category for store exception. - - - - - Performs undo of the storage operation that is pending. - - Log entry for the pending operation. - - - - Asynchronously performs undo of the storage operation that is pending. - - Log entry for the pending operation. - Task to await Undo of the operation - Currently not used anywhere since the Async APIs were added - in support of the look-up operations - - - - Establishes connection to the SMM GSM database. - - - - - Asynchronously establishes connection to the SMM GSM database. - - Task to await connection establishment - - - - Acquires the transaction scope. - - Transaction scope, operations within the scope excute atomically. - - - - Terminates the connections after finishing the operation. - - - - - Performs a SqlOperation against an LSM. - - - - - LSM connection. - - - - - Credentials for connection establishment. - - - - - Retry policy. - - - - - Constructs an instance of SqlOperationLocal. - - Credentials for connecting to SMM databases. - Retry policy for requests. - Shard location where the operation is to be performed. - Operation name. - - - - Location of LSM. - - - - - Whether this is a read-only operation. - - - - - Performs the store operation. - - Results of the operation. - - - - Disposes the object. - - - - - Performs actual Dispose of resources. - - Whether the invocation was from IDisposable.Dipose method. - - - - Execute the operation against LSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the LSM operation. - - Operation result. - - - - Returns the ShardManagementException to be thrown corresponding to a StoreException. - - Store exception that has been raised. - ShardManagementException to be thrown. - - - - Establishes connection to the target shard. - - - - - Acquires the transaction scope. - - Transaction scope, operations within the scope excute atomically. - - - - Terminates the connections after finishing the operation. - - - - - States of the operation. - - - - - Initial state on Do. - - - - - Before connect GSM on Do. - - - - - Before connect LSM source on Do. - - - - - Before connect LSM target on Do. - - - - - Before GSM operation pre LSM operations about to Start Transaction. - - - - - Before GSM operation pre LSM operations about to execute. - - - - - Before GSM operation pre LSM operations about to commit transaction. - - - - - Before LSM operation on Source shard about to start transaction. - - - - - Before LSM operation on Source shard about to execute. - - - - - Before LSM operation on Source shard about to commit transaction transaction. - - - - - Before LSM operation on Target shard about to start transaction. - - - - - Before LSM operation on Target shard about to execute. - - - - - Before LSM operation on Target shard about to commit transaction transaction. - - - - - Before GSM operation post LSM operations about to Start Transaction. - - - - - Before GSM operation post LSM operations about to execute. - - - - - Before GSM operation post LSM operations about to commit transaction. - - - - - Before disconnect on Do. - - - - - Initial state on Undo. - - - - - Before connect GSM on Undo. - - - - - Before connect LSM source on Undo. - - - - - Before connect LSM target on Undo. - - - - - Before GSM operation pre LSM operations about to Start Transaction. - - - - - Before GSM operation pre LSM operations about to execute. - - - - - Before GSM operation pre LSM operations about to commit transaction. - - - - - Before LSM operation on Target shard about to start transaction. - - - - - Before LSM operation on Target shard about to execute. - - - - - Before LSM operation on Target shard about to commit transaction transaction. - - - - - Before LSM operation on Source shard about to start transaction. - - - - - Before LSM operation on Source shard about to execute. - - - - - Before LSM operation on Source shard about to commit transaction transaction. - - - - - Before GSM operation post LSM operations about to Start Transaction. - - - - - Before GSM operation post LSM operations about to execute. - - - - - Before GSM operation post LSM operations about to commit transaction. - - - - - Before disconnect on Undo. - - - - - Represents a SQL store operation. - - - - - GSM connection. - - - - - Source LSM connection. - - - - - Target LSM connection. - - - - - State of the operation. - - - - - Maximum state reached during Do operation. - - - - - Constructs an instance of StoreOperation. - - ShardMapManager object. - Operation Id. - State from which Undo operation starts. - Operation code. - Original shard version for removes. - Original shard version for adds. - - - - ShardMapManager object. - - - - - Operation Id. - - - - - Operation code. - - - - - Operation Name. - - - - - Earliest point to start Undo operation. - - - - - Original shard version on source. - - - - - Original shard version on target. - - - - - Performs the store operation. - - Results of the operation. - - - - Performs the undo store operation. - - - - - Disposes the object. - - - - - Performs actual Dispose of resources. - - Whether the invocation was from IDisposable.Dipose method. - - - - Requests the derived class to provide information regarding the connections - needed for the operation. - - Information about shards involved in the operation. - - - - Performs the initial GSM operation prior to LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the initial GSM operation prior to LSM operations. - - Operation result. - - - - Performs the LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the the LSM operation on the source shard. - - Operation result. - - - - Performs the LSM operation on the target shard. - - Transaction scope. - Result of the operation. - - - - Performs the final GSM operation after the LSM operations. - - Operation result. - - - - Performs the final GSM operation after the LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the final GSM operation after the LSM operations. - - Operation result. - - - - Refreshes the cache on successful commit of the final GSM operation after the LSM operations. - - Operation result. - - - - Performs undo of LSM operation on the target shard. - - Transaction scope. - Result of the operation. - - - - Performs undo of LSM operation on the target shard. - - Operation result. - - - - Performs the undo of GSM operation prior to LSM operations. - - Transaction scope. - Result of the operation. - - - - Handles errors from the undo of GSM operation prior to LSM operations. - - Operation result. - - - - Performs the undo of LSM operation on the source shard. - - Transaction scope. - Result of the operation. - - - - Handles errors from the undo of LSM operation on the source shard. - - Operation result. - - - - Performs the undo of GSM operation after LSM operations. - - Transaction scope. - Pending operations on the target objects if any. - - - - Handles errors from the undo of GSM operation after LSM operations. - - Operation result. - - - - Returns the ShardManagementException to be thrown corresponding to a StoreException. - - Store Exception that has been raised. - SQL operation state. - ShardManagementException to be thrown. - - - - Source location of error. - - - - - Target location of error. - - - - - Error category for error. - - - - - Obtains the connection string for an LSM location. - - Connection string for LSM given its location. - - - - Given a state of the Do operation progress, gets the corresponding starting point - for Undo operations. - - State at which Do operation was executing. - Corresponding state for Undo operation. - - - - Attempts to Undo the current operation which actually had caused an exception. - - This is basically a best effort attempt. - - - - Established connections to the target databases. - - Is this undo operation. - - - - Acquires the transaction scope. - - Transaction scope, operations within the scope excute atomically. - - - - Performs the initial GSM operation prior to LSM operations. - - Pending operations on the target objects if any. - - - - Performs the LSM operation on the source shard. - - - - - Performs the LSM operation on the target shard. - - - - - Performs the final GSM operation after the LSM operations. - - Results of the GSM operation. - - - - Perform undo of GSM operations before LSM operations. Basically checks if the operation - to be undone is still present in the log. - - - true if further undo operations are necessary, false otherwise. - - - - - Performs the undo of LSM operation on the target shard. - - - - - Performs the undo of LSM operation on the source shard. - - - - - Performs the undo of GSM operation after LSM operations. - - - - - Terminates connections to target databases. - - - - - Instantiates the operations that need to be undone corresponding to a request. - - - - - Create instance of StoreOperationFactory. - - - - - Constructs request for deploying SMM storage objects to target GSM database. - - Credentials for connection. - Retry policy. - Operation name, useful for diagnostics. - Creation mode. - target version of store to deploy, this will be used mainly for upgrade testing purposes. - The store operation. - - - - Constructs request for obtaining shard map manager object if the GSM has the SMM objects in it. - - Credentials for connection. - Retry policy. - Operation name, useful for diagnostics. - Whether to throw exception on failure or return error code. - The store operation. - - - - Constructs request for Detaching the given shard and mapping information to the GSM database. - - Shard map manager object. - Operation name. - Location to be detached. - Shard map from which shard is being detached. - The store operation. - - - - Constructs request for replacing the GSM mappings for given shard map with the input mappings. - - Shard map manager. - Operation name. - GSM Shard map. - GSM Shard. - Optional list of mappings to remove. - List of mappings to add. - The store operation. - - - - Constructs a request to add schema info to GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Schema info to add. - The store operation. - - - - Constructs a request to find schema info in GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Name of schema info to search. - The store operation. - - - - Constructs a request to get all schema info objects from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - The store operation. - - - - Constructs a request to delete schema info from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Name of schema info to delete. - The store operation. - - - - Constructs a request to update schema info to GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Schema info to update. - The store operation. - - - - Constructs request to get shard with specific location for given shard map from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map for which shard is being requested. - Location of shard being searched. - The store operation. - - - - Constructs request to get all shards for given shard map from GSM. - - Operation name, useful for diagnostics. - Shard map manager object. - Shard map for which shards are being requested. - The store operation. - - - - Constructs request to add given shard map to GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map to add. - The store operation. - - - - Constructs request to find shard map with given name from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Name of the shard map being searched. - The store operation. - - - - Constructs request to get distinct shard locations from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - The store operation. - - - - Constructs request to get all shard maps from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - The store operation. - - - - Constructs request to get all shard maps from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - The store operation. - - - - Constructs request to remove given shard map from GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map to remove. - The store operation. - - - - Constructs request for obtaining mapping from GSM based on given key. - - Shard map manager. - Operation being executed. - Local shard map. - Mapping whose Id will be used. - Error category. - The store operation. - - - - Constructs request for obtaining mapping from GSM based on given key. - - Shard map manager. - Operation being executed. - Local shard map. - Key for lookup operation. - Policy for cache update. - Error category. - Whether to cache the results of the operation. - Ignore shard map not found error. - The store operation. - - - - Constructs request for obtaining all the mappings from GSM based on given shard and mappings. - - Shard map manager. - Operation being executed. - Local shard map. - Local shard. - Optional range to get mappings from. - Error category. - Whether to cache the results of the operation. - Ignore shard map not found error. - The store operation. - - - - Constructs request to lock or unlock given mappings in GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Shard map to add. - Mapping to lock or unlock. Null means all mappings. - Lock owner. - Lock operation type. - Error category. - The store operation. - - - - Constructs a request to upgrade global store. - - Shard map manager object. - Operation name, useful for diagnostics. - Target version of store to deploy. - The store operation. - - - - Constructs request for obtaining all the shard maps and shards from an LSM. - - Operation name. - Shard map manager. - Location of the LSM. - - - - Constructs request for obtaining all the shard maps and shards from an LSM. - - Shard map manager. - Location of the LSM. - Operation name. - Local shard map. - Local shard. - Optional range to get mappings from. - Ignore shard map not found error. - - - - Constructs request for obtaining all the shard maps and shards from an LSM. - - Shard map manager. - Location of the LSM. - Operatio name. - - - - Constructs request for replacing the LSM mappings for given shard map with the input mappings. - - Shard map manager. - Location of the LSM. - Operation name. - Local shard map. - Local shard. - Optional list of ranges to minimize amount of deletions. - List of mappings to add. - - - - Constructs a request to upgrade store location. - - Shard map manager object. - Location to upgrade. - Operation name, useful for diagnostics. - Target version of store to deploy. - The store operation. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Shard map for which to add shard. - Shard to add. - The store operation. - - - - Creates request to remove shard from given shard map. - - Shard map manager object. - Shard map for which to remove shard. - Shard to remove. - The store operation. - - - - Creates request to update shard in given shard map. - - Shard map manager object. - Shard map for which to remove shard. - Shard to update. - Updated shard. - The store operation. - - - - Constructs request for attaching the given shard map and shard information to the GSM database. - - Shard map manager object. - Shard to attach - Shard map to attach specified shard - The store operation. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Store operation code. - Shard map for which to add mapping. - Mapping to add. - The store operation. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Store operation code. - Shard map from which to remove mapping. - Mapping to add. - Id of lock owner. - The store operation. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Store operation code. - Shard map for which to update mapping. - Mapping to update. - Updated mapping. - Pattern for kill commands. - Id of lock owner. - Whether to kill open connections. - The store operation. - - - - Creates request to replace mappings within shard map. - - Shard map manager object. - Store operation code. - Shard map for which to update mapping. - Original mappings. - Target mappings mapping. - The store operation. - - - - Create operation corresponding to the information. - - ShardMapManager instance for undo operation. - Store operation information. - The operation to be undone. - - - - Creates request to add shard to given shard map. - - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - The store operation. - - - - Creates request to remove shard from given shard map. - - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - The store operation. - - - - Creates request to update shard in given shard map. - - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - The store operation. - - - - Creates request to add a mapping in given shard map. - - Operation code. - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - Original shard version. - The store operation. - - - - Creates request to remove a mapping in given shard map. - - Operation code. - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - Original shard version for Removes. - The store operation. - - - - Creates request to update a mapping in given shard map. - - Operation code. - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - Original shard version for removes. - Original shard version for adds. - The store operation. - - - - Creates request to replace a set of mappings with new set in given shard map. - - Operation code. - Shard map manager object. - Operation Id. - Undo start state. - Xml representation of the object. - Original shard Id of source. - The store operation. - - - - Upgrade store hosting GSM. - - - - - Target version of GSM to deploy, this will be used mainly for upgrade testing purpose. - - - - - Constructs request to upgrade store hosting GSM. - - Shard map manager object. - Operation name, useful for diagnostics. - Target version to upgrade. - - - - Whether this is a read-only operation. - - - - - Execute the operation against GSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Handles errors from the GSM operation after the LSM operations. - - Operation result. - - - - Error category for store exception. - - - - - Upgrade store structures at specified location. - - - - - Target version of LSM to deploy, this will be used mainly for upgrade testing purpose. - - - - - Constructs request to upgrade store hosting LSM. - - Shard map manager object. - Store location to upgrade. - Operation name, useful for diagnostics. - Target version to upgrade. - - - - Whether this is a read-only operation. - - - - - Execute the operation against LSM in the current transaction scope. - - Transaction scope. - - Results of the operation. - - - - - Utility class for handling SqlOperation errors returned from stored procedures. - - - - - Returns the proper ShardManagementException corresponding to given error code in - for ShardMapManager operations. - - Operation result object. - Shard map object. - Operation being performed. - Stored procedure being executed. - ShardManagementException to be raised. - - - - Returns the proper ShardManagementException corresponding to given error code in - for ShardMap operations. - - Operation result object. - Shard map object. - Shard object. - Error category to use for raised errors. - Operation being performed. - Stored procedure being executed. - ShardManagementException to be raised. - - - - Returns the proper ShardManagementException corresponding to given error code in - for ShardMap operations. - - Operation result object. - Shard map object. - Location of LSM operation. - Error category to use for raised errors. - Operation being performed. - Stored procedure being executed. - ShardManagementException to be raised. - - - - Returns the proper ShardManagementException corresponding to given error code in - for ShardMapper operations. - - Operation result object. - Shard map object. - Shard object. - Error category to use for raised errors. - Operation being performed. - Stored procedure being executed. - ShardManagementException to be raised. - - - - Returns the proper ShardManagementException corresponding to given error code in - for ShardMapper operations. - - Operation result object. - Location of LSM operation. - Operation being performed. - Stored procedure being executed. - ShardManagementException to be raised. - - - - Returns the proper ShardManagementException corresponding to given error code in - for ShardMap operations. - - Operation result object. - Shard map object. - Location of LSM operation. - Operation being performed. - Stored procedure being executed. - ShardManagementException to be raised. - - - - Returns the proper ShardManagementException corresponding to given error code in - for ShardMapper operations. - - Operation result object. - Name of shard map. - Operation being performed. - Stored procedure being executed. - - - - - Returns the proper ShardManagementException corresponding to given error code in - for ShardMap operations. - - Operation result object. - Shard map object. - Shard object. - Error category to use for raised errors. - Operation being performed. - Stored procedure being executed. - ShardManagementException to be raised. - - - - Returns the proper ShardManagementException corresponding to given error code in - for ShardMap operations. - - Operation result object. - Shard map object. - Location of operation. - Error category to use for raised errors. - Operation being performed. - Stored procedure being executed. - ShardManagementException to be raised. - - - - Returns the proper ShardManagementException corresponding to given common error code - in . - - Operation result object. - Operation being performed. - Stored procedure being executed. - ShardManagementException to be raised. - - - - Returns the proper ShardManagementException corresponding to given common error code - in . - - Operation result object. - Location of LSM. - Operation being performed. - Stored procedure being executed. - ShardManagementException to be raised. - - - - Given an operation code, returns the corresponding operation name. - - Operation code. - Operation name corresponding to given operation code. - - - - Scope of a transactional operation. Operations within scope happen atomically. - - - - - Connection used for operation. - - - - - Transaction used for operation. - - - - - Constructs an instance of an atom transaction scope. - - Type of transaction scope. - Connection to use for the transaction scope. - - - - Type of transaction scope. - - - - - Property used to mark successful completion of operation. The transaction - will be committed if this is true and rolled back if this is false. - - - - - Executes the given stored procedure using the values - as the parameter and a single output parameter. - - Operation to execute. - Input data for operation. - Storage results object. - - - - Asynchronously executes the given operation using the values - as input to the operation. - - Operation to execute. - Input data for operation. - Task encapsulating storage results object. - - - - Executes the given command. - - Command to execute. - Storage results object. - - - - Executes the given set of commands. - - Collection of commands to execute. - - - - Disposes the object. Commits or rolls back the transaction. - - - - - Performs actual Dispose of resources. - - Whether the invocation was from IDisposable.Dipose method. - - - - Types of transaction scopes used during store operations. - - - - - Scope of GSM. - - - - - Scope of source LSM. - - - - - Scope of target LSM. - - - - - Constructs requests for store operations. - - - - - Step kind for for Bulk Operations. - - - - - Remove operation. - - - - - Update operation. - - - - - Add operation. - - - - - Element representing GSM version. - - - - - Element representing LSM version. - - - - - FindAndUpdateOperationLogEntryByIdGlobal stored procedure. - - - - - GetAllShardMapsGlobal stored procedure. - - - - - FindShardMapByNameGlobal stored procedure. - - - - - GetAllDistinctShardLocationsGlobal stored procedure. - - - - - AddShardMapGlobal stored procedure. - - - - - RemoveShardMapGlobal stored procedure. - - - - - GetAllShardsGlobal stored procedure. - - - - - FindShardByLocationGlobal stored procedure. - - - - - BulkOperationShardsGlobalBegin stored procedure. - - - - - BulkOperationShardsGlobalEnd stored procedure. - - - - - GetAllShardMappingsGlobal stored procedure. - - - - - FindShardMappingByKeyGlobal stored procedure. - - - - - FindShardMappingByIdGlobal stored procedure. - - - - - BulkShardMappingOperationsGlobalBegin stored procedure. - - - - - BulkShardMappingOperationsGlobalEnd stored procedure. - - - - - LockOrUnLockShardMappingsGlobal stored procedure. - - - - - GetAllShardingSchemaInfosGlobal stored procedure. - - - - - FindShardingSchemaInfoByNameGlobal stored procedure. - - - - - AddShardingSchemaInfoGlobal stored procedure. - - - - - RemoveShardingSchemaInfoGlobal stored procedure. - - - - - UpdateShardingSchemaInfoGlobal stored procedure. - - - - - AttachShardGlobal stored procedure. - - - - - DetachShardGlobal stored procedure. - - - - - ReplaceShardMappingsGlobal stored procedure. - - - - - GetAllShardsLocal stored procedure. - - - - - ValidateShardLocal stored procedure. - - - - - AddShardLocal stored procedure. - - - - - RemoveShardLocal stored procedure. - - - - - UpdateShardLocal stored procedure. - - - - - GetAllShardMappingsLocal stored procedure. - - - - - FindShardMappingByKeyLocal stored procedure. - - - - - ValidateShardMappingLocal stored procedure. - - - - - BulkOperationShardMappingsLocal stored procedure. - - - - - KillSessionsForShardMappingLocal stored procedure. - - - - - Find operation log entry by Id from GSM. - - Operation Id. - Minimum start from which to start undo operation. - Xml formatted request. - - - - Request to get all shard maps from GSM. - - Xml formatted request. - - - - Request to get shard map with the given name from GSM. - - Name of shard map. - Xml formatted request. - - - - Request to get all distinct shard locations from GSM. - - Xml formatted request. - - - - Request to add shard map to GSM. - - Shard map to add. - Xml formatted request. - - - - Request to remove shard map from GSM. - - Shard map to remove. - Xml formatted request. - - - - Request to get all shards for a shard map from GSM. - - Shard map for which to get all shards. - Xml formatted request. - - - - Request to get shard with specified location for a shard map from GSM. - - Shard map for which to get shard. - Location for which to find shard. - Xml formatted request. - - - - Request to add shard to given shard map in GSM. - - Operation Id - Operation code. - Whether this is an undo request. - Shard map for which operation is being requested. - Shard to add. - Xml formatted request. - - - - Request to remove shard from given shard map in GSM. - - Operation Id - Operation code. - Whether this is an undo request. - Shard map for which operation is being requested. - Shard to remove. - Xml formatted request. - - - - Request to update shard in given shard map in GSM. - - Operation Id - Operation code. - Whether this is an undo request. - Shard map for which operation is being requested. - Shard to update. - Updated shard. - Xml formatted request. - - - - Request to get all shard mappings from GSM for a particular shard map - and optional shard and range. - - Shard map whose mappings are being requested. - Optional shard for which mappings are being requested. - Optional range for which mappings are being requested. - Xml formatted request. - - - - Request to get mapping from GSM for a particular key belonging to a shard map. - - Shard map whose mappings are being requested. - Key being searched. - Xml formatted request. - - - - Request to get mapping from GSM for a particular mapping Id. - - Shard map whose mappings are being requested. - Mapping to look up. - Xml formatted request. - - - - Request to add shard to given shard map in GSM. - - Operation Id. - Operation code. - Whether this is an undo request. - Shard map for which operation is being requested. - Mapping to add. - Xml formatted request. - - - - Request to remove shard from given shard map in GSM. - - Operation Id. - Operation code. - Whether this is an undo request. - Shard map for which operation is being requested. - Mapping to remove. - Lock owner. - Xml formatted request. - - - - Request to update mapping in given shard map in GSM. - - Operation Id. - Operation code. - Whether this is an undo request. - Pattern to use for kill connection. - Shard map for which operation is being requested. - Shard to update. - Updated shard. - Lock owner. - Whether to kill open connections. - Xml formatted request. - - - - Request to replace mappings in given shard map in GSM. - - Operation Id. - Operation code. - Whether this is an undo request. - Shard map for which operation is being requested. - Original mappings. - New mappings. - Xml formatted request. - - - - Request to lock or unlock mappings in GSM. - - Shard map whose mappings are being requested. - Mapping being locked or unlocked. - Lock Id. - Lock operation code. - Xml formatted request. - - - - Request to get all schema info objects from GSM. - - Xml formatted request. - - - - Request to find schema info in GSM. - - Schema info name to find. - Xml formatted request. - - - - Request to add schema info to GSM. - - Schema info object to add - Xml formatted request. - - - - Request to delete schema info object from GSM. - - Name of schema info to delete. - Xml formatted request. - - - - Request to update schema info to GSM. - - Schema info object to update - Xml formatted request. - - - - Request to attach shard to GSM. - - Shard map to attach. - Shard to attach. - Xml formatted request. - - - - Request to detach shard to GSM. - - Optional shard map name to detach. - Location to detach. - Xml formatted request. - - - - Request to replace mappings in given shard map in GSM without logging. - - Shard map for which operation is being requested. - Original mappings. - New mappings. - Xml formatted request. - - - - Request to get all shards and shard maps from LSM. - - Xml formatted request. - - - - Validation request for shard for LSM. - - Shard map Id. - Shard Id. - Shard version. - Xml formatted request. - - - - Request to add shard to given shard map in LSM. - - Operation Id. - Shard map to add shard to. - Shard to add. - Whether this is undo request. - Xml formatted request. - - - - Request to remove shard from given shard map in LSM. - - Operation Id. - Shard map to remove shard from. - Shard to remove. - Xml formatted request. - - - - Request to update shard in given shard map in LSM. - - Operation Id. - Shard map to remove shard from. - Shard to update. - Xml formatted request. - - - - Request to get all shard mappings from LSM for a particular shard map - and optional shard and range. - - Shard map whose mappings are being requested. - Optional shard for which mappings are being requested. - Optional range for which mappings are being requested. - Xml formatted request. - - - - Request to get mapping from LSM for a particular key belonging to a shard map. - - Shard map whose mappings are being requested. - Key being searched. - Xml formatted request. - - - - Validation request for shard mapping for LSM. - - Shard map Id. - Shard mapping Id. - Xml formatted request. - - - - Request to add mapping to given shard map in LSM. - - Operation Id. - Shard map for which operation is being requested. - Mapping to add. - Whether this is undo request. - Xml formatted request. - - - - Request to remove mapping from given shard map in LSM. - - Operation Id. - Shard map for which operation is being requested. - Mapping to remove. - Whether this is undo operation. - Xml formatted request. - - - - Request to update mapping in given shard map in LSM. - - Operation Id. - Shard map for which operation is being requested. - Mapping to update. - Updated mapping. - Whether this is undo request. - Xml formatted request. - - - - Request to replace mapping in given shard map in LSM. - - Operation Id. - Shard map for which operation is being requested. - Mappings to remove. - Mappings to add. - Whether this is undo request. - Xml formatted request. - - - - Request to kill sessions with given application name pattern in LSM. - - Pattern for application name. - Xml formatted request. - - - - Adds OperationId attribute. - - Id of operation. - XAttribute for the operationId. - - - - Adds UndoStartState attribute. - - Number of remove steps. - XAttribute for the removeStepsCount. - - - - Adds OperationCode attribute. - - Code of operation. - XAttribute for the operationCode. - - - - Adds StepsCount attribute. - - Number of steps. - XAttribute for the StepsCount. - - - - Adds StepKind attribute. - - Type of step. - XAttribute for the StepKind. - - - - Adds RemoveStepsCount attribute. - - Number of remove steps. - XAttribute for the removeStepsCount. - - - - Adds AddStepsCount attribute. - - Number of add steps. - XAttribute for the addStepsCount. - - - - Adds Undo attribute. - - Undo request. - XAttribute for the undo. - - - - Adds Validate attribute. - - Validate request. - XAttribute for the validation. - - - - SQL backed storage representation of a location. - - - - - Constructs an instance of IStoreLocation using parts of a row from SqlDataReader. - Used for creating the shard location instance. - - SqlDataReader whose row has shard information. - Reader offset for column that begins shard information. - - - - Data source location. - - - - - Implementation of a store operation. - - - - - Constructs an instance of IStoreLogEntry using parts of a row from SqlDataReader. - Used for creating the store operation for Undo. - - SqlDataReader whose row has operation information. - Reader offset for column that begins operation information. - - - - Identity of operation. - - - - - Operation code. Helps in deserialization during factory method. - - - - - Serialized representation of the operation. - - - - - State from which Undo will start. - - - - - Original shard version for remove steps. - - - - - Original shard version for add steps. - - - - - SQL backed storage representation of a schema info object. - - - - - Constructs an instance of IStoreSchemaInfo using parts of a row from SqlDataReader. - - SqlDataReader whose row has shard information. - Reader offset for column that begins shard information. - - - - Schema info name. - - - - - Schema info represented in XML. - - - - - Container for the credentials for SQL Server backed ShardMapManager. - - - - - Connection string for shard map manager database. - - - - - Connection string for individual shards. - - - - - Instantiates the object that holds the credentials for accessing SQL Servers - containing the shard map manager data. - - Connection string for Shard map manager data source. - - - - Connection string for shard map manager database. - - - - - Connection string for shards. - - - - - Location of Shard Map Manager used for logging purpose. - - - - - Ensures that credentials are provided for the given connection string object. - - Input connection string object. - Parameter name of the connection string object. - - - - Base class for keyed mappers. - - - - - Base shard mapper, which is just a holder of some fields. - - Reference to ShardMapManager. - Containing shard map. - - - - Reference to ShardMapManager. - - - - - Containing shard map. - - - - - The Tracer - - - - - Sets the status of a shardmapping - - Mapping type. - Update type. - Status type. - Mapping being added. - Status of mapping being added. - Delegate to construct new status from - input status. - Delegate to construct new update from new status returned by - getStatus. - Delegate to perform update from the input mapping and - the update object returned by createUpdate. - Lock owner id of this mapping - Options for validation operations to perform on opened connection to affected shard. - - - - - Given a key value, obtains a SqlConnection to the shard in the mapping - that contains the key value. - - Mapping type. - Key type. - Input key value. - Delegate to construct a mapping object. - Error category. - - Connection string with credential information, the DataSource and Database are - obtained from the results of the lookup operation for key. - - Options for validation operations to perform on opened connection. - An opened SqlConnection. - - - - Given a key value, asynchronously obtains a SqlConnection to the shard in the mapping - that contains the key value. - - Mapping type. - Key type. - Input key value. - Delegate to construct a mapping object. - Error category. - - Connection string with credential information, the DataSource and Database are - obtained from the results of the lookup operation for key. - - Options for validation operations to perform on opened connection. - A task encapsulating an opened SqlConnection as the result. - - - - Adds a mapping to shard map. - - Mapping type. - Mapping being added. - Delegate to construct a mapping object. - The added mapping object. - - - - Removes a mapping from shard map. - - Mapping type. - Mapping being removed. - Delegate to construct a mapping object. - Lock owner id of this mapping - - - - Looks up the key value and returns the corresponding mapping. - - Mapping type. - Key type. - Input key value. - Whether to use cache for lookups. - Delegate to construct a mapping object. - Category under which errors must be thrown. - Mapping that contains the key value. - - - - Finds mapping in store for OpenConnectionForKey operation. - - Key to find. - Cache update policy. - Error category. - Mapping corresponding to the given key if found. - - - - Asynchronously finds the mapping in store for OpenConnectionForKey operation. - - Key to find. - Cache update policy. - Error category. - Task with the Mapping corresponding to the given key if found as the result. - - - - Gets all the mappings that exist within given range. - - Optional range value, if null, we cover everything. - Optional shard parameter, if null, we cover all shards. - Delegate to construct a mapping object. - Category under which errors will be posted. - Name of mapping type. - Read-only collection of mappings that overlap with given range. - - - - Allows for update to a mapping with the updates provided in - the parameter. - - Mapping being updated. - Updated properties of the Shard. - Delegate to construct a mapping object. - Delegate to get the mapping status as an integer value. - Delegate to get the mapping status from an integer value. - Lock owner id of this mapping - Options for validation operations to perform on opened connection to affected shard. - New instance of mapping with updated information. - - - - Gets the lock owner of a mapping. - - The mapping - Error category to use for the store operation - Lock owner for the mapping. - - - - Locks or unlocks a given mapping or all mappings. - - Optional mapping - The lock onwer id - Operation to perform on this mapping with the given lockOwnerId - Error category to use for the store operation - - - - Validates the input parameters and ensures that the mapping parameter belong to this shard map. - - Mapping to be validated. - Operation being performed. - Parameter name for mapping parameter. - - - - Default shard mapper, that basically is a container of shards with no keys. - - - - - Default shard mapper, which just manages Shards. - - Reference to ShardMapManager. - Containing shard map. - - - - Given a shard, obtains a SqlConnection to the shard. The shard must exist in the mapper. - - Input shard. - - Connection string with credential information, the DataSource and Database are - obtained from the results of the lookup operation. - - Options for validation operations to perform on opened connection. - An opened SqlConnection. - - - - Given a shard, asynchronously obtains a SqlConnection to the shard. The shard must exist in the mapper. - - Input shard. - - Connection string with credential information, the DataSource and Database are - obtained from the results of the lookup operation. - - Options for validation operations to perform on opened connection. - An opened SqlConnection. - - - - Adds a shard. - - Shard being added. - The added shard object. - - - - Removes a shard. - - Shard being removed. - Lock owner id of this mapping - - - - Looks up the given shard in the mapper. - - Input shard. - Whether to use cache for lookups. - Returns the shard after verifying that it is present in mapper. - - - - Tries to looks up the key value and returns the corresponding mapping. - - Input shard. - Whether to use cache for lookups. - Shard that contains the key value. - true if shard is found, false otherwise. - - - - Gets all shards for a shard map. - - All the shards belonging to the shard map. - - - - Gets shard object based on given location. - - Input location. - Shard belonging to ShardMap. - - - - Allows for update to a shard with the updates provided in the parameter. - - Shard to be updated. - Updated properties of the Shard. - New Shard instance with updated information. - - - - Allows users to specify operations such as validation, to perform - on the connection opened by the shard map manager. - - - - - No operation will be performed on the opened connection. - - - - - Validation will be performed on the connection to ensure that - the state of the corresponding mapping has not changed since - the mapping information was last cached at the client. - - - - - Allows users to specify operations such as validation, to perform - on the affected shard in the mapping. - - - - - No operation will be performed on the affected shard. - - - - - Validation operations will be performed on affected shard. - When a mapping is taken offline, connections to the affected - shard will be killed in order to prevent inconsistent or - incomplete results for queries directed against mappings - being changed. - - - - - Container for a collection of keys to shards mappings. - - - - - Container for a collection of keys to shards mappings. - Can provide connection to a shard given a key. - - Key type. - - - - Given a key value, obtains a SqlConnection to the shard in the mapping - that contains the key value. - - Input key value. - - Connection string with credential information, the DataSource and Database are - obtained from the results of the lookup operation for key. - - Options for validation operations to perform on opened connection. - An opened SqlConnection. - - - - Given a key value, asynchronously obtains a SqlConnection to the shard in the mapping - that contains the key value. - - Input key value. - - Connection string with credential information, the DataSource and Database are - obtained from the results of the lookup operation for key. - - Options for validation operations to perform on opened connection. - An opened SqlConnection. - - - - Holder of keys to shards mappings and provides operations over such mappings. - - Type of individual mapping. - Type of values mapped to shards in a mapping. - Key type. - - - - Adds a mapping. - - Mapping being added. - - - - Removes a mapping. - - Mapping being removed. - Lock owner id of the mapping - - - - Looks up the key value and returns the corresponding mapping. - - Input key value. - Whether to use cache for lookups. - Mapping that contains the key value. - - - - Tries to looks up the key value and returns the corresponding mapping. - - Input key value. - Whether to use cache for lookups. - Mapping that contains the key value. - true if mapping is found, false otherwise. - - - - Mapper from single keys (points) to their corresponding shards. - - Key type. - - - - List shard mapper, which managers point mappings. - - Reference to ShardMapManager. - Containing shard map. - - - - Given a key value, obtains a SqlConnection to the shard in the mapping - that contains the key value. - - Input key value. - - Connection string with credential information, the DataSource and Database are - obtained from the results of the lookup operation for key. - - Options for validation operations to perform on opened connection. - An opened SqlConnection. - - - - Given a key value, asynchronously obtains a SqlConnection to the shard in the mapping - that contains the key value. - - Input key value. - - Connection string with credential information, the DataSource and Database are - obtained from the results of the lookup operation for key. - - Options for validation operations to perform on opened connection. - A Task encapsulating an opened SqlConnection. - All non usage-error exceptions will be reported via the returned Task - - - - Marks the given mapping offline. - - Input point mapping. - Lock owner id of this mapping - Options for validation operations to perform on opened connection to affected shard. - An offline mapping. - - - - Marks the given mapping online. - - Input point mapping. - Lock owner id of this mapping - An online mapping. - - - - Adds a point mapping. - - Mapping being added. - The added mapping object. - - - - Removes a point mapping. - - Mapping being removed. - Lock owner id of the mapping - - - - Looks up the key value and returns the corresponding mapping. - - Input key value. - Whether to use cache for lookups. - Mapping that contains the key value. - - - - Tries to looks up the key value and returns the corresponding mapping. - - Input key value. - Whether to use cache for lookups. - Mapping that contains the key value. - true if mapping is found, false otherwise. - - - - Gets all the mappings that exist within given range. - - Optional range value, if null, we cover everything. - Optional shard parameter, if null, we cover all shards. - Read-only collection of mappings that overlap with given range. - - - - Allows for update to a point mapping with the updates provided in - the parameter. - - Mapping being updated. - Updated properties of the Shard. - Lock owner id of this mapping - Options for validation operations to perform on opened connection to affected shard. - New instance of mapping with updated information. - - - - Gets the lock owner of a mapping. - - The mapping - Lock owner for the mapping. - - - - Locks or unlocks a given mapping or all mappings. - - Optional mapping - The lock onwer id - Operation to perform on this mapping with the given lockOwnerId - - - - Mapper from a range of keys to their corresponding shards. - - Key type. - - - - Range shard mapper, which managers range mappings. - - Reference to ShardMapManager. - Containing shard map. - - - - Given a key value, obtains a SqlConnection to the shard in the mapping - that contains the key value. - - Input key value. - - Connection string with credential information, the DataSource and Database are - obtained from the results of the lookup operation for key. - - Options for validation operations to perform on opened connection. - An opened SqlConnection. - - - - Given a key value, asynchronously obtains a SqlConnection to the shard in the mapping - that contains the key value. - - Input key value. - - Connection string with credential information, the DataSource and Database are - obtained from the results of the lookup operation for key. - - Options for validation operations to perform on opened connection. - A Task encapsulating an opened SqlConnection. - - - - Marks the given mapping offline. - - Input range mapping. - Lock owner id of this mapping - Options for validation operations to perform on opened connection to affected shard. - An offline mapping. - - - - Marks the given mapping online. - - Input range mapping. - Lock owner id of this mapping - An online mapping. - - - - Adds a range mapping. - - Mapping being added. - The added mapping object. - - - - Removes a range mapping. - - Mapping being removed. - Lock owner id of this mapping - - - - Looks up the key value and returns the corresponding mapping. - - Input key value. - Whether to use cache for lookups. - Mapping that contains the key value. - - - - Tries to looks up the key value and returns the corresponding mapping. - - Input key value. - Whether to use cache for lookups. - Mapping that contains the key value. - true if mapping is found, false otherwise. - - - - Gets all the mappings that exist within given range. - - Optional range value, if null, we cover everything. - Optional shard parameter, if null, we cover all shards. - Read-only collection of mappings that overlap with given range. - - - - Allows for update to a range mapping with the updates provided in - the parameter. - - Mapping being updated. - Updated properties of the Shard. - Lock owner id of this mapping - Options for validation operations to perform on opened connection to affected shard. - New instance of mapping with updated information. - - - - Splits the given mapping into 2 at the given key. The new mappings point to the same shard - as the existing mapping. - - Given existing mapping. - Split point. - Lock owner id of this mapping - Read-only collection of 2 new mappings thus created. - - - - Merges 2 contiguous mappings into a single mapping. Both left and right mappings should point - to the same location and must be contiguous. - - Left mapping. - Right mapping. - Lock owner id of the left mapping - Lock owner id of the right mapping - Mapping that results from the merge operation. - - - - Gets the lock owner of a mapping. - - The mapping - Lock owner for the mapping. - - - - Locks or unlocks a given mapping or all mappings. - - Optional mapping - The lock onwer id - Operation to perform on this mapping with the given lockOwnerId - - - - Helper methods related to shard map instantiation. - - - - - SqlConnectionStringBuilder property that allows one - to specify the number of reconnect attempts on connection failure - - - - - SqlConnectionStringBuilder property that allows specifying - active directoty authentication to connect to SQL instance. - - - - - String representation of SqlAuthenticationMethod.ActiveDirectoryIntegrated - SqlAuthenticationMethod.ActiveDirectoryIntegrated.ToString() cannot be used - because it may not be available in the .NET framework version that we are running in - - - - - Whether this SqlClient instance supports Connection Resiliency - - - - - Converts IStoreShardMap to ShardMap. - - Reference to shard map manager. - Storage representation for ShardMap. - ShardMap object corresponding to storange representation. - - - - Base class for updates to mappings from shardlets to shards. - - Type of status field. - - - - Records the modified properties for update. - - - - - Holder for update to status property. - - - - - Holder for update to shard property. - - - - - Gets or sets the Status property. - - - - - Gets or sets the Shard property. - - - - - Status property. - - - - - Shard property. - - - - - Checks if any property is set in the given bitmap. - - Properties bitmap. - True if any of the properties is set, false otherwise. - - - - Checks if the mapping is being taken offline. - - Original status. - True of the update will take the mapping offline. - - - - Detects if the current mapping is being taken offline. - - Original status. - Updated status. - Detects in the derived types if the mapping is being taken offline. - - - - Types of supported mappings. - - - - - Interface that represents capability to provide information - relavant to Add/Remove/Update operations for a mapping object. - - - - - ShardMapManager for the object. - - - - - Shard map associated with the mapping. - - - - - Storage representation of the mapping. - - - - - Type of the mapping. - - - - - Mapping type, useful for diagnostics. - - - - - Records the updated properties for a mapping update object. - - - - - Common interface for point/range mapping updates. - - Status type. - - - - Status property. - - - - - Shard property. - - - - - Checks if any property is set in the given bitmap. - - Properties bitmap. - True if any of the properties is set, false otherwise. - - - - Checks if the mapping is being taken offline. - - Original status. - True of the update will take the mapping offline. - - - - Represents capabilities to provide a Shard. - - - - - Shard for the ShardProvider object. - - - - - Performs validation that the local representation is as - up-to-date as the representation on the backing - data store. - - Shard map to which the shard provider belongs. - Connection used for validation. - - - - Asynchronously performs validation that the local representation is as - up-to-date as the representation on the backing - data store. - - Shard map to which the shard provider belongs. - Connection used for validation. - A task to await validation completion - - - - Represents capabilities to provide a Shard along with an associated value. - - Value type. Examples are primitive types, ranges or shards themselves. - - - - Value corresponding to the Shard. Represents traits of the Shard - object provided by the ShardInfo property. - - - - - The Tracer - - - - - Performs validation that the local representation is as up-to-date - as the representation on the backing data store. - - Connection used for validation. - ShardMapManager reference. - Shard map for the mapping. - Mapping to validate. - - - - Asynchronously performs validation that the local representation is as up-to-date - as the representation on the backing data store. - - Connection used for validation. - ShardMapManager reference. - Shard map for the mapping. - Mapping to validate. - A task to await validation completion - - - - Performs validation that the local representation is as - up-to-date as the representation on the backing data store. - - Connection used for validation. - ShardMapManager reference. - Shard map for the shard. - Shard to validate. - - - - Asynchronously performs validation that the local representation is as - up-to-date as the representation on the backing data store. - - Connection used for validation. - ShardMapManager reference. - Shard map for the shard. - Shard to validate. - A task to await validation completion - - - - Represents updates to a mapping between the singleton key value of a shardlet (a point) and the shard that holds its data. - Also see . - - - - - Instantiates a new point mapping update object. - - - - - Detects if the current mapping is being taken offline. - - Original status. - Updated status. - Detects in the derived types if the mapping is being taken offline. - - - - Represents updates to a mapping between a of values and the that stores its data. - Also see . - - - - - Instantiates a new range mapping update object. - - - - - Detects if the current mapping is being taken offline. - - Original status. - Updated status. - Detects in the derived types if the mapping is being taken offline. - - - - Records the updated properties on the shard. - - - - - Represents updates to a Shard. - - - - - Records the modified properties for update. - - - - - Holder for update to status property. - - - - - Instantiates the shard update object with no property set. - - - - - Status property. - - - - - Checks if any of the properties specified in the given bitmap have - been set by the user. - - Bitmap of properties. - True if any property is set, false otherwise. - - - - SQL backed storage representation of a mapping b/w key ranges and shards. - - - - - Constructs an instance of IStoreMapping using a row from SqlDataReader. - - SqlDataReader whose row has mapping information. - Reader offset for column that begins mapping information. - - - - Mapping Id. - - - - - Shard map Id. - - - - - Min value. - - - - - Max value. - - - - - Mapping status. - - - - - The lock owner id of this mapping - - - - - Shard referenced by mapping. Null value means this mapping is local. - - - - - Container for results of Store operations. - - - - - Kinds of results from storage operations. - - - - - Mapping from column name to result type. - - - - - Collection of shard maps in result. - - - - - Collection of shards in result. - - - - - Collection of shard mappings in result. - - - - - Collection of shard locations in result. - - - - - Collection of store operations in result. - - - - - Collection of Schema info in result. - - - - - Version of global or local shard map in result. - - - - - Constructs instance of SqlResults. - - - - - Populates instance of SqlResults using rows from SqlDataReader. - - SqlDataReader whose rows are to be read. - - - - Asynchronously populates instance of SqlResults using rows from SqlDataReader. - - SqlDataReader whose rows are to be read. - A task to await read completion - - - - Storage operation result. - - - - - Collection of shard maps. - - - - - Collection of shards. - - - - - Collection of mappings. - - - - - Collection of store operations. - - - - - Collection of locations. - - - - - Collection of SchemaInfo objects. - - - - - Store version. - - - - - Obtains the result type from first column's name. - - First column's name. - Sql result type. - - - - SQL backed storage representation of a shard. - - - - - Constructs an instance of IStoreShard using parts of a row from SqlDataReader. - Used for creating the shard instance for a mapping. - - SqlDataReader whose row has shard information. - Reader offset for column that begins shard information. - - - - Shard Id. - - - - - Shard version. - - - - - Containing shard map's Id. - - - - - Data source location. - - - - - Shard status. - - - - - SQL based storage representation of a shard map. - - - - - Constructs an instance of IStoreShardMap using a row from SqlDataReader starting at specified offset. - - SqlDataReader whose row has shard map information. - Reader offset for column that begins shard map information.. - - - - Shard map's identity. - - - - - Shard map name. - - - - - Kind of shard map. - - - - - Key type. - - - - - Arguments used to create a . - - Type of the key (point). - - - - Arguments used to create a point mapping. - - Point value being mapped. - Shard used as the mapping target. - Status of the mapping. - - - - Gets the point value being mapped. - - - - - Gets the Shard of the mapping. - - - - - Gets the Status of the mapping. - - - - - Gets the key value associated with the . - - - - - Represents a mapping between the singleton key value of a shardlet (a point) and a . - - Type of the key (point). - - - - Shard object associated with the mapping. - - - - - Constructs a point mapping given mapping creation arguments. - - Owning ShardMapManager. - Mapping creation information. - - - - Internal constructor used for deserialization from store representation of - the mapping object. - - Owning ShardMapManager. - Owning shard map. - Storage representation of the mapping. - - - - Gets Status of the mapping. - - - - - Gets Shard that contains the key value. - - - - - Gets key value. - - - - - Holder of the key value's binary representation. - - - - - Identity of the mapping. - - - - - Identify of the ShardMap this shard belongs to. - - - - - Reference to the ShardMapManager. - - - - - Storage representation of the mapping. - - - - - The Tracer - - - - - Converts the object to its string representation. - - String representation of the object. - - - - Determines whether the specified object is equal to the current object. - - The object to compare with the current object. - True if the specified object is equal to the current object; otherwise, false. - - - - Calculates the hash code for this instance. - - Hash code for the object. - - - - Shard that contains the key value. - - - - - Performs validation that the local representation is as up-to-date - as the representation on the backing data store. - - Shard map to which the shard provider belongs. - Connection used for validation. - - - - Asynchronously performs validation that the local representation is as - up-to-date as the representation on the backing data store. - - Shard map to which the shard provider belongs. - Connection used for validation. - A task to await validation completion - - - - The key value. - - - - - Clones the instance. - - Clone of the instance. - - - - ShardMapManager for the object. - - - - - Shard map associated with the mapping. - - - - - Storage representation of the mapping. - - - - - Type of the mapping. - - - - - Mapping type, useful for diagnostics. - - - - - Public type that represents the owner of a lock held on a mapping - - This class is immutable - - - - Token representing the default state where the mapping isn't locked - - - - - Token that can be used to force an unlock on any locked mapping - - - - - Instantiates an instance of - with the given lock owner id - - The lock owner id - - - - Creates an instance of - - An instance of - - - - Determines whether the specified object is equal to the current object. - - The object to compare with the current object. - True if the specified object is equal to the current object; otherwise, false. - - - - Compares two instances of - to see if they have the same owner - - - True if they both belong to the same lock owner - - - - Equality operator. - - An instance of - An instance of - True if both belong to the same lock owner - - - - Inequality operator. - - An instance of - An instance of - True if both belong to the same lock owner - - - - Calculates the hash code for this instance. - - Hash code for the object. - - - Represents a left-inclusive, right-exclusive range of values of type T. - Type of values. - - - - The shard range value corresponding to this value. - - - - - Constructs range based on its low and high boundary values. - - Low boundary value (inclusive). - High boundary value (exclusive). - - - - Constructs range based on its low boundary value. The low boundary value is - set to the one specified in while the - high boundary value is set to maximum possible value i.e. +infinity. - - Low boundary value (inclusive). - - - - Gets the low boundary value (inclusive). - - - - - Gets the high boundary value (exclusive). - - - - - True if the high boundary value equals +infinity; otherwise, false. - - - - - Converts the object to its string representation. - - String representation of the object. - - - - Calculates the hash code for this instance. - - Hash code for the object. - - - - Determines whether the specified object is equal to the current object. - - The object to compare with the current object. - True if the specified object is equal to the current object; otherwise, false. - - - - Performs equality comparison with another Range. - - Range to compare with. - True if same Range, false otherwise. - - - - Set of operations that can be performed on mappings with lockOwnerId. - - - - - Lock the range mapping with the given lockOwnerId - - - - - Unlock the range mapping that has the given lockOwnerId - - - - - Unlock all the range mappings that have the given lockOwnerId - - - - - Unlock all locked range mappings - - - - - Arguments used to create a . - - Type of the key (boundary values). - - - - Arguments used for creation of a range mapping. - - Range being mapped. - Shard used as the mapping target. - Status of the mapping. - - - - Gets Range being mapped. - - - - - Gets Shard for the mapping. - - - - - Gets Status of the mapping. - - - - - Gets Range associated with the . - - - - - Represents a mapping between a range of key values and a . - - Key type. - - - - Shard object associated with the mapping. - - - - - Constructs a range mapping given mapping creation arguments. - - Owning ShardMapManager. - Mapping creation information. - - - - Internal constructor used for deserialization from store representation of - the mapping object. - - Owning ShardMapManager. - Owning shard map. - Storage representation of the mapping. - - - - Gets the of the mapping. - - - - - Gets Shard that contains the range of values. - - - - - Gets the Range of the mapping. - - - - - Holder of the range value's binary representation. - - - - - Identity of the mapping. - - - - - Identify of the ShardMap this shard belongs to. - - - - - Reference to the ShardMapManager. - - - - - Storage representation of the mapping. - - - - - The Tracer - - - - - Converts the object to its string representation. - - String representation of the object. - - - - Determines whether the specified object is equal to the current object. - - The object to compare with the current object. - True if the specified object is equal to the current object; otherwise, false. - - - - Calculates the hash code for this instance. - - Hash code for the object. - - - - Shard that contains the range of values. - - - - - Performs validation that the local representation is as up-to-date - as the representation on the backing data store. - - Shard map to which the shard provider belongs. - Connection used for validation. - - - - Asynchronously performs validation that the local representation is as - up-to-date as the representation on the backing data store. - - Shard map to which the shard provider belongs. - Connection used for validation. - A task to await validation completion - - - - The range of values. - - - - - Clones the instance which implements the interface. - - Clone of the instance. - - - - ShardMapManager for the object. - - - - - Shard map associated with the mapping. - - - - - Storage representation of the mapping. - - - - - Type of the mapping. - - - - - Mapping type, useful for diagnostics. - - - - - Arguments used to create a . - - - - - Arguments used to create a . - - Location of the shard. - - - - Arguments used to create a . - - Location of the shard. - Status of the shard. - - - - Gets Location of the shard. - - - - - Gets Status of the shard. Users can assign application-specific - values to the status field, which are kept together with the shard for convenience. - - - - - Representation of a single shard. Shards are basically locators for - data sources i.e. s that have been - registered with a shard map. Shards are used in - mapping as targets of mappings (see - and ). - - - - Hashcode for the shard. - - - - Constructs a Shard given shard creation arguments. - - Owning ShardMapManager. - Owning shard map. - Shard creation information. - - - - Internal constructor that uses storage representation. - - Owning ShardMapManager. - Owning shard map. - Storage representation of the shard. - - - - Gets Location of the shard. - - - - - Gets the status of the shard which can be either online or offline. - Connections can only be opened using - on the shard map when the shard is online. Setting the shard status to offline - prevents connections when the shard is undergoing maintenance operations. - - - - - Identity of the shard. Each shard should have a unique one. - - - - - Shard version. - - - - - Shard for the ShardProvider object. - - - - - Value corresponding to the Shard. Represents traits of the Shard - object provided by the ShardInfo property. - - - - - Shard map object to which shard belongs. - - - - - Identify of the ShardMap this shard belongs to. - - - - - Reference to the ShardMapManager. - - - - - Storage representation of the shard. - - - - - The Tracer - - - - - Opens a regular to the specified shard, with . - - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - - - - - Opens a regular to the specified shard. - - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - Options for validation operations to perform on opened connection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - - - - - Asynchronously opens a regular to the specified shard, with . - - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - A Task encapsulating an opened SqlConnection - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - All non-usage errors will be propagated via the returned Task. - - - - - Asynchronously a regular to the specified shard. - - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - Options for validation operations to perform on opened connection. - A Task encapsulating an opened SqlConnection - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - All non-usage errors will be propagated via the returned Task. - - - - - Shard for the ShardProvider object. - - - - - Performs validation that the local representation is as - up-to-date as the representation on the backing data store. - - Shard map to which the shard provider belongs. - Connection used for validation. - - - - Asynchronously performs validation that the local representation is as - up-to-date as the representation on the backing data store. - - Shard map to which the shard provider belongs. - Connection used for validation. - A task to await validation completion - - - - Value corresponding to the Shard. Represents traits of the Shard - object provided by the ShardInfo property. - - - - - Clones the instance. - - Clone of the instance. - - - - Converts the object to its string representation. - - String representation of the object. - - - - Determines whether the specified object is equal to the current object. - - The object to compare with the current object. - True if the specified object is equal to the current object; otherwise, false. - - - - Performs equality comparison with given Shard. - - Shard to compare with. - True if this object is equal to other object, false otherwise. - - - - Calculates the hash code for this instance. - - Hash code for the object. - - - - Calculates the hash code for the object. - - Hash code for the object. - - - - Type of shard key. Currently, only Int32, Int64, Guid and byte[] are the data types supported as shard keys. - - - - - No type specified. - - - - - 32-bit integral value. - - - - - 64-bit integral value. - - - - - UniqueIdentifier value. - - - - - Array of bytes value. - - - - - Date and time value. - - - - - Time value. - - - - - Date and time value with offset. - - - - - A range of shard keys between a low key and a high key. - - - The low key is inclusive (part of the range) while the high key is exclusive - (not part of the range). The ShardRange class is immutable. - - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Full range that starts from the min value for a key to the max value. - - - Hashcode for the shard range. - - - Constructs a shard range from low boundary (inclusive) to high high boundary (exclusive) - Low boundary (inclusive) - High boundary (exclusive) - - - Accessor for low boundary (inclusive). - - - Accessor for high boundary (exclusive). - - - Gets the key type of shard range. - - - - Converts the object to its string representation. - - String representation of the object. - - - - Calculates the hash code for this instance. - - Hash code for the object. - - - - Determines whether the specified object is equal to the current object. - - The object to compare with the current object. - True if the specified object is equal to the current object; otherwise, false. - - - - Performs equality comparison with another given ShardRange. - - ShardRange to compare with. - True if same shard range, false otherwise. - - - Checks whether the specified key is inside the range. - The key to check - True if inside, false otherwise - - - Checks whether the range is inside the range. - The range to check. - True if inside, false otherwise. - - - - Performs comparison between two shard range values. - - The shard range compared with this object. - - -1 : if this range's low boundary is less than the 's low boundary; - -1 : if the low boundary values match and the high boundary value of this range is less than the 's. - 1 : if this range's high boundary is greater than the 's high boundary; - 1 : if the low boundary value of this range is higher than 's low boundary and high boundary value of this range is less than or equal to 's high boundary . - 0 : if this range has the same boundaries as . - - - - - Compares two using lexicographic order (less than). - - Left hand side of the operator. - Right hand side of the operator. - True if lhs < rhs - - - - Compares two using lexicographic order (greater than). - - Left hand side of the operator. - Right hand side of the operator. - True if lhs > rhs - - - - Compares two using lexicographic order (less or equal). - - Left hand side of the operator. - Right hand side of the operator. - True if lhs <= rhs - - - - Compares two using lexicographic order (greater or equal). - - Left hand side of the operator. - Right hand side of the operator. - True if lhs >= rhs - - - - Equality operator. - - Left hand side - Right hand side - True if the two objects are equal, false in all other cases - - - - Inequality operator. - - Left hand side - Right hand side - True if the two objects are not equal, false in all other cases - - - - Gets a shard range corresponding to a specified key type. - - Type of key. - Full range for given key type. - - - Checks whether the range intersects with the current range. - The range to check. - True if it intersects, False otherwise. - - - Returns the intersection of two ranges. - Range to intersect with. - - The intersection of the current range and the specified range, null if ranges dont intersect. - - - - - Calculates the hash code for the object. - - Hash code for the object. - - - - Describes the policy used for initialization of from the store. - - - - - Load all shard maps and their corresponding - mappings into the cache for fast retrieval. - - - - - Load all shard maps and their corresponding - mappings on as needed basis. - - - - - Describes the creation options for shard map manager storage representation. - - - - - If the shard map manager data structures are already present - in the store, then this method will raise exception. - - - - - If the shard map manager data structures are already present - in the store, then this method will overwrite them. - - - - - Factory for s facilitates the creation and management - of shard map manager persistent state. Use this class as the entry point to the library's - object hierarchy. - - - - - The Tracer - - - - - Creates a and its corresponding storage structures in the specified SQL Server database, - with and . - - Connection parameters used for creating shard map manager database. - - A shard map manager object used for performing management and read operations for - shard maps, shards and shard mappings. - - - - - Creates a and its corresponding storage structures in the specified SQL Server database, - with . - - Connection parameters used for creating shard map manager database. - Describes the option selected by the user for creating shard map manager database. - - A shard map manager object used for performing management and read operations for - shard maps, shards and shard mappings. - - - - - Creates a and its corresponding storage structures in the specified SQL Server database, - with . - - Connection parameters used for creating shard map manager database. - Describes the option selected by the user for creating shard map manager database. - Target version of store to create. - - - - Creates a and its corresponding storage structures in the specified SQL Server database, - with . - - Connection parameters used for creating shard map manager database. - Behavior for detecting transient exceptions in the store. - - A shard map manager object used for performing management and read operations for - shard maps, shards and shard mappings. - - - - - Creates a and its corresponding storage structures in the specified SQL Server database. - - Connection parameters used for creating shard map manager database. - Describes the option selected by the user for creating shard map manager database. - Behavior for detecting transient exceptions in the store. - - A shard map manager object used for performing management and read operations for - shard maps, shards and shard mappings. - - - - - Creates a and its corresponding storage structures in the specified SQL Server database. - - Connection parameters used for creating shard map manager database. - Describes the option selected by the user for creating shard map manager database. - Behavior for detecting transient exceptions in the store. - Event handler for store operation retry events. - - A shard map manager object used for performing management and read operations for - shard maps, shards and shard mappings. - - - - - Creates a and its corresponding storage structures in the specified SQL Server database. - - Connection parameters used for creating shard map manager database. - Describes the option selected by the user for creating shard map manager database. - Behavior for performing retries on connections to shard map manager database. - Target version of Store to deploy, this is mainly used for upgrade testing. - Event handler for store operation retry events. - - A shard map manager object used for performing management and read operations for - shard maps, shards and shard mappings. - - - - - Gets from persisted state in a SQL Server database. - - Connection parameters used for performing operations against shard map manager database(s). - Initialization policy. - Shard map manager object used for performing management and read operations for shard maps, - shards and shard mappings or null in case shard map manager does not exist. - - true if a shard map manager object was created, false otherwise. - - - - - Gets from persisted state in a SQL Server database. - - Connection parameters used for performing operations against shard map manager database(s). - Initialization policy. - Shard map manager object used for performing management and read operations for shard maps, - shards and shard mappings or null in case shard map manager does not exist. - Behavior for detecting transient exceptions in the store. - - true if a shard map manager object was created, false otherwise. - - - - - Gets from persisted state in a SQL Server database. - - Connection parameters used for performing operations against shard map manager database(s). - Initialization policy. - Shard map manager object used for performing management and read operations for shard maps, - shards and shard mappings or null in case shard map manager does not exist. - Behavior for detecting transient exceptions in the store. - Event handler for store operation retry events. - - true if a shard map manager object was created, false otherwise. - - - - - Gets from persisted state in a SQL Server database, with . - - Connection parameters used for performing operations against shard map manager database(s). - Initialization policy. - - A shard map manager object used for performing management and read operations for - shard maps, shards and shard mappings. - - - - - Gets from persisted state in a SQL Server database. - - Connection parameters used for performing operations against shard map manager database(s). - Initialization policy. - Behavior for detecting transient exceptions in the store. - - A shard map manager object used for performing management and read operations for - shard maps, shards and shard mappings. - - - - - Create shard management performance counter category and counters - - - - - Gets from persisted state in a SQL Server database. - - Connection parameters used for performing operations against shard map manager database(s). - Initialization policy. - Behavior for detecting transient exceptions in the store. - Event handler for store operation retry events. - - A shard map manager object used for performing management and read operations for - shard maps, shards and shard mappings. - - - - - Gets from persisted state in a SQL Server database. - - Connection parameters used for performing operations against shard map manager database(s). - Initialization policy. - Behavior for detecting transient exceptions in the store. - Event handler for store operation retry events. - Whether to raise exception on failure. - - A shard map manager object used for performing management and read operations for - shard maps, shards and shard mappings or null if the object could not be created. - - - - - Shard key value. Wraps the type and value and allows normalization/denormalization - for serialization. - - - - Size of Guid. - - - Size of Guid. - - - Maximum size allowed for VarBytes keys. - - - String representation of +ve infinity. - - - An empty array. - - - Mapping b/w CLR type and corresponding ShardKeyType. - - - Mapping b/w ShardKeyType and corresponding CLR type. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Represents negative infinity. - - - Type of shard key. - - - - Value as saved in persistent storage. Empty byte array represents the minimum value, - and a null value represents the maximum value. - - - - Hashcode for the shard key. - - - Constructs a shard key using 32-bit integer value. - Input 32-bit integer. - - - Constructs a shard key using 64-bit integer value. - Input 64-bit integer. - - - Constructs a shard key using a Guid. - Input Guid. - - - Constructs a shard key using a byte array. - Input byte array. - - - Constructs a shard key using DateTime value. - Input DateTime. - - - Constructs a shard key using TimeSpan value. - Input TimeSpan. - - - Constructs a shard key using TimeSpan value. - Input DateTimeOffset. - - - Constructs a shard key using given object. - Input object. - - - - Constructs a shard key using given object and keyType. - - The key type of value in object. - Input object. - - - - Instantiates the key with given type and raw value and optionally validates - the key type and raw representation of the value. - - Type of shard key. - Raw value of the key. - Whether to validate the key type and raw value. - - - - True if the key has a value; otherwise, false. Positive infinity returns false. - - - - - Returns true if the key value is negative infinity; otherwise, false. - - - - - True if the key value is positive infinity; otherwise, false. - - - - - Gets a byte array representing the key value. - - - - - Gets the denormalized value of the key. - - - - - Gets the type of the shard key. - - - - - Gets the type of the value present in the object. - - - - - Instantiates a new shard key using the specified type and binary representation. - - Type of the shard key (Int32, Int64, Guid, byte[] etc.). - Binary representation of the key. - A new shard key instance. - - - - Gets the strongly typed value of the shard key. - - Type of the key. - Value of the key. - - - - Converts the object to its string representation. - - String representation of the object. - - - - Calculates the hash code for this instance. - - Hash code for the object. - - - - Determines whether the specified object is equal to the current object. - - The object to compare with the current object. - True if the specified object is equal to the current object; otherwise, false. - - - - Performs equality comparison with another given ShardKey. - - ShardKey to compare with. - True if same shard key, false otherwise. - - - - Compares between two values. - - The compared with this object. - 0 for equality, < -1 if this key is less than , > 1 otherwise. - - - - Compares two using lexicographic order (less than). - - Left hand side of the operator. - Right hand side of the operator. - True if lhs < rhs - - - - Compares two using lexicographic order (greater than). - - Left hand side of the operator. - Right hand side of the operator. - True if lhs > rhs - - - - Compares two using lexicographic order (less or equal). - - Left hand side of the operator. - Right hand side of the operator. - True if lhs <= rhs - - - - Compares two using lexicographic order (greater or equal). - - Left hand side of the operator. - Right hand side of the operator. - True if lhs >= rhs - - - - Equality operator. - - Left hand side - Right hand side - True if the two objects are equal, false in all other cases - - - - Inequality operator. - - Left hand side - Right hand side - True if the two objects are not equal, false in all other cases - - - - Gets the minimum of two shard keys. - - Left hand side. - Right hand side. - Minimum of two shard keys. - - - - Gets the maximum of two shard keys. - - Left hand side. - Right hand side. - Maximum of two shard keys. - - - - Given an object detect its ShardKeyType. - - Given value. Must be non-null. - Corresponding ShardKeyType. - - - - Checks whether the specified type is supported as ShardKey type. - - Input type. - True if supported, false otherwise. - - - - Gets the CLR type corresponding to the specified ShardKeyType. - - Input ShardKeyType. - CLR type. - - - - Gets the ShardKeyType corresponding to CLR type. - - CLR type. - ShardKey type. - - - - Gets the next higher key - - Incremented newly constructed ShardKey - Returns a new ShardKey that is the numerical successor of this ShardKey (add a binary bit). - For example, if this ShardKey has the integer value 0, GetNextKey() returns a ShardKey - with the value 1. Alternatively, if this ShardKey is a byte array with the value 0x1234, - GetNextKey() returns a ShardKey with the value 0x1234...251 zeros....1 - - - - - Mix up the hash key and add the specified value into it. - - The previous value of the hash - The additional value to mix into the hash - The updated hash value - - - - Take an object and convert it to its normalized representation as a byte array. - - The type of the . - The value - The normalized information - - - - Takes a byte array and a shard key type and convert it to its native denormalized C# type. - - The denormalized object - - - - Converts given 32-bit integer to normalized binary representation. - - Input 32-bit integer. - Normalized array of bytes. - - - - Converts given 64-bit integer to normalized binary representation. - - Input 64-bit integer. - Normalized array of bytes. - - - - Converts given GUID to normalized binary representation. - - Input GUID. - Normalized array of bytes. - - - - Converts given DateTime to normalized binary representation. - - Input DateTime value. - Normalized array of bytes. - - - - Converts given TimeSpan to normalized binary representation. - - Input TimeSpan value. - Normalized array of bytes. - - - - Converts given DateTimeOffset to normalized binary representation. - - Input DateTimeOffset value. - Normalized array of bytes. - - - - Converts given byte array to normalized binary representation. - - Input byte array. - Normalized array of bytes. - - - - Truncate tailing zero of a byte array. - - The array from which truncate trailing zeros - a new byte array with non-zero tail - - - - Calculates the hash code for the object. - - Hash code for the object. - - - - Types of transport protocols supported in SQL Server connections. - - - - - Default protocol. - - - - - TCP/IP protocol. - - - - - Named pipes protocol. - - - - - Shared memory protocol. - - - - - Represents the location of a shard in terms of its server name and database name. - This is used to manage connections to the shard and to support other operations on shards. - As opposed to a , a shard location is not registered with the shard map. - - - - Hashcode for the shard location. - - - - Constructor that allows specification of protocol, address, port and database to identify a shard. - - Fully qualified hostname of the server for the shard database. - Name of the shard database. - Transport protcol used for the connection. - Port number for TCP/IP connections. Specify 0 to use the default port for the specified . - - - - Constructor that allows specification of address and database to identify a shard. - - Fully qualified hostname of the server for the shard database. - Name of the shard database. - - - - Constructor that allows specification of address and database to identify a shard. - - Fully qualified hostname of the server for the shard database. - Name of the shard database. - Transport protcol used for the connection. - - - - Protocol name prefix. - - - - - Gets the fully qualified hostname of the server for the shard database. - - - - - Communication port for TCP/IP protocol. If no port is specified, the property returns 0. - - - - - DataSource name which can be used to construct connection string Data Source property. - - - - - Gets the database name of the shard. - - - - - Converts the shard location to its string representation. - - String representation of shard location. - - - - Calculates the hash code for this instance. - - Hash code for the object. - - - - Determines whether the specified object is equal to the current object. - - The object to compare with the current object. - True if the specified object is equal to the current object; otherwise, false. - - - - Performs equality comparison with another given ShardLocation. - - ShardLocation to compare with. - True if same locations, false otherwise. - - - - Calculates the hash code for the object. - - Hash code for the object. - - - - Gets the connection string data source prefix for the supported protocol. - - Connection string prefix containing string representation of protocol. - - - - Gets the connection string data source suffix for supplied port number. - - Connection string suffix containing string representation of port. - - - - Serves as the entry point for creation, management and lookup operations over shard maps. - - - - - Given the connection string, opens up the corresponding data source and obtains the ShardMapManager. - - Credentials for performing ShardMapManager operations. - Factory for store connections. - Factory for store operations. - Cache store. - Initialization policy. - Policy for performing retries on connections to shard map manager database. - Policy for detecting transient errors. - - - - Given the connection string, opens up the corresponding data source and obtains the ShardMapManager. - - Credentials for performing ShardMapManager operations. - Factory for store connections. - Factory for store operations. - Cache store. - Initialization policy. - Policy for performing retries on connections to shard map manager database. - Policy for detecting transient errors. - Event handler for store operation retry events. - - - - Event to be raised on Shard Map Manager store retries. - - - - - Credentials for performing ShardMapManager operations. - - - - - Factory for store connections. - - - - - Factory for store operations. - - - - - Policy for performing retries on connections to shard map manager database. - - - - - Local cache. - - - - - The Tracer - - - - - Creates a list based . - - Type of keys. - Name of shard map. - List shard map with the specified name. - - - - Create a range based . - - Type of keys. - Name of shard map. - Range shard map with the specified name. - - - - Removes the specified shard map. - - Shardmap to be removed. - - - - Obtains all shard maps associated with the shard map manager. - - Collection of shard maps associated with the shard map manager. - - - - Obtains a given the name. - - Name of shard map. - Shardmap with the specificed name. - - - - Tries to obtains a given the name. - - Name of shard map. - Shard map with the specified name. - true if shard map with the specified name was found, false otherwise. - - - - Obtains a given the name. - - Key type. - Name of shard map. - Resulting ShardMap. - - - - Tries to obtains a given the name. - - Key type. - Name of shard map. - Shard map with the specified name. - true if shard map with the specified name was found, false otherwise. - - - - Obtains a given the name. - - Key type. - Name of shard map. - Resulting ShardMap. - - - - Tries to obtains a given the name. - - Key type. - Name of shard map. - Shard map with the specified name. - true if shard map with the specified name was found, false otherwise. - - - - Obtains distinct shard locations from the shard map manager. - - Collection of shard locations associated with the shard map manager. - - - - Upgrades store hosting global shard map to the latest version supported by library. - - - - - Upgrades store location to the latest version supported by library. - - Shard location to upgrade. - - - - Obtains the recovery manager for the current shard map manager instance. - - - Recovery manager for the shard map manager. - - - - - Obtains the schema info collection object for the current shard map manager instance. - - schema info collection for shard map manager. - - - - Finds a shard map from cache if requested and if necessary from global shard map. - - Operation name, useful for diagnostics. - Name of shard map. - Whether to skip first lookup in cache. - Shard map object corresponding to one being searched. - - - - Subscriber function to RetryPolicy.Retrying event. - - Sender object (RetryPolicy) - Event argument. - - - - Publisher for ShardMapManagerRetryingEvent event. - - Event argument. - - - - Upgrades store hosting global shard map to specified version. This will be used for upgrade testing. - - Target store version to deploy. - - - - Upgrades store location to the specified version. This will be used for upgrade testing. - - Shard location to upgrade. - Target store version to deploy. - - - - Performs lookup and conversion operation for shard map with given name. - - Type to convert shard map to. - Operation name, useful for diagnostics. - Shard map name. - Function to downcast a shard map to List/Range/Hash. - Whether to throw exception or return null on failure. - The converted shard map. - - - - Loads the shard map manager and shards from Store. - - - - - Adds a shard to global shard map. - - Operation name, useful for diagnostics. - Storage representation of shard map object. - - - - Removes a shard map from global shard map. - - Shard map to remove. - - - - Obtains all ShardMaps associated with the shard map manager. - - Collection of shard maps associated with the shard map manager. - - - - Get distinct locations for the shard map manager from store. - - Distinct locations from shard map manager. - - - - Upgrades store hosting GSM. - - Target version for store to upgrade to. - - - - Upgrades store at specified location. - - Store location to upgrade. - Target version for store to upgrade to. - - - - - Finds shard map with given name in global shard map. - - Operation name, useful for diagnostics. - Name of shard map to search. - Shard map corresponding to given Id. - - - - Validates the input shard map. This includes: - * Ensuring that shard map belongs to this instance of shard map manager. - - Input shard map. - - - - Ensures that the given shard map name is valid. - - Input shard map name. - - - - Represents a shard map of points where points are of the specified key. - - Key type. - - - - Mapper b/w points and shards. - - - - - Constructs a new instance. - - Reference to ShardMapManager. - Storage representation. - - - - Opens a regular to the shard - to which the specified key value is mapped, with . - - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - An opened SqlConnection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - - - - - Opens a regular to the shard - to which the specified key value is mapped. - - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - Options for validation operations to perform on opened connection. - An opened SqlConnection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - - - - - Asynchronously opens a regular to the shard - to which the specified key value is mapped, with . - - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - A Task encapsulating an open SqlConnection as the result - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - All non-usage error related exceptions are reported via the returned Task. - - - - - Asynchronously opens a regular to the shard - to which the specified key value is mapped. - - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - Options for validation operations to perform on opened connection. - A Task encapsulating an opened SqlConnection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - All non-usage error related exceptions are reported via the returned Task. - - - - - Creates and adds a point mapping to ShardMap. - - Information about mapping to be added. - Newly created mapping. - - - - Creates and adds a point mapping to ShardMap. - - Point for which to create the mapping. - Shard associated with the point mapping. - Newly created mapping. - - - - Removes a point mapping. - - Mapping being removed. - - - - Looks up the key value and returns the corresponding mapping. - - Input key value. - Mapping that contains the key value. - - - - Tries to looks up the key value and place the corresponding mapping in . - - Input key value. - Mapping that contains the key value. - true if mapping is found, false otherwise. - - - - Gets all the point mappings for the shard map. - - Read-only collection of all point mappings on the shard map. - - - - Gets all the mappings that exist within given range. - - Point value, any mapping overlapping with the range will be returned. - Read-only collection of mappings that satisfy the given range constraint. - - - - Gets all the mappings that exist for the given shard. - - Shard for which the mappings will be returned. - Read-only collection of mappings that satisfy the given shard constraint. - - - - Gets all the mappings that exist within given range and given shard. - - Point value, any mapping overlapping with the range will be returned. - Shard for which the mappings will be returned. - Read-only collection of mappings that satisfy the given range and shard constraints. - - - - Marks the specified mapping offline. - - Input point mapping. - An offline mapping. - - - - Marks the specified mapping offline. - - Input point mapping. - Options for validation operations to perform on opened connection to affected shard. - An offline mapping. - - - - Marks the specified mapping online. - - Input point mapping. - An online mapping. - - - - Updates a with the updates provided in - the parameter. - - Mapping being updated. - Updated properties of the mapping. - New instance of mapping with updated information. - - - - Updates a point mapping with the changes provided in - the parameter. - - Mapping being updated. - Updated properties of the Shard. - An instance of - New instance of mapping with updated information. - - - - Gets the lock owner id of the specified mapping. - - Input range mapping. - An instance of - - - - Locks the mapping for the specified owner - The state of a locked mapping can only be modified by the lock owner. - - Input range mapping. - An instance of - - - - Unlocks the specified mapping - - Input range mapping. - An instance of - - - - Unlocks all mappings in this map that belong to the given - - An instance of - - - - Gets the mapper. This method is used by OpenConnection/Lookup of V. - - Shard provider type. - ListShardMapper for given key type. - - - - The Tracer - - - - - Clones the specified list shard map. - - A cloned instance of the list shard map. - - - - Clones the specified shard map. - - A cloned instance of the shard map. - - - - Clones the current shard map instance. - - Cloned shard map instance. - - - - Represents a shard map of ranges. - - Key type. - - - - Mapping b/w key ranges and shards. - - - - - Constructs a new instance. - - Reference to ShardMapManager. - Storage representation. - - - - Opens a regular to the shard - to which the specified key value is mapped, with . - - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - An opened SqlConnection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - - - - - Opens a regular to the shard - to which the specified key value is mapped. - - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - Options for validation operations to perform on opened connection. - An opened SqlConnection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - - - - - Asynchronously opens a regular to the shard - to which the specified key value is mapped, with . - - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - A Task encapsulating an opened SqlConnection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - All non-usage errors will be propagated via the returned Task. - - - - - Asynchronously opens a regular to the shard - to which the specified key value is mapped. - - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - Options for validation operations to perform on opened connection. - A Task encapsulating an opened SqlConnection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - All non-usage errors will be propagated via the returned Task. - - - - - Creates and adds a range mapping to ShardMap. - - Information about mapping to be added. - Newly created mapping. - - - - Creates and adds a range mapping to ShardMap. - - Range for which to create the mapping. - Shard associated with the range mapping. - Newly created mapping. - - - - Removes a range mapping. - - Mapping being removed. - - - - Removes a range mapping. - - Mapping being removed. - An instance of - - - - Looks up the key value and returns the corresponding mapping. - - Input key value. - Mapping that contains the key value. - - - - Tries to looks up the key value and place the corresponding mapping in . - - Input key value. - Mapping that contains the key value. - true if mapping is found, false otherwise. - - - - Gets all the range mappings for the shard map. - - Read-only collection of all range mappings on the shard map. - - - - Gets all the range mappings that exist within given range. - - Range value, any mapping overlapping with the range will be returned. - Read-only collection of mappings that satisfy the given range constraint. - - - - Gets all the range mappings that exist for the given shard. - - Shard for which the mappings will be returned. - Read-only collection of mappings that satisfy the given shard constraint. - - - - Gets all the range mappings that exist within given range and given shard. - - Range value, any mapping overlapping with the range will be returned. - Shard for which the mappings will be returned. - Read-only collection of mappings that satisfy the given range and shard constraints. - - - - Marks the specified mapping offline. - - Input range mapping. - An offline mapping. - - - - Marks the specified mapping offline. - - Input range mapping. - An instance of - An offline mapping. - - - - Marks the specified mapping offline. - - Input range mapping. - Options for validation operations to perform on opened connection to affected shard. - An offline mapping. - - - - Marks the specified mapping offline. - - Input range mapping. - An instance of - Options for validation operations to perform on opened connection to affected shard. - An offline mapping. - - - - Marks the specified mapping online. - - Input range mapping. - An online mapping. - - - - Marks the specified mapping online. - - Input range mapping. - An instance of - An online mapping. - - - - Gets the lock owner id of the specified mapping. - - Input range mapping. - An instance of - - - - Locks the mapping for the specified owner - The state of a locked mapping can only be modified by the lock owner. - - Input range mapping. - An instance of - - - - Unlocks the specified mapping - - Input range mapping. - An instance of - - - - Unlocks all mappings in this map that belong to the given - - An instance of - - - - Updates a with the updates provided in - the parameter. - - Mapping being updated. - Updated properties of the mapping. - New instance of mapping with updated information. - - - - Updates a with the updates provided in - the parameter. - - Mapping being updated. - Updated properties of the mapping. - An instance of - New instance of mapping with updated information. - - - - Splits the specified mapping into two new mappings using the specified key as boundary. - The new mappings point to the same shard as the existing mapping. - - Existing mapping. - Split point. - Read-only collection of two new mappings that were created. - - - - Splits the specified mapping into two new mappings using the specified key as boundary. - The new mappings point to the same shard as the existing mapping. - - Existing mapping. - Split point. - An instance of - Read-only collection of two new mappings that were created. - - - - Merges 2 contiguous mappings into a single mapping. Both left and right mappings should point - to the same location and must be contiguous. - - Left mapping. - Right mapping. - Mapping that results from the merge operation. - - - - Merges 2 contiguous mappings into a single mapping. Both left and right mappings should point - to the same location and must be contiguous. - - Left mapping. - Right mapping. - An instance of for the left mapping - An instance of for the right mapping - Mapping that results from the merge operation. - - - - Gets the mapper. This method is used by OpenConnection/Lookup of V. - - Shard provider type. - RangeShardMapper for given key type. - - - - Clones the given range shard map. - - A cloned instance of the range shard map. - - - - Clones the given shard map. - - A cloned instance of the shard map. - - - - Clones the current shard map instance. - - Cloned shard map instance. - - - - The Tracer - - - - - Represents a collection of shards and mappings between keys and shards in the collection. - - - - - The mapper belonging to the ShardMap. - - - - - Constructs an instance of ShardMap. - - Reference to ShardMapManager. - Storage representation. - - - Shard map name. - - - Shard map type. - - - Shard map key type. - - - - Identity. - - - - - Reference to ShardMapManager. - - - - - Storage representation. - - - - - Suffix added to application name in connections. - - - - - The tracer - - - - - Converts the object to its string representation. - - String representation of the object. - - - - Opens a regular to the shard - to which the specified key value is mapped, with . - - Type of the key. - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - An opened SqlConnection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - This call only works if there is a single default mapping. - - - - - Opens a regular to the shard - to which the specified key value is mapped. - - Type of the key. - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - Options for validation operations to perform on opened connection. - An opened SqlConnection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - This call only works if there is a single default mapping. - - - - - Asynchronously opens a regular to the shard - to which the specified key value is mapped, with . - - Type of the key. - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - A Task encapsulating an opened SqlConnection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - This call only works if there is a single default mapping. - - - - - Asynchronously opens a regular to the shard - to which the specified key value is mapped. - - Type of the key. - Input key value. - - Connection string with credential information such as SQL Server credentials or Integrated Security settings. - The hostname of the server and the database name for the shard are obtained from the lookup operation for key. - - Options for validation operations to perform on opened connection. - A Task encapsulating an opened SqlConnection. - - Note that the object returned by this call is not protected against transient faults. - Callers should follow best practices to protect the connection against transient faults - in their application code, e.g., by using the transient fault handling - functionality in the Enterprise Library from Microsoft Patterns and Practices team. - This call only works if there is a single default mapping. - - - - - Gets all shards from the shard map. - - All shards belonging to the shard map. - - - - Obtains the shard for the specified location. - - Location of the shard. - Shard which has the specified location. - - - - Tries to obtains the shard for the specified location. - - Location of the shard. - Shard which has the specified location. - true if shard with specified location is found, false otherwise. - - - - Creates a new shard and registers it with the shard map. - - Information about shard to be added. - A new shard registered with this shard map. - - - - Atomically adds a shard to ShardMap using the specified location. - - Location of shard to be added. - A shard attached to this shard map. - - - - Removes a shard from ShardMap. - - Shard to remove. - - - - Updates a shard with the changes specified in the parameter. - - Shard being updated. - Updated properties of the shard. - New Shard with updated information. - - - - Opens a connection to the given shard provider. - - Shard provider containing shard to be connected to. - Connection string for connection. Must have credentials. - Options for validation operations to perform on opened connection. - - - - Asynchronously opens a connection to the given shard provider. - - Shard provider containing shard to be connected to. - Connection string for connection. Must have credentials. - Options for validation operations to perform on opened connection. - A task encapsulating the SqlConnection - All exceptions are reported via the returned task. - - - - Gets the mapper. This method is used by OpenConnection and Lookup of V. - - Shard provider type. - Appropriate mapper for the given shard map. - - - - Clones the given shard map. - - A cloned instance of the shard map. - - - - Clones the current shard map instance. - - Cloned shard map instance. - - - - Ensures that the provided connection string is valid and builds the connection string - to be used for DDR connection to the given shard provider. - - Shard provider containing shard to be connected to. - Input connection string. - Connection string for DDR connection. - - - - Extension methods on ShardMaps that allow down-casting. - - - - - Downcasts to ListShardMap of TKey. - - Key type. - Input shard map. - ListShardMap representation of this object. - - - - Downcasts to ListShardMap of TKey. - - Key type. - Input shard map. - Whether to throw exception or return null on failure. - ListShardMap representation of this object. - - - - Downcasts to RangeShardMap of TKey. - - Key type. - Input shard map. - RangeShardMap representation of this object. - - - - Downcasts to RangeShardMap of TKey. - - Key type. - Input shard map. - Whether to throw exception or return null on failure. - RangeShardMap representation of this object. - - - - Raise conversion exception. - - Key type. - Shard map whose conversion failed. - Requested type of shard map. - - - Type of shard map. - - - - Invalid kind of shard map. Only used for serialization/deserialization. - - - - - Shard map with list based mappings. - - - - - Shard map with range based mappings. - - - - - Used for generating storage representation from client side mapping objects. - - - - - Constructs the storage representation from client side objects. - - Identify of mapping. - Shard being converted. - Min key value. - Max key value. - Mapping status. - - - - Constructs the storage representation from client side objects. - - Identify of mapping. - Id of parent shardmap. - IStoreShard - Min key value. - Max key value. - Mapping status. - Lock owner id. - - - - Mapping Id. - - - - - Shard map Id. - - - - - Min value. - - - - - Max value. - - - - - Mapping status. - - - - - The lock owner id of the mapping - - - - - Shard referenced by mapping. - - - - - Used for generating storage representation from client side mapping objects. - - - - - Constructs the storage representation from client side objects. - - Schema info name. - Schema info represented in XML. - - - - Schema info name. - - - - - Schema info represented in XML. - - - - - Used for generating storage representation from client side shard objects. - - - - - Constructs the storage representation from client side objects. - - Shard Id. - Shard version. - Identify of shard map. - Data source location. - Status of the shard. - - - - Shard Id. - - - - - Shard version. - - - - - Containing shard map's Id. - - - - - Data source location. - - - - - Shard status. - - - - - Storage representation of a shard map. - - - - - Constructs an instance of DefaultStoreShardMap used for creating new shard maps. - - Shard map Id. - Shard map name. - Shard map kind. - Shard map key type. - Optional argument for shardId if this instance is for a local shardmap. - - - - Shard map's identity. - - - - - Shard map name. - - - - - Type of shard map. - - - - - Key type. - - - - - The id of the local shardmap. Null if a global shardmap. - - - - - Types of store connections. - - - - - Connection to GSM. - - - - - Connection to LSM Source Shard. - - - - - Connection to LSM Target Shard (useful for Update Location operation only). - - - - - Instance of a store connection. - - - - - Type of store connection. - - - - - Open the store connection. - - - - - Asynchronously opens the store connection. - - Task to await completion of the Open - - - - Open the store connection, and acquire a lock on the store. - - Lock Id. - - - - Closes the store connection. - - - - - Closes the store connection after releasing lock. - - Lock Id. - - - - Acquires a transactional scope on the connection. - - Type of transaction scope. - Transaction scope on the store connection. - - - - Factory for store connections. - - - - - Constructs a new instance of store connection. - - Type of store connection. - Connection string for store. - An unopened instance of the store connection. - - - - Constructs a new instance of user connection. - - Connection string of user. - An unopened instance of the user connection. - - - - Storage representation of a single location. - - - - - Data source location. - - - - - Represents a store operation. - - - - - Identity of operation. - - - - - Operation code. Helps in deserialization during factory method. - - - - - Serialized representation of the operation. - - - - - State from which Undo will start. - - - - - Original shard version for remove steps. - - - - - Original shard version for add steps. - - - - - Storage representation of a mapping b/w key ranges and shards. - - - - - Mapping Id. - - - - - Shard map Id. - - - - - Min value. - - - - - Max value. - - - - - Mapping status. - - - - - Lock owner id of this mapping - - - - - Shard referenced by mapping. - - - - - Numeric storage operation result. - Keep these in sync with GSM and LSM stored procs. - - - - - Representation of storage results from storage API execution. - - - - - Storage operation result. - - - - - Collection of shard maps. - - - - - Collection of shards. - - - - - Collection of mappings. - - - - - Collection of locations. - - - - - Collection of operations. - - - - - Collection of SchemaInfo objects. - - - - - Version of store. - - - - - Storage representation of a shard schema info. - - - - - Schema info name. - - - - - Schema info represented in XML. - - - - - Storage representation of a single shard. - - - - - Shard Id. - - - - - Shard version. - - - - - Containing shard map's Id. - - - - - Data source location. - - - - - Shard status. - - - - - Store representation of a shard map. - - - - - Shard map's identity. - - - - - Shard map name. - - - - - Type of shard map. - - - - - Key type. - - - - - Type of transaction scope. - - - - - A non-transactional scope, uses auto-commit transaction mode. - Useful for performing operations that are not allowed to be - executed within transactions such as Kill connections. - - - - - Read only transaction scope, uses read-committed transaction mode. - Read locks are acquired purely during row read and then released. - - - - - Read write transaction scope, uses repeatable-read transaction mode. - Read locks are held till Commit or Rollback. - - - - - Allows scoping of a transactional operation on the store. - - - - - Type of transaction scope. - - - - - When set to true, implies that the transaction is ready for commit. - - - - - Executes the given operation using the values - as input to the operation. - - Operation to execute. - Input data for operation. - Storage results object. - - - - Asynchronously executes the given operation using the values - as input to the operation. - - Operation to execute. - Input data for operation. - Task encapsulating storage results object. - - - - Executes the given command. - - Command to execute. - Storage results object. - - - - Executes the given set of commands. - - Collection of commands to execute. - - - - Serializes and deserializes the store objects to/from xml format. - - - - - Serializes shard map to xml. - - Element name for shard map. - Shard Map to serialize. - XElement representing Shard Map. - - - - Deserializes shard map from xml. - - XElement representing shard map. - ShardMap read from . - - - - Serializes shard to xml. - - Element name for shard. - Shard to serialize. - XElement representing Shard. - - - - Deserializes shard from xml. - - XElement representing shard. - Shard read from . - - - - Serializes shard mapping to xml. - - Element name for shard mapping. - Shard mapping to serialize. - XElement representing shard mapping. - - - - Deserializes shard mapping from xml. - - XElement representing shard mapping. - XElement representing shard corresponding to shard mapping. - Shard mapping read from and . - - - - Serializes shard location to xml. - - Element name for shard location. - Shard location to serialize. - XElement representing shard location. - - - - Deserializes shard location from xml. - - XElement representing shard location. - Shard location read from . - - - - Serializes a lock object. - - Lock owner. - XElement representing serializes lock object. - - - - Deserializes a lock object. - - XElement representing lock. - Lock owner id for the lock object. - - - - Converts a given shard range to xml. - - Input range. - XElement representing the given range. - - - - Converts a given shard key to xml. - - Input key. - XElement representing the given key. - - - - Serializes schema information to xml. - - Name of the schema information element. - Actual schema info. - XElement representing the given schema info. - - - - Storage representation of shard map manager version - - - - - Store version information. - - - - - SQL backed storage representation of shard map manager store version. - - - - - Constructs an instance of IStoreVersion using parts of a row from SqlDataReader. - - SqlDataReader whose row has shard information. - Reader offset for column that begins shard information. - - - - Store version. - - - - - Instance of a user connection to store. - - - - - Underlying SQL server connection. - - - - - Opens the connection. - - - - - Asynchronously opens the connection. - - Task to await completion of the Open - - - - Representation of exceptions that occur during storage operations. - - - - - Initializes a new instance with a specified error message. - - - - - Initializes a new instance with a specified error message. - - Error message. - - - - Initializes a new instance with a specified formatted error message. - - The format message that describes the error - The arguments to the format string - - - - Initializes a new instance with a specified error message and a reference to the inner exception - that is the cause of this exception. - - A message that describes the error - The exception that is the cause of the current exception - - - - Initializes a new instance with a specified formatted error message and a reference to the - inner exception that is the cause of this exception. - - The format message that describes the error - The exception that is the cause of the current exception - The arguments to the format string - - - - Initializes a new instance with serialized data. - - The object that holds the serialized object data - The contextual information about the source or destination - - - - Utility classes for exception and error handling. - - - - - Checks if given argument is null and if it is, throws an . - - Type of value. - Value provided. - Name of argument whose value is provided in . - - - - Checks if given string argument is null or empty and if it is, throws an . - - Input string. - Name of argument whose value is provided in . - - - - Ensures that the shard map and shard map manager information for given - shard matches the one for current shard map. - - Current shard map manager. - Current shard map. - Input shard. - Operation being performed. - Type of mapping. - - - - Constructs a global store exception object based on the given input parameters. - - Error category. - Underlying store exception. - Operation name. - - ShardManagementException corresponding to the given store exception. - - - - - Constructs a global store exception object based on the given input parameters. - - Error category. - Underlying store exception. - Operation name. - Location of server where error occurred. - - ShardManagementException corresponding to the given store exception. - - - - - Definition of globally useful constants. - - - - - GSM version of store supported by this library. - - - - - LSM version of store supported by this library. - - - - - Default locking timeout value for application locks. - - - - - Version information for Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement code - - - - - Prefix for ShardMapManager in ApplicationName for user connections. - - - - - ShardMapManager ApplicationName for Storage connections. - - - - - ShardMapManager ApplicationName for Storage connections. - - - - - Maximum length of shard map name. - - - - - Maximum length of ApplicationName. - - - - - Maximum size of shard map name. - - - - - Maximum length of shard key. - - - - - Maximum size of shard key. - - - - - Maximum length for a server. - - - - - Maximum size for a server. - - - - - Maximum length for a database. - - - - - Maximum size for a database. - - - - - Represents objects that can clone themselves. - - Type of object - - - - Clones the instance which implements the interface. - - Clone of the instance. - - - - Utility properties and methods used for managing scripts and errors. - - - - - Regular expression for go tokens. - - - - - Regular expression for comment lines. - - - - - Special version number representing first step in upgrade script. - - - - - Special version number representing last step in upgrade script. - Keep this number in sync with upgrade t-sql scripts. - - - - - structure to hold upgrade command batches along with the starting version to apply the upgrade step. - - - - - Major version to apply this upgrade step. - - - - - Minor version to apply this upgrade step. - - - - - Commands in this upgrade step batch. These will be executed only when store is at (this.InitialMajorVersion, this.InitialMinorVersion). - - - - - Construct upgrade steps. - - Expected major version of store to run this upgrade step. - Expected minor version of store to run this upgrade step. - Commands to execute as part of this upgrade step. - - - - Parsed representation of GSM existence check script. - - - - - Parsed representation of GSM creation script. - - - - - Parsed representation of GSM drop script. - - - - - Parsed representation of GSM upgrade script. - - - - - Parsed representation of LSM existence check script. - - - - - Parsed representation of LSM creation script. - - - - - Parsed representation of LSM drop script. - - - - - Parsed representation of LSM upgrade script. - - - - - SQL transient fault detection strategy. - - - - - Transient failure detector function. - - - - - Transient failure detector function. - - - - - Parsed representation of GSM existence check script. - - - - - Parsed representation of GSM creation script. - - - - - Parsed representation of GSM drop script. - - - - - Parsed representation of GSM upgrade script. - - - - - Parsed representation of LSM existence check script. - - - - - Parsed representation of LSM creation script. - - - - - Parsed representation of LSM drop script. - - - - - Parsed representation of LSM upgrade script. - - - - - Reads a varbinary column from the given reader. - - Input reader. - Index of the column. - Buffer representing the data value. - - - - Adds parameter to given command. - - Command to add parameter to. - Parameter name. - Parameter type. - Parameter direction. - Size of parameter, useful for variable length types only. - Parameter value. - Parameter object this created. - - - - Executes the code with SqlException handling. - - Operation to execute. - - - - Executes the code asynchronously with SqlException handling. - - Operation to execute. - Task to await sql exception handling completion - - - - Executes the code with SqlException handling. - - Type of result. - Operation to execute. - Result of the operation. - - - - Asynchronously executes the code with SqlException handling. - - Type of result. - Operation to execute. - Task encapsulating the result of the operation. - - - - Filters collection of upgrade steps based on the specified target version of store. - - Collection of upgrade steps. - Target version of store. - Current version of store. - Collection of string builder that represent batches of commands to upgrade store to specified target version. - - - - Splits the input script into batches of individual commands, the go token is - considered the separation boundary. Also skips comment lines. - - Input script. - Collection of string builder that represent batches of commands. - - - - Split upgrade scripts into batches of upgrade steps, the go token is - considered as separation boundary of batches. - - Whether to parse ShardMapManagerLocal upgrade scripts, default = false - - - - - Utility class for high precision time keeping. - - - - - Ticks per millisecond = 10,000 - - - - - Ticks per second = 10,000,000 - - - - - Frequency per tick of timer. - - - - - Finds the appropriate tick frequency based on the timer we are using. - - - - - Obtains the current timestamp. - - Current timestamp. - - - - Finds the time that has elapsed since the given . - - Original start timestamp. - Milliseconds interval b/w original and current time. - - - - Mutual exclusion construct for values. - - Type of values. - - - - Global lock for mutual exclusion on the global dictionary of values. - - - - - Existing collection of values. - - - - - Value being locked. - - - - - Reference counter for the value. - - - - - Constructs an instace of lock on input value and locks it. - - Value being locked. - - - - Releases the reference on the value, unlocks it if reference - count reaches 0. - - - - - Reference counter implementation. - - - - - Number of references. - - - - - Instantiates the reference counter, initally set to 1. - - - - - Increments reference count. - - - - - Decrements the reference count. - - New value of reference count. - - - - Implementation of name locks. Allows mutual exclusion on names. - - - - - Instantiates a name lock with given name and acquires the name lock. - - Given name. - - - - Implementation of Id locks. Allows mutual exclusion on Ids. - - - - - Instantiates an Id lock with given Id and acquires the name lock. - - Given id. - - - - Utility methods for string manipulation. - - - - - Lookup array for converting byte[] to string. - - - - - Creates a formatted string which is culture invariant with given arguments. - - Input string. - Collection of formatting arguments. - Formatted string. - - - - Converts the given byte array to its string representation. - - Input byte array. - String representation of the byte array. - - - - Converts the given string to its byte array representation. - - Input string. - Byte representation of the string. - - - - Converts given character to its binary representation. - - Input character. - Byte representation of input character. - - - - Version information for Microsoft.Azure.SqlDatabase.ElasticScale.Query code. - - - - - Custom exception that is thrown when the is in an invalid state. - If you experience this exception repeatedly, please contact Microsoft Customer Support. - - - - - Initializes a new instance of the MultiShardDataReaderInternalException class. - - - - - Initializes a new instance of the MultiShardDataReaderInternalException class with a - specified error message. - - The message that describes the error. - - - - Initializes a new instance of the MultiShardDataReaderInternalException class - with a message and an inner exception. - - The message to encapsulate in the exception. - The underlying exception that causes this exception. - - - - Initializes a new instance of the MultiShardDataReaderInternalException class - with serialized data and context. - - - The holds the serialized object data about the exception being thrown. - - - The that contains contextual information about the source or destination. - - - - - Simple, immutable class for affiliating a DbDataReader with additional information - related to the reader (e.g. DbCommand, shard, exceptions encountered etc) - Useful when grabbing DbDataReaders asynchronously. - - - - - Whether DbDataReader has been disposed or not. - - - - - Simple constructor to set up an immutable LabeledDbDataReader object. - - The DbDataReader to keep track of. - The Shard this reader belongs to - The command object that produced ther reader. - - If either of the arguments is null. - - - - - The location of the shard - - - - - The Shard location information - - - - - The exception encountered when trying to execute against this reader - Could be null if the DbDataReader was instantiated successfully for this Shard - - - - - The DbDataReader to keep track of. - Could be null if we encountered an exception whilst executing the command against this shard - - - - - The DbConnection associated with this reader - - - - - The command object that produces this reader. - - - - - Custom exception to throw when the is closed and - the user attempts to perform an operation on the closed reader. - - - - - Initializes a new instance of the MultiShardReaderClosedException class with a specified error message and a - reference to the inner exception that is the cause of this exception. - - The error message that explains the reason for the exception. - - The exception that is the cause of the current exception, or a null reference - if no inner exception is specified. - - - - - Initializes a new instance of the MultiShardDataReaderClosedException class with a specified error message. - - The message that describes the error. - - - - Initializes a new instance of the MultiShardDataReaderClosedException class. - - - - - Initializes a new instance of the MultiShardDataReaderClosedException class with serialized data. - - - The SerializationInfo that holds the serialized object data about the exception being thrown. - - - The StreamingContext that contains contextual information about the source or destination. - - - - - Represents one or more errors that occured - when executing a query across a shard set. The InnerExceptions field collects - these exceptions and one can iterate through the InnerExceptions - for further inspection or processing. - - - - - Initializes a new instance of the class - - - - - Initializes a new instance of the class - - The error message that explains the reason for the exception - - - - Initializes a new instance of the class - - The that caused the current exception - - - - Initializes a new instance of the MultiShardAggregateException class with serialized data. - - The object that holds the serialized object data. - The contextual information about the source or destination. - - - - - - - - - - - Initializes a new instance of the class - - A list of that caused the current exception - - - - Initializes a new instance of the class - - The error message that explains the reason for the exception - A list of that caused the current exception - The is null - - - - Populates a SerializationInfo with the data needed to serialize the target object. - - The SerializationInfo to populate with data. - The destination (see StreamingContext) for this serialization. - - - - Gets a read-only collection of the instances - that caused the current exception. - - - - - Provides a string representation of this exception - including its inner exceptions. - - - - - DEVNOTE: Encapsulate SMM ShardLocation type for now since Shard isn't Serializable - Support for serialization of ShardLocation is in the works. - - A MultiShardException represents an exception that occured when performing operations against a shard. - It provides information about both the identity of the shard and the expection that occurred. - Depending on the nature of the exception, one can try re-running the multi-shard query, - execute a separate query targeted directly at the shard(s) on that yielded the expection, - or lastly execute the query manually against the shard using a common tool such as SSMS. - - - - - Initializes a new instance of the class with - the specified shard location. - - specifies the location of the shard where the exception occurred. - - - - Initializes a new instance of the class with - the specified shard location and error message. - - specifies the location of the shard where the exception occurred. - specifices the message that explains the reason for the exception. - - - - Initializes a new instance of the class with - the specified shard location and exception. - - specifies the location of the shard where the exception occurred. - specifies the exception encountered at the shard. - - - - Initializes a new instance of the class with - the specified shard location, error message and exception encountered. - - specifies the location of the shard where the exception occurred. - specifices the message that explains the reason for the exception. - specifies the exception encountered at the shard. - The is null - - - - Initializes a new instance of the MultiShardException class with the specified error message and the - reference to the inner exception that is the cause of this exception. - - specifices the message that explains the reason for the exception. - specifies the exception encountered at the shard. - - - - Initializes a new instance of the MultiShardException class with the specified error message. - - specifies the exception encountered at the shard. - - - - Initializes a new instance of the MultiShardException class. - - - - - Initializes a new instance of the MultiShardException class with serialized data. - - - The see that holds the serialized object data about the exception being thrown. - - - The that contains contextual information about the source or destination. - - - - - Populates the provided parameter with the data needed to serialize the target object. - - object to populate with data. - The destination object for this serialization. - - - - The shard associated with this exception - - - - - Creates and returns a string representation of the current . - - String representation of the current exception. - - - - Trace helper for CrossShardQuery - - - - - The trace source name for cross shard query - - - - - The tracer - - - - - Defines the available options when - executing commands against multiple shards - - This enumeration has a flags attribute - - - , - Execute without any options enabled - - - - - Whether the $ShardName pseudo column should be included - in the result-sets. - - - - - Defines the possible query execution policies - - - - - With the complete results execution policy an unsuccessful - execution against any shard leads to all results being discarded - and an exception being thrown either by the ExecuteReader method - on the command or the Read method on the reader. - - - - - A best-effort execution policy that, unlike CompleteResults, tolerates unsuccessful command execution - on some (but not all) shards and returns the results of the successful commands. - Any errors encountered are returned to the user along with the partial results. - The caller can inspect exceptions encountered during execution through - the property of . - - - - - Provides the transient error detection logic for transient faults that are specific to cross shard query. - - - - - Delegate used for detecting transient faults. - - - - - Standard transient error detection strategy. - - - - - Creates a new instance of transient error detection strategy for Shard map manager. - - Behavior for detecting transient errors. - - - - Determines whether the specified exception represents a transient failure that can be compensated by a retry. - - The exception object to be verified. - true if the specified exception is considered as transient; otherwise, false. - - - - Input to be passed to per-shard event handlers. - - - - - The exception to process, if applicable. Null if no exception was thrown. - - - - - The location of the shard on which the MultiShardCommand is currently executing. - - - - - FOR INTERNAL USE ONLY: - The returned input reader. - - - - - Custom exception thrown when the schema on at least one of the shards - participating in the overall query does not conform to the expected schema - for the multi-shard query as a whole. - - - - - Initializes a new instance of the MultiShardSchemaMismatchException class with the specified error message and the - reference to the inner exception that is the cause of this exception. - - specifices the message that explains the reason for the exception. - specifies the exception encountered at the shard. - - - - Initializes a new instance of the MultiShardSchemaMismatchException class with the specified error message. - - specifices the message that explains the reason for the exception. - - - - Initializes a new instance of the MultiShardSchemaMismatchException class. - - - - - Initializes a new instance of the MultiShardSchemaMismatchException class with serialized data. - - - The see that holds the serialized object data about the exception being thrown. - - - The that contains contextual information about the source or destination. - - - - - Represents a connection to a set of shards and provides the ability to process queries across the shard set. - - - - - The suffix to append to each shard's ApplicationName - Will help with server-side telemetry - - - - - The tracer - - - - - Whether this instance has already been disposed - - - - - Initializes a new instance of the class. - - The collection of s used for this connection instances. - - These credentials will be used to connect to the s. - The same credentials are used on all shards. - Therefore, all shards need to provide the appropriate permissions for these credentials to execute the command. - - - Multiple Active Result Sets (MARS) are not supported and are disabled for any processing at the shards. - - - - - Initializes a new instance of the class. - - The collection of s used for this connection instances. - - These credentials will be used to connect to the s. - The same credentials are used on all shards. - Therefore, all shards need to provide the appropriate permissions for these credentials to execute the command. - - - Multiple Active Result Sets (MARS) are not supported and are disabled for any processing at the shards. - - - - - Creates an instance of this class - /* TEST ONLY */ - - Connections to the shards - - - - Gets the collection of s associated with this connection. - - - - - Gets the collection of s associated with this connection. - - - - - Creates and returns a object. - The object can then be used to - execute a command against all shards specified in the connection. - - the with set to null. - - - - Releases all resources used by this object. - - - - - Closes any open connections to shards - - Does a best-effort close and doesn't throw - - - - Complements the with a command object - similar to the triad of , , and . - The takes a T-SQL command statement as its input and executes the - command across its collection of shards specified by its corresponding . - The results from processing the are made available through the - execute methods and the . - - - - - Default command timeout per shard in seconds - - - - - Default command timeout in seconds - - - - - The ILogger - - - - - The sql command to be executed against shards - - - - - Lock to enable thread-safe Cancel() - - - - - Global token source to enable cancellation of commands being executed - - - - - Task associated with current command invocation - - - - - ActivityId of the current command being executed - - - - - Whether this command has already been disposed. - - - - - Creates an instance of this class - - The connection to shards - The command to execute against the shards - Command timeout - against ALL shards - - - - Instance constructor of this class - Default command timeout of 300 seconds is used - - The connection to shards - The command text to execute against shards - - - - - Instance constructor of this class - Default command type is text - - The connection to shards - - Command timeout for given commandText to be run - against ALL shards - - - - - Creates an instance of this class - - The connection handle to all shards - A sql command from which the commandText, commandTimeout, commandType will be inferred. Should implement ICloneable - Command timeout for given commandText to be run against ALL shards - - DEVNOTE: Should we expose a DbCommand instead? Do we even want to expose this at all? - - - - Gets or sets the command text to execute against the set of shards. - - - - - Time in seconds to wait for the command to be executed on ALL shards. - A value of 0 indicates no wait time limit. The default is 300 seconds. - - - - - This property controls the timeout for running - a command against individual shards. - - - - - The of the command to be executed. - - - - - The associated with this command. - - - - - The retry behavior for detecting transient faults that could occur when connecting to and - executing commands against individual shards. - - - The is the default. - - - - - The execution policy to use when executing - commands against shards. Through this policy, - users can control whether complete results are required, - or whether partial results are acceptable. - - - - - Gets the current instance of the associated with this command. - - - - - Gets or sets options that control how the command is executed. - For instance, you can use this to include the shard name as - an additional column into the result. - - - - - The event handler invoked when execution has begun on a given shard. - - - - - The event handler invoked when execution has successfully completed on a given shard or its - shard-specific has been returned. - - - - - The event handler invoked when execution on a given shard has faulted. This handler is only - invoked on exceptions for which execution could not be retried further as a result of - the exception's non-transience or as a result of the chosen . - - - - - The event handler invoked when execution on a given shard is canceled, either explicitly via - the provided or implicitly as a result of the chosen - . - - - - - The event handler invoked when ExecuteDataReader on a certain shard has successfully returned - a reader. This is an internal-only method, and differs from ShardExecutionSucceeded in that - it is invoked BEFORE the reader is added to the MultiShardDataReader; this adding is rife - with side effects that are difficult to isolate. - - - - - The retry policy to use when connecting to and - executing commands against individual shards. - - - - - Gets the SqlParameter Collection - - - - - The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard - and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a - . The execution policy regarding result completeness can be controlled - by setting the . The default execution policy is to return complete results. - - the instance with the overall concatenated result set. - thrown if the commandText is null or empty - thrown if the CommandTimeout elapsed prior to completion - - - - - Runs the given query against all shards and returns - a reader that encompasses results from them. - - Uses the MultiShardExecutionPolicy.CompleteResults as the default execution policy - - Includes the $ShardName pseudo column in the results - Command behavior to use - MultiShardDataReader instance that encompasses results from all shards - If the commandText is null or empty - If the command behavior is not supported - (CloseConnection or SingleResult or SingleRow) - If the CommandTimeout elapsed prior to completion - - - - - The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard - and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a - . The execution policy regarding result completeness can be controlled - by setting the . The default execution policy is to return complete results. - - the instance with the overall concatenated result set. - thrown if the commandText is null or empty, or if the - specified command behavior is not supported such as CloseConnection or SingleRow. - thrown if the CommandTimeout elapsed prior to completion. - specifies the to use. - - - - - Runs the given query against all shards and returns - a reader that encompasses results from them. - - Design Principles - - Commands are executed in a parallel, non-blocking manner. - - Only the calling thread is blocked until the command is complete against all shards. - - Command behavior to use - The retry policy to use when executing commands against the shards - The retry policy to use when connecting to shards - The execution policy to use - MultiShardDataReader instance that encompasses results from all shards - If the commandText is null or empty - If the CommandTimeout elapsed prior to completion - If one or more errors occured while executing the command - - - - The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard - and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a - . The execution policy regarding result completeness can be controlled - by setting the . The default execution policy is to return complete results. - - a task warapping the instance with the overall concatenated result set. - thrown if the commandText is null or empty, or if the - specified command behavior is not supported such as CloseConnection or SingleRow. - thrown if the CommandTimeout elapsed prior to completion. - Any exceptions during command execution are conveyed via the returned Task. - - - - The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard - and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a - . The execution policy regarding result completeness can be controlled - by setting the . The default execution policy is to return complete results. - - a task warapping the instance with the overall concatenated result set. - thrown if the commandText is null or empty, or if the - specified command behavior is not supported such as CloseConnection or SingleRow. - thrown if the CommandTimeout elapsed prior to completion. - Cancellation token to cancel the command execution - Any exceptions during command execution are conveyed via the returned Task. - - - - - Executes the given query against all shards asynchronously - - Uses the MultiShardExecutionPolicy.CompleteResults as the default execution policy - - Includes the $ShardName pseudo column in the results - - Command behavior to use - Cancellation token to cancel the command execution - A task with a TResult that encompasses results from all shards - Any exceptions during command execution are conveyed via the returned Task - If the commandText is null or empty - - - - The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard - and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a - . The execution policy regarding result completeness can be controlled - by setting the . The default execution policy is to return complete results. - - a task warapping the instance with the overall concatenated result set. - thrown if the commandText is null or empty, or if the - specified command behavior is not supported such as CloseConnection or SingleRow. - thrown if the CommandTimeout elapsed prior to completion. - Command behavior to use - Cancellation token to cancel the command execution - Any exceptions during command execution are conveyed via the returned Task. - - - - Executes the given query against all shards asynchronously - - Command behavior to use - Cancellation token to cancel the command execution - The retry policy to use when executing commands against the shards - The retry policy to use when connecting to shards - The execution policy to use - A task with a TResult that encompasses results from all shards - Any exceptions during command execution are conveyed via the returned Task - If the commandText is null or empty - - - - Terminates any active commands/readers for scenarios where we fail the request due to - strict execution policy or cancellation. - - Collection of reader tasks associated with execution across all shards. - - - - Helper that generates a Task to return a LabaledDbDataReader rather than just a plain DbDataReader - so that we can affiliate the shard label with the Task returned from a call to DbCommand.ExecuteReaderAsync. - - Command behavior to use - A tuple of the Shard and the command to be executed - Manages the cancellation tokens - The retry policy to use when executing commands against the shards - The retry policy to use when connecting to shards - The execution policy to use - A Task that will return a LabaledDbDataReader. - - We should be able to tap into this code to trap and gracefully deal with command execution errors as well. - - - - - Attempts to cancel an in progress - and any ongoing work that is performed at the shards on behalf of the command. - - - - - Creates a new instance of a object. - - - - - - Creates an instance of the DbParameter - - - - - - Dispose off any unmanaged/managed resources held - - - - - - Resets the property - to its default value - - - - - Resets the property - to its default value - - - - - Whether execution is already in progress - against this command instance - - True if execution is in progress - - - - Creates a list of commands to be executed against the shards associated with the connection. - - Pairs of shard locations and associated commands. - - - - Raise the ShardExecutionBegan event. - - The shard for which this event is raised. - - - - Raise the ShardExecutionSucceeded event. - - The shard for which this event is raised. - The reader to pass in the associated eventArgs. - - - - Raise the ShardExecutionReaderReturned event. - - The shard for which this event is raised. - The reader to pass in the associated eventArgs. - - - - Raise the ShardExecutionFaulted event. - - The shard for which this event is raised. - The exception causing the execution on this shard to fault. - - - - Raise the ShardExecutionCanceled event. - - The shard for which this event is raised. - - - - This method is currently not supported. Invoking the property will result in an exception. - - - - - ExecuteNonQuery is currently not supported - - - - - - ExecuteNonQueryAsync is currently not supported - - The cancellation token - - - - - Test only for now - - - - - - - - ExecuteScalar is currently not supported - - - - - - ExecuteScalarAsync is currently not supported - - The cancellation token - - - - - This property is currently not supported. Accessing the property will result in an exception. - - - - - This property is currently not supported. Accessing the property will result in an exception. - - - - - This property is currently not supported. Accessing the property will result in an exception. - - DEVNOTE(VSTS 2202707): Do we want to support this? - - - - Connections to shards. Not supported/exposed - since connections are managed internally by this instance - - - - - Sets up and manages the cancellation of the Execute* methods. - - - - - Encapsulates data structures representing state of tasks executing across all the shards. - - - - - Parent task of all per-shard tasks. - - - - - Collection of inner tasks that run against each shard. - - - - - Provides a way of reading a forward-only stream of rows that is retrieved from a shard set. - - - - - Name of Shard Id pseudo column. - - - - - Collection of labeled readers. - - - - - Lock for mutually exclusive access to labeled readers collection. - - - - - Lock for mutual exclusion between cancellation request and close of readers while trying - to read next row from MultiShardDataReader object. - - - - - Whether the reader has a shard-id column. - - - - - Instantiates a MultiShardDataReader object that wraps DbDataReader objects. - The DbDataReader objects themselves get added to the MultiShardDataReader via - calls to AddReader. - - The associated with this reader - The from each shard - The execution policy to use - True if we should add the $ShardName pseudo column, false if not. - (Optional) If a number greater than the length of inputReaders is - specified, the MultiShardDataReader is left open for additional calls to AddReader at a later time. - If the complete results execution policy is used and - the schema isn't the same across shards - - - - Gets the associated with the MultiShardDataReader. - - - - - Gets the collection of exceptions encountered when processing the command across the shards. - The collection is populated when is chosen - as the execution policy for the command. - - - - - Gets the execution policy that will be used to execute commands. - - - - - Closes the MultiShardDataReader object. - - - Similar to DbDataReader, close is idempotent. - - - - - This method is currently not supported. Invoking the method will result in an exception. - - The of the object that the new will reference. - - - - Determines whether the specified object is equal to the current object. (Inherited from .) - - the object to compare with the current object. - True if the specified object is equal to the current object; otherwise, false. - - - - Gets the value of the specified column as a Boolean. - - The zero-based column ordinal. - The value of the specified column. - - - - Gets the value of the specified column as a byte. - - The zero-based column ordinal. - The value of the specified column. - - - - Reads a stream of bytes from the specified column, starting at location indicated by dataOffset, into the - buffer, starting at the location indicated by bufferOffset. - - The zero-based column ordinal. - The index within the row from which to begin the read operation. - The buffer into which to copy the data. - The index with the buffer to which the data will be copied. - The maximum number of characters to read. - The actual number of bytes read. - - - - Gets the value of the specified column as a single character. - - The zero-based column ordinal. - The value of the specified column. - Per MSDN, this is not supported for SqlDataReader. - - - - Reads a stream of characters from the specified column, starting at location indicated by dataOffset, into - the buffer, starting at the location indicated by bufferOffset. - - The zero-based column ordinal. - The index within the row from which to begin the read operation. - The buffer into which to copy the data. - The index with the buffer to which the data will be copied. - The maximum number of characters to read. - The actual number of characters read. - - - - Gets name of the data type of the specified column. - - The zero-based column ordinal. - A string representing the name of the data type. - - - - Gets the value of the specified column as a DateTime object. - - The zero-based column ordinal. - The value of the specified column. - - - - Gets the value of the specified column as a DateTimeOffset object. - - The zero-based column ordinal. - The value of the specified column. - - - - Returns a DbDataReader object for the requested column ordinal that can be overridden with a - provider-specific implementation. - - The zero-based column ordinal. - A DbDataReader object. - - - - - - Gets the value of the specified column as a decimal object. - - The zero-based column ordinal. - The value of the specified column. - - - - Gets the value of the specified column as a double object. - - The zero-based column ordinal. - The value of the specified column. - - - - This method is currently not supported. Invoking the method will result in an exception. - - DEVNOTE VSTS 2202727: Right now this throws a NotSupportedException. We need to create an object that handles the iteration properly. - When we do the implementation we should consider sub-classing DbEnumerator. - - - - Gets the data type of the specified column. - - The zero-based column ordinal. - The data type of the specified column. - - - - Synchronously gets the value of the specified column as a type. - - The Type to get the value of the column as. - The zero-based column ordinal. - The value of the specified column. - - - - Asynchronously gets the value of the specified column as a type. - - The type of the value to be returned. - The zero-based column ordinal. - - The cancellation instruction, which propagates a notification that operations should be canceled. This does - not guarantee the cancellation. A setting of CancellationToken.None makes this method equivalent to - GetFieldValueAsync. The returned task must be marked as cancelled. - - The value of the specified column. - - - - Gets the value of the specified column as a single-precision floating point number. - - The zero-based column ordinal. - The value of the specified column. - - - - Gets the value of the specified column as a globally-unique identifier (GUID). - - The zero-based column ordinal. - The value of the specified column. - - - - Serves as the default hash function that is useful for quick checks on equality. - - A hash code for the current object. - - - - Gets the value of the specified column as a 16-bit signed integer. - - The zero-based column ordinal. - The value of the specified column. - - - - Gets the value of the specified column as a 32-bit signed integer. - - The zero-based column ordinal. - The value of the specified column. - - - - Gets the value of the specified column as a 64-bit signed integer. - - The zero-based column ordinal. - The value of the specified column. - - - - Gets the name of the column, given the zero-based column ordinal. - - The zero-based column ordinal. - The name of the specified column. - - - - Gets the column ordinal given the name of the column. - - The name of the column. - The zero-based column ordinal. - - - - Returns the provider-specific field type of the specified column. - - The zero-based column ordinal. - The Type object that describes the data type of the specified column. - - - - Gets the value of the specified column as an instance of Object. - - The zero-based column ordinal. - The value of the specified column. - - - - Gets all provider-specific attribute columns in the collection for the current row. - - An array of Object into which to copy the attribute columns. - The number of instances of Object in the array. - - - - Returns a that describes the column metadata of the MultiShardDataReader. - - A that describes the column metadata. - - - - Gets the value of the specified column as a SqlBinary. - - The zero-based column ordinal. - The value of the column expressed as a SqlBinary. - - - - Gets the value of the specified column as a SqlBoolean. - - The zero-based column ordinal. - The value of the column expressed as a SqlBoolean. - - - - Gets the value of the specified column as a SqlByte. - - The zero-based column ordinal. - The value of the column expressed as a SqlByte. - - - - Gets the value of the specified column as a SqlBytes. - - The zero-based column ordinal. - The value of the column expressed as a SqlBytes. - - - - Gets the value of the specified column as a SqlChars. - - The zero-based column ordinal. - The value of the column expressed as a SqlChars. - - - - Gets the value of the specified column as a SqlDateTime. - - The zero-based column ordinal. - The value of the column expressed as a SqlDateTime. - - - - Gets the value of the specified column as a SqlDecimal. - - The zero-based column ordinal. - The value of the column expressed as a SqlDecimal. - - - - Gets the value of the specified column as a SqlDouble. - - The zero-based column ordinal. - The value of the column expressed as a SqlDouble. - - - - Gets the value of the specified column as a SqlGuid. - - The zero-based column ordinal. - The value of the column expressed as a SqlGuid. - - - - Gets the value of the specified column as a SqlInt16. - - The zero-based column ordinal. - The value of the column expressed as a SqlInt16. - - - - Gets the value of the specified column as a SqlInt32. - - The zero-based column ordinal. - The value of the column expressed as a SqlInt32. - - - - Gets the value of the specified column as a SqlInt64. - - The zero-based column ordinal. - The value of the column expressed as a SqlInt64. - - - - Gets the value of the specified column as a SqlMoney. - - The zero-based column ordinal. - The value of the column expressed as a SqlMoney. - - - - Gets the value of the specified column as a SqlSingle. - - The zero-based column ordinal. - The value of the column expressed as a SqlSingle. - - - - Gets the value of the specified column as a SqlString. - - The zero-based column ordinal. - The value of the column expressed as a SqlString. - - - - Returns the data value in the specified column as a native SQL Server type. - - The zero-based column ordinal. - The value of the column expressed as a SqlDbType. - - - - Fills an array of Object that contains the values for all the columns in the record, - expressed as native SQL Server types. - - - An array of Object into which to copy the values. The column values are expressed as SQL Server types. - - An integer indicating the number of columns copied. - - - - Gets the value of the specified column as an XML value. - - The zero-based column ordinal. - A SqlXml value that contains the XML stored within the corresponding field. - - - - Retrieves data as a Stream. - - The zero-based column ordinal. - The returned object. - Let the active DbDataReader handle it. It only supports Binary, VarBinary, Udt and Xml types - - - - Gets the value of the specified column as an instance of String. - - The zero-based column ordinal. - The value of the specified column. - - - - Retrieves data as a TextReader. - - The zero-based column ordinal. - The returned object. - We let DbDataReader handle it which returns a TextReader to read the column - - - - Retrieves the value of the specified column as a TimeSpan object. - - The zero-based column ordinal. - The value of the specified column. - - - - Gets the value of the specified column as an instance of Object. - - The zero-based column ordinal. - The value of the specified column. - - - - Populates an array of objects with the column values of the current row. - - An array of Object into which to copy the attribute columns. - The number of instances of Object in the array. - - - - Retrieves data of type XML as an XmlReader. - - The zero-based column ordinal. - The data as an XmlReader. - - - - This method is currently not supported. Invoking the method will result in an exception. - - - - - Gets a value that indicates whether the column contains nonexistent or missing values (NULL values). - - The zero-based column ordinal. - True if the specified column is equivalent to DBNull; otherwise false. - - - - An asynchronous version of IsDBNull, which gets a value that indicates whether the column contains - nonexistent or missing values (NULL values). - - The zero-based column to be retrieved. - - The cancellation instruction, which propagates a notification that operations should be canceled. This does - not guarantee the cancellation. A setting of CancellationToken.None makes this method equivalent to - IsDBNullAsync. The returned task must be marked as cancelled. - - True if the specified column value is equivalent to DBNull otherwise false. - - - - - - This method is currently not supported. Invoking the method will result in an exception. - - DEVNOTE (VSTS: 2202747): For now we are only supporting single result set. Need to do some more work if we want to - handle the multiple result set case. Especially if we attempt to move to a non "give me them all up front" - approach. This comment applies to all the NextResult-related methods. - - - - This method is currently not supported. Invoking the method will result in an exception. - - The cancellation token - - - - Advances the reader to the next record in a result set. - - True if there are more rows; otherwise false. - - - - An asynchronous version of Read, which advances the MultiShardDataReader to the next record. - - The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. - Exceptions will be reported via the returned Task object. - - The cancellation instruction. - A task representing the asynchronous operation. - - - - Returns a string that represents the current object. - - A string that represents the current object. - We mimic DbDataReader and just call Object.ToString() - Overriden to convey intent clearly. - - - - Gets a value indicating the depth of nesting for the current row. - - - - - Gets the number of columns in the current row. - - - - - Gets a value that indicates whether this MultiShardDataReader contains one or more rows. - - - - - Gets a value indicating whether the specified MultiShardDataReader is closed. - - - - - Gets the value of the specified column in its native format as an instance of Object. - - The zero-based column ordinal. - The value of the specified column. - - - - Gets the value of the specified column in its native format as an instance of Object. - - The name of the column. - The value of the specified column. - - - - This property is currently not supported. Accessing the property will result in an exception. - - However, from the DbDataReader source, it looks like the property is updated before the reader is closed - and is initialized to -1 by default. So, we'll return -1 always since we only allow SELECT statements. - - - - Gets the number of fields in the MultiShardDataReader that are not hidden. - - - - - Cancels all the active commands executing for this reader. - - - - - Releases the managed resources used by the DbDataReader and optionally releases the unmanaged resources. - - - true to release managed and unmanaged resources; false to release only unmanaged resources. - - - - - Method to add another DbDataReader to the set of underlying sources we are concatenating. - - The DbDataReader to add. - - If the input DbDataReader is null. - - - If the input DbDataReader is malformed (e.g., null schema table) or if we are in an invalid state - for adding a reader (e.g., Close, or MarkReaderSetComplete has already been called). - - - If the schema table underlying the data in the input DbDataReader does not match the schema table we are - expecting for the DbDataReader objects underlying this MultiShardDataReader object. - - Null if we added successfully. The encountered exception if we hit an error. - - - - - Decrements the number of expected readers. - - - - - Checks the schema of the passed in DbDataReader against the schema we are expecting for our - fan-out result set. - - The LabeledDbDataReader object to check against our expected schema. - - - - Helper that compares the columns present in two different DataTables to ensure that they match. - - The shard being validated - The DataTable to validate. - The DataTable we expect to see. - - We should expect to see few (if any) errors actually encountered in here since these are - Schema Table structure comparisons (i.e., comparisons in how the Schema information is reported out) - and not comparisons on the schema of the returned result sets themselves (which is contained in - the rows of these tables). - - - - - Checks all the column specifications (as encapsulated by a DataRow from a SchemaTable) for - compatibility with the expected column specification. - - The shard being validated - The DataRow representing the column specification we wish to validate. - The DataRow representing the expectd column specification. - - There are lot of opportunities in here for relaxed comparison semantics, but for now let's - just be super strict. - DEVNOTE (2244709): Need to tighten up our schema checking! - - - If there is a mismatch on any column information in for any column of the table (i.e., if any pair - of corresponding rows don't match exactly.) - - - - - Handles the case where a reader has a null schema table - - Behavior- - - Any exception will not be thrown if ALL readers have a null schema (regardless of execution - policy). Otherwise, a will be thrown. - - A shard that resulted in a reader with a null Schema table - - - - Closes the current DbDataReader and increments the current reader counter. - - - - - Helper method to grab the current data reader based on the m_inputsCompletedReadingCount pointer into the m_inputReaders array. - - The current DbDataReader. - - - - Helper to grab the ShardLocation for the current reader. - - The current Shard Label. - - - - Helper to grab the ShardLabel for the current reader. - - The current Shard Label. - - - - Helper to grab the active LabaeledDataReader without removing it from the collection. - - The current LabeledDbDataReader. - - - - Helper to grab the active LabaeledDataReader without removing it from the collection. - - The current LabeledDbDataReader. - - - - Helper method to grab the current data reader and cast it to a SqlDataReader. - Useful for SqlDataReader specific calls. - - - The current data reader cast as a SqlDataReader. - - - If the cast failed. - - - - - Helper method that sets up the SchemaTemplate to use as our "Ground Truth" for - performing schema comparisons. In addition to storing a copy of the schema - information, this method adds an additional row for the "ShardIdPseudoColumn". - - - The DbDataReader to use as the source for the ground truth schema information. - - - - - Helper method that throws an InvalidCastException for the case when we have detected - a call to get the value for our ShardIdPseudoColumn for anything but the String data type. - We need to do this because if we just pass the call down to the input reader we will get - the wrong exception type (since the pseudo column does not exist on the input readers). - - The ordinal of the column we are attempting to read from. - - - - Helper method that checks whether the ordinal passed in matches the ordinal of the - shard id pseudo column. - - The ordinal to check. - True if the input matches the shard id pseudo column ordinal, False if not. - - - - Helper to grab column data and perform necessary state and pseudo column reference checks. - - The type of the column we wish to return. - The function to use to pull the column value. - The zero-based column ordinal. - - The desired column value. - - - - Helper function that returns a property or variable after preceding it with a state check. - - The type of the property or variable to return. - The property or variable to return. - The desired property or variable. - - - - Helper function that returns an int property or variable after preceding it with a state check - and following it with a check that will increment it if this reader has a $ShardName pseudo column. - - The property or variable to return (potentially adjusted) after the state check. - The value parameter incremented, if necessary, to account for the pseudo column. - - - - Helper that centralizes the logic for processing references that could potentially refer to the $ShardName - pseudo column. All these functions follow the same basic pattern: - WaitForReaderOrThrow - Induce an error if we are closed - Check if this is a pseudo column reference. - If so: - Return some pseudo column specific value - If not: - Call some function that takes the column ordinal as a param. - This function just templatizes that logic in one place. - - The type to return. - The ordinal of the column of interest. - The value to return if the ordinal points at the pseudo column. - - The function to invoke (with "ordinal" as an arg) if the ordinal does not point to the pseudo column. - - - - - - Helper that centralizes the logic for the Get*Values methods. The basic pattern of all of these is: - Throw if we have a state violation - Call the proper Get*Values method to fill the values array and get back the number of values entered. - If we have a PseudoColumn and there is enough room in the arry for its values, then: - Grab its value via the right Get*Value method - Put it into the values array in the right place - Increment the count of values entered into the array - Return the count of values entered into the array. - - The array to fill with values. - The function to call to fill the array from the SqlDataReader. - The function to call to get the pseudo column value. - - - - - Helper that throws a ReaderClosed exception if we are in a closed state. - - - - - Helper that waits for a reader if one is expected to be added or throws if no readers remain. - - - - - Helper that performs a read call on the current data reader. It is done via ReadAsync() - to ensure that we buffer the whole row on the client so that we don't have to deal - with messy partial row read error cases. - - The cancellation instruction. - - An async task to perform the read; when executed the task returns true - if we read another row from the current reader, false if we hit the end. - - - - - Helper that adds the Shard Id Pseudo Column schema information to the schema table - that we expose to end users. - - - - - Asynchronously opens the given connection. - - The connection to Open - The cancellation token to be passed down - The task handling the Open. A completed task if the conn is already Open - - - - The retry policy to use when connecting to sql databases - - An instance of the class - Behavior to use for detecting transient faults. - An instance of the class - Separate method from the one below because we - might allow for custom retry strategies in the near future - - - - The retry policy to use when executing commands against sql databases - - An instance of the class - Behavior to use for detecting transient faults. - An instance of the class - - - - Clones the given command object and associates with the given connection. - - Command object to clone. - Connection associated with the cloned command. - Clone of . - - - - Provides logging utilities - - - - - For now just pretty print to console with date time - DEVNOTE: Look into logging frameworks like NLog - - - - - - - The throws this exception when - an exception has been hit reading data from one of the underlying shards. - This indicates that not all rows have been successfully retrieved - from the targeted shard(s). Users can then take - the steps necessary to decide whether to re-run the query, or whether - to continue working with the rows that have already been retrieved. - - - This exception is only thrown with the partial results policy. - - - - - Initializes a new instance of the MultiShardPartialReadException class with the specified error message and - reference to the inner exception causing the MultiShardPartialReadException. - - specifices the message that explains the reason for the exception. - specifies the exception encountered at the shard. - - - - Initializes a new instance of the MultiShardPartialReadException class with the specified error message. - - specifices the message that explains the reason for the exception. - - - - Initializes a new instance of the MultiShardPartialReadException class. - - - - - Initializes a new instance of the MultiShardPartialReadException class with serialized data. - - - The see that holds the serialized object data about the exception being thrown. - - - The that contains contextual information about the source or destination. - - - - - A strongly-typed resource class, for looking up localized strings, etc. - - - - - Returns the cached ResourceManager instance used by this class. - - - - - Overrides the current thread's CurrentUICulture property for all - resource lookups using this strongly typed resource class. - - - - - Looks up a localized string similar to The specified argument {0} cannot be greater than its ceiling value of {1}.. - - - - - Looks up a localized string similar to The specified argument {0} cannot be initialized with a negative value.. - - - - - Looks up a localized string similar to Default retry strategy for technology {0}, named '{1}', is not defined.. - - - - - Looks up a localized string similar to Default retry strategy for technology {0} was not not defined, and there is no overall default strategy.. - - - - - Looks up a localized string similar to The RetryManager is already set.. - - - - - Looks up a localized string similar to The default RetryManager has not been set. Set it by invoking the RetryManager.SetDefault static method, or if you are using declarative configuration, you can invoke the RetryPolicyFactory.CreateDefault() method to automatically create the retry manager from the configuration file.. - - - - - Looks up a localized string similar to The action has exceeded its defined retry limit.. - - - - - Looks up a localized string similar to The retry strategy with name '{0}' cannot be found.. - - - - - Looks up a localized string similar to The specified string argument {0} must not be empty.. - - - - - Looks up a localized string similar to The specified argument '{0}' cannot return a null task when invoked.. - - - - - Looks up a localized string similar to The specified argument '{0}' must return a scheduled task (also known as "hot" task) when invoked.. - - - - diff --git a/Src/ElasticScale.Client/Properties/AssemblyInfo.cs b/Src/ElasticScale.Client/Properties/AssemblyInfo.cs index c83df49..3fba5c9 100644 --- a/Src/ElasticScale.Client/Properties/AssemblyInfo.cs +++ b/Src/ElasticScale.Client/Properties/AssemblyInfo.cs @@ -7,67 +7,19 @@ using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Microsoft.Azure.SqlDatabase.ElasticScale.Client")] -[assembly: AssemblyDescription("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("4599fe76-62a2-4da8-8a0f-dd190c0c6c58")] - -[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.ServiceCommon" + AssemblyRef.ProductPublicKey)] -[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests" + AssemblyRef.ProductPublicKey)] -[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests" + AssemblyRef.ProductPublicKey)] -[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.SplitMerge.Client" + AssemblyRef.ProductPublicKey)] -[assembly: InternalsVisibleTo("Microsoft.SqlServer.DataWarehouse.Engine" + AssemblyRef.ElasticQueryPublicKey)] -[assembly: InternalsVisibleTo("SplitMergeWorker" + AssemblyRef.ProductPublicKey)] -[assembly: InternalsVisibleTo("ShardSplitMergeTests" + AssemblyRef.ProductPublicKey)] - -[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.Client.Fakes" + AssemblyRef.FakesPublicKey)] - -// No-op, purely for Resharper's intellisense, as it does not understand AssemblyRef.ProductPublicKey -#if DEBUG -#pragma warning disable 1700 -[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.ServiceCommon, PublicKey=00")] -[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests, PublicKey=00")] -[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests, PublicKey=00")] -[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.SplitMerge.Client, PublicKey=00")] -[assembly: InternalsVisibleTo("SplitMergeWorker, PublicKey=00")] -[assembly: InternalsVisibleTo("ShardSplitMergeTests, PublicKey=00")] -#pragma warning restore 1700 -#endif - -// Added reference to the nuget package in the unsigned versions -[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.ServiceCommon" + AssemblyRef.TestPublicKey)] -[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.SplitMerge.Client" + AssemblyRef.TestPublicKey)] -[assembly: InternalsVisibleTo("SplitMergeWorker" + AssemblyRef.TestPublicKey)] -[assembly: InternalsVisibleTo("ShardSplitMergeTests" + AssemblyRef.TestPublicKey)] +[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests")] +[assembly: InternalsVisibleTo("Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests")] [assembly: CLSCompliant(true)] -// Associated VSTS #2466045 [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1824:MarkAssembliesWithNeutralResourcesLanguage", Justification = "Too many dubious spelling errors.")] -// [assembly: NeutralResourcesLanguageAttribute("en-US")] - -// The Microsoft Azure SQL Database team's build system automatically creates the AssemblyRef class during the build process. -// This class contains the values of the public keys that the assemblies are signed with. When building externally, we manually define it here. -#if STANDALONE_BUILD -internal static class AssemblyRef -{ - public const string ProductPublicKey = ""; - public const string TestPublicKey = ""; - public const string FakesPublicKey = ""; - public const string ElasticQueryPublicKey = ""; -} internal static class ElasticScaleVersionInfo { - public const string ProductVersion = "1.0.0"; + public const string ProductVersion = "2.0.0"; } -#endif diff --git a/Src/ElasticScale.Client/Query/DbCommandExtensions.cs b/Src/ElasticScale.Client/Query/DbCommandExtensions.cs new file mode 100644 index 0000000..c5cae04 --- /dev/null +++ b/Src/ElasticScale.Client/Query/DbCommandExtensions.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query { + public static class DbCommandExtensions { + + /// + /// Make best attempt to clone DbCommand + /// + /// + /// + public static DbCommand BestAttemptClone(this DbCommand from) { + if(from is ICloneable) { + return (DbCommand)(from as ICloneable).Clone(); + } + + DbCommand newcmd = null; + + if(from is SqlCommand) { + // do some special magic for SqlCommand + newcmd = new SqlCommand(from.CommandText, (from as SqlCommand).Connection, (from as SqlCommand).Transaction); + } else { + var mi = from.GetType().GetMethod("Clone"); + if(mi != null && mi.ReturnType != null && typeof(DbCommand).IsAssignableFrom(mi.ReturnType) && (mi.GetParameters()?.Count() ?? 0) == 0) { + return (DbCommand)mi.Invoke(from, null); + } else { + newcmd = (DbCommand)Activator.CreateInstance(from.GetType()); + newcmd.CommandText = from.CommandText; + } + } + newcmd.CommandTimeout = from.CommandTimeout; + newcmd.CommandType = from.CommandType; + newcmd.DesignTimeVisible = from.DesignTimeVisible; + newcmd.UpdatedRowSource = from.UpdatedRowSource; + if(from.Parameters.Count > 0) { + DbParameter[] p = new DbParameter[from.Parameters.Count]; + from.Parameters.CopyTo(p, 0); + foreach(object current in p) { + newcmd.Parameters.Add(current); + } + } + return newcmd; + } + + } +} diff --git a/Src/ElasticScale.Client/Query/Exceptions/MultiShardAggregateException.cs b/Src/ElasticScale.Client/Query/Exceptions/MultiShardAggregateException.cs index fb80eaf..b274eca 100644 --- a/Src/ElasticScale.Client/Query/Exceptions/MultiShardAggregateException.cs +++ b/Src/ElasticScale.Client/Query/Exceptions/MultiShardAggregateException.cs @@ -26,7 +26,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query { private readonly ReadOnlyCollection _innerExceptions; - #region Standard Exception Constructors +#region Standard Exception Constructors /// /// Initializes a new instance of the class @@ -66,9 +66,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query _innerExceptions = (ReadOnlyCollection)(info.GetValue("InnerExceptions", typeof(ReadOnlyCollection))); } - #endregion Standard Exception Constructors +#endregion Standard Exception Constructors - #region Additional Constructors +#region Additional Constructors /// /// @@ -113,9 +113,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query _innerExceptions = new ReadOnlyCollection(exceptions); } - #endregion Additional Constructors +#endregion Additional Constructors - #region Serialization Support +#region Serialization Support /// /// Populates a SerializationInfo with the data needed to serialize the target object. @@ -128,7 +128,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query info.AddValue("InnerExceptions", _innerExceptions); } - #endregion Serialization Support +#endregion Serialization Support /// /// Gets a read-only collection of the instances diff --git a/Src/ElasticScale.Client/Query/Exceptions/MultiShardException.cs b/Src/ElasticScale.Client/Query/Exceptions/MultiShardException.cs index 9294939..675c1b7 100644 --- a/Src/ElasticScale.Client/Query/Exceptions/MultiShardException.cs +++ b/Src/ElasticScale.Client/Query/Exceptions/MultiShardException.cs @@ -142,7 +142,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query info.AddValue("ShardLocation", _shardLocation); } - #endregion Serialization Methods +#endregion Serialization Methods /// /// The shard associated with this exception diff --git a/Src/ElasticScale.Client/Query/Logging/TraceHelper.cs b/Src/ElasticScale.Client/Query/Logging/TraceHelper.cs index 10dd597..5df8802 100644 --- a/Src/ElasticScale.Client/Query/Logging/TraceHelper.cs +++ b/Src/ElasticScale.Client/Query/Logging/TraceHelper.cs @@ -42,7 +42,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query params object[] vars) { string fmtMessage = string.Format(message, vars); - logger.Info("Method: {0}; {1}; ActivityId: {2};", methodName, fmtMessage, Trace.CorrelationManager.ActivityId); + logger.Info("Method: {0}; {1}; ActivityId: {2};", methodName, fmtMessage, CorrelationManager.ActivityId); } internal static void TraceWarning(this ILogger logger, @@ -52,7 +52,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query { string fmtMessage = string.Format(message, vars); logger.Warning("Method: {0}; {1}; ActivityId: {2};", methodName, fmtMessage, - Trace.CorrelationManager.ActivityId); + CorrelationManager.ActivityId); } internal static void TraceError(this ILogger logger, @@ -63,7 +63,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query { string fmtMessage = string.Format(message, vars); logger.Error("Method: {0}; {1}; Exception: {2}; ActivityId: {3};", methodName, fmtMessage, ex.ToString(), - Trace.CorrelationManager.ActivityId); + CorrelationManager.ActivityId); } } } diff --git a/Src/ElasticScale.Client/Query/MultiShardCommand.cs b/Src/ElasticScale.Client/Query/MultiShardCommand.cs index 75635a8..4fe7406 100644 --- a/Src/ElasticScale.Client/Query/MultiShardCommand.cs +++ b/Src/ElasticScale.Client/Query/MultiShardCommand.cs @@ -1,1778 +1,1779 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// -// Purpose: -// Complements the MultiShardConnection and abstracts away -// the work of running a given dbcommand against mulitple shards -// -// Notes: -// * This class is NOT thread-safe. -// * Since the Sync API internally invokes the async API, connections to shards with -// connection string property "context connection = true" are not supported. -// * Transaction semantics are not supported - -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Diagnostics; -using System.Diagnostics.Contracts; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Xml; -using Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement; - -namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query -{ - // Suppression rationale: "Multi" is the spelling we want here. - // - /// - /// Complements the with a command object - /// similar to the triad of , , and . - /// The takes a T-SQL command statement as its input and executes the - /// command across its collection of shards specified by its corresponding . - /// The results from processing the are made available through the - /// execute methods and the . - /// - [System.ComponentModel.DesignerCategory("Code")] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi")] - public sealed class MultiShardCommand : DbCommand - { - #region Global Vars - - /// - /// Default command timeout per shard in seconds - /// - private const int DefaultCommandTimeoutPerShard = 30; - - /// - /// Default command timeout in seconds - /// - private const int DefaultCommandTimeout = 300; - - /// - /// The ILogger - /// - private static readonly ILogger s_tracer = TraceHelper.Tracer; - - /// - /// The sql command to be executed against shards - /// - private readonly DbCommand _dbCommand; - - /// - /// Lock to enable thread-safe Cancel() - /// - private readonly object _cancellationLock = new Object(); - - /// - /// Global token source to enable cancellation of commands being executed - /// - private CancellationTokenSource _innerCts = new CancellationTokenSource(); - - /// - /// Task associated with current command invocation - /// - private Task _currentCommandTask = Task.FromResult(null); - - /// - /// ActivityId of the current command being executed - /// - private Guid _activityId; - - /// - /// Whether this command has already been disposed. - /// - private bool _disposed = false; - - #endregion - - #region Ctors - - /// - /// Creates an instance of this class - /// - /// The connection to shards - /// The command to execute against the shards - /// Command timeout - /// against ALL shards - private MultiShardCommand(MultiShardConnection connection, DbCommand command, int commandTimeout) - { - this.Connection = connection; - this.CommandTimeout = commandTimeout; - - _dbCommand = command; - - // Set defaults - this.RetryPolicy = RetryPolicy.DefaultRetryPolicy; - this.RetryBehavior = RetryBehavior.DefaultRetryBehavior; - this.ExecutionPolicy = MultiShardExecutionPolicy.CompleteResults; - this.ExecutionOptions = MultiShardExecutionOptions.None; - } - - #endregion - - #region Instance Factories - - // Suppression rationale: - // The SqlCommand underlies the object we will return. We don't want to dispose it. - // The point of this c-tor is to allow the user to specify whatever sql text they wish. - /// - /// Instance constructor of this class - /// Default command timeout of 300 seconds is used - /// - /// The connection to shards - /// The command text to execute against shards - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - internal static MultiShardCommand Create(MultiShardConnection connection, string commandText) - { - SqlCommand cmd = new SqlCommand(commandText); - cmd.CommandTimeout = MultiShardCommand.DefaultCommandTimeoutPerShard; // Default sql command timeout of 30secs per shard - cmd.CommandType = CommandType.Text; - - return MultiShardCommand.Create( - connection, - cmd, - MultiShardCommand.DefaultCommandTimeout); - } - - // Suppression rationale: - // The SqlCommand underlies the object we will return. We don't want to dispose it. - // The point of this c-tor is to allow the user to specify whatever sql text they wish. - /// - /// Instance constructor of this class - /// Default command type is text - /// - /// The connection to shards - /// - /// Command timeout for given commandText to be run - /// against ALL shards - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities"), - System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - internal static MultiShardCommand Create(MultiShardConnection connection, string commandText, int commandTimeout) - { - SqlCommand cmd = new SqlCommand(commandText); - cmd.CommandTimeout = MultiShardCommand.DefaultCommandTimeoutPerShard; // Default sql command timeout of 30secs per shard - cmd.CommandType = CommandType.Text; - - return MultiShardCommand.Create( - connection, - cmd, - commandTimeout); - } - - /// - /// Creates an instance of this class - /// - /// The connection handle to all shards - /// A sql command from which the commandText, commandTimeout, commandType will be inferred. Should implement ICloneable - /// Command timeout for given commandText to be run against ALL shards - /// - /// DEVNOTE: Should we expose a DbCommand instead? Do we even want to expose this at all? - internal static MultiShardCommand Create(MultiShardConnection connection, DbCommand command, int commandTimeout) - { - Contract.Requires(command is ICloneable); - - return new MultiShardCommand(connection, command, commandTimeout); - } - - #endregion - - #region Public Properties - - // Suppression rationale: The point of this property is precisely to allow the user to specify whatever SQL they wish. - /// - /// Gets or sets the command text to execute against the set of shards. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] - public override string CommandText - { - get - { - return _dbCommand.CommandText; - } - set - { - _dbCommand.CommandText = value; - } - } - - /// - /// Time in seconds to wait for the command to be executed on ALL shards. - /// A value of 0 indicates no wait time limit. The default is 300 seconds. - /// - public override int CommandTimeout - { - get; - set; - } - - /// - /// This property controls the timeout for running - /// a command against individual shards. - /// - public int CommandTimeoutPerShard - { - get - { - return _dbCommand.CommandTimeout; - } - set - { - _dbCommand.CommandTimeout = value; - } - } - - /// - /// The of the command to be executed. - /// - public override CommandType CommandType - { - get - { - return _dbCommand.CommandType; - } - set - { - _dbCommand.CommandType = value; - } - } - - /// - /// The associated with this command. - /// - public new SqlParameterCollection Parameters - { - get - { - return (SqlParameterCollection)_dbCommand.Parameters; - } - } - - /// - /// The retry behavior for detecting transient faults that could occur when connecting to and - /// executing commands against individual shards. - /// - /// - /// The is the default. - /// - public RetryBehavior RetryBehavior - { - get; - set; - } - - /// - /// The execution policy to use when executing - /// commands against shards. Through this policy, - /// users can control whether complete results are required, - /// or whether partial results are acceptable. - /// - public MultiShardExecutionPolicy ExecutionPolicy - { - get; - set; - } - - /// - /// Gets the current instance of the associated with this command. - /// - public new MultiShardConnection Connection - { - get; - private set; - } - - /// - /// Gets or sets options that control how the command is executed. - /// For instance, you can use this to include the shard name as - /// an additional column into the result. - /// - public MultiShardExecutionOptions ExecutionOptions - { - get; - set; - } - - /// - /// The event handler invoked when execution has begun on a given shard. - /// - public event EventHandler ShardExecutionBegan; - - /// - /// The event handler invoked when execution has successfully completed on a given shard or its - /// shard-specific has been returned. - /// - public event EventHandler ShardExecutionSucceeded; - - /// - /// The event handler invoked when execution on a given shard has faulted. This handler is only - /// invoked on exceptions for which execution could not be retried further as a result of - /// the exception's non-transience or as a result of the chosen . - /// - public event EventHandler ShardExecutionFaulted; - - /// - /// The event handler invoked when execution on a given shard is canceled, either explicitly via - /// the provided or implicitly as a result of the chosen - /// . - /// - public event EventHandler ShardExecutionCanceled; - - /// - /// The event handler invoked when ExecuteDataReader on a certain shard has successfully returned - /// a reader. This is an internal-only method, and differs from ShardExecutionSucceeded in that - /// it is invoked BEFORE the reader is added to the MultiShardDataReader; this adding is rife - /// with side effects that are difficult to isolate. - /// - internal event EventHandler ShardExecutionReaderReturned; - - #endregion Public Properties - - #region Internal Properties - - /// - /// The retry policy to use when connecting to and - /// executing commands against individual shards. - /// - internal RetryPolicy RetryPolicy - { - get; - set; - } - - #endregion Internal Properties - - #region Protected Properties - - /// - /// Gets the SqlParameter Collection - /// - protected override DbParameterCollection DbParameterCollection - { - get - { - return this.Parameters; - } - } - - #endregion Protected Properties - - #region APIs - - #region Supported DbCommand APIs - - #region ExecuteReader Methods - - #region Synchronous Methods - - /// - /// The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard - /// and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a - /// . The execution policy regarding result completeness can be controlled - /// by setting the . The default execution policy is to return complete results. - /// - /// the instance with the overall concatenated result set. - /// thrown if the commandText is null or empty - /// thrown if the CommandTimeout elapsed prior to completion - public new MultiShardDataReader ExecuteReader() - { - return this.ExecuteReader(CommandBehavior.Default); - } - - /// - /// - Runs the given query against all shards and returns - /// a reader that encompasses results from them. - /// - Uses the MultiShardExecutionPolicy.CompleteResults as the default execution policy - /// - Includes the $ShardName pseudo column in the results - /// Command behavior to use - /// MultiShardDataReader instance that encompasses results from all shards - /// If the commandText is null or empty - /// If the command behavior is not supported - /// (CloseConnection or SingleResult or SingleRow) - /// If the CommandTimeout elapsed prior to completion - /// - protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) - { - return this.ExecuteReader(behavior); - } - - /// - /// The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard - /// and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a - /// . The execution policy regarding result completeness can be controlled - /// by setting the . The default execution policy is to return complete results. - /// - /// the instance with the overall concatenated result set. - /// thrown if the commandText is null or empty, or if the - /// specified command behavior is not supported such as CloseConnection or SingleRow. - /// thrown if the CommandTimeout elapsed prior to completion. - /// specifies the to use. - public new MultiShardDataReader ExecuteReader(CommandBehavior behavior) - { - return this.ExecuteReader( - behavior, - MultiShardUtils.GetSqlCommandRetryPolicy(this.RetryPolicy, this.RetryBehavior), - MultiShardUtils.GetSqlConnectionRetryPolicy(this.RetryPolicy, this.RetryBehavior), - this.ExecutionPolicy); - } - - /// - /// - Runs the given query against all shards and returns - /// a reader that encompasses results from them. - /// - /// Design Principles - /// - Commands are executed in a parallel, non-blocking manner. - /// - Only the calling thread is blocked until the command is complete against all shards. - /// - /// Command behavior to use - /// The retry policy to use when executing commands against the shards - /// The retry policy to use when connecting to shards - /// The execution policy to use - /// MultiShardDataReader instance that encompasses results from all shards - /// If the commandText is null or empty - /// If the CommandTimeout elapsed prior to completion - /// If one or more errors occured while executing the command - internal MultiShardDataReader ExecuteReader( - CommandBehavior behavior, - TransientFaultHandling.RetryPolicy commandRetryPolicy, - TransientFaultHandling.RetryPolicy connectionRetryPolicy, - MultiShardExecutionPolicy executionPolicy) - { - Contract.Requires(commandRetryPolicy != null && connectionRetryPolicy != null); - - try - { - return this.ExecuteReaderAsync( - behavior, - CancellationToken.None, - commandRetryPolicy, - connectionRetryPolicy, - executionPolicy).Result; - } - catch (Exception ex) - { - AggregateException aex = ex as AggregateException; - - if (null != aex) - { - throw aex.Flatten().InnerException; - } - - throw; - } - } - - #endregion - - #region Async Methods - - /// - /// The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard - /// and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a - /// . The execution policy regarding result completeness can be controlled - /// by setting the . The default execution policy is to return complete results. - /// - /// a task warapping the instance with the overall concatenated result set. - /// thrown if the commandText is null or empty, or if the - /// specified command behavior is not supported such as CloseConnection or SingleRow. - /// thrown if the CommandTimeout elapsed prior to completion. - /// Any exceptions during command execution are conveyed via the returned Task. - public new Task ExecuteReaderAsync() - { - return this.ExecuteReaderAsync(CancellationToken.None); - } - - /// - /// The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard - /// and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a - /// . The execution policy regarding result completeness can be controlled - /// by setting the . The default execution policy is to return complete results. - /// - /// a task warapping the instance with the overall concatenated result set. - /// thrown if the commandText is null or empty, or if the - /// specified command behavior is not supported such as CloseConnection or SingleRow. - /// thrown if the CommandTimeout elapsed prior to completion. - /// Cancellation token to cancel the command execution - /// Any exceptions during command execution are conveyed via the returned Task. - public new Task ExecuteReaderAsync(CancellationToken cancellationToken) - { - return this.ExecuteReaderAsync(CommandBehavior.Default, cancellationToken); - } - - /// - /// - Executes the given query against all shards asynchronously - /// - Uses the MultiShardExecutionPolicy.CompleteResults as the default execution policy - /// - Includes the $ShardName pseudo column in the results - /// - /// Command behavior to use - /// Cancellation token to cancel the command execution - /// A task with a TResult that encompasses results from all shards - /// Any exceptions during command execution are conveyed via the returned Task - /// If the commandText is null or empty - protected override Task ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) - { - return this.ExecuteReaderAsync(behavior, cancellationToken) - .ContinueWith( - (t) => - { - if (t.IsFaulted) - { - throw t.Exception.InnerException; - } - - return t.Result; - }, - CancellationToken.None, - TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled, - TaskScheduler.Default); - } - - /// - /// The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard - /// and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a - /// . The execution policy regarding result completeness can be controlled - /// by setting the . The default execution policy is to return complete results. - /// - /// a task warapping the instance with the overall concatenated result set. - /// thrown if the commandText is null or empty, or if the - /// specified command behavior is not supported such as CloseConnection or SingleRow. - /// thrown if the CommandTimeout elapsed prior to completion. - /// Command behavior to use - /// Cancellation token to cancel the command execution - /// Any exceptions during command execution are conveyed via the returned Task. - public new Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) - { - return this.ExecuteReaderAsync( - behavior, - cancellationToken, - MultiShardUtils.GetSqlCommandRetryPolicy(this.RetryPolicy, this.RetryBehavior), - MultiShardUtils.GetSqlConnectionRetryPolicy(this.RetryPolicy, this.RetryBehavior), - this.ExecutionPolicy); - } - - // Suppression rationale: - // We want to return exceptions via the task so that they can be dealt with on the main thread. Gotta catch 'em all. - // We are returning the shardedReader variable via the task. We don't want to dispose it. - // This method is part of the defined API. We can't move it to a different class. - // - /// - /// Executes the given query against all shards asynchronously - /// - /// Command behavior to use - /// Cancellation token to cancel the command execution - /// The retry policy to use when executing commands against the shards - /// The retry policy to use when connecting to shards - /// The execution policy to use - /// A task with a TResult that encompasses results from all shards - /// Any exceptions during command execution are conveyed via the returned Task - /// If the commandText is null or empty - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling"), - System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope"), - System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - internal Task ExecuteReaderAsync( - CommandBehavior behavior, - CancellationToken outerCancellationToken, - TransientFaultHandling.RetryPolicy commandRetryPolicy, - TransientFaultHandling.RetryPolicy connectionRetryPolicy, - MultiShardExecutionPolicy executionPolicy) - { - TaskCompletionSource currentCompletion = new TaskCompletionSource(); - - // Check if cancellation has already been requested by the user - if (outerCancellationToken.IsCancellationRequested) - { - currentCompletion.SetCanceled(); - return currentCompletion.Task; - } - - try - { - this.ValidateCommand(behavior); - - // Create a list of sql commands to run against each of the shards - List> shardCommands = this.GetShardDbCommands(); - - // Don't allow a new invocation if a Cancel() is already in progress - lock (_cancellationLock) - { - // Set the activity id - _activityId = Guid.NewGuid(); - using (var activityIdScope = new ActivityIdScope(_activityId)) - { - Stopwatch stopwatch = Stopwatch.StartNew(); - - // Setup the Cancellation manager - CommandCancellationManager cmdCancellationMgr = new CommandCancellationManager( - _innerCts.Token, - outerCancellationToken, - executionPolicy, - this.CommandTimeout); - - s_tracer.TraceInfo( - "MultiShardCommand.ExecuteReaderAsync", - "Start; Command Timeout: {0}; Command Text: {1}; Execution Policy: {2}", - this.CommandTimeout, - this.CommandText, - this.ExecutionPolicy); - - FanOutTask fanOutTask = this.ExecuteReaderAsyncInternal( - behavior, - shardCommands, - cmdCancellationMgr, - commandRetryPolicy, - connectionRetryPolicy, - executionPolicy); - - Task commandTask = fanOutTask - .OuterTask - .ContinueWith>( - (t) => - { - stopwatch.Stop(); - - string completionTrace = string.Format("Complete; Execution Time: {0}", stopwatch.Elapsed); - - switch (t.Status) - { - case TaskStatus.Faulted: - // Close any active readers. - if (this.ExecutionPolicy == MultiShardExecutionPolicy.CompleteResults) - { - MultiShardCommand.TerminateActiveCommands(fanOutTask.InnerTasks); - } - - this.HandleCommandExecutionException( - currentCompletion, - new MultiShardAggregateException(t.Exception.InnerExceptions), - completionTrace); - break; - - case TaskStatus.Canceled: - // Close any active readers. - if (this.ExecutionPolicy == MultiShardExecutionPolicy.CompleteResults) - { - MultiShardCommand.TerminateActiveCommands(fanOutTask.InnerTasks); - } - - this.HandleCommandExecutionCanceled( - currentCompletion, - cmdCancellationMgr, - completionTrace); - break; - - case TaskStatus.RanToCompletion: - try - { - s_tracer.TraceInfo("MultiShardCommand.ExecuteReaderAsync", completionTrace); - - // If all child readers have exceptions, then aggregate the exceptions into this parent task. - IEnumerable childExceptions = t.Result.Select(r => r.Exception); - - if (childExceptions.All(e => e != null)) - { - // All child readers have exceptions - - // This should only happen on PartialResults, because if we were in - // CompleteResults then any failed child reader should have caused - // the task to be in TaskStatus.Faulted - Debug.Assert(this.ExecutionPolicy == MultiShardExecutionPolicy.PartialResults); - - this.HandleCommandExecutionException( - currentCompletion, - new MultiShardAggregateException(childExceptions), - completionTrace); - } - else - { - // At least one child reader has succeeded - bool includeShardNameColumn = (this.ExecutionOptions & MultiShardExecutionOptions.IncludeShardNameColumn) != 0; - - // Hand-off the responsibility of cleanup to the MultiShardDataReader. - MultiShardDataReader shardedReader = new MultiShardDataReader( - this, - t.Result, - executionPolicy, - includeShardNameColumn); - - currentCompletion.SetResult(shardedReader); - } - } - catch (Exception ex) - { - HandleCommandExecutionException(currentCompletion, new MultiShardAggregateException(ex)); - } - break; - - default: - currentCompletion.SetException(new InvalidOperationException("Unexpected task status.")); - break; - } - - return currentCompletion.Task; - }, - TaskContinuationOptions.ExecuteSynchronously) - .Unwrap(); - - _currentCommandTask = commandTask; - - return commandTask; - } - } - } - catch (Exception ex) - { - currentCompletion.SetException(ex); - return currentCompletion.Task; - } - } - - #endregion - - /// - /// Terminates any active commands/readers for scenarios where we fail the request due to - /// strict execution policy or cancellation. - /// - /// Collection of reader tasks associated with execution across all shards. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We do not want to throw Close or Cancel errors.")] - private static void TerminateActiveCommands(Task[] readerTasks) - { - for (int i = 0; i < readerTasks.Length; i++) - { - if (readerTasks[i].Status == TaskStatus.RanToCompletion) - { - Debug.Assert(readerTasks[i].Result != null, "Must have a LabeledDbDataReader if task finished."); - LabeledDbDataReader labeledReader = readerTasks[i].Result; - - // This is a candidate for closing since we are in a faulted state. - Debug.Assert(labeledReader.DbDataReader != null, "Expecting reader for completed task."); - - try - { - using (labeledReader.Command) - using (labeledReader.DbDataReader) - { - // Invoke cancellation before closing the reader. This is safe from deadlocks that - // arise potentially due to parallel Cancel and Close calls because this is the only - // thread that will be responsible for cleanup. - labeledReader.Command.Cancel(); - labeledReader.DbDataReader.Close(); - } - } - catch (Exception) - { - // Catch everything for Cancel/Close. - } - } - } - } - - private FanOutTask ExecuteReaderAsyncInternal( - CommandBehavior behavior, - List> commands, - CommandCancellationManager cancellationToken, - TransientFaultHandling.RetryPolicy commandRetryPolicy, - TransientFaultHandling.RetryPolicy connectionRetryPolicy, - MultiShardExecutionPolicy executionPolicy) - { - Task[] shardCommandTasks = new Task[commands.Count]; - - for (int i = 0; i < shardCommandTasks.Length; i++) - { - Tuple shardCommand = commands[i]; - - shardCommandTasks[i] = this.GetLabeledDbDataReaderTask( - behavior, - shardCommand, - cancellationToken, - commandRetryPolicy, - connectionRetryPolicy, - executionPolicy); - } - - return new FanOutTask - { - OuterTask = Task.WhenAll(shardCommandTasks), - InnerTasks = shardCommandTasks - }; - } - - // Suppression rationale: We are returning the LabeledDataReader via the task. We don't want to dispose it. - // - /// - /// Helper that generates a Task to return a LabaledDbDataReader rather than just a plain DbDataReader - /// so that we can affiliate the shard label with the Task returned from a call to DbCommand.ExecuteReaderAsync. - /// - /// Command behavior to use - /// A tuple of the Shard and the command to be executed - /// Manages the cancellation tokens - /// The retry policy to use when executing commands against the shards - /// The retry policy to use when connecting to shards - /// The execution policy to use - /// A Task that will return a LabaledDbDataReader. - /// - /// We should be able to tap into this code to trap and gracefully deal with command execution errors as well. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling"), - System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - private Task GetLabeledDbDataReaderTask( - CommandBehavior behavior, - Tuple commandTuple, - CommandCancellationManager cmdCancellationMgr, - TransientFaultHandling.RetryPolicy commandRetryPolicy, - TransientFaultHandling.RetryPolicy connectionRetryPolicy, - MultiShardExecutionPolicy executionPolicy) - { - TaskCompletionSource currentCompletion = new TaskCompletionSource(); - - ShardLocation shard = commandTuple.Item1; - DbCommand command = commandTuple.Item2; - Stopwatch stopwatch = Stopwatch.StartNew(); - - // Always the close connection once the reader is done - // - // Commented out because of VSTS BUG# 3936154: When this command behavior is enabled, - // SqlClient seems to be running into a deadlock when we invoke a cancellation on - // SqlCommand.ExecuteReaderAsync(cancellationToken) with a SqlCommand.CommandText that would - // lead to an error (Ex. "select * from non_existant_table"). - // As a workaround, we now explicitly close the connection associated with each shard's SqlDataReader - // once we are done reading through it in MultiShardDataReader. - // Please refer to the bug to find a sample app with a repro, dump and symbols. - // - // behavior |= CommandBehavior.CloseConnection; - - s_tracer.TraceInfo( - "MultiShardCommand.GetLabeledDbDataReaderTask", - "Starting command execution for Shard: {0}; Behavior: {1}; Retry Policy: {2}", - shard, - behavior, - this.RetryPolicy); - - Task> commandExecutionTask = commandRetryPolicy.ExecuteAsync>( - () => - { - // Execute command in the Threadpool - return Task.Run( - async () => - { - // In certain cases sqlcommand doesn't reset its internal state correctly upon - // failure of an async command (especially if the connection is still open). - // This leads to unsuccessful retries on our part (see bug#2711396). - // The recommendation from the Sqlclient team is to either start off with a new sqlcommand instance - // on every retry or close and reopen the connection. - // We're going with the former approach here. - DbCommand commandToExecute = MultiShardUtils.CloneDbCommand(command, command.Connection); - - // Open the connection if it isn't already - await this.OpenConnectionWithRetryAsync( - commandToExecute, - cmdCancellationMgr.Token, - connectionRetryPolicy) - .ConfigureAwait(false); - - // The connection to the shard has been successfully opened and the per-shard command is about to execute. - // Raise the ShardExecutionBegan event. - this.OnShardExecutionBegan(shard); - - DbDataReader perShardReader = await commandToExecute.ExecuteReaderAsync( - behavior, - cmdCancellationMgr.Token) - .ConfigureAwait(false); - - return new Tuple(perShardReader, commandToExecute); - }); - }, - cmdCancellationMgr.Token); - - return commandExecutionTask.ContinueWith>( - (t) => - { - stopwatch.Stop(); - - string traceMsg = string.Format( - "Completed command execution for Shard: {0}; Execution Time: {1}; Task Status: {2}", - shard, - stopwatch.Elapsed, - t.Status); - - switch (t.Status) - { - case TaskStatus.Faulted: - MultiShardException exception = new MultiShardException(shard, t.Exception.InnerException); - - // Close the connection - command.Connection.Close(); - - // Workaround: SqlCommand sets the task status to Faulted if the token was - // canceled while ExecuteReaderAsync was in progress. Interpret it and raise a canceled event instead. - if (cmdCancellationMgr.Token.IsCancellationRequested) - { - s_tracer.TraceError( - "MultiShardCommand.GetLabeledDbDataReaderTask", - exception, - "Command was canceled. {0}", - traceMsg); - - currentCompletion.SetCanceled(); - - // Raise the ShardExecutionCanceled event. - this.OnShardExecutionCanceled(shard); - } - else - { - s_tracer.TraceError( - "MultiShardCommand.GetLabeledDbDataReaderTask", - exception, - "Command failed. {0}", - traceMsg); - - if (executionPolicy == MultiShardExecutionPolicy.CompleteResults) - { - currentCompletion.SetException(exception); - - // Cancel any other tasks in-progress - cmdCancellationMgr.CompleteResultsCts.Cancel(); - } - else - { - LabeledDbDataReader failedLabeledReader = new LabeledDbDataReader(exception, shard, command); - - currentCompletion.SetResult(failedLabeledReader); - } - - // Raise the ShardExecutionFaulted event. - this.OnShardExecutionFaulted(shard, t.Exception.InnerException); - } - - break; - - case TaskStatus.Canceled: - s_tracer.TraceWarning( - "MultiShardCommand.GetLabeledDbDataReaderTask", - "Command was canceled. {0}", - traceMsg); - - command.Connection.Close(); - - currentCompletion.SetCanceled(); - - // Raise the ShardExecutionCanceled event. - this.OnShardExecutionCanceled(shard); - break; - - case TaskStatus.RanToCompletion: - s_tracer.TraceInfo("MultiShardCommand.GetLabeledDbDataReaderTask", traceMsg); - - LabeledDbDataReader labeledReader = new LabeledDbDataReader(t.Result.Item1, shard, t.Result.Item2); - - // Raise the ShardExecutionReaderReturned event. - this.OnShardExecutionReaderReturned(shard, labeledReader); - - currentCompletion.SetResult(labeledReader); - - // Raise the ShardExecutionSucceeded event. - this.OnShardExecutionSucceeded(shard, labeledReader); - break; - - default: - currentCompletion.SetException(new InvalidOperationException("Unexpected task status..")); - break; - } - - return currentCompletion.Task; - }, - TaskContinuationOptions.ExecuteSynchronously) - .Unwrap(); - } - - private async Task OpenConnectionWithRetryAsync( - DbCommand shardCommand, - CancellationToken cancellationToken, - TransientFaultHandling.RetryPolicy connectionRetryPolicy) - { - var shardConnection = shardCommand.Connection; - - await connectionRetryPolicy.ExecuteAsync( - () => MultiShardUtils.OpenShardConnectionAsync( - shardConnection, - cancellationToken), - cancellationToken) - .ConfigureAwait(false); - } - - #endregion ExecuteReader Methods - - // Suppression rationale: We don't want cancel throwing any exceptions. Just cancel. - // - /// - /// Attempts to cancel an in progress - /// and any ongoing work that is performed at the shards on behalf of the command. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - public override void Cancel() - { - lock (_cancellationLock) - { - try - { - Task currentTask = _currentCommandTask; - - if (currentTask != null) - { - if (IsExecutionInProgress()) - { - // Call could've been made from a worker thread - using (ActivityIdScope activityIdScope = new ActivityIdScope(_activityId)) - { - s_tracer.TraceWarning( - "MultiShardCommand.Cancel", - "Command was canceled; Current task status: {0}", - currentTask.Status); - - _innerCts.Cancel(); - - currentTask.Wait(); - } - } - - Debug.Assert(currentTask.IsCompleted, "Current task should be complete."); - - // For tasks that failed or were cancelled we assume that they are already cleaned up. - if (currentTask.Status == TaskStatus.RanToCompletion) - { - Task executeReaderTask = currentTask as Task; - - if (currentTask != null) - { - // Cancel all the active readers on MultiShardDataReader. - executeReaderTask.Result.Cancel(); - } - } - } - } - catch // Cancel doesn't throw any exceptions - { - } - finally - { - if (_innerCts.IsCancellationRequested) - { - _innerCts = new CancellationTokenSource(); - } - } - } - } - - /// - /// Creates a new instance of a object. - /// - /// - public static new SqlParameter CreateParameter() - { - return new SqlParameter(); - } - - /// - /// Creates an instance of the DbParameter - /// - /// - protected override DbParameter CreateDbParameter() - { - return CreateParameter(); - } - - // Suppression rationale: We purposely want to ignore exceptions when disposing. - // - /// - /// Dispose off any unmanaged/managed resources held - /// - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - protected override void Dispose(bool disposing) - { - if (!_disposed) - { - if (disposing) - { - try - { - // Cancel any commands that are in progress - this.Cancel(); - - // Close any open connections - this.Connection.Close(); - } - catch (Exception) // Ignore any exceptions - { - } - - // Dispose the cancellation token source - using (_innerCts) - { - } - - _disposed = true; - - s_tracer.TraceWarning("MultiShardCommand.Dispose", "Command disposed"); - } - - base.Dispose(disposing); - } - } - - #endregion Supported DbCommand APIs - - /// - /// Resets the property - /// to its default value - /// - public void ResetCommandTimeout() - { - this.CommandTimeout = MultiShardCommand.DefaultCommandTimeout; - } - - /// - /// Resets the property - /// to its default value - /// - public void ResetCommandTimeoutPerShard() - { - this.CommandTimeoutPerShard = MultiShardCommand.DefaultCommandTimeoutPerShard; - } - - #endregion APIs - - #region Helpers - - private void ValidateCommand(CommandBehavior behavior) - { - // Enforce only one async invocation at a time - if (IsExecutionInProgress()) - { - var ex = new InvalidOperationException("The command execution cannot proceed due to a pending asynchronous operation already in progress."); - - s_tracer.TraceError( - "MultiShardCommand.ValidateCommand", - ex, - "Current Task Status: {0}", - _currentCommandTask.Status); - - throw ex; - } - - // Make sure command text is valid - if (string.IsNullOrWhiteSpace(CommandText)) - { - throw new InvalidOperationException("CommandText cannot be null"); - } - - // Validate the command behavior - ValidateCommandBehavior(behavior); - - // Validate the parameters - ValidateParameters(); - } - - private static void ValidateCommandBehavior(CommandBehavior cmdBehavior) - { - if (((cmdBehavior & CommandBehavior.CloseConnection) != 0) || - ((cmdBehavior & CommandBehavior.SingleResult) != 0) || - ((cmdBehavior & CommandBehavior.SingleRow) != 0)) - { - throw new NotSupportedException(string.Format("CommandBehavior {0} is not supported", cmdBehavior)); - } - } - - private void ValidateParameters() - { - int parameterCount = Parameters.Count; - for (int i = 0; i < parameterCount; i++) - { - SqlParameter parameter = Parameters[i]; - - // We only allow input parameters - if (parameter.Direction != ParameterDirection.Input) - { - throw new NotSupportedException(string.Format("Only ParameterDirection.Input is currently supported. Parameter Name: {0} Direction: {1}", - parameter.ParameterName, parameter.Direction)); - } - - // We don't allow streaming to sqlserver - if (parameter.Value != null && - (parameter.Value is Stream || - parameter.Value is TextReader || - parameter.Value is XmlReader || - parameter.Value is DbDataReader)) - { - throw new NotSupportedException(string.Format("Streaming to sql server is currently not supported. Parameter Name: {0} Value type: {1}", - parameter.ParameterName, parameter.Value.GetType())); - } - } - } - - /// - /// Whether execution is already in progress - /// against this command instance - /// - /// True if execution is in progress - private bool IsExecutionInProgress() - { - Task currentTask = _currentCommandTask; - - return currentTask != null && !currentTask.IsCompleted; - } - - /// - /// Creates a list of commands to be executed against the shards associated with the connection. - /// - /// Pairs of shard locations and associated commands. - private List> GetShardDbCommands() - { - return this.Connection - .ShardConnections - .Select(sc => new Tuple(sc.Item1, MultiShardUtils.CloneDbCommand(_dbCommand, sc.Item2))) - .ToList(); - } - - private void HandleCommandExecutionException( - TaskCompletionSource tcs, - Exception ex, - string trace = "") - { - // Close any open connections - this.Connection.Close(); - s_tracer.TraceError("MultiShardCommand.ExecuteReaderAsync", ex, trace); - tcs.SetException(ex); - } - - private void HandleCommandExecutionCanceled( - TaskCompletionSource tcs, - CommandCancellationManager cancellationMgr, - string trace = "") - { - // Close any open connections - this.Connection.Close(); - - s_tracer.TraceWarning("MultiShardCommand.ExecuteReaderAsync", "Command was canceled; {0}", trace); - - if (cancellationMgr.HasTimeoutExpired) - { - // The ConnectionTimeout elapsed - tcs.SetException(new TimeoutException - (string.Format("Command timeout of {0} elapsed.", CommandTimeout))); - } - else - { - tcs.SetCanceled(); - } - } - - #region Event Raisers - - /// - /// Raise the ShardExecutionBegan event. - /// - /// The shard for which this event is raised. - private void OnShardExecutionBegan(ShardLocation shardLocation) - { - if (ShardExecutionBegan != null) - { - ShardExecutionEventArgs args = new ShardExecutionEventArgs() - { - ShardLocation = shardLocation, - Exception = null - }; - - try - { - ShardExecutionBegan(this, args); - } - catch (Exception e) - { - throw new MultiShardException(shardLocation, e); - } - } - } - - /// - /// Raise the ShardExecutionSucceeded event. - /// - /// The shard for which this event is raised. - /// The reader to pass in the associated eventArgs. - private void OnShardExecutionSucceeded(ShardLocation shardLocation, LabeledDbDataReader reader) - { - if (ShardExecutionSucceeded != null) - { - ShardExecutionEventArgs args = new ShardExecutionEventArgs() - { - ShardLocation = shardLocation, - Exception = null, - Reader = reader - }; - - try - { - ShardExecutionSucceeded(this, args); - } - catch (Exception e) - { - throw new MultiShardException(shardLocation, e); - } - } - } - - /// - /// Raise the ShardExecutionReaderReturned event. - /// - /// The shard for which this event is raised. - /// The reader to pass in the associated eventArgs. - private void OnShardExecutionReaderReturned(ShardLocation shardLocation, LabeledDbDataReader reader) - { - if (ShardExecutionReaderReturned != null) - { - ShardExecutionEventArgs args = new ShardExecutionEventArgs() - { - ShardLocation = shardLocation, - Exception = null, - Reader = reader - }; - - try - { - ShardExecutionReaderReturned(this, args); - } - catch (Exception e) - { - throw new MultiShardException(shardLocation, e); - } - } - } - - /// - /// Raise the ShardExecutionFaulted event. - /// - /// The shard for which this event is raised. - /// The exception causing the execution on this shard to fault. - private void OnShardExecutionFaulted(ShardLocation shardLocation, Exception executionException) - { - if (ShardExecutionFaulted != null) - { - ShardExecutionEventArgs args = new ShardExecutionEventArgs() - { - ShardLocation = shardLocation, - Exception = executionException - }; - - try - { - ShardExecutionFaulted(this, args); - } - catch (Exception e) - { - throw new MultiShardException(shardLocation, e); - } - } - } - - /// - /// Raise the ShardExecutionCanceled event. - /// - /// The shard for which this event is raised. - private void OnShardExecutionCanceled(ShardLocation shardLocation) - { - if (ShardExecutionCanceled != null) - { - ShardExecutionEventArgs args = new ShardExecutionEventArgs() - { - ShardLocation = shardLocation, - Exception = null - }; - - try - { - ShardExecutionCanceled(this, args); - } - catch (Exception e) - { - throw new MultiShardException(shardLocation, e); - } - } - } - - #endregion Event Raisers - - #endregion Helpers - - #region UnSupported DbCommand APIs - - /// - /// This method is currently not supported. Invoking the property will result in an exception. - /// - public override void Prepare() - { - throw new NotSupportedException("Prepare is currently not supported"); - } - - #region ExecuteNonQuery Methods - - /// - /// ExecuteNonQuery is currently not supported - /// - /// - public override int ExecuteNonQuery() - { - throw new NotSupportedException("ExecuteNonQuery is not supported"); - } - - /// - /// ExecuteNonQueryAsync is currently not supported - /// - /// The cancellation token - /// - public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) - { - return base.ExecuteNonQueryAsync(cancellationToken); - } - - // Suppression rationale: - // We do want to catch all exceptions and set them on the Task where they can be dealt with on the main thread. - // - /// - /// Test only for now - /// - /// - /// - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - internal Task ExecuteNonQueryAsync(CancellationToken cancellationToken, MultiShardExecutionPolicy executionPolicy) - { - var currentCompletion = new TaskCompletionSource(); - var behavior = CommandBehavior.Default; - var commandRetryPolicy = MultiShardUtils.GetSqlCommandRetryPolicy(this.RetryPolicy, this.RetryBehavior); - var connectionRetryPolicy = MultiShardUtils.GetSqlConnectionRetryPolicy(this.RetryPolicy, this.RetryBehavior); - - // Check if cancellation has already been requested by the user - if (cancellationToken.IsCancellationRequested) - { - currentCompletion.SetCanceled(); - return currentCompletion.Task; - } - - try - { - ValidateCommand(behavior); - - // Create a list of sql commands to run against each of the shards - List> shardCommands = this.GetShardDbCommands(); - - // Don't allow a new invocation if a Cancel() is already in progress - lock (_cancellationLock) - { - // Setup the Cancellation manager - CommandCancellationManager cmdCancellationMgr = new CommandCancellationManager( - _innerCts.Token, - cancellationToken, - executionPolicy, - CommandTimeout); - - var commandTask = ExecuteReaderAsyncInternal( - behavior, - shardCommands, - cmdCancellationMgr, - commandRetryPolicy, - connectionRetryPolicy, - executionPolicy) - .OuterTask - .ContinueWith>( - (t) => - { - switch (t.Status) - { - case TaskStatus.Faulted: - HandleCommandExecutionException( - currentCompletion, - new MultiShardAggregateException(t.Exception.InnerExceptions)); - break; - - case TaskStatus.Canceled: - HandleCommandExecutionCanceled( - currentCompletion, - cmdCancellationMgr); - break; - - case TaskStatus.RanToCompletion: - // Close all connections to shards - Connection.Close(); - - // Check for any exceptions if this is a partial results execution policy - bool success = true; - - if (executionPolicy == MultiShardExecutionPolicy.PartialResults) - { - var exceptions = new List(); - foreach (var ldr in t.Result) - { - if (ldr.Exception != null) - { - exceptions.Add(ldr.Exception); - } - } - - if (exceptions.Count != 0) - { - success = false; - HandleCommandExecutionException(currentCompletion, - new MultiShardAggregateException(exceptions)); - } - } - - if (success) - { - currentCompletion.SetResult(-1); - } - break; - default: - currentCompletion.SetException(new InvalidOperationException("Unexpected task status.")); - break; - } - - return currentCompletion.Task; - }, cancellationToken) - .Unwrap(); - - _currentCommandTask = commandTask; - return commandTask; - } - } - catch (Exception ex) - { - currentCompletion.SetException(ex); - return currentCompletion.Task; - } - } - - #endregion - - #region ExecuteScalar Methods - - /// - /// ExecuteScalar is currently not supported - /// - /// - public override object ExecuteScalar() - { - throw new NotSupportedException("ExecuteScalar is not supported"); - } - - /// - /// ExecuteScalarAsync is currently not supported - /// - /// The cancellation token - /// - public override Task ExecuteScalarAsync(CancellationToken cancellationToken) - { - return base.ExecuteScalarAsync(cancellationToken); - } - #endregion - - #endregion - - #region UnSupported DbCommand Properties - - // DEVNOTE (VSTS 2202707): We also do not suppport SqlNotificationRequest and - // NotificationAutoEnlist handling yet - - /// - /// This property is currently not supported. Accessing the property will result in an exception. - /// - public override bool DesignTimeVisible - { - get - { - throw new NotSupportedException("DesignTimeVisible is not supported"); - } - set - { - throw new NotSupportedException("DesignTimeVisible is not supported"); - } - } - - /// - /// This property is currently not supported. Accessing the property will result in an exception. - /// - protected override DbTransaction DbTransaction - { - get - { - throw new NotSupportedException("DbTransaction is not supported"); - } - set - { - throw new NotSupportedException("DbTransaction is not supported"); - } - } - - /// - /// This property is currently not supported. Accessing the property will result in an exception. - /// - /// DEVNOTE(VSTS 2202707): Do we want to support this? - public override UpdateRowSource UpdatedRowSource - { - get - { - throw new NotSupportedException("UpdatedRowSource is not supported"); - } - set - { - throw new NotSupportedException("UpdatedRowSource is not supported"); - } - } - - /// - /// Connections to shards. Not supported/exposed - /// since connections are managed internally by this instance - /// - protected override DbConnection DbConnection - { - get - { - throw new NotSupportedException("Connections to shards are not exposed"); - } - set - { - throw new NotSupportedException("Connections to shards are not exposed"); - } - } - - #endregion - - #region Inner Helper Classes - - /// - /// Sets up and manages the cancellation of the Execute* methods. - /// - private class CommandCancellationManager : IDisposable - { - private readonly CancellationTokenSource _timeoutCts; - private readonly CancellationTokenSource _completeResultsCts; - - private readonly CancellationToken _linkedToken; - - private bool _disposed; - - public CommandCancellationManager( - CancellationToken innerCts, - CancellationToken outerCts, - MultiShardExecutionPolicy executionPolicy, - int commandTimeout) - { - // Create a Cts to cancel any tasks in-progress if a - // complete results execution policy is used - if (executionPolicy == MultiShardExecutionPolicy.CompleteResults) - { - _completeResultsCts = new CancellationTokenSource(); - } - - // Setup the command timeout Cts - if (commandTimeout > 0) - { - _timeoutCts = new CancellationTokenSource(); - _timeoutCts.CancelAfter(TimeSpan.FromSeconds(commandTimeout)); - } - - // Create the uber-token - _linkedToken = CreateLinkedToken(innerCts, outerCts); - } - - #region Properties - - public CancellationToken Token - { - get - { - return _linkedToken; - } - } - - public CancellationTokenSource CompleteResultsCts - { - get - { - if (_completeResultsCts == null) - { - throw new InvalidOperationException("No CancellationTokenSource exists for specified execution policy."); - } - - return _completeResultsCts; - } - } - public bool HasTimeoutExpired - { - get - { - return _timeoutCts != null && _timeoutCts.IsCancellationRequested; - } - } - - #endregion - - public void Dispose() - { - if (!_disposed) - { - if (null != _timeoutCts) - { - _timeoutCts.Dispose(); - } - - if (null != _completeResultsCts) - { - _completeResultsCts.Dispose(); - } - - _disposed = true; - } - } - - // Suppression rationale: We are returning the object. We don't want to dispose it. - // - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - private CancellationToken CreateLinkedToken(CancellationToken innerToken, CancellationToken outerToken) - { - CancellationToken completeResultsToken = (_completeResultsCts == null) ? CancellationToken.None : _completeResultsCts.Token; - - CancellationToken timeoutToken = (_timeoutCts == null) ? CancellationToken.None : _timeoutCts.Token; - - return CancellationTokenSource.CreateLinkedTokenSource( - innerToken, - outerToken, - completeResultsToken, - timeoutToken) - .Token; - } - } - - /// - /// Encapsulates data structures representing state of tasks executing across all the shards. - /// - private class FanOutTask - { - /// - /// Parent task of all per-shard tasks. - /// - internal Task OuterTask { get; set; } - - /// - /// Collection of inner tasks that run against each shard. - /// - internal Task[] InnerTasks { get; set; } - } - - #endregion Inner Helper Classes - } -} +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// +// Purpose: +// Complements the MultiShardConnection and abstracts away +// the work of running a given dbcommand against mulitple shards +// +// Notes: +// * This class is NOT thread-safe. +// * Since the Sync API internally invokes the async API, connections to shards with +// connection string property "context connection = true" are not supported. +// * Transaction semantics are not supported + + +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.SqlClient; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Xml; +using Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement; + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query +{ + // Suppression rationale: "Multi" is the spelling we want here. + // + /// + /// Complements the with a command object + /// similar to the triad of , , and . + /// The takes a T-SQL command statement as its input and executes the + /// command across its collection of shards specified by its corresponding . + /// The results from processing the are made available through the + /// execute methods and the . + /// + [System.ComponentModel.DesignerCategory("Code")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi")] + public sealed class MultiShardCommand : DbCommand + { + #region Global Vars + + /// + /// Default command timeout per shard in seconds + /// + private const int DefaultCommandTimeoutPerShard = 30; + + /// + /// Default command timeout in seconds + /// + private const int DefaultCommandTimeout = 300; + + /// + /// The ILogger + /// + private static readonly ILogger s_tracer = TraceHelper.Tracer; + + /// + /// The sql command to be executed against shards + /// + private readonly DbCommand _dbCommand; + + /// + /// Lock to enable thread-safe Cancel() + /// + private readonly object _cancellationLock = new Object(); + + /// + /// Global token source to enable cancellation of commands being executed + /// + private CancellationTokenSource _innerCts = new CancellationTokenSource(); + + /// + /// Task associated with current command invocation + /// + private Task _currentCommandTask = Task.FromResult(null); + + /// + /// ActivityId of the current command being executed + /// + private Guid _activityId; + + /// + /// Whether this command has already been disposed. + /// + private bool _disposed = false; + + #endregion + + #region Ctors + + /// + /// Creates an instance of this class + /// + /// The connection to shards + /// The command to execute against the shards + /// Command timeout + /// against ALL shards + private MultiShardCommand(MultiShardConnection connection, DbCommand command, int commandTimeout) + { + this.Connection = connection; + this.CommandTimeout = commandTimeout; + + _dbCommand = command; + + // Set defaults + this.RetryPolicy = RetryPolicy.DefaultRetryPolicy; + this.RetryBehavior = RetryBehavior.DefaultRetryBehavior; + this.ExecutionPolicy = MultiShardExecutionPolicy.CompleteResults; + this.ExecutionOptions = MultiShardExecutionOptions.None; + } + + #endregion + + #region Instance Factories + + // Suppression rationale: + // The SqlCommand underlies the object we will return. We don't want to dispose it. + // The point of this c-tor is to allow the user to specify whatever sql text they wish. + /// + /// Instance constructor of this class + /// Default command timeout of 300 seconds is used + /// + /// The connection to shards + /// The command text to execute against shards + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] + internal static MultiShardCommand Create(MultiShardConnection connection, string commandText) + { + SqlCommand cmd = new SqlCommand(commandText); + cmd.CommandTimeout = MultiShardCommand.DefaultCommandTimeoutPerShard; // Default sql command timeout of 30secs per shard + cmd.CommandType = CommandType.Text; + + return MultiShardCommand.Create( + connection, + cmd, + MultiShardCommand.DefaultCommandTimeout); + } + + // Suppression rationale: + // The SqlCommand underlies the object we will return. We don't want to dispose it. + // The point of this c-tor is to allow the user to specify whatever sql text they wish. + /// + /// Instance constructor of this class + /// Default command type is text + /// + /// The connection to shards + /// + /// Command timeout for given commandText to be run + /// against ALL shards + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] + internal static MultiShardCommand Create(MultiShardConnection connection, string commandText, int commandTimeout) + { + SqlCommand cmd = new SqlCommand(commandText); + cmd.CommandTimeout = MultiShardCommand.DefaultCommandTimeoutPerShard; // Default sql command timeout of 30secs per shard + cmd.CommandType = CommandType.Text; + + return MultiShardCommand.Create( + connection, + cmd, + commandTimeout); + } + + /// + /// Creates an instance of this class + /// + /// The connection handle to all shards + /// A sql command from which the commandText, commandTimeout, commandType will be inferred. Should implement ICloneable + /// Command timeout for given commandText to be run against ALL shards + /// + /// DEVNOTE: Should we expose a DbCommand instead? Do we even want to expose this at all? + internal static MultiShardCommand Create(MultiShardConnection connection, DbCommand command, int commandTimeout) + { + Contract.Requires(command is ICloneable); + + return new MultiShardCommand(connection, command, commandTimeout); + } + +#endregion + +#region Public Properties + + // Suppression rationale: The point of this property is precisely to allow the user to specify whatever SQL they wish. + /// + /// Gets or sets the command text to execute against the set of shards. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] + public override string CommandText + { + get + { + return _dbCommand.CommandText; + } + set + { + _dbCommand.CommandText = value; + } + } + + /// + /// Time in seconds to wait for the command to be executed on ALL shards. + /// A value of 0 indicates no wait time limit. The default is 300 seconds. + /// + public override int CommandTimeout + { + get; + set; + } + + /// + /// This property controls the timeout for running + /// a command against individual shards. + /// + public int CommandTimeoutPerShard + { + get + { + return _dbCommand.CommandTimeout; + } + set + { + _dbCommand.CommandTimeout = value; + } + } + + /// + /// The of the command to be executed. + /// + public override CommandType CommandType + { + get + { + return _dbCommand.CommandType; + } + set + { + _dbCommand.CommandType = value; + } + } + + /// + /// The associated with this command. + /// + public new SqlParameterCollection Parameters + { + get + { + return (SqlParameterCollection)_dbCommand.Parameters; + } + } + + /// + /// The retry behavior for detecting transient faults that could occur when connecting to and + /// executing commands against individual shards. + /// + /// + /// The is the default. + /// + public RetryBehavior RetryBehavior + { + get; + set; + } + + /// + /// The execution policy to use when executing + /// commands against shards. Through this policy, + /// users can control whether complete results are required, + /// or whether partial results are acceptable. + /// + public MultiShardExecutionPolicy ExecutionPolicy + { + get; + set; + } + + /// + /// Gets the current instance of the associated with this command. + /// + public new MultiShardConnection Connection + { + get; + private set; + } + + /// + /// Gets or sets options that control how the command is executed. + /// For instance, you can use this to include the shard name as + /// an additional column into the result. + /// + public MultiShardExecutionOptions ExecutionOptions + { + get; + set; + } + + /// + /// The event handler invoked when execution has begun on a given shard. + /// + public event EventHandler ShardExecutionBegan; + + /// + /// The event handler invoked when execution has successfully completed on a given shard or its + /// shard-specific has been returned. + /// + public event EventHandler ShardExecutionSucceeded; + + /// + /// The event handler invoked when execution on a given shard has faulted. This handler is only + /// invoked on exceptions for which execution could not be retried further as a result of + /// the exception's non-transience or as a result of the chosen . + /// + public event EventHandler ShardExecutionFaulted; + + /// + /// The event handler invoked when execution on a given shard is canceled, either explicitly via + /// the provided or implicitly as a result of the chosen + /// . + /// + public event EventHandler ShardExecutionCanceled; + + /// + /// The event handler invoked when ExecuteDataReader on a certain shard has successfully returned + /// a reader. This is an internal-only method, and differs from ShardExecutionSucceeded in that + /// it is invoked BEFORE the reader is added to the MultiShardDataReader; this adding is rife + /// with side effects that are difficult to isolate. + /// + internal event EventHandler ShardExecutionReaderReturned; + +#endregion Public Properties + +#region Internal Properties + + /// + /// The retry policy to use when connecting to and + /// executing commands against individual shards. + /// + internal RetryPolicy RetryPolicy + { + get; + set; + } + +#endregion Internal Properties + +#region Protected Properties + + /// + /// Gets the SqlParameter Collection + /// + protected override DbParameterCollection DbParameterCollection + { + get + { + return this.Parameters; + } + } + +#endregion Protected Properties + +#region APIs + +#region Supported DbCommand APIs + +#region ExecuteReader Methods + +#region Synchronous Methods + + /// + /// The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard + /// and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a + /// . The execution policy regarding result completeness can be controlled + /// by setting the . The default execution policy is to return complete results. + /// + /// the instance with the overall concatenated result set. + /// thrown if the commandText is null or empty + /// thrown if the CommandTimeout elapsed prior to completion + public new MultiShardDataReader ExecuteReader() + { + return this.ExecuteReader(CommandBehavior.Default); + } + + /// + /// - Runs the given query against all shards and returns + /// a reader that encompasses results from them. + /// - Uses the MultiShardExecutionPolicy.CompleteResults as the default execution policy + /// - Includes the $ShardName pseudo column in the results + /// Command behavior to use + /// MultiShardDataReader instance that encompasses results from all shards + /// If the commandText is null or empty + /// If the command behavior is not supported + /// (CloseConnection or SingleResult or SingleRow) + /// If the CommandTimeout elapsed prior to completion + /// + protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) + { + return this.ExecuteReader(behavior); + } + + /// + /// The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard + /// and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a + /// . The execution policy regarding result completeness can be controlled + /// by setting the . The default execution policy is to return complete results. + /// + /// the instance with the overall concatenated result set. + /// thrown if the commandText is null or empty, or if the + /// specified command behavior is not supported such as CloseConnection or SingleRow. + /// thrown if the CommandTimeout elapsed prior to completion. + /// specifies the to use. + public new MultiShardDataReader ExecuteReader(CommandBehavior behavior) + { + return this.ExecuteReader( + behavior, + MultiShardUtils.GetSqlCommandRetryPolicy(this.RetryPolicy, this.RetryBehavior), + MultiShardUtils.GetSqlConnectionRetryPolicy(this.RetryPolicy, this.RetryBehavior), + this.ExecutionPolicy); + } + + /// + /// - Runs the given query against all shards and returns + /// a reader that encompasses results from them. + /// + /// Design Principles + /// - Commands are executed in a parallel, non-blocking manner. + /// - Only the calling thread is blocked until the command is complete against all shards. + /// + /// Command behavior to use + /// The retry policy to use when executing commands against the shards + /// The retry policy to use when connecting to shards + /// The execution policy to use + /// MultiShardDataReader instance that encompasses results from all shards + /// If the commandText is null or empty + /// If the CommandTimeout elapsed prior to completion + /// If one or more errors occured while executing the command + internal MultiShardDataReader ExecuteReader( + CommandBehavior behavior, + TransientFaultHandling.RetryPolicy commandRetryPolicy, + TransientFaultHandling.RetryPolicy connectionRetryPolicy, + MultiShardExecutionPolicy executionPolicy) + { + Contract.Requires(commandRetryPolicy != null && connectionRetryPolicy != null); + + try + { + return this.ExecuteReaderAsync( + behavior, + CancellationToken.None, + commandRetryPolicy, + connectionRetryPolicy, + executionPolicy).Result; + } + catch (Exception ex) + { + AggregateException aex = ex as AggregateException; + + if (null != aex) + { + throw aex.Flatten().InnerException; + } + + throw; + } + } + +#endregion + +#region Async Methods + + /// + /// The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard + /// and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a + /// . The execution policy regarding result completeness can be controlled + /// by setting the . The default execution policy is to return complete results. + /// + /// a task warapping the instance with the overall concatenated result set. + /// thrown if the commandText is null or empty, or if the + /// specified command behavior is not supported such as CloseConnection or SingleRow. + /// thrown if the CommandTimeout elapsed prior to completion. + /// Any exceptions during command execution are conveyed via the returned Task. + public new Task ExecuteReaderAsync() + { + return this.ExecuteReaderAsync(CancellationToken.None); + } + + /// + /// The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard + /// and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a + /// . The execution policy regarding result completeness can be controlled + /// by setting the . The default execution policy is to return complete results. + /// + /// a task warapping the instance with the overall concatenated result set. + /// thrown if the commandText is null or empty, or if the + /// specified command behavior is not supported such as CloseConnection or SingleRow. + /// thrown if the CommandTimeout elapsed prior to completion. + /// Cancellation token to cancel the command execution + /// Any exceptions during command execution are conveyed via the returned Task. + public new Task ExecuteReaderAsync(CancellationToken cancellationToken) + { + return this.ExecuteReaderAsync(CommandBehavior.Default, cancellationToken); + } + + /// + /// - Executes the given query against all shards asynchronously + /// - Uses the MultiShardExecutionPolicy.CompleteResults as the default execution policy + /// - Includes the $ShardName pseudo column in the results + /// + /// Command behavior to use + /// Cancellation token to cancel the command execution + /// A task with a TResult that encompasses results from all shards + /// Any exceptions during command execution are conveyed via the returned Task + /// If the commandText is null or empty + protected override Task ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) + { + return this.ExecuteReaderAsync(behavior, cancellationToken) + .ContinueWith( + (t) => + { + if (t.IsFaulted) + { + throw t.Exception.InnerException; + } + + return t.Result; + }, + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled, + TaskScheduler.Default); + } + + /// + /// The ExecuteReader methods of the MultiShardCommand execute the given command statement on each shard + /// and return the concatenation (i.e. UNION ALL) of the individual results from the shards in a + /// . The execution policy regarding result completeness can be controlled + /// by setting the . The default execution policy is to return complete results. + /// + /// a task warapping the instance with the overall concatenated result set. + /// thrown if the commandText is null or empty, or if the + /// specified command behavior is not supported such as CloseConnection or SingleRow. + /// thrown if the CommandTimeout elapsed prior to completion. + /// Command behavior to use + /// Cancellation token to cancel the command execution + /// Any exceptions during command execution are conveyed via the returned Task. + public new Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) + { + return this.ExecuteReaderAsync( + behavior, + cancellationToken, + MultiShardUtils.GetSqlCommandRetryPolicy(this.RetryPolicy, this.RetryBehavior), + MultiShardUtils.GetSqlConnectionRetryPolicy(this.RetryPolicy, this.RetryBehavior), + this.ExecutionPolicy); + } + + // Suppression rationale: + // We want to return exceptions via the task so that they can be dealt with on the main thread. Gotta catch 'em all. + // We are returning the shardedReader variable via the task. We don't want to dispose it. + // This method is part of the defined API. We can't move it to a different class. + // + /// + /// Executes the given query against all shards asynchronously + /// + /// Command behavior to use + /// Cancellation token to cancel the command execution + /// The retry policy to use when executing commands against the shards + /// The retry policy to use when connecting to shards + /// The execution policy to use + /// A task with a TResult that encompasses results from all shards + /// Any exceptions during command execution are conveyed via the returned Task + /// If the commandText is null or empty + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + internal Task ExecuteReaderAsync( + CommandBehavior behavior, + CancellationToken outerCancellationToken, + TransientFaultHandling.RetryPolicy commandRetryPolicy, + TransientFaultHandling.RetryPolicy connectionRetryPolicy, + MultiShardExecutionPolicy executionPolicy) + { + TaskCompletionSource currentCompletion = new TaskCompletionSource(); + + // Check if cancellation has already been requested by the user + if (outerCancellationToken.IsCancellationRequested) + { + currentCompletion.SetCanceled(); + return currentCompletion.Task; + } + + try + { + this.ValidateCommand(behavior); + + // Create a list of sql commands to run against each of the shards + List> shardCommands = this.GetShardDbCommands(); + + // Don't allow a new invocation if a Cancel() is already in progress + lock (_cancellationLock) + { + // Set the activity id + _activityId = Guid.NewGuid(); + using (var activityIdScope = new ActivityIdScope(_activityId)) + { + Stopwatch stopwatch = Stopwatch.StartNew(); + + // Setup the Cancellation manager + CommandCancellationManager cmdCancellationMgr = new CommandCancellationManager( + _innerCts.Token, + outerCancellationToken, + executionPolicy, + this.CommandTimeout); + + s_tracer.TraceInfo( + "MultiShardCommand.ExecuteReaderAsync", + "Start; Command Timeout: {0}; Command Text: {1}; Execution Policy: {2}", + this.CommandTimeout, + this.CommandText, + this.ExecutionPolicy); + + FanOutTask fanOutTask = this.ExecuteReaderAsyncInternal( + behavior, + shardCommands, + cmdCancellationMgr, + commandRetryPolicy, + connectionRetryPolicy, + executionPolicy); + + Task commandTask = fanOutTask + .OuterTask + .ContinueWith>( + (t) => + { + stopwatch.Stop(); + + string completionTrace = string.Format("Complete; Execution Time: {0}", stopwatch.Elapsed); + + switch (t.Status) + { + case TaskStatus.Faulted: + // Close any active readers. + if (this.ExecutionPolicy == MultiShardExecutionPolicy.CompleteResults) + { + MultiShardCommand.TerminateActiveCommands(fanOutTask.InnerTasks); + } + + this.HandleCommandExecutionException( + currentCompletion, + new MultiShardAggregateException(t.Exception.InnerExceptions), + completionTrace); + break; + + case TaskStatus.Canceled: + // Close any active readers. + if (this.ExecutionPolicy == MultiShardExecutionPolicy.CompleteResults) + { + MultiShardCommand.TerminateActiveCommands(fanOutTask.InnerTasks); + } + + this.HandleCommandExecutionCanceled( + currentCompletion, + cmdCancellationMgr, + completionTrace); + break; + + case TaskStatus.RanToCompletion: + try + { + s_tracer.TraceInfo("MultiShardCommand.ExecuteReaderAsync", completionTrace); + + // If all child readers have exceptions, then aggregate the exceptions into this parent task. + IEnumerable childExceptions = t.Result.Select(r => r.Exception); + + if (childExceptions.All(e => e != null)) + { + // All child readers have exceptions + + // This should only happen on PartialResults, because if we were in + // CompleteResults then any failed child reader should have caused + // the task to be in TaskStatus.Faulted + Debug.Assert(this.ExecutionPolicy == MultiShardExecutionPolicy.PartialResults); + + this.HandleCommandExecutionException( + currentCompletion, + new MultiShardAggregateException(childExceptions), + completionTrace); + } + else + { + // At least one child reader has succeeded + bool includeShardNameColumn = (this.ExecutionOptions & MultiShardExecutionOptions.IncludeShardNameColumn) != 0; + + // Hand-off the responsibility of cleanup to the MultiShardDataReader. + MultiShardDataReader shardedReader = new MultiShardDataReader( + this, + t.Result, + executionPolicy, + includeShardNameColumn); + + currentCompletion.SetResult(shardedReader); + } + } + catch (Exception ex) + { + HandleCommandExecutionException(currentCompletion, new MultiShardAggregateException(ex)); + } + break; + + default: + currentCompletion.SetException(new InvalidOperationException("Unexpected task status.")); + break; + } + + return currentCompletion.Task; + }, + TaskContinuationOptions.ExecuteSynchronously) + .Unwrap(); + + _currentCommandTask = commandTask; + + return commandTask; + } + } + } + catch (Exception ex) + { + currentCompletion.SetException(ex); + return currentCompletion.Task; + } + } + +#endregion + + /// + /// Terminates any active commands/readers for scenarios where we fail the request due to + /// strict execution policy or cancellation. + /// + /// Collection of reader tasks associated with execution across all shards. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We do not want to throw Close or Cancel errors.")] + private static void TerminateActiveCommands(Task[] readerTasks) + { + for (int i = 0; i < readerTasks.Length; i++) + { + if (readerTasks[i].Status == TaskStatus.RanToCompletion) + { + Debug.Assert(readerTasks[i].Result != null, "Must have a LabeledDbDataReader if task finished."); + LabeledDbDataReader labeledReader = readerTasks[i].Result; + + // This is a candidate for closing since we are in a faulted state. + Debug.Assert(labeledReader.DbDataReader != null, "Expecting reader for completed task."); + + try + { + using (labeledReader.Command) + using (labeledReader.DbDataReader) + { + // Invoke cancellation before closing the reader. This is safe from deadlocks that + // arise potentially due to parallel Cancel and Close calls because this is the only + // thread that will be responsible for cleanup. + labeledReader.Command.Cancel(); + labeledReader.DbDataReader.Close(); + } + } + catch (Exception) + { + // Catch everything for Cancel/Close. + } + } + } + } + + private FanOutTask ExecuteReaderAsyncInternal( + CommandBehavior behavior, + List> commands, + CommandCancellationManager cancellationToken, + TransientFaultHandling.RetryPolicy commandRetryPolicy, + TransientFaultHandling.RetryPolicy connectionRetryPolicy, + MultiShardExecutionPolicy executionPolicy) + { + Task[] shardCommandTasks = new Task[commands.Count]; + + for (int i = 0; i < shardCommandTasks.Length; i++) + { + Tuple shardCommand = commands[i]; + + shardCommandTasks[i] = this.GetLabeledDbDataReaderTask( + behavior, + shardCommand, + cancellationToken, + commandRetryPolicy, + connectionRetryPolicy, + executionPolicy); + } + + return new FanOutTask + { + OuterTask = Task.WhenAll(shardCommandTasks), + InnerTasks = shardCommandTasks + }; + } + + // Suppression rationale: We are returning the LabeledDataReader via the task. We don't want to dispose it. + // + /// + /// Helper that generates a Task to return a LabaledDbDataReader rather than just a plain DbDataReader + /// so that we can affiliate the shard label with the Task returned from a call to DbCommand.ExecuteReaderAsync. + /// + /// Command behavior to use + /// A tuple of the Shard and the command to be executed + /// Manages the cancellation tokens + /// The retry policy to use when executing commands against the shards + /// The retry policy to use when connecting to shards + /// The execution policy to use + /// A Task that will return a LabaledDbDataReader. + /// + /// We should be able to tap into this code to trap and gracefully deal with command execution errors as well. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] + private Task GetLabeledDbDataReaderTask( + CommandBehavior behavior, + Tuple commandTuple, + CommandCancellationManager cmdCancellationMgr, + TransientFaultHandling.RetryPolicy commandRetryPolicy, + TransientFaultHandling.RetryPolicy connectionRetryPolicy, + MultiShardExecutionPolicy executionPolicy) + { + TaskCompletionSource currentCompletion = new TaskCompletionSource(); + + ShardLocation shard = commandTuple.Item1; + DbCommand command = commandTuple.Item2; + Stopwatch stopwatch = Stopwatch.StartNew(); + + // Always the close connection once the reader is done + // + // Commented out because of VSTS BUG# 3936154: When this command behavior is enabled, + // SqlClient seems to be running into a deadlock when we invoke a cancellation on + // SqlCommand.ExecuteReaderAsync(cancellationToken) with a SqlCommand.CommandText that would + // lead to an error (Ex. "select * from non_existant_table"). + // As a workaround, we now explicitly close the connection associated with each shard's SqlDataReader + // once we are done reading through it in MultiShardDataReader. + // Please refer to the bug to find a sample app with a repro, dump and symbols. + // + // behavior |= CommandBehavior.CloseConnection; + + s_tracer.TraceInfo( + "MultiShardCommand.GetLabeledDbDataReaderTask", + "Starting command execution for Shard: {0}; Behavior: {1}; Retry Policy: {2}", + shard, + behavior, + this.RetryPolicy); + + Task> commandExecutionTask = commandRetryPolicy.ExecuteAsync>( + () => + { + // Execute command in the Threadpool + return Task.Run( + async () => + { + // In certain cases sqlcommand doesn't reset its internal state correctly upon + // failure of an async command (especially if the connection is still open). + // This leads to unsuccessful retries on our part (see bug#2711396). + // The recommendation from the Sqlclient team is to either start off with a new sqlcommand instance + // on every retry or close and reopen the connection. + // We're going with the former approach here. + DbCommand commandToExecute = MultiShardUtils.CloneDbCommand(command, command.Connection); + + // Open the connection if it isn't already + await this.OpenConnectionWithRetryAsync( + commandToExecute, + cmdCancellationMgr.Token, + connectionRetryPolicy) + .ConfigureAwait(false); + + // The connection to the shard has been successfully opened and the per-shard command is about to execute. + // Raise the ShardExecutionBegan event. + this.OnShardExecutionBegan(shard); + + DbDataReader perShardReader = await commandToExecute.ExecuteReaderAsync( + behavior, + cmdCancellationMgr.Token) + .ConfigureAwait(false); + + return new Tuple(perShardReader, commandToExecute); + }); + }, + cmdCancellationMgr.Token); + + return commandExecutionTask.ContinueWith>( + (t) => + { + stopwatch.Stop(); + + string traceMsg = string.Format( + "Completed command execution for Shard: {0}; Execution Time: {1}; Task Status: {2}", + shard, + stopwatch.Elapsed, + t.Status); + + switch (t.Status) + { + case TaskStatus.Faulted: + MultiShardException exception = new MultiShardException(shard, t.Exception.InnerException); + + // Close the connection + command.Connection.Close(); + + // Workaround: SqlCommand sets the task status to Faulted if the token was + // canceled while ExecuteReaderAsync was in progress. Interpret it and raise a canceled event instead. + if (cmdCancellationMgr.Token.IsCancellationRequested) + { + s_tracer.TraceError( + "MultiShardCommand.GetLabeledDbDataReaderTask", + exception, + "Command was canceled. {0}", + traceMsg); + + currentCompletion.SetCanceled(); + + // Raise the ShardExecutionCanceled event. + this.OnShardExecutionCanceled(shard); + } + else + { + s_tracer.TraceError( + "MultiShardCommand.GetLabeledDbDataReaderTask", + exception, + "Command failed. {0}", + traceMsg); + + if (executionPolicy == MultiShardExecutionPolicy.CompleteResults) + { + currentCompletion.SetException(exception); + + // Cancel any other tasks in-progress + cmdCancellationMgr.CompleteResultsCts.Cancel(); + } + else + { + LabeledDbDataReader failedLabeledReader = new LabeledDbDataReader(exception, shard, command); + + currentCompletion.SetResult(failedLabeledReader); + } + + // Raise the ShardExecutionFaulted event. + this.OnShardExecutionFaulted(shard, t.Exception.InnerException); + } + + break; + + case TaskStatus.Canceled: + s_tracer.TraceWarning( + "MultiShardCommand.GetLabeledDbDataReaderTask", + "Command was canceled. {0}", + traceMsg); + + command.Connection.Close(); + + currentCompletion.SetCanceled(); + + // Raise the ShardExecutionCanceled event. + this.OnShardExecutionCanceled(shard); + break; + + case TaskStatus.RanToCompletion: + s_tracer.TraceInfo("MultiShardCommand.GetLabeledDbDataReaderTask", traceMsg); + + LabeledDbDataReader labeledReader = new LabeledDbDataReader(t.Result.Item1, shard, t.Result.Item2); + + // Raise the ShardExecutionReaderReturned event. + this.OnShardExecutionReaderReturned(shard, labeledReader); + + currentCompletion.SetResult(labeledReader); + + // Raise the ShardExecutionSucceeded event. + this.OnShardExecutionSucceeded(shard, labeledReader); + break; + + default: + currentCompletion.SetException(new InvalidOperationException("Unexpected task status..")); + break; + } + + return currentCompletion.Task; + }, + TaskContinuationOptions.ExecuteSynchronously) + .Unwrap(); + } + + private async Task OpenConnectionWithRetryAsync( + DbCommand shardCommand, + CancellationToken cancellationToken, + TransientFaultHandling.RetryPolicy connectionRetryPolicy) + { + var shardConnection = shardCommand.Connection; + + await connectionRetryPolicy.ExecuteAsync( + () => MultiShardUtils.OpenShardConnectionAsync( + shardConnection, + cancellationToken), + cancellationToken) + .ConfigureAwait(false); + } + +#endregion ExecuteReader Methods + + // Suppression rationale: We don't want cancel throwing any exceptions. Just cancel. + // + /// + /// Attempts to cancel an in progress + /// and any ongoing work that is performed at the shards on behalf of the command. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + public override void Cancel() + { + lock (_cancellationLock) + { + try + { + Task currentTask = _currentCommandTask; + + if (currentTask != null) + { + if (IsExecutionInProgress()) + { + // Call could've been made from a worker thread + using (ActivityIdScope activityIdScope = new ActivityIdScope(_activityId)) + { + s_tracer.TraceWarning( + "MultiShardCommand.Cancel", + "Command was canceled; Current task status: {0}", + currentTask.Status); + + _innerCts.Cancel(); + + currentTask.Wait(); + } + } + + Debug.Assert(currentTask.IsCompleted, "Current task should be complete."); + + // For tasks that failed or were cancelled we assume that they are already cleaned up. + if (currentTask.Status == TaskStatus.RanToCompletion) + { + Task executeReaderTask = currentTask as Task; + + if (currentTask != null) + { + // Cancel all the active readers on MultiShardDataReader. + executeReaderTask.Result.Cancel(); + } + } + } + } + catch // Cancel doesn't throw any exceptions + { + } + finally + { + if (_innerCts.IsCancellationRequested) + { + _innerCts = new CancellationTokenSource(); + } + } + } + } + + /// + /// Creates a new instance of a object. + /// + /// + public static new SqlParameter CreateParameter() + { + return new SqlParameter(); + } + + /// + /// Creates an instance of the DbParameter + /// + /// + protected override DbParameter CreateDbParameter() + { + return CreateParameter(); + } + + // Suppression rationale: We purposely want to ignore exceptions when disposing. + // + /// + /// Dispose off any unmanaged/managed resources held + /// + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + protected override void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + try + { + // Cancel any commands that are in progress + this.Cancel(); + + // Close any open connections + this.Connection.Close(); + } + catch (Exception) // Ignore any exceptions + { + } + + // Dispose the cancellation token source + using (_innerCts) + { + } + + _disposed = true; + + s_tracer.TraceWarning("MultiShardCommand.Dispose", "Command disposed"); + } + + base.Dispose(disposing); + } + } + +#endregion Supported DbCommand APIs + + /// + /// Resets the property + /// to its default value + /// + public void ResetCommandTimeout() + { + this.CommandTimeout = MultiShardCommand.DefaultCommandTimeout; + } + + /// + /// Resets the property + /// to its default value + /// + public void ResetCommandTimeoutPerShard() + { + this.CommandTimeoutPerShard = MultiShardCommand.DefaultCommandTimeoutPerShard; + } + +#endregion APIs + +#region Helpers + + private void ValidateCommand(CommandBehavior behavior) + { + // Enforce only one async invocation at a time + if (IsExecutionInProgress()) + { + var ex = new InvalidOperationException("The command execution cannot proceed due to a pending asynchronous operation already in progress."); + + s_tracer.TraceError( + "MultiShardCommand.ValidateCommand", + ex, + "Current Task Status: {0}", + _currentCommandTask.Status); + + throw ex; + } + + // Make sure command text is valid + if (string.IsNullOrWhiteSpace(CommandText)) + { + throw new InvalidOperationException("CommandText cannot be null"); + } + + // Validate the command behavior + ValidateCommandBehavior(behavior); + + // Validate the parameters + ValidateParameters(); + } + + private static void ValidateCommandBehavior(CommandBehavior cmdBehavior) + { + if (((cmdBehavior & CommandBehavior.CloseConnection) != 0) || + ((cmdBehavior & CommandBehavior.SingleResult) != 0) || + ((cmdBehavior & CommandBehavior.SingleRow) != 0)) + { + throw new NotSupportedException(string.Format("CommandBehavior {0} is not supported", cmdBehavior)); + } + } + + private void ValidateParameters() + { + int parameterCount = Parameters.Count; + for (int i = 0; i < parameterCount; i++) + { + SqlParameter parameter = Parameters[i]; + + // We only allow input parameters + if (parameter.Direction != ParameterDirection.Input) + { + throw new NotSupportedException(string.Format("Only ParameterDirection.Input is currently supported. Parameter Name: {0} Direction: {1}", + parameter.ParameterName, parameter.Direction)); + } + + // We don't allow streaming to sqlserver + if (parameter.Value != null && + (parameter.Value is Stream || + parameter.Value is TextReader || + parameter.Value is XmlReader || + parameter.Value is DbDataReader)) + { + throw new NotSupportedException(string.Format("Streaming to sql server is currently not supported. Parameter Name: {0} Value type: {1}", + parameter.ParameterName, parameter.Value.GetType())); + } + } + } + + /// + /// Whether execution is already in progress + /// against this command instance + /// + /// True if execution is in progress + private bool IsExecutionInProgress() + { + Task currentTask = _currentCommandTask; + + return currentTask != null && !currentTask.IsCompleted; + } + + /// + /// Creates a list of commands to be executed against the shards associated with the connection. + /// + /// Pairs of shard locations and associated commands. + private List> GetShardDbCommands() + { + return this.Connection + .ShardConnections + .Select(sc => new Tuple(sc.Item1, MultiShardUtils.CloneDbCommand(_dbCommand, sc.Item2))) + .ToList(); + } + + private void HandleCommandExecutionException( + TaskCompletionSource tcs, + Exception ex, + string trace = "") + { + // Close any open connections + this.Connection.Close(); + s_tracer.TraceError("MultiShardCommand.ExecuteReaderAsync", ex, trace); + tcs.SetException(ex); + } + + private void HandleCommandExecutionCanceled( + TaskCompletionSource tcs, + CommandCancellationManager cancellationMgr, + string trace = "") + { + // Close any open connections + this.Connection.Close(); + + s_tracer.TraceWarning("MultiShardCommand.ExecuteReaderAsync", "Command was canceled; {0}", trace); + + if (cancellationMgr.HasTimeoutExpired) + { + // The ConnectionTimeout elapsed + tcs.SetException(new TimeoutException + (string.Format("Command timeout of {0} elapsed.", CommandTimeout))); + } + else + { + tcs.SetCanceled(); + } + } + +#region Event Raisers + + /// + /// Raise the ShardExecutionBegan event. + /// + /// The shard for which this event is raised. + private void OnShardExecutionBegan(ShardLocation shardLocation) + { + if (ShardExecutionBegan != null) + { + ShardExecutionEventArgs args = new ShardExecutionEventArgs() + { + ShardLocation = shardLocation, + Exception = null + }; + + try + { + ShardExecutionBegan(this, args); + } + catch (Exception e) + { + throw new MultiShardException(shardLocation, e); + } + } + } + + /// + /// Raise the ShardExecutionSucceeded event. + /// + /// The shard for which this event is raised. + /// The reader to pass in the associated eventArgs. + private void OnShardExecutionSucceeded(ShardLocation shardLocation, LabeledDbDataReader reader) + { + if (ShardExecutionSucceeded != null) + { + ShardExecutionEventArgs args = new ShardExecutionEventArgs() + { + ShardLocation = shardLocation, + Exception = null, + Reader = reader + }; + + try + { + ShardExecutionSucceeded(this, args); + } + catch (Exception e) + { + throw new MultiShardException(shardLocation, e); + } + } + } + + /// + /// Raise the ShardExecutionReaderReturned event. + /// + /// The shard for which this event is raised. + /// The reader to pass in the associated eventArgs. + private void OnShardExecutionReaderReturned(ShardLocation shardLocation, LabeledDbDataReader reader) + { + if (ShardExecutionReaderReturned != null) + { + ShardExecutionEventArgs args = new ShardExecutionEventArgs() + { + ShardLocation = shardLocation, + Exception = null, + Reader = reader + }; + + try + { + ShardExecutionReaderReturned(this, args); + } + catch (Exception e) + { + throw new MultiShardException(shardLocation, e); + } + } + } + + /// + /// Raise the ShardExecutionFaulted event. + /// + /// The shard for which this event is raised. + /// The exception causing the execution on this shard to fault. + private void OnShardExecutionFaulted(ShardLocation shardLocation, Exception executionException) + { + if (ShardExecutionFaulted != null) + { + ShardExecutionEventArgs args = new ShardExecutionEventArgs() + { + ShardLocation = shardLocation, + Exception = executionException + }; + + try + { + ShardExecutionFaulted(this, args); + } + catch (Exception e) + { + throw new MultiShardException(shardLocation, e); + } + } + } + + /// + /// Raise the ShardExecutionCanceled event. + /// + /// The shard for which this event is raised. + private void OnShardExecutionCanceled(ShardLocation shardLocation) + { + if (ShardExecutionCanceled != null) + { + ShardExecutionEventArgs args = new ShardExecutionEventArgs() + { + ShardLocation = shardLocation, + Exception = null + }; + + try + { + ShardExecutionCanceled(this, args); + } + catch (Exception e) + { + throw new MultiShardException(shardLocation, e); + } + } + } + +#endregion Event Raisers + +#endregion Helpers + +#region UnSupported DbCommand APIs + + /// + /// This method is currently not supported. Invoking the property will result in an exception. + /// + public override void Prepare() + { + throw new NotSupportedException("Prepare is currently not supported"); + } + +#region ExecuteNonQuery Methods + + /// + /// ExecuteNonQuery is currently not supported + /// + /// + public override int ExecuteNonQuery() + { + throw new NotSupportedException("ExecuteNonQuery is not supported"); + } + + /// + /// ExecuteNonQueryAsync is currently not supported + /// + /// The cancellation token + /// + public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) + { + return base.ExecuteNonQueryAsync(cancellationToken); + } + + // Suppression rationale: + // We do want to catch all exceptions and set them on the Task where they can be dealt with on the main thread. + // + /// + /// Test only for now + /// + /// + /// + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + internal Task ExecuteNonQueryAsync(CancellationToken cancellationToken, MultiShardExecutionPolicy executionPolicy) + { + var currentCompletion = new TaskCompletionSource(); + var behavior = CommandBehavior.Default; + var commandRetryPolicy = MultiShardUtils.GetSqlCommandRetryPolicy(this.RetryPolicy, this.RetryBehavior); + var connectionRetryPolicy = MultiShardUtils.GetSqlConnectionRetryPolicy(this.RetryPolicy, this.RetryBehavior); + + // Check if cancellation has already been requested by the user + if (cancellationToken.IsCancellationRequested) + { + currentCompletion.SetCanceled(); + return currentCompletion.Task; + } + + try + { + ValidateCommand(behavior); + + // Create a list of sql commands to run against each of the shards + List> shardCommands = this.GetShardDbCommands(); + + // Don't allow a new invocation if a Cancel() is already in progress + lock (_cancellationLock) + { + // Setup the Cancellation manager + CommandCancellationManager cmdCancellationMgr = new CommandCancellationManager( + _innerCts.Token, + cancellationToken, + executionPolicy, + CommandTimeout); + + var commandTask = ExecuteReaderAsyncInternal( + behavior, + shardCommands, + cmdCancellationMgr, + commandRetryPolicy, + connectionRetryPolicy, + executionPolicy) + .OuterTask + .ContinueWith>( + (t) => + { + switch (t.Status) + { + case TaskStatus.Faulted: + HandleCommandExecutionException( + currentCompletion, + new MultiShardAggregateException(t.Exception.InnerExceptions)); + break; + + case TaskStatus.Canceled: + HandleCommandExecutionCanceled( + currentCompletion, + cmdCancellationMgr); + break; + + case TaskStatus.RanToCompletion: + // Close all connections to shards + Connection.Close(); + + // Check for any exceptions if this is a partial results execution policy + bool success = true; + + if (executionPolicy == MultiShardExecutionPolicy.PartialResults) + { + var exceptions = new List(); + foreach (var ldr in t.Result) + { + if (ldr.Exception != null) + { + exceptions.Add(ldr.Exception); + } + } + + if (exceptions.Count != 0) + { + success = false; + HandleCommandExecutionException(currentCompletion, + new MultiShardAggregateException(exceptions)); + } + } + + if (success) + { + currentCompletion.SetResult(-1); + } + break; + default: + currentCompletion.SetException(new InvalidOperationException("Unexpected task status.")); + break; + } + + return currentCompletion.Task; + }, cancellationToken) + .Unwrap(); + + _currentCommandTask = commandTask; + return commandTask; + } + } + catch (Exception ex) + { + currentCompletion.SetException(ex); + return currentCompletion.Task; + } + } + +#endregion + +#region ExecuteScalar Methods + + /// + /// ExecuteScalar is currently not supported + /// + /// + public override object ExecuteScalar() + { + throw new NotSupportedException("ExecuteScalar is not supported"); + } + + /// + /// ExecuteScalarAsync is currently not supported + /// + /// The cancellation token + /// + public override Task ExecuteScalarAsync(CancellationToken cancellationToken) + { + return base.ExecuteScalarAsync(cancellationToken); + } +#endregion + +#endregion + +#region UnSupported DbCommand Properties + + // DEVNOTE (VSTS 2202707): We also do not suppport SqlNotificationRequest and + // NotificationAutoEnlist handling yet + + /// + /// This property is currently not supported. Accessing the property will result in an exception. + /// + public override bool DesignTimeVisible + { + get + { + throw new NotSupportedException("DesignTimeVisible is not supported"); + } + set + { + throw new NotSupportedException("DesignTimeVisible is not supported"); + } + } + + /// + /// This property is currently not supported. Accessing the property will result in an exception. + /// + protected override DbTransaction DbTransaction + { + get + { + throw new NotSupportedException("DbTransaction is not supported"); + } + set + { + throw new NotSupportedException("DbTransaction is not supported"); + } + } + + /// + /// This property is currently not supported. Accessing the property will result in an exception. + /// + /// DEVNOTE(VSTS 2202707): Do we want to support this? + public override UpdateRowSource UpdatedRowSource + { + get + { + throw new NotSupportedException("UpdatedRowSource is not supported"); + } + set + { + throw new NotSupportedException("UpdatedRowSource is not supported"); + } + } + + /// + /// Connections to shards. Not supported/exposed + /// since connections are managed internally by this instance + /// + protected override DbConnection DbConnection + { + get + { + throw new NotSupportedException("Connections to shards are not exposed"); + } + set + { + throw new NotSupportedException("Connections to shards are not exposed"); + } + } + +#endregion + +#region Inner Helper Classes + + /// + /// Sets up and manages the cancellation of the Execute* methods. + /// + private class CommandCancellationManager : IDisposable + { + private readonly CancellationTokenSource _timeoutCts; + private readonly CancellationTokenSource _completeResultsCts; + + private readonly CancellationToken _linkedToken; + + private bool _disposed; + + public CommandCancellationManager( + CancellationToken innerCts, + CancellationToken outerCts, + MultiShardExecutionPolicy executionPolicy, + int commandTimeout) + { + // Create a Cts to cancel any tasks in-progress if a + // complete results execution policy is used + if (executionPolicy == MultiShardExecutionPolicy.CompleteResults) + { + _completeResultsCts = new CancellationTokenSource(); + } + + // Setup the command timeout Cts + if (commandTimeout > 0) + { + _timeoutCts = new CancellationTokenSource(); + _timeoutCts.CancelAfter(TimeSpan.FromSeconds(commandTimeout)); + } + + // Create the uber-token + _linkedToken = CreateLinkedToken(innerCts, outerCts); + } + +#region Properties + + public CancellationToken Token + { + get + { + return _linkedToken; + } + } + + public CancellationTokenSource CompleteResultsCts + { + get + { + if (_completeResultsCts == null) + { + throw new InvalidOperationException("No CancellationTokenSource exists for specified execution policy."); + } + + return _completeResultsCts; + } + } + public bool HasTimeoutExpired + { + get + { + return _timeoutCts != null && _timeoutCts.IsCancellationRequested; + } + } + +#endregion + + public void Dispose() + { + if (!_disposed) + { + if (null != _timeoutCts) + { + _timeoutCts.Dispose(); + } + + if (null != _completeResultsCts) + { + _completeResultsCts.Dispose(); + } + + _disposed = true; + } + } + + // Suppression rationale: We are returning the object. We don't want to dispose it. + // + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] + private CancellationToken CreateLinkedToken(CancellationToken innerToken, CancellationToken outerToken) + { + CancellationToken completeResultsToken = (_completeResultsCts == null) ? CancellationToken.None : _completeResultsCts.Token; + + CancellationToken timeoutToken = (_timeoutCts == null) ? CancellationToken.None : _timeoutCts.Token; + + return CancellationTokenSource.CreateLinkedTokenSource( + innerToken, + outerToken, + completeResultsToken, + timeoutToken) + .Token; + } + } + + /// + /// Encapsulates data structures representing state of tasks executing across all the shards. + /// + private class FanOutTask + { + /// + /// Parent task of all per-shard tasks. + /// + internal Task OuterTask { get; set; } + + /// + /// Collection of inner tasks that run against each shard. + /// + internal Task[] InnerTasks { get; set; } + } + +#endregion Inner Helper Classes + } +} diff --git a/Src/ElasticScale.Client/Query/MultiShardConnection.cs b/Src/ElasticScale.Client/Query/MultiShardConnection.cs index c6d8cdd..e64d7da 100644 --- a/Src/ElasticScale.Client/Query/MultiShardConnection.cs +++ b/Src/ElasticScale.Client/Query/MultiShardConnection.cs @@ -26,7 +26,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi")] public sealed class MultiShardConnection : IDisposable { - #region Global Vars +#region Global Vars /// /// The suffix to append to each shard's ApplicationName @@ -44,9 +44,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// private bool _disposed = false; - #endregion +#endregion - #region Ctors +#region Ctors /// /// Initializes a new instance of the class. @@ -124,9 +124,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query this.ShardConnections = shardConnections; } - #endregion +#endregion - #region Properties +#region Properties /// /// Gets the collection of s associated with this connection. @@ -154,9 +154,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query private set; } - #endregion +#endregion - #region Public Methods +#region Public Methods /// /// Creates and returns a object. @@ -192,9 +192,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } } - #endregion +#endregion - #region Helpers +#region Helpers private static void ValidateConnectionArguments( IEnumerable namedCollection, @@ -267,6 +267,6 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } } - #endregion +#endregion } } diff --git a/Src/ElasticScale.Client/Query/MultiShardDataReader.cs b/Src/ElasticScale.Client/Query/MultiShardDataReader.cs index 3a17b31..0687ab7 100644 --- a/Src/ElasticScale.Client/Query/MultiShardDataReader.cs +++ b/Src/ElasticScale.Client/Query/MultiShardDataReader.cs @@ -2,8 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // Purpose: -// Logic that wraps multiple DbDataReader objects and aggregates them -// (UNION ALL semantics) under the hood to provide the illusion that all +// Logic that wraps multiple DbDataReader objects and aggregates them +// (UNION ALL semantics) under the hood to provide the illusion that all // results came from a single DbDataReader. // // Notes: @@ -22,7 +22,9 @@ using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; +#if NETFRAMEWORK using System.Runtime.Remoting; +#endif using System.Threading; using System.Threading.Tasks; using System.Xml; @@ -34,13 +36,13 @@ using Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement; namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query { - // Suppression rationale: + // Suppression rationale: // MultiShardDataReader is not a collection. // "Multi" is the spelling we want. // We can't move the methods to other types because that would break the interface we are aiming to provide. // /// - /// Provides a way of reading a forward-only stream of rows that is retrieved from a shard set. + /// Provides a way of reading a forward-only stream of rows that is retrieved from a shard set. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix"), @@ -53,7 +55,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// private const String NameOfShardIdPseudoColumn = "$ShardName"; - #region Private Fields +#region Private Fields private readonly static ILogger s_tracer = TraceHelper.Tracer; @@ -93,9 +95,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query private bool _closed; private bool _disposed; - #endregion Private Fields +#endregion Private Fields - #region Constructors +#region Constructors /// /// Instantiates a MultiShardDataReader object that wraps DbDataReader objects. @@ -106,9 +108,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// The from each shard /// The execution policy to use /// True if we should add the $ShardName pseudo column, false if not. - /// (Optional) If a number greater than the length of inputReaders is + /// (Optional) If a number greater than the length of inputReaders is /// specified, the MultiShardDataReader is left open for additional calls to AddReader at a later time. - /// If the complete results execution policy is used and + /// If the complete results execution policy is used and /// the schema isn't the same across shards internal MultiShardDataReader( MultiShardCommand command, @@ -142,9 +144,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } } - #endregion Constructors +#endregion Constructors - #region Properties +#region Properties /// /// Gets the associated with the MultiShardDataReader. @@ -180,9 +182,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query private set; } - #endregion +#endregion - #region Public Methods +#region Public Methods /// /// Closes the MultiShardDataReader object. @@ -222,7 +224,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query arbitraryClosedReader = currentReader; } - // To avoid writing special case logic for when the queue is empty, we are going to + // To avoid writing special case logic for when the queue is empty, we are going to // add an arbitrary closed reader back to the queue, presuming we have any to choose from. // If we don't, then default to the "No Data Reader" terminal state instead of introducing // the possibility of a new NullReferenceException. @@ -240,6 +242,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } } +#if NETFRAMEWORK /// /// This method is currently not supported. Invoking the method will result in an exception. /// @@ -248,6 +251,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query { throw new RemotingException("MultiShardDataReader is not a valid remoting object."); } +#endif /// /// Determines whether the specified object is equal to the current object. (Inherited from .) @@ -283,7 +287,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } /// - /// Reads a stream of bytes from the specified column, starting at location indicated by dataOffset, into the + /// Reads a stream of bytes from the specified column, starting at location indicated by dataOffset, into the /// buffer, starting at the location indicated by bufferOffset. /// /// The zero-based column ordinal. @@ -317,7 +321,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } /// - /// Reads a stream of characters from the specified column, starting at location indicated by dataOffset, into + /// Reads a stream of characters from the specified column, starting at location indicated by dataOffset, into /// the buffer, starting at the location indicated by bufferOffset. /// /// The zero-based column ordinal. @@ -411,7 +415,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } /// - /// Returns a DbDataReader object for the requested column ordinal that can be overridden with a + /// Returns a DbDataReader object for the requested column ordinal that can be overridden with a /// provider-specific implementation. /// /// The zero-based column ordinal. @@ -477,7 +481,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query if (this.IsPseudoColumnReference(ordinal)) { // It is a reference to our ShardName pseudo column. - // In this case, only a string type is valid for our T parameter, so check that, and + // In this case, only a string type is valid for our T parameter, so check that, and // either return properly or throw an InvalidCast. // @@ -500,8 +504,8 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// The type of the value to be returned. /// The zero-based column ordinal. /// - /// The cancellation instruction, which propagates a notification that operations should be canceled. This does - /// not guarantee the cancellation. A setting of CancellationToken.None makes this method equivalent to + /// The cancellation instruction, which propagates a notification that operations should be canceled. This does + /// not guarantee the cancellation. A setting of CancellationToken.None makes this method equivalent to /// GetFieldValueAsync. The returned task must be marked as cancelled. /// /// The value of the specified column. @@ -801,7 +805,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } /// - /// Returns the data value in the specified column as a native SQL Server type. + /// Returns the data value in the specified column as a native SQL Server type. /// /// The zero-based column ordinal. /// The value of the column expressed as a SqlDbType. @@ -811,7 +815,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } /// - /// Fills an array of Object that contains the values for all the columns in the record, + /// Fills an array of Object that contains the values for all the columns in the record, /// expressed as native SQL Server types. /// /// @@ -929,17 +933,17 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query return ProcessPotentialPseudoColumnReference(ordinal, (null == GetCurrentShardLabel()), GetCurrentDataReader().IsDBNull); } - // Cannot override IsDBNullAsync(int ordinal). should we use new? + // Cannot override IsDBNullAsync(int ordinal). should we use new? // /// - /// An asynchronous version of IsDBNull, which gets a value that indicates whether the column contains + /// An asynchronous version of IsDBNull, which gets a value that indicates whether the column contains /// nonexistent or missing values (NULL values). /// /// The zero-based column to be retrieved. /// /// The cancellation instruction, which propagates a notification that operations should be canceled. This does - /// not guarantee the cancellation. A setting of CancellationToken.None makes this method equivalent to + /// not guarantee the cancellation. A setting of CancellationToken.None makes this method equivalent to /// IsDBNullAsync. The returned task must be marked as cancelled. /// /// True if the specified column value is equivalent to DBNull otherwise false. @@ -968,7 +972,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// /// This method is currently not supported. Invoking the method will result in an exception. /// - /// DEVNOTE (VSTS: 2202747): For now we are only supporting single result set. Need to do some more work if we want to + /// DEVNOTE (VSTS: 2202747): For now we are only supporting single result set. Need to do some more work if we want to /// handle the multiple result set case. Especially if we attempt to move to a non "give me them all up front" /// approach. This comment applies to all the NextResult-related methods. public override bool NextResult() @@ -992,7 +996,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query if (hasNextResult) { - // Invalidate this instance of the MultiShardDataReader and throw an exception. + // Invalidate this instance of the MultiShardDataReader and throw an exception. // We currently do not support multiple result sets this.Close(); @@ -1026,7 +1030,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// /// An asynchronous version of Read, which advances the MultiShardDataReader to the next record. /// - /// The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. + /// The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. /// Exceptions will be reported via the returned Task object. /// /// The cancellation instruction. @@ -1114,9 +1118,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query return base.ToString(); } - #endregion Public Methods +#endregion Public Methods - #region Public Properties +#region Public Properties /// /// Gets a value indicating the depth of nesting for the current row. @@ -1130,7 +1134,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } /// - /// Gets the number of columns in the current row. + /// Gets the number of columns in the current row. /// public override int FieldCount { @@ -1141,7 +1145,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } /// - /// Gets a value that indicates whether this MultiShardDataReader contains one or more rows. + /// Gets a value that indicates whether this MultiShardDataReader contains one or more rows. /// public override bool HasRows { @@ -1206,9 +1210,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } } - #endregion Public Properties +#endregion Public Properties - #region Internal Methods +#region Internal Methods /// /// Cancels all the active commands executing for this reader. @@ -1231,9 +1235,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } } - #endregion Internal Methods +#endregion Internal Methods - #region Protected Methods +#region Protected Methods /// /// Releases the managed resources used by the DbDataReader and optionally releases the unmanaged resources. @@ -1285,9 +1289,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } } - #endregion Protected Methods +#endregion Protected Methods - #region Internal Methods +#region Internal Methods /// /// Method to add another DbDataReader to the set of underlying sources we are concatenating. @@ -1305,12 +1309,12 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// expecting for the DbDataReader objects underlying this MultiShardDataReader object. /// /// Null if we added successfully. The encountered exception if we hit an error. - /// + /// internal void AddReader(LabeledDbDataReader toAdd) { if (toAdd != null) { - // Don't try to read from readers that encountered an exception + // Don't try to read from readers that encountered an exception if (toAdd.Exception != null) { // We tried adding a reader that we expected, but it was invalid. Let's expect one fewer inputReader as a result. @@ -1389,8 +1393,8 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query // We tried adding a reader that we expected, but it was invalid. Let's expect one fewer inputReader as a result. // Is this the correct logic when we have complete results turned on? I understand that it is null so we // don't know where it came from, but that seems like something that should cause us to throw anyway... - // Is it correct when we have partial turned on? We may not want to throw, but we should probably log this - // somewhere. + // Is it correct when we have partial turned on? We may not want to throw, but we should probably log this + // somewhere. // Likely related to VSTS 2616238. Philip will be modifying logic/augmenting tests in this area. // this.DecrementExpectedReaders(); @@ -1462,12 +1466,12 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } } - #endregion Internal Methods +#endregion Internal Methods - #region Private Methods +#region Private Methods /// - /// Checks the schema of the passed in DbDataReader against the schema we are expecting for our + /// Checks the schema of the passed in DbDataReader against the schema we are expecting for our /// fan-out result set. /// /// The LabeledDbDataReader object to check against our expected schema. @@ -1490,7 +1494,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query throw new MultiShardDataReaderInternalException("Unexpected reader with null schema encountered among non-null readers"); } - // The SchemaTable holds 1 *row* for each *column* of the actual output returned. So in order to compare + // The SchemaTable holds 1 *row* for each *column* of the actual output returned. So in order to compare // column metadata for the inputDataReaders we need to compare row information contained in the schemaTable. // DataRowCollection currentRows = currentDataTable.Rows; @@ -1501,7 +1505,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query if (null == _schemaComparisonTemplate) { - // This is our first call to validate, so grab the table template off of this guy and use it as the + // This is our first call to validate, so grab the table template off of this guy and use it as the // expected schema for our results. No need to validate since we are using this one as ground truth. // InitSchemaTemplate(reader); @@ -1583,15 +1587,15 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query } /// - /// Checks all the column specifications (as encapsulated by a DataRow from a SchemaTable) for + /// Checks all the column specifications (as encapsulated by a DataRow from a SchemaTable) for /// compatibility with the expected column specification. /// /// The shard being validated /// The DataRow representing the column specification we wish to validate. /// The DataRow representing the expectd column specification. /// - /// There are lot of opportunities in here for relaxed comparison semantics, but for now let's - /// just be super strict. + /// There are lot of opportunities in here for relaxed comparison semantics, but for now let's + /// just be super strict. /// DEVNOTE (2244709): Need to tighten up our schema checking! /// /// @@ -1605,7 +1609,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query DataRowCollection rowsExpected = expected.Rows; // Eventually we may wish to be a bit more relaxed about the comparisons (e.g., if we expect bigint and we - // see int that may be ok) but for now let's just be super-strict and make the behavior different and/or + // see int that may be ok) but for now let's just be super-strict and make the behavior different and/or // configurable later. // for (int curRowIndex = 0; curRowIndex < rowsExpected.Count; curRowIndex++) @@ -1627,7 +1631,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// /// Handles the case where a reader has a null schema table - /// + /// /// Behavior- /// - Any exception will not be thrown if ALL readers have a null schema (regardless of execution /// policy). Otherwise, a will be thrown. @@ -1684,7 +1688,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query // let it slide. } - // It should never be closed already if the top-level reader is not closed, but in case it + // It should never be closed already if the top-level reader is not closed, but in case it // happens we don't want to completely freeze the reader with no way to move forward and // no way to close, so just ignore that it's already closed. } @@ -1770,7 +1774,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// /// Helper method that sets up the SchemaTemplate to use as our "Ground Truth" for - /// performing schema comparisons. In addition to storing a copy of the schema + /// performing schema comparisons. In addition to storing a copy of the schema /// information, this method adds an additional row for the "ShardIdPseudoColumn". /// /// @@ -1820,7 +1824,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// The type of the column we wish to return. /// The function to use to pull the column value. /// The zero-based column ordinal. - /// + /// /// The desired column value. private T GetColumn(Func getterFunction, int ordinal) { @@ -1963,7 +1967,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// /// The cancellation instruction. /// - /// An async task to perform the read; when executed the task returns true + /// An async task to perform the read; when executed the task returns true /// if we read another row from the current reader, false if we hit the end. /// private async Task PerformReadToFillBufferAsync(CancellationToken token) @@ -2009,45 +2013,45 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query DataRow theRow = _finalSchemaTable.NewRow(); - #region Shard Id Pseudo Column Schema Table information +#region Shard Id Pseudo Column Schema Table information theRow[SchemaTableColumn.ColumnName] = MultiShardDataReader.NameOfShardIdPseudoColumn; theRow[SchemaTableColumn.ColumnOrdinal] = _indexOfShardIdPseudoColumn; theRow[SchemaTableColumn.ColumnSize] = (Int32)4000; theRow[SchemaTableColumn.NumericPrecision] = (Int16)255; theRow[SchemaTableColumn.NumericScale] = (Int16)255; theRow[SchemaTableColumn.IsUnique] = (Boolean)false; - theRow[SchemaTableColumn.IsKey] = DBNull.Value; //Boolean - theRow[SchemaTableOptionalColumn.BaseServerName] = null; //string - theRow[SchemaTableOptionalColumn.BaseCatalogName] = null; //string + theRow[SchemaTableColumn.IsKey] = DBNull.Value; //Boolean + theRow[SchemaTableOptionalColumn.BaseServerName] = null; //string + theRow[SchemaTableOptionalColumn.BaseCatalogName] = null; //string theRow[SchemaTableColumn.BaseColumnName] = MultiShardDataReader.NameOfShardIdPseudoColumn; - theRow[SchemaTableColumn.BaseSchemaName] = null; //string - theRow[SchemaTableColumn.BaseTableName] = null; //string + theRow[SchemaTableColumn.BaseSchemaName] = null; //string + theRow[SchemaTableColumn.BaseTableName] = null; //string theRow[SchemaTableColumn.DataType] = typeof(string); //System.Type theRow[SchemaTableColumn.AllowDBNull] = (Boolean)true; theRow[SchemaTableColumn.ProviderType] = (Int32)12; - theRow[SchemaTableColumn.IsAliased] = DBNull.Value; //Boolean - theRow[SchemaTableColumn.IsExpression] = DBNull.Value; //Boolean + theRow[SchemaTableColumn.IsAliased] = DBNull.Value; //Boolean + theRow[SchemaTableColumn.IsExpression] = DBNull.Value; //Boolean theRow["IsIdentity"] = (Boolean)false; theRow[SchemaTableOptionalColumn.IsAutoIncrement] = (Boolean)false; theRow[SchemaTableOptionalColumn.IsRowVersion] = (Boolean)false; - theRow[SchemaTableOptionalColumn.IsHidden] = DBNull.Value; //Boolean + theRow[SchemaTableOptionalColumn.IsHidden] = DBNull.Value; //Boolean theRow[SchemaTableColumn.IsLong] = (Boolean)false; theRow[SchemaTableOptionalColumn.IsReadOnly] = (Boolean)false; theRow[SchemaTableOptionalColumn.ProviderSpecificDataType] = typeof(SqlString); //System.Type theRow["DataTypeName"] = "nvarchar"; //string - theRow["XmlSchemaCollectionDatabase"] = null; //string - theRow["XmlSchemaCollectionOwningSchema"] = null; //string - theRow["XmlSchemaCollectionName"] = null; //string - theRow["UdtAssemblyQualifiedName"] = null; //string + theRow["XmlSchemaCollectionDatabase"] = null; //string + theRow["XmlSchemaCollectionOwningSchema"] = null; //string + theRow["XmlSchemaCollectionName"] = null; //string + theRow["UdtAssemblyQualifiedName"] = null; //string theRow[SchemaTableColumn.NonVersionedProviderType] = (Int32)12; theRow["IsColumnSet"] = (Boolean)false; - #endregion Shard Id Pseudo Column Schema Table information +#endregion Shard Id Pseudo Column Schema Table information _finalSchemaTable.Rows.Add(theRow); _finalSchemaTable.AcceptChanges(); } - #endregion Private Methods +#endregion Private Methods } } diff --git a/Src/ElasticScale.Client/Query/MultiShardExecutionOptions.cs b/Src/ElasticScale.Client/Query/MultiShardExecutionOptions.cs index 1d02e6e..b35631d 100644 --- a/Src/ElasticScale.Client/Query/MultiShardExecutionOptions.cs +++ b/Src/ElasticScale.Client/Query/MultiShardExecutionOptions.cs @@ -24,4 +24,4 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// IncludeShardNameColumn }; -} +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/Query/MultiShardExecutionPolicy.cs b/Src/ElasticScale.Client/Query/MultiShardExecutionPolicy.cs index 832948d..72a1a01 100644 --- a/Src/ElasticScale.Client/Query/MultiShardExecutionPolicy.cs +++ b/Src/ElasticScale.Client/Query/MultiShardExecutionPolicy.cs @@ -31,4 +31,4 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// PartialResults }; -} +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/Query/MultiShardUtils.cs b/Src/ElasticScale.Client/Query/MultiShardUtils.cs index 4a1817a..9335618 100644 --- a/Src/ElasticScale.Client/Query/MultiShardUtils.cs +++ b/Src/ElasticScale.Client/Query/MultiShardUtils.cs @@ -68,7 +68,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query /// Clone of . internal static DbCommand CloneDbCommand(DbCommand cmd, DbConnection conn) { - DbCommand clone = (DbCommand)(cmd as ICloneable).Clone(); + DbCommand clone = cmd.BestAttemptClone(); clone.Connection = conn; return clone; diff --git a/Src/ElasticScale.Client/ShardManagement/Cache/PerfCounterInstance.cs b/Src/ElasticScale.Client/ShardManagement/Cache/PerfCounterInstance.cs index 2ccb9a0..520b393 100644 --- a/Src/ElasticScale.Client/ShardManagement/Cache/PerfCounterInstance.cs +++ b/Src/ElasticScale.Client/ShardManagement/Cache/PerfCounterInstance.cs @@ -31,6 +31,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement /// internal struct PerfCounterCreationData { +#if NETFRAMEWORK private PerformanceCounterName counterName; private PerformanceCounterType counterType; private string counterDisplayName; @@ -63,6 +64,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement { get { return counterHelpText; } } +#endif } /// @@ -70,6 +72,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement /// internal class PerfCounterInstance : IDisposable { +#if NETFRAMEWORK private static object _lockObject = new object(); private static ILogger Tracer @@ -96,6 +99,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement private bool _initialized; private string _instanceName; +#endif /// /// Initialize perf counter instance based on shard map name @@ -103,6 +107,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement /// public PerfCounterInstance(string shardMapName) { +#if NETFRAMEWORK _initialized = false; _instanceName = string.Concat(Process.GetCurrentProcess().Id.ToString(), "-", shardMapName); @@ -125,7 +130,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement { // We are not creating performance counter category here as per recommendation in documentation, copying note from // https://msdn.microsoft.com/en-us/library/sb32hxtc(v=vs.110).aspx - // It is strongly recommended that new performance counter categories be created + // It is strongly recommended that new performance counter categories be created // during the installation of the application, not during the execution of the application. // This allows time for the operating system to refresh its list of registered performance counter categories. // If the list has not been refreshed, the attempt to use the category will fail. @@ -180,6 +185,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement "Exception caught while creating performance counter instance, no performance data will be collected. Exception: {0}", e.ToString()); } +#endif } /// @@ -188,6 +194,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement /// Counter to increment. internal void IncrementCounter(PerformanceCounterName counterName) { +#if NETFRAMEWORK if (_initialized) { PerformanceCounterWrapper pc; @@ -196,6 +203,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement pc.Increment(); } } +#endif } /// @@ -205,6 +213,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement /// New value. internal void SetCounter(PerformanceCounterName counterName, long value) { +#if NETFRAMEWORK if (_initialized) { PerformanceCounterWrapper pc; @@ -213,12 +222,15 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement pc.SetRawValue(value); } } +#endif } + /// /// Static method to recreate Shard Management performance counter catagory with given counter list. /// internal static void CreatePerformanceCategoryAndCounters() { +#if NETFRAMEWORK // Creation of performance counters need Administrator privilege if (HasCreatePerformanceCategoryPermissions()) { @@ -248,8 +260,10 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement "createCategory", "User does not have permissions to create performance counter category"); } +#endif } +#if NETFRAMEWORK /// /// Check if caller has permissions to create performance counter catagory. /// @@ -272,12 +286,14 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent()); return wp.IsInRole(WindowsBuiltInRole.Administrator) || wp.IsInRole(PerformanceCounters.PerformanceMonitorUsersGroupName); } +#endif /// /// Dispose performance counter instance /// public void Dispose() { +#if NETFRAMEWORK if (_initialized) { lock (_lockObject) @@ -300,6 +316,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement _initialized = false; } } +#endif } } -} \ No newline at end of file +} diff --git a/Src/ElasticScale.Client/ShardManagement/Cache/PerformanceCounterWrapper.cs b/Src/ElasticScale.Client/ShardManagement/Cache/PerformanceCounterWrapper.cs index dcbeb61..9e0fdec 100644 --- a/Src/ElasticScale.Client/ShardManagement/Cache/PerformanceCounterWrapper.cs +++ b/Src/ElasticScale.Client/ShardManagement/Cache/PerformanceCounterWrapper.cs @@ -23,7 +23,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement } } +#if NETFRAMEWORK private PerformanceCounter _counter; +#endif internal bool _isValid; @@ -47,6 +49,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement this._instanceName = instanceName; this._counterName = counterName; +#if NETFRAMEWORK // Check if counter exists in the specified category and then create its instance if (PerformanceCounterCategory.CounterExists(_counterName, _categoryName)) { @@ -75,6 +78,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement "initialize", "Performance counter {0} does not exist in shard management catagory.", counterName); } +#endif } /// @@ -82,10 +86,12 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement /// public void Close() { +#if NETFRAMEWORK if (_isValid) { _counter.Close(); } +#endif } /// @@ -94,6 +100,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void Increment() { +#if NETFRAMEWORK if (_isValid) { try @@ -105,6 +112,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement PerformanceCounterWrapper.TraceException("increment", "counter increment failed.", e); } } +#endif } /// @@ -114,6 +122,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void SetRawValue(long value) { +#if NETFRAMEWORK if (_isValid) { try @@ -125,6 +134,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement PerformanceCounterWrapper.TraceException("SetRawValue", "failed to set raw value", e); } } +#endif } /// @@ -146,7 +156,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement /// public void Dispose() { +#if NETFRAMEWORK _counter.Dispose(); +#endif } } } \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Errors.Designer.cs b/Src/ElasticScale.Client/ShardManagement/Errors.Designer.cs index 58db213..144cab4 100644 --- a/Src/ElasticScale.Client/ShardManagement/Errors.Designer.cs +++ b/Src/ElasticScale.Client/ShardManagement/Errors.Designer.cs @@ -19,7 +19,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Errors { diff --git a/Src/ElasticScale.Client/ShardManagement/Errors.resx b/Src/ElasticScale.Client/ShardManagement/Errors.resx index 31c7af3..164c471 100644 --- a/Src/ElasticScale.Client/ShardManagement/Errors.resx +++ b/Src/ElasticScale.Client/ShardManagement/Errors.resx @@ -117,29 +117,23 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Mapping referencing shard '{0}' in the shard map '{1}' cannot be added because the {2} it covers is already mapped by another mapping. Error occurred while executing stored procedure '{3}' for operation '{4}'. This can occur if another concurrent user has already added a mapping covering the given {2}. + + Unsupport value '{0}' specified for parameter '{1}'. - - Mapping referencing shard '{0}' in the shard map '{1}' does not exist. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can occur if another concurrent user has already removed the mapping. + + The specified ShardRange {0} was not in the set of ShardRanges from which the local shardmap information can be rebuilt at location '{1}'. - - Mapping containing the given key value could not be located in the shard map '{0}'. Error occurred while executing stored procedure '{1}' for operation '{2}'. + + Recovery token {0} was not recognized. - - Mapping referencing shard '{0}' associated with shard map '{1}' no longer exists in store. Error occurred while executing stored procedure '{2}' for operation '{3}' on the shard. This can happen if another concurrent user has deleted or modified the mapping. + + The given location '{0}' does not have the necessary storage structures present for a shard. Error occurred while performing operation '{1}'. - - Requested range is not a subset of the existing range mapping. + + The SchemaInfo object already contains a {0} table by the given name of [{1}].[{2}]. - - Mappings provided for the merge operation which belong to shard map '{0}' belong to different shards '{1}' and '{2}'. Merge operation is only allowed for mappings belonging to the same shard. - - - Mappings provided for the merge operation are not adjacent. Merge operation is only allowed for adjacent mappings. - - - Mappings provided for the Merge operation belonging to shard map '{0}' differ in their Status property. Merge operation is only allowed for mappings with same values for Status. + + Shard key has maximum value which cannot be incremented. Perform the IsMax check on shard key before requesting next key. Shard key has maximum value which cannot be represented. Perform the IsMax check on shard key before requesting a conversion. @@ -165,62 +159,23 @@ The length of raw value specified for the shard key ({0} bytes) does not match the expected length ({1} bytes) for the ShardKeyType ({2}) specified. + + The given port number '{0}' is invalid. + + + The given '{0}' name is longer than the allowed length of '{1}' characters. + + + The given protocol value '{0}' is not supported. + Shard map '{0}' can not be converted to the target type {1}ShardMap<{2}>. Its actual type is {3}ShardMap<{4}>. - - Data structures for shard map manager persistence already exists at the target location. - - - Shard map with name '{0}' already exists in the store. Error occurred while executing stored procedure '{1}' for operation '{2}'. - - - Shard map '{0}' could not be found in the shard map manager store at '{1}'. - - - Shard map '{0}' has shards associated with it. Shard maps can only be removed if there are no shards associated with them. Error occurred while executing stored procedure '{1}' for operation '{2}'. - Shard map '{0}' is not associated with the current instance of shard map manager at '{1}'. Only shard maps that are obtained from the same 'ShardMapManager' instance can be used. - - Store Error: {0}. The error occurred while attempting to perform the underlying storage operation during '{1}' operation on the shard map manager database. See the inner StoreException for details. - - - Key values of type '{0}' are not supported. OpenConnectionForKey requests for the shard map '{1}' requires keys of type '{2}'. - - - Property '{0}' must not be set in the input connection string for 'OpenConnection' operations. - - - Shard '{0}' belonging to shard map '{1}' has mappings associated with it. Error occurred while executing stored procedure '{2}' for operation '{3}'. Remove all the mappings associated with the shard before attempting the operation. - - - Shard '{0}' belonging to shard map '{1}' could not be found in the shard map manager database. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen when another concurrent user removes the shard from the store. - - - Shard '{0}' belonging to shard map '{1}' has been updated in store. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can occur if another concurrent user updates the shard. Perform a GetShard operation for the shard location to obtain the updated instance. - - - The low value {0} is greater than or equal to the high value {1}. Lower value must be less than the higher value. - - - Shard '{0}' belonging to shard map '{1}' no longer exists in store. Error occurred while executing stored procedure '{2}' for operation '{3}' on the shard. This can happen if another concurrent user deletes the shard. - - - Shard map '{0}' associated with shard '{1}' no longer exists in store. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen if another concurrent user deletes the shard map. - - - The required property '{0}' must be set in the connection string. - - - Shard '{0}' provided for the given '{1}' is not associated with current shard map '{2}'. The '{3}' operations required the shard to be associated with the current shard map. - - - Shard '{0}' provided for the given '{1}' is not associated with current shard map manager at '{2}'. The '{3}' operations required the shard to be associated with the current shard map manager. - - - The given '{0}' name is longer than the allowed length of '{1}' characters. + + Shard map '{0}' could not be found in the shard map manager store at '{1}'. Shard map name '{0}' is not supported. Shard map names are only allowed to contain unicode letters and digits. @@ -228,41 +183,53 @@ Length of shard map name '{0}' exceeds the maximum allowed length of '{1}' characters. - - The shard key value for an OpenConnection request is associated with a mapping that is marked ‘Offline’. Data containing this key value is likely being moved, and the connection is blocked to avoid data corruption. Validated connection requests for this shardlet will succeed when the mapping is back ‘Online’. Shard: '{0}'. Shard map: '{1}'. Error occurred while executing stored procedure '{3}' for operation '{2}' on the shard. + + '{0}' provided for operation '{1}' is not associated with the current shard map '{2}'. Only mappings associated with the same shard map as the given shard map can be used. Error occurred for parameter '{3}'. - - Mapping referencing shard '{0}' belonging to shard map '{1}' could not be taken offline because all existing connections on the shard could not be terminated. Error occurred during '{2}' operation while executing stored procedure '{3}' on shard '{4}'. + + '{0}' provided for operation '{1}' is not associated with the current instance of shard map manager at '{2}'. Only mappings associated with the same 'ShardMapManager' instance as the the one associated with current shard map '{3}' can be used. Error occurred for parameter '{4}'. - - The given location '{0}' does not have the necessary storage structures present for a shard. Error occurred while performing operation '{1}'. + + Mappings provided for the Merge operation belonging to shard map '{0}' differ in their Status property. Merge operation is only allowed for mappings with same values for Status. - - The specified ShardRange {0} was not in the set of ShardRanges from which the local shardmap information can be rebuilt at location '{1}'. + + LockId for locking the mapping referencing shard {0} with shard map name {1} has unsupported value '{2}'. - - Recovery token {0} was not recognized. + + Mappings provided for the merge operation which belong to shard map '{0}' belong to different shards '{1}' and '{2}'. Merge operation is only allowed for mappings belonging to the same shard. - - Mapping referencing shard '{0}' in the shard map '{1}' has 'Online' status. Error occurred while executing stored procedure '{2}' for operation '{3}'. Updates to a mapping involving modification of the shard location or removal require the mapping to be 'Offline'. + + Mappings provided for the merge operation are not adjacent. Merge operation is only allowed for adjacent mappings. - - Unable to create schema info with name '{0}' as there is already an entry with the same name. + + Requested range is exactly the range for existing mapping. Operation is only allowed for proper subsets of existing range. - - Unable to {0} schema info with name '{1}' since there is no entry by the given name. + + Requested range is not a subset of the existing range mapping. - - Unsupport value '{0}' specified for parameter '{1}'. - - - Data structures for shard map manager persistence do not exist at the target location. + + Split point lies on the boundary or outside of the specified range mapping. Shard corresponding to location '{0}' could not be found in shard map '{1}' . - - The SchemaInfo object already contains a {0} table by the given name of [{1}].[{2}]. + + Key values of type '{0}' are not supported. OpenConnectionForKey requests for the shard map '{1}' requires keys of type '{2}'. + + + Property '{0}' must not be set in the input connection string for 'OpenConnection' operations. + + + The low value {0} is greater than or equal to the high value {1}. Lower value must be less than the higher value. + + + Shard '{0}' provided for the given '{1}' is not associated with current shard map '{2}'. The '{3}' operations required the shard to be associated with the current shard map. + + + Shard '{0}' provided for the given '{1}' is not associated with current shard map manager at '{2}'. The '{3}' operations required the shard to be associated with the current shard map manager. + + + The required property '{0}' must be set in the connection string. All required parameters for operation '{0}' are not supplied. Error occurred while executing procedure '{1}' on the shard map manager database. Please verify and match library and store version. @@ -270,47 +237,17 @@ All required parameters for operation '{0}' at shard '{1}' are not supplied. Error occurred while executing procedure '{2}' on the shard. Please verify and match library and store version. - - Shard map manager store version '{0}' is not compatible with the version '{1}' supported by client library. Please upgrade the {2}. + + Unable to create schema info with name '{0}' as there is already an entry with the same name. - - Shard map manager store version '{0}' at shard '{1}' is not compatible with the version '{2}' supported by client library. Please upgrade the {3}. + + Unable to {0} schema info with name '{1}' since there is no entry by the given name. - - Split point lies on the boundary or outside of the specified range mapping. + + Data structures for shard map manager persistence already exists at the target location. - - Unexpected error code found while processing errors returned from the shard map manager store. This can occur because of a defect in the client library. - - - Exclusive access to application resource '{0}' could not be acquired. - - - Shard map '{0}' does not exist in the store. Error occurred while executing stored procedure '{1}' for operation '{2}' for shard '{3}'. This can happen if another concurrent user deletes the shard map. - - - '{0}' provided for operation '{1}' is not associated with the current shard map '{2}'. Only mappings associated with the same shard map as the given shard map can be used. Error occurred for parameter '{3}'. - - - '{0}' provided for operation '{1}' is not associated with the current instance of shard map manager at '{2}'. Only mappings associated with the same 'ShardMapManager' instance as the the one associated with current shard map '{3}' can be used. Error occurred for parameter '{4}'. - - - Shard '{0}' already exists in store for shard map '{1}'. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen when another concurrent user adds the shard to the store. - - - Shard referecing location '{0}' already exists in store for shard map '{1}'. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen when another concurrent user has added a shard with specified location in store. - - - Store Error: {0}. The error occurred while attempting to perform the underlying storage operation during '{1}' operation on shard '{2}'. See the inner StoreException for details. - - - Unexpected error code found while processing errors returned from the shard location '{0}'. This can occur because of a defect in the client library. - - - Requested range is exactly the range for existing mapping. Operation is only allowed for proper subsets of existing range. - - - LockId for locking the mapping referencing shard {0} with shard map name {1} has unsupported value '{2}'. + + Data structures for shard map manager persistence do not exist at the target location. Mapping referencing shard '{0}' belonging to shard map '{1}' is already locked. Error occurred while executing procedure '{2}' for operation '{3}' on the shard map manager database. This can happen if another concurrent user locks the mapping. @@ -318,25 +255,88 @@ Mapping referencing shard '{0}' belonging to shard map '{1}' is locked and correct lock token is not provided. Error occurred while executing procedure '{2}' for operation '{3}' on the shard map manager database. This can happen if another concurrent user locks the mapping. + + Mapping referencing shard '{0}' in the shard map '{1}' does not exist. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can occur if another concurrent user has already removed the mapping. + + + Mapping referencing shard '{0}' in the shard map '{1}' has 'Online' status. Error occurred while executing stored procedure '{2}' for operation '{3}'. Updates to a mapping involving modification of the shard location or removal require the mapping to be 'Offline'. + + + Mapping containing the given key value could not be located in the shard map '{0}'. Error occurred while executing stored procedure '{1}' for operation '{2}'. + + + Mapping referencing shard '{0}' in the shard map '{1}' cannot be added because the {2} it covers is already mapped by another mapping. Error occurred while executing stored procedure '{3}' for operation '{4}'. This can occur if another concurrent user has already added a mapping covering the given {2}. + + + Mapping referencing shard '{0}' belonging to shard map '{1}' could not be taken offline because all existing connections on the shard could not be terminated. Error occurred during '{2}' operation while executing stored procedure '{3}' on shard '{4}'. + + + Shard map with name '{0}' already exists in the store. Error occurred while executing stored procedure '{1}' for operation '{2}'. + + + Shard map '{0}' has shards associated with it. Shard maps can only be removed if there are no shards associated with them. Error occurred while executing stored procedure '{1}' for operation '{2}'. + + + Shard map '{0}' does not exist in the store. Error occurred while executing stored procedure '{1}' for operation '{2}' for shard '{3}'. This can happen if another concurrent user deletes the shard map. + Shard map '{0}' does not exist on shard '{1}'. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen if another concurrent user deletes the shard map. - - Shard '{0}' belonging to shard map '{1}' has been modified in the store. Error occurred while executing stored procedure '{2}' for operation '{3}' on the shard. This can happen if another concurrent user performs modification operations on the shard or its associated mappings. + + Shard '{0}' already exists in store for shard map '{1}'. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen when another concurrent user adds the shard to the store. - - The given protocol value '{0}' is not supported. + + Shard '{0}' belonging to shard map '{1}' could not be found in the shard map manager database. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen when another concurrent user removes the shard from the store. - - Error occurred while performing store operation. See the inner SqlException for details. + + Shard '{0}' belonging to shard map '{1}' has mappings associated with it. Error occurred while executing stored procedure '{2}' for operation '{3}'. Remove all the mappings associated with the shard before attempting the operation. - - Shard key has maximum value which cannot be incremented. Perform the IsMax check on shard key before requesting next key. + + Shard referecing location '{0}' already exists in store for shard map '{1}'. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen when another concurrent user has added a shard with specified location in store. - - The given port number '{0}' is invalid. + + Shard '{0}' belonging to shard map '{1}' has been updated in store. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can occur if another concurrent user updates the shard. Perform a GetShard operation for the shard location to obtain the updated instance. + + + Store Error: {0}. The error occurred while attempting to perform the underlying storage operation during '{1}' operation on the shard map manager database. See the inner StoreException for details. + + + Store Error: {0}. The error occurred while attempting to perform the underlying storage operation during '{1}' operation on shard '{2}'. See the inner StoreException for details. + + + Exclusive access to application resource '{0}' could not be acquired. Exclusive access to application resource '{0}' could not be released. + + Error occurred while performing store operation. See the inner SqlException for details. + + + Unexpected error code found while processing errors returned from the shard map manager store. This can occur because of a defect in the client library. + + + Unexpected error code found while processing errors returned from the shard location '{0}'. This can occur because of a defect in the client library. + + + Shard map manager store version '{0}' is not compatible with the version '{1}' supported by client library. Please upgrade the {2}. + + + Shard map manager store version '{0}' at shard '{1}' is not compatible with the version '{2}' supported by client library. Please upgrade the {3}. + + + Mapping referencing shard '{0}' associated with shard map '{1}' no longer exists in store. Error occurred while executing stored procedure '{2}' for operation '{3}' on the shard. This can happen if another concurrent user has deleted or modified the mapping. + + + The shard key value for an OpenConnection request is associated with a mapping that is marked ‘Offline’. Data containing this key value is likely being moved, and the connection is blocked to avoid data corruption. Validated connection requests for this shardlet will succeed when the mapping is back ‘Online’. Shard: '{0}'. Shard map: '{1}'. Error occurred while executing stored procedure '{3}' for operation '{2}' on the shard. + + + Shard '{0}' belonging to shard map '{1}' no longer exists in store. Error occurred while executing stored procedure '{2}' for operation '{3}' on the shard. This can happen if another concurrent user deletes the shard. + + + Shard map '{0}' associated with shard '{1}' no longer exists in store. Error occurred while executing stored procedure '{2}' for operation '{3}'. This can happen if another concurrent user deletes the shard map. + + + Shard '{0}' belonging to shard map '{1}' has been modified in the store. Error occurred while executing stored procedure '{2}' for operation '{3}' on the shard. This can happen if another concurrent user performs modification operations on the shard or its associated mappings. + \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Logging/TraceHelper.cs b/Src/ElasticScale.Client/ShardManagement/Logging/TraceHelper.cs index bfd7d51..288b59a 100644 --- a/Src/ElasticScale.Client/ShardManagement/Logging/TraceHelper.cs +++ b/Src/ElasticScale.Client/ShardManagement/Logging/TraceHelper.cs @@ -42,7 +42,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement params object[] vars) { string fmtMessage = string.Format(message, vars); - logger.Verbose("{0}.{1}; {2}; ActivityId: {3};", componentName, methodName, fmtMessage, Trace.CorrelationManager.ActivityId); + logger.Verbose("{0}.{1}; {2}; ActivityId: {3};", componentName, methodName, fmtMessage, CorrelationManager.ActivityId); } /// @@ -60,7 +60,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement params object[] vars) { string fmtMessage = string.Format(message, vars); - logger.Info("{0}.{1}; {2}; ActivityId: {3};", componentName, methodName, fmtMessage, Trace.CorrelationManager.ActivityId); + logger.Info("{0}.{1}; {2}; ActivityId: {3};", componentName, methodName, fmtMessage, CorrelationManager.ActivityId); } /// @@ -78,7 +78,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement params object[] vars) { string fmtMessage = string.Format(message, vars); - logger.Warning("{0}.{1}; {2}; ActivityId: {3};", componentName, methodName, fmtMessage, Trace.CorrelationManager.ActivityId); + logger.Warning("{0}.{1}; {2}; ActivityId: {3};", componentName, methodName, fmtMessage, CorrelationManager.ActivityId); } /// @@ -96,7 +96,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement params object[] vars) { string fmtMessage = string.Format(message, vars); - logger.Error("{0}.{1}; {2}; ActivityId: {3};", componentName, methodName, fmtMessage, Trace.CorrelationManager.ActivityId); + logger.Error("{0}.{1}; {2}; ActivityId: {3};", componentName, methodName, fmtMessage, CorrelationManager.ActivityId); } } } diff --git a/Src/ElasticScale.Client/ShardManagement/PerformanceCounters.Designer.cs b/Src/ElasticScale.Client/ShardManagement/PerformanceCounters.Designer.cs index fcb9dd1..c9682d2 100644 --- a/Src/ElasticScale.Client/ShardManagement/PerformanceCounters.Designer.cs +++ b/Src/ElasticScale.Client/ShardManagement/PerformanceCounters.Designer.cs @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:4.0.30319.34209 +// Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. @@ -19,7 +19,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class PerformanceCounters { diff --git a/Src/ElasticScale.Client/ShardManagement/ReadOnlyScripts.Designer.cs b/Src/ElasticScale.Client/ShardManagement/ReadOnlyScripts.Designer.cs deleted file mode 100644 index a481a12..0000000 --- a/Src/ElasticScale.Client/ShardManagement/ReadOnlyScripts.Designer.cs +++ /dev/null @@ -1,97 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.34209 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class ReadOnlyScripts { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal ReadOnlyScripts() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.ReadOnlyScripts", typeof(ReadOnlyScripts).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Reads from shard map manager version information table if it exists. - ///--------------------------------------------------------------------------------------------------- - /// - ///declare @stmt varchar(128) - ///if object_id(N'__ShardManagement.ShardMapManagerGlobal', N'U [rest of string was truncated]";. - /// - internal static string CheckShardMapManagerGlobal { - get { - return ResourceManager.GetString("CheckShardMapManagerGlobal", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Reads from shard map manager version information table if it exists. - ///--------------------------------------------------------------------------------------------------- - /// - ///declare @stmt varchar(128) - ///if object_id(N'__ShardManagement.ShardMapManagerLocal', N'U' [rest of string was truncated]";. - /// - internal static string CheckShardMapManagerLocal { - get { - return ResourceManager.GetString("CheckShardMapManagerLocal", resourceCulture); - } - } - } -} diff --git a/Src/ElasticScale.Client/ShardManagement/ReadOnlyScripts.resx b/Src/ElasticScale.Client/ShardManagement/ReadOnlyScripts.resx deleted file mode 100644 index f57625e..0000000 --- a/Src/ElasticScale.Client/ShardManagement/ReadOnlyScripts.resx +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - scripts\checkshardmapmanagerglobal.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - scripts\checkshardmapmanagerlocal.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/SchemaInformation/SchemaInfoException.cs b/Src/ElasticScale.Client/ShardManagement/SchemaInformation/SchemaInfoException.cs index 2196abd..a4a3778 100644 --- a/Src/ElasticScale.Client/ShardManagement/SchemaInformation/SchemaInfoException.cs +++ b/Src/ElasticScale.Client/ShardManagement/SchemaInformation/SchemaInfoException.cs @@ -88,7 +88,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.Schema private SchemaInfoException(SerializationInfo info, StreamingContext context) : base(info, context) { - this.ErrorCode = (SchemaInfoErrorCode)info.GetValue("ErrorCode", typeof(ShardManagementErrorCode)); + this.ErrorCode = (SchemaInfoErrorCode)info.GetValue("ErrorCode", typeof(SchemaInfoErrorCode)); } /// diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts.Designer.cs b/Src/ElasticScale.Client/ShardManagement/Scripts.Designer.cs deleted file mode 100644 index cc7fa2b..0000000 --- a/Src/ElasticScale.Client/ShardManagement/Scripts.Designer.cs +++ /dev/null @@ -1,281 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.34209 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Scripts { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Scripts() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.Scripts", typeof(Scripts).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Schema - ///--------------------------------------------------------------------------------------------------- - ///if schema_id('__ShardManagement') is null - ///begin - /// exec sp_executesql N'create schema __ShardManagement' - ///end - ///go - /// - ///--------------------------------------- [rest of string was truncated]";. - /// - internal static string CreateShardMapManagerGlobal { - get { - return ResourceManager.GetString("CreateShardMapManagerGlobal", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Schema - ///--------------------------------------------------------------------------------------------------- - ///if schema_id('__ShardManagement') is null - ///begin - /// exec sp_executesql N'create schema __ShardManagement' - ///end - ///go - /// - ///--------------------------------------- [rest of string was truncated]";. - /// - internal static string CreateShardMapManagerLocal { - get { - return ResourceManager.GetString("CreateShardMapManagerLocal", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Stored Procedures - ///--------------------------------------------------------------------------------------------------- - ///--------------------------------------------------------------------------------------------------- - ///-- Recovery - ///--------------------------- [rest of string was truncated]";. - /// - internal static string DropShardMapManagerGlobal { - get { - return ResourceManager.GetString("DropShardMapManagerGlobal", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Stored Procedures - ///--------------------------------------------------------------------------------------------------- - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Shard Mappings - ///-------------------- [rest of string was truncated]";. - /// - internal static string DropShardMapManagerLocal { - get { - return ResourceManager.GetString("DropShardMapManagerLocal", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Script to upgrade Global Shard Map from version 0.0 to 1.0 - ///--------------------------------------------------------------------------------------------------- - /// - ///-- add a column to ShardMapManagerGlobal table to hold SCH-M lock during upgrade - ///alter table __Sh [rest of string was truncated]";. - /// - internal static string UpgradeShardMapManagerGlobalFrom0_0To1_0 { - get { - return ResourceManager.GetString("UpgradeShardMapManagerGlobalFrom0_0To1_0", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Script to upgrade Global Shard Map from version 1.0 to 1.1 - ///--------------------------------------------------------------------------------------------------- - /// - ///-- drop ShardMapManagerGlobal table - ///drop table __ShardManagement.ShardMapManagerGlobal - /// - ///-- creat [rest of string was truncated]";. - /// - internal static string UpgradeShardMapManagerGlobalFrom1_0To1_1 { - get { - return ResourceManager.GetString("UpgradeShardMapManagerGlobalFrom1_0To1_1", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Script to upgrade Global Shard Map from version 1.1 to 1.2 - ///-- Fix for VSTS# 3410606 - ///--------------------------------------------------------------------------------------------------- - /// - ///-- drop extra objects from version 1.1 - /// - ///if object_id(N'__ShardManagement [rest of string was truncated]";. - /// - internal static string UpgradeShardMapManagerGlobalFrom1_1To1_2 { - get { - return ResourceManager.GetString("UpgradeShardMapManagerGlobalFrom1_1To1_2", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Script to upgrade Global Shard Map from version 1000.0 to 1000.1 - ///--------------------------------------------------------------------------------------------------- - /// - ///-- drop extra column from ShardMapManagerGlobal table which was added as first step to hold [rest of string was truncated]";. - /// - internal static string UpgradeShardMapManagerGlobalFrom1000_0To1000_1 { - get { - return ResourceManager.GetString("UpgradeShardMapManagerGlobalFrom1000_0To1000_1", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Script to upgrade Local Shard Map from version 0.0 to 1.0 - ///--------------------------------------------------------------------------------------------------- - /// - ///-- add a column to ShardMapManagerLocal table to hold SCH-M lock during upgrade - ///alter table __Shar [rest of string was truncated]";. - /// - internal static string UpgradeShardMapManagerLocalFrom0_0To1_0 { - get { - return ResourceManager.GetString("UpgradeShardMapManagerLocalFrom0_0To1_0", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Script to upgrade Local Shard Map from version 1.0 to 1.1 - ///--------------------------------------------------------------------------------------------------- - /// - ///-- drop ShardMapManagerLocal table - ///drop table __ShardManagement.ShardMapManagerLocal - /// - ///-- create S [rest of string was truncated]";. - /// - internal static string UpgradeShardMapManagerLocalFrom1_0To1_1 { - get { - return ResourceManager.GetString("UpgradeShardMapManagerLocalFrom1_0To1_1", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Script to upgrade Local Shard Map from version 1.1 to 1.2 - ///--------------------------------------------------------------------------------------------------- - /// - ///-- drop extra objects from version 1.1 - /// - ///if object_id(N'__ShardManagement.spUpdateShardLocal', N'P' [rest of string was truncated]";. - /// - internal static string UpgradeShardMapManagerLocalFrom1_1To1_2 { - get { - return ResourceManager.GetString("UpgradeShardMapManagerLocalFrom1_1To1_2", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to -- Copyright (c) Microsoft. All rights reserved. - ///-- Licensed under the MIT license. See LICENSE file in the project root for full license information. - /// - ///--------------------------------------------------------------------------------------------------- - ///-- Script to upgrade Local Shard Map from version 1000.0 to 1000.1 - ///--------------------------------------------------------------------------------------------------- - /// - ///-- drop extra column from ShardMapManagerLocal table which was added as first step to hold S [rest of string was truncated]";. - /// - internal static string UpgradeShardMapManagerLocalFrom1000_0To1000_1 { - get { - return ResourceManager.GetString("UpgradeShardMapManagerLocalFrom1000_0To1000_1", resourceCulture); - } - } - } -} diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts.resx b/Src/ElasticScale.Client/ShardManagement/Scripts.resx deleted file mode 100644 index 6d37a0b..0000000 --- a/Src/ElasticScale.Client/ShardManagement/Scripts.resx +++ /dev/null @@ -1,157 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - Scripts\CreateShardMapManagerGlobal.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - Scripts\CreateShardMapManagerLocal.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - Scripts\DropShardMapManagerGlobal.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - Scripts\DropShardMapManagerLocal.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - Scripts\UpgradeShardMapManagerGlobalFrom0.0To1.0.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - Scripts\UpgradeShardMapManagerGlobalFrom1000.0To1000.1.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - Scripts\UpgradeShardMapManagerGlobalFrom1.0To1.1.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - Scripts\UpgradeShardMapManagerGlobalFrom1.1To1.2.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - Scripts\UpgradeShardMapManagerLocalFrom0.0To1.0.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - Scripts\UpgradeShardMapManagerLocalFrom1000.0To1000.1.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - Scripts\UpgradeShardMapManagerLocalFrom1.0To1.1.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - Scripts\UpgradeShardMapManagerLocalFrom1.1To1.2.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerGlobal.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerGlobal.cs similarity index 66% rename from Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerGlobal.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerGlobal.cs index 2a11475..068ccec 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerGlobal.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerGlobal.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class ReadOnlyScripts + { + internal const string CheckShardMapManagerGlobal = @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -19,3 +30,6 @@ begin exec(@stmt) end go +"; + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerLocal.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerLocal.cs similarity index 66% rename from Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerLocal.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerLocal.cs index f793c7a..5c8c04d 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerLocal.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/CheckShardMapManagerLocal.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class ReadOnlyScripts + { + internal const string CheckShardMapManagerLocal = @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -19,3 +30,6 @@ begin exec(@stmt) end go +"; + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerGlobal.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerGlobal.cs similarity index 98% rename from Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerGlobal.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerGlobal.cs index 795dd0f..3f08d88 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerGlobal.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerGlobal.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal const string CreateShardMapManagerGlobal = @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -836,7 +847,7 @@ begin while (@stepIndex <= @stepsCount) begin select - @currentStep = x.query('(./Step[@Id = sql:variable("@stepIndex")])[1]') + @currentStep = x.query('(./Step[@Id = sql:variable(""@stepIndex"")])[1]') from @input.nodes('/BulkOperationShardsGlobal/Steps') as t(x) @@ -1133,7 +1144,7 @@ begin while (@stepIndex <= @stepsCount) begin select - @currentStep = x.query('(./Step[@Id = sql:variable("@stepIndex")])[1]') + @currentStep = x.query('(./Step[@Id = sql:variable(""@stepIndex"")])[1]') from @input.nodes('/BulkOperationShardsGlobal/Steps') as t(x) @@ -1285,10 +1296,10 @@ begin select @gsmVersionClient = x.value('(GsmVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), - @shardId = x.value('(Shard[@Null="0"]/Id)[1]', 'uniqueidentifier'), - @shardVersion = x.value('(Shard[@Null="0"]/Version)[1]', 'uniqueidentifier'), - @minValue = convert(varbinary(128), x.value('(Range[@Null="0"]/MinValue)[1]', 'varchar(258)'), 1), - @maxValue = convert(varbinary(128), x.value('(Range[@Null="0"]/MaxValue[@Null="0"])[1]', 'varchar(258)'), 1) + @shardId = x.value('(Shard[@Null=""0""]/Id)[1]', 'uniqueidentifier'), + @shardVersion = x.value('(Shard[@Null=""0""]/Version)[1]', 'uniqueidentifier'), + @minValue = convert(varbinary(128), x.value('(Range[@Null=""0""]/MinValue)[1]', 'varchar(258)'), 1), + @maxValue = convert(varbinary(128), x.value('(Range[@Null=""0""]/MaxValue[@Null=""0""])[1]', 'varchar(258)'), 1) from @input.nodes('/GetAllShardMappingsGlobal') as t(x) @@ -1845,7 +1856,7 @@ begin while (@stepIndex <= @stepsCount) begin select - @currentStep = x.query('(./Step[@Id = sql:variable("@stepIndex")])[1]') + @currentStep = x.query('(./Step[@Id = sql:variable(""@stepIndex"")])[1]') from @input.nodes('/BulkOperationShardMappingsGlobal/Steps') as t(x) @@ -1960,7 +1971,7 @@ begin @stepShouldValidate = x.value('(@Validate)[1]', 'bit'), @stepMappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier'), @stepMinValue = convert(varbinary(128), x.value('(Mapping/MinValue)[1]', 'varchar(258)'), 1), - @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null="0"])[1]', 'varchar(258)'), 1), + @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null=""0""])[1]', 'varchar(258)'), 1), @stepStatus = x.value('(Mapping/Status)[1]', 'int'), @stepLockOwnerId = x.value('(Mapping/LockOwnerId)[1]', 'uniqueidentifier') from @@ -2224,7 +2235,7 @@ begin while (@stepIndex <= @stepsCount) begin select - @currentStep = x.query('(./Step[@Id = sql:variable("@stepIndex")])[1]') + @currentStep = x.query('(./Step[@Id = sql:variable(""@stepIndex"")])[1]') from @input.nodes('/BulkOperationShardMappingsGlobal/Steps') as t(x) @@ -2935,7 +2946,7 @@ begin @serverName = x.value('(Location/ServerName)[1]', 'nvarchar(128)'), @port = x.value('(Location/Port)[1]', 'int'), @databaseName = x.value('(Location/DatabaseName)[1]', 'nvarchar(128)'), - @name = x.value('(Shardmap[@Null="0"]/Name)[1]', 'nvarchar(50)') + @name = x.value('(Shardmap[@Null=""0""]/Name)[1]', 'nvarchar(50)') from @input.nodes('/DetachShardGlobal') as t(x) @@ -3062,7 +3073,7 @@ begin while (@removeStepIndex <= @removeStepsCount) begin select - @currentRemoveStep = x.query('(./Step[@Id = sql:variable("@removeStepIndex")])[1]') + @currentRemoveStep = x.query('(./Step[@Id = sql:variable(""@removeStepIndex"")])[1]') from @input.nodes('ReplaceShardMappingsGlobal/RemoveSteps') as t(x) @@ -3111,14 +3122,14 @@ begin while (@addStepIndex <= @addStepsCount) begin select - @currentAddStep = x.query('(./Step[@Id = sql:variable("@addStepIndex")])[1]') + @currentAddStep = x.query('(./Step[@Id = sql:variable(""@addStepIndex"")])[1]') from @input.nodes('ReplaceShardMappingsGlobal/AddSteps') as t(x) select @stepMappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier'), @stepMinValue = convert(varbinary(128), x.value('(Mapping/MinValue)[1]', 'varchar(258)'), 1), - @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null="0"])[1]', 'varchar(258)'), 1), + @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null=""0""])[1]', 'varchar(258)'), 1), @stepStatus = x.value('(Mapping/Status)[1]', 'int') from @currentAddStep.nodes('./Step') as t(x) @@ -3177,3 +3188,6 @@ Error_GSMVersionMismatch: Exit_Procedure: end go +"; + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerLocal.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerLocal.cs similarity index 90% rename from Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerLocal.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerLocal.cs index 88d7e77..ea54b6e 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerLocal.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/CreateShardMapManagerLocal.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal const string CreateShardMapManagerLocal = @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -19,7 +30,7 @@ StoreVersion int not null go create table __ShardManagement.ShardMapsLocal( -ShardMapId uniqueidentifier not null, +ShardMapId uniqueidentifier not null, Name nvarchar(50) collate SQL_Latin1_General_CP1_CI_AS not null, MapType int not null, KeyType int not null, @@ -30,11 +41,11 @@ go create table __ShardManagement.ShardsLocal( ShardId uniqueidentifier not null, Version uniqueidentifier not null, -ShardMapId uniqueidentifier not null, +ShardMapId uniqueidentifier not null, Protocol int not null, -ServerName nvarchar(128) collate SQL_Latin1_General_CP1_CI_AS not null, +ServerName nvarchar(128) collate SQL_Latin1_General_CP1_CI_AS not null, Port int not null, -DatabaseName nvarchar(128) collate SQL_Latin1_General_CP1_CI_AS not null, +DatabaseName nvarchar(128) collate SQL_Latin1_General_CP1_CI_AS not null, Status int not null, -- user defined LastOperationId uniqueidentifier default('00000000-0000-0000-0000-000000000000') not null ) @@ -44,7 +55,7 @@ create table __ShardManagement.ShardMappingsLocal( MappingId uniqueidentifier not null, ShardId uniqueidentifier not null, ShardMapId uniqueidentifier not null, -MinValue varbinary(128) not null, +MinValue varbinary(128) not null, MaxValue varbinary(128), -- nulls are allowed since +ve infinity is represented by null Status int not null, -- 0 online, 1 offline LockOwnerId uniqueidentifier default('00000000-0000-0000-0000-000000000000') not null, @@ -55,11 +66,11 @@ go --------------------------------------------------------------------------------------------------- -- Constraints --------------------------------------------------------------------------------------------------- -alter table __ShardManagement.ShardMapManagerLocal +alter table __ShardManagement.ShardMapManagerLocal add constraint pkShardMapManagerLocal_StoreVersion primary key (StoreVersion) go -alter table __ShardManagement.ShardMapsLocal +alter table __ShardManagement.ShardMapsLocal add constraint pkShardMapsLocal_ShardMapId primary key (ShardMapId) go @@ -99,9 +110,9 @@ go --------------------------------------------------------------------------------------------------- -- Data --------------------------------------------------------------------------------------------------- -insert into +insert into __ShardManagement.ShardMapManagerLocal (StoreVersion) -values +values (1) go @@ -199,7 +210,7 @@ as begin select 5, StoreVersion - from + from __ShardManagement.ShardMapManagerLocal end go @@ -223,9 +234,9 @@ as begin declare @lsmVersionClient int - select + select @lsmVersionClient = x.value('(LsmVersion)[1]', 'int') - from + from @input.nodes('/GetAllShardsLocal') as t(x) if (@lsmVersionClient is null) @@ -235,14 +246,14 @@ begin goto Error_LSMVersionMismatch; -- shard maps - select + select 1, ShardMapId, Name, MapType, KeyType - from + from __ShardManagement.ShardMapsLocal -- shards - select - 2, ShardId, Version, ShardMapId, Protocol, ServerName, Port, DatabaseName, Status + select + 2, ShardId, Version, ShardMapId, Protocol, ServerName, Port, DatabaseName, Status from __ShardManagement.ShardsLocal @@ -279,12 +290,12 @@ begin @shardMapId uniqueidentifier, @shardId uniqueidentifier, @shardVersion uniqueidentifier - select + select @lsmVersionClient = x.value('(LsmVersion)[1]', 'int'), @shardMapId = x.value('(ShardMapId)[1]', 'uniqueidentifier'), @shardId = x.value('(ShardId)[1]', 'uniqueidentifier'), @shardVersion = x.value('(ShardVersion)[1]', 'uniqueidentifier') - from + from @input.nodes('/ValidateShardLocal') as t(x) if (@lsmVersionClient is null or @shardMapId is null or @shardId is null or @shardVersion is null) @@ -295,12 +306,12 @@ begin -- find shard map declare @currentShardMapId uniqueidentifier - - select - @currentShardMapId = ShardMapId - from + + select + @currentShardMapId = ShardMapId + from __ShardManagement.ShardMapsLocal - where + where ShardMapId = @shardMapId if (@currentShardMapId is null) @@ -308,11 +319,11 @@ begin declare @currentShardVersion uniqueidentifier - select - @currentShardVersion = Version - from + select + @currentShardVersion = Version + from __ShardManagement.ShardsLocal - where + where ShardMapId = @shardMapId and ShardId = @shardId if (@currentShardVersion is null) @@ -373,7 +384,7 @@ begin @databaseName nvarchar(128), @shardStatus int - select + select @lsmVersionClient = x.value('(LsmVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @@ -387,11 +398,11 @@ begin @port = x.value('(Shard/Location/Port)[1]', 'int'), @databaseName = x.value('(Shard/Location/DatabaseName)[1]', 'nvarchar(128)'), @shardStatus = x.value('(Shard/Status)[1]', 'int') - from + from @input.nodes('/AddShardLocal') as t(x) - if (@lsmVersionClient is null or @shardMapId is null or @operationId is null or @name is null or @sm_kind is null or @sm_keykind is null or - @shardId is null or @shardVersion is null or @protocol is null or @serverName is null or + if (@lsmVersionClient is null or @shardMapId is null or @operationId is null or @name is null or @sm_kind is null or @sm_keykind is null or + @shardId is null or @shardVersion is null or @protocol is null or @serverName is null or @port is null or @databaseName is null or @shardStatus is null) goto Error_MissingParameters; @@ -400,7 +411,7 @@ begin -- check for reentrancy if exists ( - select + select ShardMapId from __ShardManagement.ShardMapsLocal @@ -409,34 +420,34 @@ begin goto Success_Exit; -- add shard map row - insert into - __ShardManagement.ShardMapsLocal + insert into + __ShardManagement.ShardMapsLocal (ShardMapId, Name, MapType, KeyType, LastOperationId) - values - (@shardMapId, @name, @sm_kind, @sm_keykind, @operationId) + values + (@shardMapId, @name, @sm_kind, @sm_keykind, @operationId) -- add shard row - insert into + insert into __ShardManagement.ShardsLocal( - ShardId, - Version, - ShardMapId, - Protocol, - ServerName, - Port, - DatabaseName, + ShardId, + Version, + ShardMapId, + Protocol, + ServerName, + Port, + DatabaseName, Status, LastOperationId) values ( - @shardId, - @shardVersion, + @shardId, + @shardVersion, @shardMapId, - @protocol, - @serverName, - @port, - @databaseName, + @protocol, + @serverName, + @port, + @databaseName, @shardStatus, - @operationId) + @operationId) goto Success_Exit; @@ -453,7 +464,7 @@ Error_LSMVersionMismatch: Success_Exit: set @result = 1 goto Exit_Procedure; - + Exit_Procedure: end go @@ -472,12 +483,12 @@ begin @shardMapId uniqueidentifier, @shardId uniqueidentifier - select + select @lsmVersionClient = x.value('(LsmVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @shardId = x.value('(Shard/Id)[1]', 'uniqueidentifier') - from + from @input.nodes('/RemoveShardLocal') as t(x) if (@lsmVersionClient is null or @operationId is null or @shardMapId is null or @shardId is null) @@ -488,13 +499,13 @@ begin -- remove shard row delete from - __ShardManagement.ShardsLocal + __ShardManagement.ShardsLocal where ShardMapId = @shardMapId and ShardId = @shardId -- remove shard map row delete from - __ShardManagement.ShardMapsLocal + __ShardManagement.ShardMapsLocal where ShardMapId = @shardMapId @@ -531,14 +542,14 @@ begin @shardVersion uniqueidentifier, @shardStatus int - select + select @lsmVersionClient = x.value('(LsmVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @shardId = x.value('(Shard/Id)[1]', 'uniqueidentifier'), @shardVersion = x.value('(Shard/Version)[1]', 'uniqueidentifier'), @shardStatus = x.value('(Shard/Status)[1]', 'int') - from + from @input.nodes('/UpdateShardLocal') as t(x) if (@lsmVersionClient is null or @operationId is null or @shardMapId is null or @shardId is null or @shardVersion is null or @shardStatus is null) @@ -547,7 +558,7 @@ begin if (@lsmVersionClient <> __ShardManagement.fnGetStoreVersionLocal()) goto Error_LSMVersionMismatch; - update + update __ShardManagement.ShardsLocal set Version = @shardVersion, @@ -592,13 +603,13 @@ begin declare @minValue varbinary(128) declare @maxValue varbinary(128) - select + select @lsmVersionClient = x.value('(LsmVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @shardId = x.value('(Shard/Id)[1]', 'uniqueidentifier'), - @minValue = convert(varbinary(128), x.value('(Range[@Null="0"]/MinValue)[1]', 'varchar(258)'), 1), - @maxValue = convert(varbinary(128), x.value('(Range[@Null="0"]/MaxValue[@Null="0"])[1]', 'varchar(258)'), 1) - from + @minValue = convert(varbinary(128), x.value('(Range[@Null=""0""]/MinValue)[1]', 'varchar(258)'), 1), + @maxValue = convert(varbinary(128), x.value('(Range[@Null=""0""]/MaxValue[@Null=""0""])[1]', 'varchar(258)'), 1) + from @input.nodes('/GetAllShardMappingsLocal') as t(x) if (@lsmVersionClient is null or @shardMapId is null or @shardId is null) @@ -609,7 +620,7 @@ begin declare @mapType int - select + select @mapType = MapType from __ShardManagement.ShardMapsLocal @@ -630,41 +641,41 @@ begin set @maxValueCalculated = @maxValue if (@mapType = 1) - begin - select + begin + select 3, m.MappingId, m.ShardMapId, m.MinValue, m.MaxValue, m.Status, m.LockOwnerId, -- fields for SqlMapping s.ShardId, s.Version, s.ShardMapId, s.Protocol, s.ServerName, s.Port, s.DatabaseName, s.Status -- fields for SqlShard, ShardMapId is repeated here - from - __ShardManagement.ShardMappingsLocal m - join - __ShardManagement.ShardsLocal s - on + from + __ShardManagement.ShardMappingsLocal m + join + __ShardManagement.ShardsLocal s + on m.ShardId = s.ShardId where - m.ShardMapId = @shardMapId and - m.ShardId = @shardId and - MinValue >= @minValueCalculated and + m.ShardMapId = @shardMapId and + m.ShardId = @shardId and + MinValue >= @minValueCalculated and ((@maxValueCalculated is null) or (MinValue < @maxValueCalculated)) - order by + order by m.MinValue end else begin - select + select 3, m.MappingId, m.ShardMapId, m.MinValue, m.MaxValue, m.Status, m.LockOwnerId, -- fields for SqlMapping s.ShardId, s.Version, s.ShardMapId, s.Protocol, s.ServerName, s.Port, s.DatabaseName, s.Status -- fields for SqlShard, ShardMapId is repeated here - from - __ShardManagement.ShardMappingsLocal m - join - __ShardManagement.ShardsLocal s - on + from + __ShardManagement.ShardMappingsLocal m + join + __ShardManagement.ShardsLocal s + on m.ShardId = s.ShardId where - m.ShardMapId = @shardMapId and - m.ShardId = @shardId and - ((MaxValue is null) or (MaxValue > @minValueCalculated)) and + m.ShardMapId = @shardMapId and + m.ShardId = @shardId and + ((MaxValue is null) or (MaxValue > @minValueCalculated)) and ((@maxValueCalculated is null) or (MinValue < @maxValueCalculated)) - order by + order by m.MinValue end @@ -702,13 +713,13 @@ begin @shardMapId uniqueidentifier, @keyValue varbinary(128) - select + select @lsmVersionClient = x.value('(LsmVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @keyValue = convert(varbinary(128), x.value('(Key/Value)[1]', 'varchar(258)'), 1) - from + from @input.nodes('/FindShardMappingByKeyLocal') as t(x) - + if (@lsmVersionClient is null or @shardMapId is null or @keyValue is null) goto Error_MissingParameters; @@ -717,7 +728,7 @@ begin declare @mapType int - select + select @mapType = MapType from __ShardManagement.ShardMapsLocal @@ -728,33 +739,33 @@ begin goto Error_ShardMapNotFound; if (@mapType = 1) - begin + begin select 3, m.MappingId, m.ShardMapId, m.MinValue, m.MaxValue, m.Status, m.LockOwnerId, -- fields for SqlMapping s.ShardId, s.Version, s.ShardMapId, s.Protocol, s.ServerName, s.Port, s.DatabaseName, s.Status -- fields for SqlShard, ShardMapId is repeated here from __ShardManagement.ShardMappingsLocal m - join + join __ShardManagement.ShardsLocal s - on + on m.ShardId = s.ShardId where - m.ShardMapId = @shardMapId and + m.ShardMapId = @shardMapId and m.MinValue = @keyValue end else begin - select + select 3, m.MappingId, m.ShardMapId, m.MinValue, m.MaxValue, m.Status, m.LockOwnerId, -- fields for SqlMapping s.ShardId, s.Version, s.ShardMapId, s.Protocol, s.ServerName, s.Port, s.DatabaseName, s.Status -- fields for SqlShard, ShardMapId is repeated here - from - __ShardManagement.ShardMappingsLocal m - join - __ShardManagement.ShardsLocal s - on + from + __ShardManagement.ShardMappingsLocal m + join + __ShardManagement.ShardsLocal s + on m.ShardId = s.ShardId where - m.ShardMapId = @shardMapId and + m.ShardMapId = @shardMapId and m.MinValue <= @keyValue and (m.MaxValue is null or m.MaxValue > @keyValue) end @@ -814,12 +825,12 @@ begin -- find shard map declare @currentShardMapId uniqueidentifier - - select - @currentShardMapId = ShardMapId - from + + select + @currentShardMapId = ShardMapId + from __ShardManagement.ShardMapsLocal - where + where ShardMapId = @shardMapId if (@currentShardMapId is null) @@ -827,13 +838,13 @@ begin declare @m_status_current int - select + select @m_status_current = Status from __ShardManagement.ShardMappingsLocal where ShardMapId = @shardMapId and MappingId = @mappingId - + if (@m_status_current is null) goto Error_MappingDoesNotExist; @@ -888,14 +899,14 @@ begin @shardVersion uniqueidentifier -- get operation information as well as number of steps information - select + select @lsmVersionClient = x.value('(LsmVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @stepsCount = x.value('(@StepsCount)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @shardId = x.value('(Shard/Id)[1]', 'uniqueidentifier'), @shardVersion = x.value('(Shard/Version)[1]', 'uniqueidentifier') - from + from @input.nodes('/BulkOperationShardMappingsLocal') as t(x) if (@lsmVersionClient is null or @operationId is null or @stepsCount is null or @shardMapId is null or @shardId is null or @shardVersion is null) @@ -906,7 +917,7 @@ begin -- check for reentrancy if exists ( - select + select ShardId from __ShardManagement.ShardsLocal @@ -929,9 +940,9 @@ begin while (@stepIndex <= @stepsCount) begin - select - @currentStep = x.query('(./Step[@Id = sql:variable("@stepIndex")])[1]') - from + select + @currentStep = x.query('(./Step[@Id = sql:variable(""@stepIndex"")])[1]') + from @input.nodes('/BulkOperationShardMappingsLocal/Steps') as t(x) -- Identify the step type. @@ -940,7 +951,7 @@ begin @stepMappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier') from @currentStep.nodes('./Step') as t(x) - + if (@stepType is null or @stepMappingId is null) goto Error_MissingParameters; @@ -960,9 +971,9 @@ begin @stepMappingStatus int -- AddMapping - select + select @stepMinValue = convert(varbinary(128), x.value('(Mapping/MinValue)[1]', 'varchar(258)'), 1), - @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null="0"])[1]', 'varchar(258)'), 1), + @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null=""0""])[1]', 'varchar(258)'), 1), @stepMappingStatus = x.value('(Mapping/Status)[1]', 'int') from @currentStep.nodes('./Step') as t(x) @@ -973,19 +984,19 @@ begin -- add mapping insert into __ShardManagement.ShardMappingsLocal - (MappingId, - ShardId, - ShardMapId, - MinValue, - MaxValue, + (MappingId, + ShardId, + ShardMapId, + MinValue, + MaxValue, Status, LastOperationId) values - (@stepMappingId, - @shardId, - @shardMapId, - @stepMinValue, - @stepMaxValue, + (@stepMappingId, + @shardId, + @shardMapId, + @stepMinValue, + @stepMaxValue, @stepMappingStatus, @operationId) @@ -1016,7 +1027,7 @@ Error_LSMVersionMismatch: Success_Exit: set @result = 1 goto Exit_Procedure; - + Exit_Procedure: end go @@ -1034,10 +1045,10 @@ begin @patternForKill nvarchar(128) -- get operation information as well as number of steps information - select + select @lsmVersionClient = x.value('(LsmVersion)[1]', 'int'), @patternForKill = x.value('(Pattern)[1]', 'nvarchar(128)') - from + from @input.nodes('/KillSessionsForShardMappingLocal') as t(x) if (@lsmVersionClient is null or @patternForKill is null) @@ -1049,31 +1060,31 @@ begin declare @tvKillCommands table (spid smallint primary key, commandForKill nvarchar(10)) -- insert empty row - insert into - @tvKillCommands (spid, commandForKill) - values + insert into + @tvKillCommands (spid, commandForKill) + values (0, N'') - insert into - @tvKillCommands(spid, commandForKill) - select + insert into + @tvKillCommands(spid, commandForKill) + select session_id, 'kill ' + convert(nvarchar(10), session_id) - from - sys.dm_exec_sessions - where + from + sys.dm_exec_sessions + where session_id > 50 and program_name like '%' + @patternForKill + '%' - declare @currentSpid int, + declare @currentSpid int, @currentCommandForKill nvarchar(10) declare @current_error int - select top 1 - @currentSpid = spid, - @currentCommandForKill = commandForKill - from - @tvKillCommands - order by + select top 1 + @currentSpid = spid, + @currentCommandForKill = commandForKill + from + @tvKillCommands + order by spid desc while (@currentSpid > 0) @@ -1083,18 +1094,18 @@ begin exec (@currentCommandForKill) -- remove the current row - delete - @tvKillCommands - where + delete + @tvKillCommands + where spid = @currentSpid -- get next row - select top 1 - @currentSpid = spid, - @currentCommandForKill = commandForKill - from - @tvKillCommands - order by + select top 1 + @currentSpid = spid, + @currentCommandForKill = commandForKill + from + @tvKillCommands + order by spid desc end try begin catch @@ -1106,7 +1117,7 @@ begin set @result = 1 goto Exit_Procedure; - + Error_UnableToKillSessions: set @result = 305 goto Exit_Procedure; @@ -1124,3 +1135,6 @@ Error_LSMVersionMismatch: Exit_Procedure: end go +"; + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerGlobal.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerGlobal.cs similarity index 95% rename from Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerGlobal.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerGlobal.cs index 5f01610..9430cda 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerGlobal.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerGlobal.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal const string DropShardMapManagerGlobal = @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -285,3 +296,6 @@ begin drop schema __ShardManagement end go +"; + } +} diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerLocal.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerLocal.cs similarity index 91% rename from Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerLocal.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerLocal.cs index 0bb3aa1..d017f61 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerLocal.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/DropShardMapManagerLocal.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal const string DropShardMapManagerLocal = @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -118,7 +129,7 @@ go if object_id(N'__ShardManagement.ucShardMappingsLocal_ShardMapId_MinValue', N'UQ') is not null begin - alter table __ShardManagement.ShardMappingsLocal + alter table __ShardManagement.ShardMappingsLocal drop constraint ucShardMappingsLocal_ShardMapId_MinValue end go @@ -170,3 +181,6 @@ begin drop schema __ShardManagement end go +"; + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeScripts.cs b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeScripts.cs new file mode 100644 index 0000000..a4464ce --- /dev/null +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeScripts.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Collections.Generic; + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + /// + /// structure to hold upgrade command batches along with the starting version to apply the upgrade step. + /// + internal struct UpgradeScript + { + /// + /// Major version to apply this upgrade step. + /// + public int InitialMajorVersion + { + get; + private set; + } + + /// + /// Minor version to apply this upgrade step. + /// + public int InitialMinorVersion + { + get; + private set; + } + + /// + /// Commands in this upgrade step batch. These will be executed only when store is at (this.InitialMajorVersion, this.InitialMinorVersion). + /// + public string Script + { + get; + private set; + } + + /// + /// Construct upgrade steps. + /// + /// Expected major version of store to run this upgrade step. + /// Expected minor version of store to run this upgrade step. + /// Commands to execute as part of this upgrade step. + public UpgradeScript(int initialMajorVersion, int initialMinorVersion, string commands) + : this() + { + this.InitialMajorVersion = initialMajorVersion; + this.InitialMinorVersion = initialMinorVersion; + this.Script = commands; + } + }; + + /// + /// Implemented as property to avoid static initialization ordering issues + /// + internal static IEnumerable UpgradeGlobalScripts => new[] + { + UpgradeShardMapManagerGlobalFrom0_0To1_0, + UpgradeShardMapManagerGlobalFrom1_0To1_1, + UpgradeShardMapManagerGlobalFrom1_1To1_2, + UpgradeShardMapManagerGlobalFrom1000_0To1000_1 + }; + + /// + /// Implemented as property to avoid static initialization ordering issues + /// + internal static IEnumerable UpgradeLocalScripts => new[] + { + UpgradeShardMapManagerLocalFrom0_0To1_0, + UpgradeShardMapManagerLocalFrom1_0To1_1, + UpgradeShardMapManagerLocalFrom1_1To1_2, + UpgradeShardMapManagerLocalFrom1000_0To1000_1 + }; + } +} diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom0.0To1.0.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom0.0To1.0.cs similarity index 52% rename from Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom0.0To1.0.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom0.0To1.0.cs index 0b009a3..c5587bd 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom0.0To1.0.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom0.0To1.0.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal static readonly UpgradeScript UpgradeShardMapManagerGlobalFrom0_0To1_0 = new UpgradeScript(0, 0, @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -8,3 +19,6 @@ -- add a column to ShardMapManagerGlobal table to hold SCH-M lock during upgrade alter table __ShardManagement.ShardMapManagerGlobal add UpgradeLock int null go +"); + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.0To1.1.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.0To1.1.cs similarity index 92% rename from Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.0To1.1.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.0To1.1.cs index 4f53b70..1d60088 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.0To1.1.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.0To1.1.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal static readonly UpgradeScript UpgradeShardMapManagerGlobalFrom1_0To1_1 = new UpgradeScript(1, 0, @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -5,7 +16,7 @@ -- Script to upgrade Global Shard Map from version 1.0 to 1.1 --------------------------------------------------------------------------------------------------- --- drop ShardMapManagerGlobal table +-- drop ShardMapManagerGlobal table drop table __ShardManagement.ShardMapManagerGlobal -- create ShardMapManagerGlobal table with new column names @@ -46,7 +57,7 @@ if object_id(N'__ShardManagement.spFindShardMapByNameGlobal', N'P') is not null begin drop procedure __ShardManagement.spFindShardMapByNameGlobal end - + if object_id(N'__ShardManagement.spGetAllDistinctShardLocationsGlobal', N'P') is not null begin drop procedure __ShardManagement.spGetAllDistinctShardLocationsGlobal @@ -57,7 +68,7 @@ begin drop procedure __ShardManagement.spAddShardMapGlobal end go - + if object_id(N'__ShardManagement.spRemoveShardMapGlobal', N'P') is not null begin drop procedure __ShardManagement.spRemoveShardMapGlobal @@ -199,7 +210,7 @@ as begin select 5, StoreVersionMajor, StoreVersionMinor - from + from __ShardManagement.ShardMapManagerGlobal end go @@ -232,7 +243,7 @@ begin if (@gsmVersionMajorClient <> __ShardManagement.fnGetStoreVersionMajorGlobal()) goto Error_GSMVersionMismatch; - update + update __ShardManagement.OperationsLogGlobal set UndoStartState = @undoStartState @@ -242,7 +253,7 @@ begin set @result = 1 exec __ShardManagement.spGetOperationLogEntryGlobalHelper @operationId goto Exit_Procedure; - + Error_MissingParameters: set @result = 50 exec __ShardManagement.spGetStoreVersionGlobalHelper @@ -269,10 +280,10 @@ begin declare @gsmVersionMajorClient int, @gsmVersionMinorClient int - select + select @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int') - from + from @input.nodes('/GetAllShardMapsGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null) @@ -281,9 +292,9 @@ begin if (@gsmVersionMajorClient <> __ShardManagement.fnGetStoreVersionMajorGlobal()) goto Error_GSMVersionMismatch; - select - 1, ShardMapId, Name, ShardMapType, KeyType - from + select + 1, ShardMapId, Name, ShardMapType, KeyType + from __ShardManagement.ShardMapsGlobal set @result = 1 @@ -320,7 +331,7 @@ declare @gsmVersionMajorClient int, @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @name = x.value('(ShardMap/Name)[1]', ' nvarchar(50)') - from + from @input.nodes('/FindShardMapByNameGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @name is null) @@ -333,7 +344,7 @@ declare @gsmVersionMajorClient int, 1, ShardMapId, Name, ShardMapType, KeyType from __ShardManagement.ShardMapsGlobal - where + where Name = @name set @result = 1 @@ -365,10 +376,10 @@ begin declare @gsmVersionMajorClient int, @gsmVersionMinorClient int - select + select @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int') - from + from @input.nodes('/GetAllDistinctShardLocationsGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null) @@ -377,9 +388,9 @@ begin if (@gsmVersionMajorClient <> __ShardManagement.fnGetStoreVersionMajorGlobal()) goto Error_GSMVersionMismatch; - select distinct - 4, Protocol, ServerName, Port, DatabaseName - from + select distinct + 4, Protocol, ServerName, Port, DatabaseName + from __ShardManagement.ShardsGlobal where Readable = 1 @@ -417,14 +428,14 @@ begin @mapType int, @keyType int - select + select @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @name = x.value('(ShardMap/Name)[1]', 'nvarchar(50)'), @mapType = x.value('(ShardMap/Kind)[1]', 'int'), @keyType = x.value('(ShardMap/KeyKind)[1]', 'int') - from + from @input.nodes('/AddShardMapGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @shardMapId is null or @name is null or @mapType is null or @keyType is null) @@ -432,15 +443,15 @@ begin if (@gsmVersionMajorClient <> __ShardManagement.fnGetStoreVersionMajorGlobal()) goto Error_GSMVersionMismatch; - + -- try to insert the row for the shard map, duplicate violation will be detected by the -- uniqueness constraint on the Name begin try - insert into - __ShardManagement.ShardMapsGlobal + insert into + __ShardManagement.ShardMapsGlobal (ShardMapId, Name, ShardMapType, KeyType) - values - (@shardMapId, @name, @mapType, @keyType) + values + (@shardMapId, @name, @mapType, @keyType) end try begin catch if (error_number() = 2627) @@ -455,17 +466,17 @@ begin @errorProcedure nvarchar(128) = isnull(error_procedure(), '-'); select @errorMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, Message: ' + @errorMessage; - + raiserror (@errorMessage, @errorSeverity, 1, @errorNumber, @errorSeverity, @errorState, @errorProcedure, @errorLine); - + rollback transaction; -- To avoid extra error message in response. goto Error_UnexpectedError; end end catch - + set @result = 1 goto Exit_Procedure; - + Error_ShardMapAlreadyExists: set @result = 101 goto Exit_Procedure; @@ -501,11 +512,11 @@ begin @gsmVersionMinorClient int, @shardMapId uniqueidentifier - select + select @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', ' uniqueidentifier') - from + from @input.nodes('/RemoveShardMapGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @shardMapId is null) @@ -516,7 +527,7 @@ begin declare @currentShardMapId uniqueidentifier - select + select @currentShardMapId = ShardMapId from __ShardManagement.ShardMapsGlobal with (updlock) @@ -527,18 +538,18 @@ begin goto Error_ShardMapNotFound; if exists ( - select - ShardId - from - __ShardManagement.ShardsGlobal - where + select + ShardId + from + __ShardManagement.ShardsGlobal + where ShardMapId = @shardMapId) goto Error_ShardMapHasShards; - delete from - __ShardManagement.ShardMapsGlobal - where - ShardMapId = @shardMapId + delete from + __ShardManagement.ShardMapsGlobal + where + ShardMapId = @shardMapId set @result = 1 goto Exit_Procedure; @@ -578,11 +589,11 @@ begin @gsmVersionMinorClient int, @shardMapId uniqueidentifier - select + select @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier') - from + from @input.nodes('/GetAllShardsGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @shardMapId is null) @@ -592,19 +603,19 @@ begin goto Error_GSMVersionMismatch; if not exists ( - select - ShardMapId - from - __ShardManagement.ShardMapsGlobal - where + select + ShardMapId + from + __ShardManagement.ShardMapsGlobal + where ShardMapId = @shardMapId) goto Error_ShardMapNotFound; - select + select 2, ShardId, Version, ShardMapId, Protocol, ServerName, Port, DatabaseName, Status - from - __ShardManagement.ShardsGlobal - where + from + __ShardManagement.ShardsGlobal + where ShardMapId = @shardMapId and Readable = 1 set @result = 1 @@ -645,7 +656,7 @@ begin @port int, @databaseName nvarchar(128) - select + select @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @@ -656,7 +667,7 @@ begin from @input.nodes('/FindShardByLocationGlobal') as t(x) - if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @shardMapId is null or + if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @shardMapId is null or @protocol is null or @serverName is null or @port is null or @databaseName is null) goto Error_MissingParameters; @@ -664,21 +675,21 @@ begin goto Error_GSMVersionMismatch; if not exists ( - select - ShardMapId + select + ShardMapId from __ShardManagement.ShardMapsGlobal where ShardMapId = @shardMapId) goto Error_ShardMapNotFound; - select + select 2, ShardId, Version, ShardMapId, Protocol, ServerName, Port, DatabaseName, Status - from - __ShardManagement.ShardsGlobal + from + __ShardManagement.ShardsGlobal where ShardMapId = @shardMapId and - Protocol = @protocol and ServerName = @serverName and Port = @port and DatabaseName = @databaseName and + Protocol = @protocol and ServerName = @serverName and Port = @port and DatabaseName = @databaseName and Readable = 1 set @result = 1 @@ -719,8 +730,8 @@ begin @shardMapId uniqueidentifier -- get operation information as well as number of steps - select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + select + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @operationCode = x.value('(@OperationCode)[1]', 'int'), @@ -729,7 +740,7 @@ begin from @input.nodes('/BulkOperationShardsGlobal') as t(x) - if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @operationId is null or @operationCode is null or + if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @operationId is null or @operationCode is null or @stepsCount is null or @shardMapId is null) goto Error_MissingParameters; @@ -738,9 +749,9 @@ begin -- check if shard map exists if not exists ( - select - ShardMapId - from + select + ShardMapId + from __ShardManagement.ShardMapsGlobal with (updlock) where ShardMapId = @shardMapId) @@ -773,9 +784,9 @@ begin @errorProcedure nvarchar(128) = isnull(error_procedure(), '-'); select @errorMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, Message: ' + @errorMessage; - + raiserror (@errorMessage, @errorSeverity, 1, @errorNumber, @errorSeverity, @errorState, @errorProcedure, @errorLine); - + rollback transaction; -- To avoid extra error message in response. goto Error_UnexpectedError; end @@ -799,17 +810,17 @@ begin while (@stepIndex <= @stepsCount) begin - select - @currentStep = x.query('(./Step[@Id = sql:variable("@stepIndex")])[1]') + select + @currentStep = x.query('(./Step[@Id = sql:variable(""@stepIndex"")])[1]') from @input.nodes('/BulkOperationShardsGlobal/Steps') as t(x) -- Identify the step type. - select + select @stepType = x.value('(@Kind)[1]', 'int'), @stepShardId = x.value('(Shard/Id)[1]', 'uniqueidentifier'), @stepShardVersion = x.value('(Shard/Version)[1]', 'uniqueidentifier') - from + from @currentStep.nodes('./Step') as t(x) if (@stepType is null or @stepShardId is null or @stepShardVersion is null) @@ -846,17 +857,17 @@ begin if (@stepType = 1) begin if exists ( - select - ShardId - from - __ShardManagement.ShardMappingsGlobal - where + select + ShardId + from + __ShardManagement.ShardMappingsGlobal + where ShardMapId = @shardMapId and ShardId = @stepShardId) goto Error_ShardHasMappings; end -- mark pending operation on current shard - update + update __ShardManagement.ShardsGlobal set OperationId = @operationId @@ -882,7 +893,7 @@ begin goto Error_MissingParameters; -- Check re-entrancy or pending operations - select + select @currentShardVersion = Version, @currentShardOperationId = OperationId from @@ -897,7 +908,7 @@ begin -- pending operation if (@currentShardOperationId is not null) goto Error_ShardPendingOperation; - + if (@currentShardVersion is not null) goto Error_ShardAlreadyExists; @@ -905,14 +916,14 @@ begin set @currentShardVersion = null set @currentShardOperationId = null - select - @currentShardVersion = Version, + select + @currentShardVersion = Version, @currentShardOperationId = OperationId - from - __ShardManagement.ShardsGlobal + from + __ShardManagement.ShardsGlobal where ShardMapId = @shardMapId and - Protocol = @stepProtocol and + Protocol = @stepProtocol and ServerName = @stepServerName and Port = @stepPort and DatabaseName = @stepDatabaseName @@ -922,35 +933,35 @@ begin if (@currentShardOperationId is not null) goto Error_ShardPendingOperation; - -- Another shard with same location already exists. + -- Another shard with same location already exists. if (@currentShardVersion is not null) goto Error_ShardLocationAlreadyExists; -- perform the add/update begin try - insert into + insert into __ShardManagement.ShardsGlobal( - ShardId, - Readable, - Version, - ShardMapId, - OperationId, - Protocol, - ServerName, - Port, - DatabaseName, + ShardId, + Readable, + Version, + ShardMapId, + OperationId, + Protocol, + ServerName, + Port, + DatabaseName, Status) values ( - @stepShardId, + @stepShardId, 0, - @stepShardVersion, + @stepShardVersion, @shardMapId, - @operationId, - @stepProtocol, - @stepServerName, - @stepPort, - @stepDatabaseName, - @stepShardStatus) + @operationId, + @stepProtocol, + @stepServerName, + @stepPort, + @stepDatabaseName, + @stepShardStatus) end try begin catch if (error_number() = 2627) @@ -965,9 +976,9 @@ begin set @errorProcedure = isnull(error_procedure(), '-') select @errorMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, Message: ' + @errorMessage; - + raiserror (@errorMessage, @errorSeverity, 2, @errorNumber, @errorSeverity, @errorState, @errorProcedure, @errorLine); - + rollback transaction; -- To avoid extra error message in response. goto Error_UnexpectedError; end @@ -1053,7 +1064,7 @@ create procedure __ShardManagement.spBulkOperationShardsGlobalEnd @result int output as begin - declare @gsmVersionMajorClient int, + declare @gsmVersionMajorClient int, @gsmVersionMinorClient int, @operationId uniqueidentifier, @operationCode int, @@ -1063,7 +1074,7 @@ begin -- get operation information as well as number of steps select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @operationCode = x.value('(@OperationCode)[1]', 'int'), @@ -1082,9 +1093,9 @@ begin -- check if shard map exists if not exists ( - select - ShardMapId - from + select + ShardMapId + from __ShardManagement.ShardMapsGlobal with (updlock) where ShardMapId = @shardMapId) @@ -1095,19 +1106,19 @@ begin @stepIndex int = 1, @stepType int, @stepShardId uniqueidentifier - + while (@stepIndex <= @stepsCount) begin - select - @currentStep = x.query('(./Step[@Id = sql:variable("@stepIndex")])[1]') + select + @currentStep = x.query('(./Step[@Id = sql:variable(""@stepIndex"")])[1]') from @input.nodes('/BulkOperationShardsGlobal/Steps') as t(x) -- Identify the step type. - select + select @stepType = x.value('(@Kind)[1]', 'int'), @stepShardId = x.value('(Shard/Id)[1]', 'uniqueidentifier') - from + from @currentStep.nodes('./Step') as t(x) if (@stepType is null or @stepShardId is null) @@ -1118,17 +1129,17 @@ begin if (@undo = 1) begin -- keep the Readable row as is - update + update __ShardManagement.ShardsGlobal set OperationId = null where - ShardMapId = @shardMapId and ShardId = @stepShardId and OperationId = @operationId + ShardMapId = @shardMapId and ShardId = @stepShardId and OperationId = @operationId end else begin -- remove the row to be deleted - delete from + delete from __ShardManagement.ShardsGlobal where ShardMapId = @shardMapId and ShardId = @stepShardId and OperationId = @operationId @@ -1143,30 +1154,30 @@ begin if (@undo = 1) begin -- keep the Readable row as is - update + update __ShardManagement.ShardsGlobal set OperationId = null where - ShardMapId = @shardMapId and ShardId = @stepShardId and OperationId = @operationId + ShardMapId = @shardMapId and ShardId = @stepShardId and OperationId = @operationId end else begin -- Update the row with new Version/Status information - select + select @newShardVersion = x.value('(Update/Shard/Version)[1]', 'uniqueidentifier'), @newStatus = x.value('(Update/Shard/Status)[1]', 'int') - from + from @currentStep.nodes('./Step') as t(x) - update + update __ShardManagement.ShardsGlobal set Version = @newShardVersion, Status = @newStatus, OperationId = null where - ShardMapId = @shardMapId and ShardId = @stepShardId and OperationId = @operationId + ShardMapId = @shardMapId and ShardId = @stepShardId and OperationId = @operationId end set @newShardVersion = null @@ -1178,7 +1189,7 @@ begin if (@undo = 1) begin -- remove the row that we tried to add - delete from + delete from __ShardManagement.ShardsGlobal where ShardMapId = @shardMapId and ShardId = @stepShardId and OperationId = @operationId @@ -1186,13 +1197,13 @@ begin else begin -- mark the new row Readable - update + update __ShardManagement.ShardsGlobal set Readable = 1, OperationId = null where - ShardMapId = @shardMapId and ShardId = @stepShardId and OperationId = @operationId + ShardMapId = @shardMapId and ShardId = @stepShardId and OperationId = @operationId end end @@ -1205,7 +1216,7 @@ begin -- remove log record delete from __ShardManagement.OperationsLogGlobal - where + where OperationId = @operationId set @result = 1 @@ -1238,7 +1249,7 @@ create procedure __ShardManagement.spGetAllShardMappingsGlobal @result int output as begin - declare @gsmVersionMajorClient int, + declare @gsmVersionMajorClient int, @gsmVersionMinorClient int, @shardMapId uniqueidentifier, @shardId uniqueidentifier, @@ -1247,13 +1258,13 @@ begin @maxValue varbinary(128) select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), - @shardId = x.value('(Shard[@Null="0"]/Id)[1]', 'uniqueidentifier'), - @shardVersion = x.value('(Shard[@Null="0"]/Version)[1]', 'uniqueidentifier'), - @minValue = convert(varbinary(128), x.value('(Range[@Null="0"]/MinValue)[1]', 'varchar(258)'), 1), - @maxValue = convert(varbinary(128), x.value('(Range[@Null="0"]/MaxValue[@Null="0"])[1]', 'varchar(258)'), 1) + @shardId = x.value('(Shard[@Null=""0""]/Id)[1]', 'uniqueidentifier'), + @shardVersion = x.value('(Shard[@Null=""0""]/Version)[1]', 'uniqueidentifier'), + @minValue = convert(varbinary(128), x.value('(Range[@Null=""0""]/MinValue)[1]', 'varchar(258)'), 1), + @maxValue = convert(varbinary(128), x.value('(Range[@Null=""0""]/MaxValue[@Null=""0""])[1]', 'varchar(258)'), 1) from @input.nodes('/GetAllShardMappingsGlobal') as t(x) @@ -1265,7 +1276,7 @@ begin declare @shardMapType int - select + select @shardMapType = ShardMapType from __ShardManagement.ShardMapsGlobal @@ -1281,8 +1292,8 @@ begin begin if (@shardVersion is null) goto Error_MissingParameters; - - select + + select @currentShardVersion = Version from __ShardManagement.ShardsGlobal @@ -1292,18 +1303,18 @@ begin if (@currentShardVersion is null) goto Error_ShardDoesNotExist; - -- DEVNOTE(wbasheer): Bring this back if we want to be strict. + -- DEVNOTE(wbasheer): Bring this back if we want to be strict. --if (@currentShardVersion <> @shardVersion) -- goto Error_ShardVersionMismatch; end - + declare @tvShards table ( - ShardId uniqueidentifier not null, - Version uniqueidentifier not null, + ShardId uniqueidentifier not null, + Version uniqueidentifier not null, Protocol int not null, - ServerName nvarchar(128) collate SQL_Latin1_General_CP1_CI_AS not null, + ServerName nvarchar(128) collate SQL_Latin1_General_CP1_CI_AS not null, Port int not null, - DatabaseName nvarchar(128) collate SQL_Latin1_General_CP1_CI_AS not null, + DatabaseName nvarchar(128) collate SQL_Latin1_General_CP1_CI_AS not null, Status int not null, primary key (ShardId) ) @@ -1322,7 +1333,7 @@ begin __ShardManagement.ShardsGlobal s where (@shardId is null or s.ShardId = @shardId) and s.ShardMapId = @shardMapId - + declare @minValueCalculated varbinary(128) = 0x, @maxValueCalculated varbinary(128) = null @@ -1341,17 +1352,17 @@ begin s.ShardId, s.Version, m.ShardMapId, s.Protocol, s.ServerName, s.Port, s.DatabaseName, s.Status -- fields for SqlShard, ShardMapId is repeated here from __ShardManagement.ShardMappingsGlobal m - join - @tvShards s - on + join + @tvShards s + on m.ShardId = s.ShardId where - m.ShardMapId = @shardMapId and + m.ShardMapId = @shardMapId and m.Readable = 1 and - (@shardId is null or m.ShardId = @shardId) and - MinValue >= @minValueCalculated and + (@shardId is null or m.ShardId = @shardId) and + MinValue >= @minValueCalculated and ((@maxValueCalculated is null) or (MinValue < @maxValueCalculated)) - order by + order by m.MinValue end else @@ -1361,15 +1372,15 @@ begin s.ShardId, s.Version, m.ShardMapId, s.Protocol, s.ServerName, s.Port, s.DatabaseName, s.Status -- fields for SqlShard, ShardMapId is repeated here from __ShardManagement.ShardMappingsGlobal m - join - @tvShards s - on + join + @tvShards s + on m.ShardId = s.ShardId where - m.ShardMapId = @shardMapId and + m.ShardMapId = @shardMapId and m.Readable = 1 and - (@shardId is null or m.ShardId = @shardId) and - ((MaxValue is null) or (MaxValue > @minValueCalculated)) and + (@shardId is null or m.ShardId = @shardId) and + ((MaxValue is null) or (MaxValue > @minValueCalculated)) and ((@maxValueCalculated is null) or (MinValue < @maxValueCalculated)) order by m.MinValue @@ -1386,7 +1397,7 @@ Error_ShardDoesNotExist: set @result = 202 goto Exit_Procedure; --- DEVNOTE(wbasheer): Bring this back if we want to be strict. +-- DEVNOTE(wbasheer): Bring this back if we want to be strict. --Error_ShardVersionMismatch: -- set @result = 204 -- goto Exit_Procedure; @@ -1420,7 +1431,7 @@ begin @keyValue varbinary(128) select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @keyValue = convert(varbinary(128), x.value('(Key/Value)[1]', 'varchar(258)'), 1) @@ -1435,7 +1446,7 @@ begin declare @shardMapType int - select + select @shardMapType = ShardMapType from __ShardManagement.ShardMapsGlobal @@ -1444,7 +1455,7 @@ begin if (@shardMapType is null) goto Error_ShardMapNotFound; - + declare @currentMappingId uniqueidentifier, @currentShardId uniqueidentifier, @currentMinValue varbinary(128), @@ -1453,7 +1464,7 @@ begin @currentLockOwnerId uniqueidentifier if (@shardMapType = 1) - begin + begin select @currentMappingId = MappingId, @currentShardId = ShardId, @@ -1464,23 +1475,23 @@ begin from __ShardManagement.ShardMappingsGlobal where - ShardMapId = @shardMapId and + ShardMapId = @shardMapId and Readable = 1 and MinValue = @keyValue end else begin - select + select @currentMappingId = MappingId, @currentShardId = ShardId, @currentMinValue = MinValue, @currentMaxValue = MaxValue, @currentStatus = Status, @currentLockOwnerId = LockOwnerId - from + from __ShardManagement.ShardMappingsGlobal where - ShardMapId = @shardMapId and + ShardMapId = @shardMapId and Readable = 1 and MinValue <= @keyValue and (MaxValue is null or MaxValue > @keyValue) end @@ -1488,15 +1499,15 @@ begin if (@@rowcount = 0) goto Error_KeyNotFound; - select + select 3, @currentMappingId as MappingId, ShardMapId, @currentMinValue, @currentMaxValue, @currentStatus, @currentLockOwnerId, -- fields for SqlMapping ShardId, Version, ShardMapId, Protocol, ServerName, Port, DatabaseName, Status -- fields for SqlShard, ShardMapId is repeated here - from + from __ShardManagement.ShardsGlobal where ShardId = @currentShardId and ShardMapId = @shardMapId - + if (@@rowcount = 0) goto Error_KeyNotFound; @@ -1540,7 +1551,7 @@ begin @mappingId uniqueidentifier select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @mappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier') @@ -1555,7 +1566,7 @@ begin declare @shardMapType int - select + select @shardMapType = ShardMapType from __ShardManagement.ShardMapsGlobal @@ -1564,7 +1575,7 @@ begin if (@shardMapType is null) goto Error_ShardMapNotFound; - + declare @currentShardId uniqueidentifier, @currentMinValue varbinary(128), @currentMaxValue varbinary(128), @@ -1577,7 +1588,7 @@ begin from __ShardManagement.ShardMappingsGlobal where - ShardMapId = @shardMapId and + ShardMapId = @shardMapId and Readable = 1 and MappingId = @mappingId @@ -1593,7 +1604,7 @@ begin from __ShardManagement.ShardMappingsGlobal where - ShardMapId = @shardMapId and + ShardMapId = @shardMapId and MinValue = @currentMinValue if (@@rowcount = 0) @@ -1654,7 +1665,7 @@ begin -- get operation information as well as number of steps information select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @operationCode = x.value('(@OperationCode)[1]', 'int'), @@ -1663,7 +1674,7 @@ begin from @input.nodes('/BulkOperationShardMappingsGlobal') as t(x) - if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @operationId is null or @operationCode is null or + if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @operationId is null or @operationCode is null or @stepsCount is null or @shardMapId is null) goto Error_MissingParameters; @@ -1673,7 +1684,7 @@ begin -- check if shard map exists declare @shardMapType int - select + select @shardMapType = ShardMapType from __ShardManagement.ShardMapsGlobal with (updlock) @@ -1689,10 +1700,10 @@ begin @originalShardVersionForAdds uniqueidentifier, @currentShardOperationId uniqueidentifier - select + select @shardIdForRemoves = x.value('(Removes/Shard/Id)[1]', 'uniqueidentifier'), @shardIdForAdds = x.value('(Adds/Shard/Id)[1]', 'uniqueidentifier') - from + from @input.nodes('/BulkOperationShardMappingsGlobal') as t(x) if (@shardIdForRemoves is null or @shardIdForAdds is null) @@ -1706,7 +1717,7 @@ begin __ShardManagement.ShardsGlobal with (updlock) where ShardMapId = @shardMapId and ShardId = @shardIdForRemoves and Readable = 1 - + -- re-entrancy if (@currentShardOperationId = @operationId) goto Success_Exit; @@ -1737,7 +1748,7 @@ begin __ShardManagement.ShardsGlobal with (updlock) where ShardMapId = @shardMapId and ShardId = @shardIdForAdds and Readable = 1 - + -- re-entrancy if (@currentShardOperationId = @operationId) goto Success_Exit; @@ -1760,7 +1771,7 @@ begin begin set @originalShardVersionForAdds = @originalShardVersionForRemoves end - + -- add log record begin try insert into __ShardManagement.OperationsLogGlobal( @@ -1788,9 +1799,9 @@ begin @errorProcedure nvarchar(128) = isnull(error_procedure(), '-'); select @errorMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, Message: ' + @errorMessage; - + raiserror (@errorMessage, @errorSeverity, 1, @errorNumber, @errorSeverity, @errorState, @errorProcedure, @errorLine); - + rollback transaction; -- To avoid extra error message in response. goto Error_UnexpectedError; end @@ -1815,9 +1826,9 @@ begin while (@stepIndex <= @stepsCount) begin - select - @currentStep = x.query('(./Step[@Id = sql:variable("@stepIndex")])[1]') - from + select + @currentStep = x.query('(./Step[@Id = sql:variable(""@stepIndex"")])[1]') + from @input.nodes('/BulkOperationShardMappingsGlobal/Steps') as t(x) -- Identify the step type. @@ -1826,7 +1837,7 @@ begin @stepMappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier') from @currentStep.nodes('./Step') as t(x) - + if (@stepType is null or @stepMappingId is null) goto Error_MissingParameters; @@ -1835,15 +1846,15 @@ begin -- Remove Mapping -- Check for locks - select + select @stepLockOwnerId = x.value('(Lock/Id)[1]', 'uniqueidentifier') - from + from @currentStep.nodes('./Step') as t(x) if (@stepLockOwnerId is null) goto Error_MissingParameters; - select + select @currentLockOwnerId = LockOwnerId, @currentStatus = Status from @@ -1851,21 +1862,21 @@ begin where ShardMapId = @shardMapId and MappingId = @stepMappingId and Readable = 1 - if (@currentLockOwnerId is null) + if (@currentLockOwnerId is null) goto Error_MappingDoesNotExist; if (@currentLockOwnerId <> @stepLockOwnerId) goto Error_MappingLockOwnerIdMismatch; -- removepoint/removerange/removerangefromrange cannot work on online mappings - if ((@currentStatus & 1) <> 0 and - (@operationCode = 5 or - @operationCode = 9 or + if ((@currentStatus & 1) <> 0 and + (@operationCode = 5 or + @operationCode = 9 or @operationCode = 13)) goto Error_MappingIsNotOffline; -- mark pending operation on current mapping - update + update __ShardManagement.ShardMappingsGlobal set OperationId = @operationId @@ -1882,10 +1893,10 @@ begin -- UpdateMapping -- Check for locks - select + select @stepLockOwnerId = x.value('(Lock/Id)[1]', 'uniqueidentifier'), @stepStatus = x.value('(Update/Mapping/Status)[1]', 'int') - from + from @currentStep.nodes('./Step') as t(x) if (@stepLockOwnerId is null or @stepStatus is null) @@ -1899,7 +1910,7 @@ begin where ShardMapId = @shardMapId and MappingId = @stepMappingId and Readable = 1 - if (@currentLockOwnerId is null) + if (@currentLockOwnerId is null) goto Error_MappingDoesNotExist; if (@currentLockOwnerId <> @stepLockOwnerId) @@ -1910,7 +1921,7 @@ begin goto Error_MappingIsNotOffline; -- mark pending operation on current mapping - update + update __ShardManagement.ShardMappingsGlobal set OperationId = @operationId @@ -1927,11 +1938,11 @@ begin if (@stepType = 3) begin -- AddMapping - select + select @stepShouldValidate = x.value('(@Validate)[1]', 'bit'), @stepMappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier'), @stepMinValue = convert(varbinary(128), x.value('(Mapping/MinValue)[1]', 'varchar(258)'), 1), - @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null="0"])[1]', 'varchar(258)'), 1), + @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null=""0""])[1]', 'varchar(258)'), 1), @stepStatus = x.value('(Mapping/Status)[1]', 'int'), @stepLockOwnerId = x.value('(Mapping/LockOwnerId)[1]', 'uniqueidentifier') from @@ -1945,7 +1956,7 @@ begin begin if (@shardMapType = 1) begin - select + select @mappingIdFromValidate = MappingId, @currentShardOperationId = OperationId from @@ -1964,14 +1975,14 @@ begin end else begin - select + select @mappingIdFromValidate = MappingId, @currentShardOperationId = OperationId from __ShardManagement.ShardMappingsGlobal where ShardMapId = @shardMapId and - (MaxValue is null or MaxValue > @stepMinValue) and + (MaxValue is null or MaxValue > @stepMinValue) and (@stepMaxValue is null or MinValue < @stepMaxValue) if (@mappingIdFromValidate is not null) @@ -1987,23 +1998,23 @@ begin -- add mapping insert into __ShardManagement.ShardMappingsGlobal( - MappingId, + MappingId, Readable, - ShardId, - ShardMapId, - OperationId, - MinValue, - MaxValue, + ShardId, + ShardMapId, + OperationId, + MinValue, + MaxValue, Status, LockOwnerId) values ( - @stepMappingId, + @stepMappingId, 0, - @shardIdForAdds, - @shardMapId, - @operationId, - @stepMinValue, - @stepMaxValue, + @shardIdForAdds, + @shardMapId, + @operationId, + @stepMinValue, + @stepMaxValue, @stepStatus, @stepLockOwnerId) @@ -2100,7 +2111,7 @@ begin -- get operation information as well as number of steps information select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @operationCode = x.value('(@OperationCode)[1]', 'int'), @@ -2119,9 +2130,9 @@ begin -- check if shard map exists if not exists ( - select - ShardMapId - from + select + ShardMapId + from __ShardManagement.ShardMapsGlobal with (updlock) where ShardMapId = @shardMapId) @@ -2132,12 +2143,12 @@ begin @shardIdForAdds uniqueidentifier, @shardVersionForAdds uniqueidentifier - select + select @shardIdForRemoves = x.value('(Removes/Shard/Id)[1]', 'uniqueidentifier'), @shardIdForAdds = x.value('(Adds/Shard/Id)[1]', 'uniqueidentifier'), @shardVersionForRemoves = x.value('(Removes/Shard/Version)[1]', 'uniqueidentifier'), @shardVersionForAdds = x.value('(Adds/Shard/Version)[1]', 'uniqueidentifier') - from + from @input.nodes('/BulkOperationShardMappingsGlobal') as t(x) if (@shardIdForRemoves is null or @shardIdForAdds is null or @shardVersionForRemoves is null or @shardVersionForAdds is null) @@ -2147,7 +2158,7 @@ begin if (@undo = 1) begin -- Unmark the pending operation - update + update __ShardManagement.ShardsGlobal set OperationId = null @@ -2156,7 +2167,7 @@ begin if (@shardIdForRemoves <> @shardIdForAdds) begin - update + update __ShardManagement.ShardsGlobal set OperationId = null @@ -2167,7 +2178,7 @@ begin else begin -- update the source shard row with new Version - update + update __ShardManagement.ShardsGlobal set Version = @shardVersionForRemoves, @@ -2178,7 +2189,7 @@ begin -- update the target shard row with new Version if (@shardIdForRemoves <> @shardIdForAdds) begin - update + update __ShardManagement.ShardsGlobal set Version = @shardVersionForAdds, @@ -2193,16 +2204,16 @@ begin @stepIndex int = 1, @stepType int, @stepMappingId uniqueidentifier - + while (@stepIndex <= @stepsCount) begin - select - @currentStep = x.query('(./Step[@Id = sql:variable("@stepIndex")])[1]') + select + @currentStep = x.query('(./Step[@Id = sql:variable(""@stepIndex"")])[1]') from @input.nodes('/BulkOperationShardMappingsGlobal/Steps') as t(x) -- Identify the step type. - select + select @stepType = x.value('(@Kind)[1]', 'int'), @stepMappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier') from @@ -2216,7 +2227,7 @@ begin if (@undo = 1) begin -- keep the Readable row as is - update + update __ShardManagement.ShardMappingsGlobal set OperationId = null @@ -2226,7 +2237,7 @@ begin else begin -- remove the row to be deleted - delete from + delete from __ShardManagement.ShardMappingsGlobal where ShardMapId = @shardMapId and MappingId = @stepMappingId @@ -2241,7 +2252,7 @@ begin if (@undo = 1) begin -- keep the Readable row as is - update + update __ShardManagement.ShardMappingsGlobal set OperationId = null @@ -2257,7 +2268,7 @@ begin from @currentStep.nodes('./Step') as t(x) - update + update __ShardManagement.ShardMappingsGlobal set MappingId = @newMappingId, @@ -2277,7 +2288,7 @@ begin if (@undo = 1) begin -- remove the row that we tried to add - delete from + delete from __ShardManagement.ShardMappingsGlobal where ShardMapId = @shardMapId and MappingId = @stepMappingId @@ -2285,7 +2296,7 @@ begin else begin -- mark the new row Readable - update + update __ShardManagement.ShardMappingsGlobal set Readable = 1, @@ -2302,7 +2313,7 @@ begin end -- delete log record - delete from + delete from __ShardManagement.OperationsLogGlobal where OperationId = @operationId @@ -2338,7 +2349,7 @@ create procedure __ShardManagement.spLockOrUnlockShardMappingsGlobal @result int output as begin - declare @gsmVersionMajorClient int, + declare @gsmVersionMajorClient int, @gsmVersionMinorClient int, @shardMapId uniqueidentifier, @mappingId uniqueidentifier, @@ -2346,7 +2357,7 @@ begin @lockOperationType int select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @mappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier'), @@ -2365,9 +2376,9 @@ begin goto Error_MissingParameters; if not exists ( - select - ShardMapId - from + select + ShardMapId + from __ShardManagement.ShardMapsGlobal with (updlock) where ShardMapId = @shardMapId) @@ -2377,14 +2388,14 @@ begin @currentOperationId uniqueidentifier if (@lockOperationType <> 2) - begin + begin declare @ForceUnLockLockOwnerId uniqueidentifier = 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF', @currentLockOwnerId uniqueidentifier - select + select @currentOperationId = OperationId, @currentLockOwnerId = LockOwnerId - from + from __ShardManagement.ShardMappingsGlobal with (updlock) where ShardMapId = @shardMapId and MappingId = @mappingId @@ -2404,16 +2415,16 @@ begin update __ShardManagement.ShardMappingsGlobal - set - LockOwnerId = case - when - @lockOperationType = 0 - then - @lockOwnerId - when + set + LockOwnerId = case + when + @lockOperationType = 0 + then + @lockOwnerId + when @lockOperationType = 1 or @lockOperationType = 2 - then - @DefaultLockOwnerId + then + @DefaultLockOwnerId end where ShardMapId = @shardMapId and (@lockOperationType = 2 or MappingId = @mappingId) @@ -2471,7 +2482,7 @@ begin select @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int') - from + from @input.nodes('/GetAllShardingSchemaInfosGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null) @@ -2515,10 +2526,10 @@ begin @name nvarchar(128) select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @name = x.value('(SchemaInfo/Name)[1]', 'nvarchar(128)') - from + from @input.nodes('/FindShardingSchemaInfoGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @name is null) @@ -2529,7 +2540,7 @@ begin select 7, Name, SchemaInfo - from + from __ShardManagement.ShardedDatabaseSchemaInfosGlobal where Name = @name @@ -2572,11 +2583,11 @@ begin @schemaInfo xml select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @name = x.value('(SchemaInfo/Name)[1]', 'nvarchar(128)'), @schemaInfo = x.query('SchemaInfo/Info/*') - from + from @input.nodes('/AddShardingSchemaInfoGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @name is null or @schemaInfo is null) @@ -2586,14 +2597,14 @@ begin goto Error_GSMVersionMismatch; if exists ( - select - Name - from - __ShardManagement.ShardedDatabaseSchemaInfosGlobal - where + select + Name + from + __ShardManagement.ShardedDatabaseSchemaInfosGlobal + where Name = @name) goto Error_SchemaInfoAlreadyExists; - + insert into __ShardManagement.ShardedDatabaseSchemaInfosGlobal (Name, SchemaInfo) @@ -2634,10 +2645,10 @@ begin @name nvarchar(128) select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @name = x.value('(SchemaInfo/Name)[1]', 'nvarchar(128)') - from + from @input.nodes('/RemoveShardingSchemaInfoGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @name is null) @@ -2689,11 +2700,11 @@ begin @schemaInfo xml select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @name = x.value('(SchemaInfo/Name)[1]', 'nvarchar(128)'), @schemaInfo = x.query('SchemaInfo/Info/*') - from + from @input.nodes('/UpdateShardingSchemaInfoGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @name is null or @schemaInfo is null) @@ -2702,9 +2713,9 @@ begin if (@gsmVersionMajorClient <> __ShardManagement.fnGetStoreVersionMajorGlobal()) goto Error_GSMVersionMismatch; - update - __ShardManagement.ShardedDatabaseSchemaInfosGlobal - set + update + __ShardManagement.ShardedDatabaseSchemaInfosGlobal + set SchemaInfo = @schemaInfo where Name = @name @@ -2742,7 +2753,7 @@ create procedure __ShardManagement.spAttachShardGlobal @result int output as begin - declare @gsmVersionMajorClient int, + declare @gsmVersionMajorClient int, @gsmVersionMinorClient int, @shardMapId uniqueidentifier, @name nvarchar(50), @@ -2757,7 +2768,7 @@ begin @shardStatus int select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @name = x.value('(ShardMap/Name)[1]', 'nvarchar(50)'), @@ -2775,7 +2786,7 @@ begin @input.nodes('/AttachShardGlobal') as t(x) if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @shardMapId is null or @name is null or @mapType is null or @keyType is null or - @shardId is null or @shardVersion is null or @protocol is null or @serverName is null or + @shardId is null or @shardVersion is null or @protocol is null or @serverName is null or @port is null or @databaseName is null or @shardStatus is null) goto Error_MissingParameters; @@ -2783,21 +2794,21 @@ begin goto Error_GSMVersionMismatch; if exists ( - select + select ShardMapId from - __ShardManagement.ShardMapsGlobal + __ShardManagement.ShardMapsGlobal where (ShardMapId = @shardMapId and Name <> @name) or (ShardMapId <> @shardMapId and Name = @name)) goto Error_ShardMapAlreadyExists; -- ignore duplicate shard maps begin try - insert into - __ShardManagement.ShardMapsGlobal + insert into + __ShardManagement.ShardMapsGlobal (ShardMapId, Name, ShardMapType, KeyType) - values - (@shardMapId, @name, @mapType, @keyType) + values + (@shardMapId, @name, @mapType, @keyType) end try begin catch if (error_number() <> 2627) @@ -2810,9 +2821,9 @@ begin @errorProcedure nvarchar(128) = isnull(error_procedure(), '-'); select @errorMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, Message: ' + @errorMessage; - + raiserror (@errorMessage, @errorSeverity, 1, @errorNumber, @errorSeverity, @errorState, @errorProcedure, @errorLine); - + rollback transaction; -- To avoid extra error message in response. goto Error_UnexpectedError; end @@ -2820,29 +2831,29 @@ begin -- attempt to add the shard begin try - insert into + insert into __ShardManagement.ShardsGlobal ( - ShardId, - Readable, - Version, - ShardMapId, - OperationId, - Protocol, - ServerName, - Port, - DatabaseName, + ShardId, + Readable, + Version, + ShardMapId, + OperationId, + Protocol, + ServerName, + Port, + DatabaseName, Status) values ( - @shardId, - 1, - @shardVersion, - @shardMapId, - null, - @protocol, - @serverName, - @port, - @databaseName, - @shardStatus) + @shardId, + 1, + @shardVersion, + @shardMapId, + null, + @protocol, + @serverName, + @port, + @databaseName, + @shardStatus) end try begin catch if (error_number() = 2627) @@ -2857,14 +2868,14 @@ begin set @errorProcedure = isnull(error_procedure(), '-') select @errorMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, Message: ' + @errorMessage; - + raiserror (@errorMessage, @errorSeverity, 2, @errorNumber, @errorSeverity, @errorState, @errorProcedure, @errorLine); - + rollback transaction; -- To avoid extra error message in response. goto Error_UnexpectedError; end end catch - + set @result = 1 goto Exit_Procedure; @@ -2903,22 +2914,22 @@ create procedure __ShardManagement.spDetachShardGlobal @result int output as begin - declare @gsmVersionMajorClient int, + declare @gsmVersionMajorClient int, @gsmVersionMinorClient int, @protocol int, @serverName nvarchar(128), @port int, @databaseName nvarchar(128), @name nvarchar(50) - + select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @protocol = x.value('(Location/Protocol)[1]', 'int'), @serverName = x.value('(Location/ServerName)[1]', 'nvarchar(128)'), @port = x.value('(Location/Port)[1]', 'int'), @databaseName = x.value('(Location/DatabaseName)[1]', 'nvarchar(128)'), - @name = x.value('(Shardmap[@Null="0"]/Name)[1]', 'nvarchar(50)') + @name = x.value('(Shardmap[@Null=""0""]/Name)[1]', 'nvarchar(50)') from @input.nodes('/DetachShardGlobal') as t(x) @@ -2931,41 +2942,41 @@ begin declare @tvShardsToDetach table (ShardMapId uniqueidentifier, ShardId uniqueidentifier) -- note the detached shards - insert into + insert into @tvShardsToDetach - select + select tShardMaps.ShardMapId, tShards.ShardId from - __ShardManagement.ShardMapsGlobal tShardMaps + __ShardManagement.ShardMapsGlobal tShardMaps join __ShardManagement.ShardsGlobal tShards - on - tShards.ShardMapId = tShardMaps.ShardMapId and + on + tShards.ShardMapId = tShardMaps.ShardMapId and tShards.Protocol = @protocol and - tShards.ServerName = @serverName and + tShards.ServerName = @serverName and tShards.Port = @port and tShards.DatabaseName = @databaseName where @name is null or tShardMaps.Name = @name -- remove all mappings - delete - tShardMappings + delete + tShardMappings from - __ShardManagement.ShardMappingsGlobal tShardMappings + __ShardManagement.ShardMappingsGlobal tShardMappings join @tvShardsToDetach tShardsToDetach - on + on tShardsToDetach.ShardMapId = tShardMappings.ShardMapId and tShardsToDetach.ShardId = tShardMappings.ShardId -- remove all shards - delete + delete tShards from - __ShardManagement.ShardsGlobal tShards + __ShardManagement.ShardsGlobal tShards join @tvShardsToDetach tShardsToDetach - on + on tShardsToDetach.ShardMapId = tShards.ShardMapId and tShardsToDetach.ShardId = tShards.ShardId set @result = 1 @@ -2994,22 +3005,22 @@ create procedure __ShardManagement.spReplaceShardMappingsGlobal @result int output as begin - declare @gsmVersionMajorClient int, + declare @gsmVersionMajorClient int, @gsmVersionMinorClient int, @removeStepsCount int, @addStepsCount int, @shardMapId uniqueidentifier - + -- get operation information as well as number of steps information select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @removeStepsCount = x.value('(@RemoveStepsCount)[1]', 'int'), @addStepsCount = x.value('(@AddStepsCount)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier') from @input.nodes('ReplaceShardMappingsGlobal') as t(x) - + if (@gsmVersionMajorClient is null or @gsmVersionMinorClient is null or @removeStepsCount is null or @addStepsCount is null or @shardMapId is null) goto Error_MissingParameters; @@ -3018,9 +3029,9 @@ begin -- check if shard map exists if not exists ( - select - ShardMapId - from + select + ShardMapId + from __ShardManagement.ShardMapsGlobal with (updlock) where ShardMapId = @shardMapId) @@ -3033,26 +3044,26 @@ begin if (@removeStepsCount > 0) begin -- read the shard information for removes - select + select @stepShardId = x.value('(Shard/Id)[1]', 'uniqueidentifier') - from + from @input.nodes('ReplaceShardMappingsGlobal/RemoveSteps') as t(x) if (@stepShardId is null) goto Error_MissingParameters; - + declare @currentRemoveStep xml, @removeStepIndex int = 1 while (@removeStepIndex <= @removeStepsCount) begin - select - @currentRemoveStep = x.query('(./Step[@Id = sql:variable("@removeStepIndex")])[1]') + select + @currentRemoveStep = x.query('(./Step[@Id = sql:variable(""@removeStepIndex"")])[1]') from @input.nodes('ReplaceShardMappingsGlobal/RemoveSteps') as t(x) -- read the remove step - select + select @stepMappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier') from @currentRemoveStep.nodes('./Step') as t(x) @@ -3060,7 +3071,7 @@ begin if (@stepMappingId is null) goto Error_MissingParameters; - delete from + delete from __ShardManagement.ShardMappingsGlobal where ShardMapId = @shardMapId and MappingId = @stepMappingId and ShardId = @stepShardId @@ -3079,9 +3090,9 @@ begin if (@addStepsCount > 0) begin -- read the shard information for removes - select + select @stepShardId = x.value('(Shard/Id)[1]', 'uniqueidentifier') - from + from @input.nodes('ReplaceShardMappingsGlobal/AddSteps') as t(x) if (@stepShardId is null) @@ -3092,44 +3103,44 @@ begin @stepMinValue varbinary(128), @stepMaxValue varbinary(128), @stepStatus int - + while (@addStepIndex <= @addStepsCount) begin - select - @currentAddStep = x.query('(./Step[@Id = sql:variable("@addStepIndex")])[1]') + select + @currentAddStep = x.query('(./Step[@Id = sql:variable(""@addStepIndex"")])[1]') from @input.nodes('ReplaceShardMappingsGlobal/AddSteps') as t(x) - + select @stepMappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier'), @stepMinValue = convert(varbinary(128), x.value('(Mapping/MinValue)[1]', 'varchar(258)'), 1), - @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null="0"])[1]', 'varchar(258)'), 1), + @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null=""0""])[1]', 'varchar(258)'), 1), @stepStatus = x.value('(Mapping/Status)[1]', 'int') from @currentAddStep.nodes('./Step') as t(x) - + if (@stepMappingId is null or @stepMinValue is null or @stepStatus is null) goto Error_MissingParameters; -- add mapping insert into __ShardManagement.ShardMappingsGlobal( - MappingId, + MappingId, Readable, - ShardId, - ShardMapId, - OperationId, - MinValue, - MaxValue, + ShardId, + ShardMapId, + OperationId, + MinValue, + MaxValue, Status) values ( - @stepMappingId, + @stepMappingId, 1, - @stepShardId, - @shardMapId, - null, - @stepMinValue, - @stepMaxValue, + @stepShardId, + @shardMapId, + null, + @stepMinValue, + @stepMaxValue, @stepStatus) -- reset state for next iteration @@ -3166,3 +3177,6 @@ go -- update version as 1.1 insert into __ShardManagement.ShardMapManagerGlobal values (1, 1) go +"); + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.1To1.2.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.1To1.2.cs similarity index 85% rename from Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.1To1.2.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.1To1.2.cs index d2fe547..5ddd4d4 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.1To1.2.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1.1To1.2.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal static readonly UpgradeScript UpgradeShardMapManagerGlobalFrom1_1To1_2 = new UpgradeScript(1, 1, @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -26,7 +37,7 @@ create procedure __ShardManagement.spLockOrUnlockShardMappingsGlobal @result int output as begin - declare @gsmVersionMajorClient int, + declare @gsmVersionMajorClient int, @gsmVersionMinorClient int, @shardMapId uniqueidentifier, @mappingId uniqueidentifier, @@ -34,7 +45,7 @@ begin @lockOperationType int select - @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), + @gsmVersionMajorClient = x.value('(GsmVersion/MajorVersion)[1]', 'int'), @gsmVersionMinorClient = x.value('(GsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @mappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier'), @@ -53,9 +64,9 @@ begin goto Error_MissingParameters; if not exists ( - select - ShardMapId - from + select + ShardMapId + from __ShardManagement.ShardMapsGlobal with (updlock) where ShardMapId = @shardMapId) @@ -65,14 +76,14 @@ begin @currentOperationId uniqueidentifier if (@lockOperationType < 2) - begin + begin declare @ForceUnLockLockOwnerId uniqueidentifier = 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF', @currentLockOwnerId uniqueidentifier - select + select @currentOperationId = OperationId, @currentLockOwnerId = LockOwnerId - from + from __ShardManagement.ShardMappingsGlobal with (updlock) where ShardMapId = @shardMapId and MappingId = @mappingId @@ -92,16 +103,16 @@ begin update __ShardManagement.ShardMappingsGlobal - set - LockOwnerId = case - when - @lockOperationType = 0 - then - @lockOwnerId - when + set + LockOwnerId = case + when + @lockOperationType = 0 + then + @lockOwnerId + when @lockOperationType = 1 or @lockOperationType = 2 or @lockOperationType = 3 - then - @DefaultLockOwnerId + then + @DefaultLockOwnerId end where ShardMapId = @shardMapId and (@lockOperationType = 3 or -- unlock all mappings @@ -149,10 +160,13 @@ go -- update version as 1.2 update - __ShardManagement.ShardMapManagerGlobal -set + __ShardManagement.ShardMapManagerGlobal +set StoreVersionMinor = 2 where StoreVersionMajor = 1 and StoreVersionMinor = 1 go +"); + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1000.0To1000.1.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1000.0To1000.1.cs similarity index 59% rename from Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1000.0To1000.1.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1000.0To1000.1.cs index 5bdc235..f40b4cc 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1000.0To1000.1.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerGlobalFrom1000.0To1000.1.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal static readonly UpgradeScript UpgradeShardMapManagerGlobalFrom1000_0To1000_1 = new UpgradeScript(1000, 0, @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -11,3 +22,6 @@ begin alter table __ShardManagement.ShardMapManagerGlobal drop column UpgradeLock end go +"); + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom0.0To1.0.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom0.0To1.0.cs similarity index 52% rename from Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom0.0To1.0.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom0.0To1.0.cs index 483514d..7c8d936 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom0.0To1.0.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom0.0To1.0.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal static readonly UpgradeScript UpgradeShardMapManagerLocalFrom0_0To1_0 = new UpgradeScript(0, 0, @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -8,3 +19,6 @@ -- add a column to ShardMapManagerLocal table to hold SCH-M lock during upgrade alter table __ShardManagement.ShardMapManagerLocal add UpgradeLock int null go +"); + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.0To1.1.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.0To1.1.cs similarity index 88% rename from Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.0To1.1.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.0To1.1.cs index f734a21..24f2039 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.0To1.1.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.0To1.1.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal static readonly UpgradeScript UpgradeShardMapManagerLocalFrom1_0To1_1 = new UpgradeScript(1, 0, @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -5,7 +16,7 @@ -- Script to upgrade Local Shard Map from version 1.0 to 1.1 --------------------------------------------------------------------------------------------------- --- drop ShardMapManagerLocal table +-- drop ShardMapManagerLocal table drop table __ShardManagement.ShardMapManagerLocal -- create ShardMapManagerLocal table with new column names @@ -33,61 +44,61 @@ go if object_id(N'__ShardManagement.spGetAllShardsLocal', N'P') is not null begin drop procedure __ShardManagement.spGetAllShardsLocal -end +end go if object_id(N'__ShardManagement.spValidateShardLocal', N'P') is not null begin drop procedure __ShardManagement.spValidateShardLocal -end +end go if object_id(N'__ShardManagement.spAddShardLocal', N'P') is not null begin drop procedure __ShardManagement.spAddShardLocal -end +end go if object_id(N'__ShardManagement.spRemoveShardLocal', N'P') is not null begin drop procedure __ShardManagement.spRemoveShardLocal -end +end go if object_id(N'__ShardManagement.spUpdateShardLocal', N'P') is not null begin drop procedure __ShardManagement.spUpdateShardLocal -end +end go if object_id(N'__ShardManagement.spGetAllShardMappingsLocal', N'P') is not null begin drop procedure __ShardManagement.spGetAllShardMappingsLocal -end +end go if object_id(N'__ShardManagement.spFindShardMappingByKeyLocal', N'P') is not null begin drop procedure __ShardManagement.spFindShardMappingByKeyLocal -end +end go if object_id(N'__ShardManagement.spValidateShardMappingLocal', N'P') is not null begin drop procedure __ShardManagement.spValidateShardMappingLocal -end +end go if object_id(N'__ShardManagement.spBulkOperationShardMappingsLocal', N'P') is not null begin drop procedure __ShardManagement.spBulkOperationShardMappingsLocal -end +end go if object_id(N'__ShardManagement.spKillSessionsForShardMappingLocal', N'P') is not null begin drop procedure __ShardManagement.spKillSessionsForShardMappingLocal -end +end go -- create new objects for version 1.1 @@ -111,7 +122,7 @@ as begin select 5, StoreVersionMajor, StoreVersionMinor - from + from __ShardManagement.ShardMapManagerLocal end go @@ -128,10 +139,10 @@ begin declare @lsmVersionMajorClient int, @lsmVersionMinorClient int - select + select @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int') - from + from @input.nodes('/GetAllShardsLocal') as t(x) if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null) @@ -141,14 +152,14 @@ begin goto Error_LSMVersionMismatch; -- shard maps - select + select 1, ShardMapId, Name, MapType, KeyType - from + from __ShardManagement.ShardMapsLocal -- shards - select - 2, ShardId, Version, ShardMapId, Protocol, ServerName, Port, DatabaseName, Status + select + 2, ShardId, Version, ShardMapId, Protocol, ServerName, Port, DatabaseName, Status from __ShardManagement.ShardsLocal @@ -169,7 +180,7 @@ Success_Exit: goto Exit_Procedure; Exit_Procedure: -end +end go --------------------------------------------------------------------------------------------------- @@ -186,13 +197,13 @@ begin @shardMapId uniqueidentifier, @shardId uniqueidentifier, @shardVersion uniqueidentifier - select - @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), + select + @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMapId)[1]', 'uniqueidentifier'), @shardId = x.value('(ShardId)[1]', 'uniqueidentifier'), @shardVersion = x.value('(ShardVersion)[1]', 'uniqueidentifier') - from + from @input.nodes('/ValidateShardLocal') as t(x) if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @shardMapId is null or @shardId is null or @shardVersion is null) @@ -203,12 +214,12 @@ begin -- find shard map declare @currentShardMapId uniqueidentifier - - select - @currentShardMapId = ShardMapId - from + + select + @currentShardMapId = ShardMapId + from __ShardManagement.ShardMapsLocal - where + where ShardMapId = @shardMapId if (@currentShardMapId is null) @@ -216,11 +227,11 @@ begin declare @currentShardVersion uniqueidentifier - select - @currentShardVersion = Version - from + select + @currentShardVersion = Version + from __ShardManagement.ShardsLocal - where + where ShardMapId = @shardMapId and ShardId = @shardId if (@currentShardVersion is null) @@ -255,7 +266,7 @@ Error_LSMVersionMismatch: goto Exit_Procedure; Exit_Procedure: -end +end go --------------------------------------------------------------------------------------------------- @@ -267,7 +278,7 @@ create procedure __ShardManagement.spAddShardLocal @result int output as begin - declare @lsmVersionMajorClient int, + declare @lsmVersionMajorClient int, @lsmVersionMinorClient int, @operationId uniqueidentifier, @shardMapId uniqueidentifier, @@ -282,8 +293,8 @@ begin @databaseName nvarchar(128), @shardStatus int - select - @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), + select + @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @@ -297,11 +308,11 @@ begin @port = x.value('(Shard/Location/Port)[1]', 'int'), @databaseName = x.value('(Shard/Location/DatabaseName)[1]', 'nvarchar(128)'), @shardStatus = x.value('(Shard/Status)[1]', 'int') - from + from @input.nodes('/AddShardLocal') as t(x) - if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @shardMapId is null or @operationId is null or @name is null or @sm_kind is null or @sm_keykind is null or - @shardId is null or @shardVersion is null or @protocol is null or @serverName is null or + if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @shardMapId is null or @operationId is null or @name is null or @sm_kind is null or @sm_keykind is null or + @shardId is null or @shardVersion is null or @protocol is null or @serverName is null or @port is null or @databaseName is null or @shardStatus is null) goto Error_MissingParameters; @@ -310,7 +321,7 @@ begin -- check for reentrancy if exists ( - select + select ShardMapId from __ShardManagement.ShardMapsLocal @@ -319,34 +330,34 @@ begin goto Success_Exit; -- add shard map row - insert into - __ShardManagement.ShardMapsLocal + insert into + __ShardManagement.ShardMapsLocal (ShardMapId, Name, MapType, KeyType, LastOperationId) - values - (@shardMapId, @name, @sm_kind, @sm_keykind, @operationId) + values + (@shardMapId, @name, @sm_kind, @sm_keykind, @operationId) -- add shard row - insert into + insert into __ShardManagement.ShardsLocal( - ShardId, - Version, - ShardMapId, - Protocol, - ServerName, - Port, - DatabaseName, + ShardId, + Version, + ShardMapId, + Protocol, + ServerName, + Port, + DatabaseName, Status, LastOperationId) values ( - @shardId, - @shardVersion, + @shardId, + @shardVersion, @shardMapId, - @protocol, - @serverName, - @port, - @databaseName, + @protocol, + @serverName, + @port, + @databaseName, @shardStatus, - @operationId) + @operationId) goto Success_Exit; @@ -363,9 +374,9 @@ Error_LSMVersionMismatch: Success_Exit: set @result = 1 goto Exit_Procedure; - + Exit_Procedure: -end +end go --------------------------------------------------------------------------------------------------- @@ -377,19 +388,19 @@ create procedure __ShardManagement.spRemoveShardLocal @result int output as begin - declare @lsmVersionMajorClient int, + declare @lsmVersionMajorClient int, @lsmVersionMinorClient int, @operationId uniqueidentifier, @shardMapId uniqueidentifier, @shardId uniqueidentifier - select + select @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @shardId = x.value('(Shard/Id)[1]', 'uniqueidentifier') - from + from @input.nodes('/RemoveShardLocal') as t(x) if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @operationId is null or @shardMapId is null or @shardId is null) @@ -400,13 +411,13 @@ begin -- remove shard row delete from - __ShardManagement.ShardsLocal + __ShardManagement.ShardsLocal where ShardMapId = @shardMapId and ShardId = @shardId -- remove shard map row delete from - __ShardManagement.ShardMapsLocal + __ShardManagement.ShardMapsLocal where ShardMapId = @shardMapId @@ -424,7 +435,7 @@ Error_LSMVersionMismatch: goto Exit_Procedure; Exit_Procedure: -end +end go --------------------------------------------------------------------------------------------------- @@ -436,7 +447,7 @@ create procedure __ShardManagement.spUpdateShardLocal @result int output as begin - declare @lsmVersionMajorClient int, + declare @lsmVersionMajorClient int, @lsmVersionMinorClient int, @operationId uniqueidentifier, @shardMapId uniqueidentifier, @@ -444,7 +455,7 @@ begin @shardVersion uniqueidentifier, @shardStatus int - select + select @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @@ -452,7 +463,7 @@ begin @shardId = x.value('(Shard/Id)[1]', 'uniqueidentifier'), @shardVersion = x.value('(Shard/Version)[1]', 'uniqueidentifier'), @shardStatus = x.value('(Shard/Status)[1]', 'int') - from + from @input.nodes('/UpdateShardLocal') as t(x) if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @operationId is null or @shardMapId is null or @shardId is null or @shardVersion is null or @shardStatus is null) @@ -461,7 +472,7 @@ begin if (@lsmVersionMajorClient <> __ShardManagement.fnGetStoreVersionMajorLocal()) goto Error_LSMVersionMismatch; - update + update __ShardManagement.ShardsLocal set Version = @shardVersion, @@ -484,7 +495,7 @@ Error_LSMVersionMismatch: goto Exit_Procedure; Exit_Procedure: -end +end go --------------------------------------------------------------------------------------------------- @@ -496,21 +507,21 @@ create procedure __ShardManagement.spGetAllShardMappingsLocal @result int output as begin - declare @lsmVersionMajorClient int, + declare @lsmVersionMajorClient int, @lsmVersionMinorClient int, @shardMapId uniqueidentifier, @shardId uniqueidentifier, @minValue varbinary(128), @maxValue varbinary(128) - select + select @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @shardId = x.value('(Shard/Id)[1]', 'uniqueidentifier'), - @minValue = convert(varbinary(128), x.value('(Range[@Null="0"]/MinValue)[1]', 'varchar(258)'), 1), - @maxValue = convert(varbinary(128), x.value('(Range[@Null="0"]/MaxValue[@Null="0"])[1]', 'varchar(258)'), 1) - from + @minValue = convert(varbinary(128), x.value('(Range[@Null=""0""]/MinValue)[1]', 'varchar(258)'), 1), + @maxValue = convert(varbinary(128), x.value('(Range[@Null=""0""]/MaxValue[@Null=""0""])[1]', 'varchar(258)'), 1) + from @input.nodes('/GetAllShardMappingsLocal') as t(x) if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @shardMapId is null or @shardId is null) @@ -521,7 +532,7 @@ begin declare @mapType int - select + select @mapType = MapType from __ShardManagement.ShardMapsLocal @@ -542,41 +553,41 @@ begin set @maxValueCalculated = @maxValue if (@mapType = 1) - begin - select + begin + select 3, m.MappingId, m.ShardMapId, m.MinValue, m.MaxValue, m.Status, m.LockOwnerId, -- fields for SqlMapping s.ShardId, s.Version, s.ShardMapId, s.Protocol, s.ServerName, s.Port, s.DatabaseName, s.Status -- fields for SqlShard, ShardMapId is repeated here - from - __ShardManagement.ShardMappingsLocal m - join - __ShardManagement.ShardsLocal s - on + from + __ShardManagement.ShardMappingsLocal m + join + __ShardManagement.ShardsLocal s + on m.ShardId = s.ShardId where - m.ShardMapId = @shardMapId and - m.ShardId = @shardId and - MinValue >= @minValueCalculated and + m.ShardMapId = @shardMapId and + m.ShardId = @shardId and + MinValue >= @minValueCalculated and ((@maxValueCalculated is null) or (MinValue < @maxValueCalculated)) - order by + order by m.MinValue end else begin - select + select 3, m.MappingId, m.ShardMapId, m.MinValue, m.MaxValue, m.Status, m.LockOwnerId, -- fields for SqlMapping s.ShardId, s.Version, s.ShardMapId, s.Protocol, s.ServerName, s.Port, s.DatabaseName, s.Status -- fields for SqlShard, ShardMapId is repeated here - from - __ShardManagement.ShardMappingsLocal m - join - __ShardManagement.ShardsLocal s - on + from + __ShardManagement.ShardMappingsLocal m + join + __ShardManagement.ShardsLocal s + on m.ShardId = s.ShardId where - m.ShardMapId = @shardMapId and - m.ShardId = @shardId and - ((MaxValue is null) or (MaxValue > @minValueCalculated)) and + m.ShardMapId = @shardMapId and + m.ShardId = @shardId and + ((MaxValue is null) or (MaxValue > @minValueCalculated)) and ((@maxValueCalculated is null) or (MinValue < @maxValueCalculated)) - order by + order by m.MinValue end @@ -598,7 +609,7 @@ Error_LSMVersionMismatch: goto Exit_Procedure; Exit_Procedure: -end +end go --------------------------------------------------------------------------------------------------- @@ -615,14 +626,14 @@ begin @shardMapId uniqueidentifier, @keyValue varbinary(128) - select + select @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int'), @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @keyValue = convert(varbinary(128), x.value('(Key/Value)[1]', 'varchar(258)'), 1) - from + from @input.nodes('/FindShardMappingByKeyLocal') as t(x) - + if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @shardMapId is null or @keyValue is null) goto Error_MissingParameters; @@ -631,7 +642,7 @@ begin declare @mapType int - select + select @mapType = MapType from __ShardManagement.ShardMapsLocal @@ -642,33 +653,33 @@ begin goto Error_ShardMapNotFound; if (@mapType = 1) - begin + begin select 3, m.MappingId, m.ShardMapId, m.MinValue, m.MaxValue, m.Status, m.LockOwnerId, -- fields for SqlMapping s.ShardId, s.Version, s.ShardMapId, s.Protocol, s.ServerName, s.Port, s.DatabaseName, s.Status -- fields for SqlShard, ShardMapId is repeated here from __ShardManagement.ShardMappingsLocal m - join + join __ShardManagement.ShardsLocal s - on + on m.ShardId = s.ShardId where - m.ShardMapId = @shardMapId and + m.ShardMapId = @shardMapId and m.MinValue = @keyValue end else begin - select + select 3, m.MappingId, m.ShardMapId, m.MinValue, m.MaxValue, m.Status, m.LockOwnerId, -- fields for SqlMapping s.ShardId, s.Version, s.ShardMapId, s.Protocol, s.ServerName, s.Port, s.DatabaseName, s.Status -- fields for SqlShard, ShardMapId is repeated here - from - __ShardManagement.ShardMappingsLocal m - join - __ShardManagement.ShardsLocal s - on + from + __ShardManagement.ShardMappingsLocal m + join + __ShardManagement.ShardsLocal s + on m.ShardId = s.ShardId where - m.ShardMapId = @shardMapId and + m.ShardMapId = @shardMapId and m.MinValue <= @keyValue and (m.MaxValue is null or m.MaxValue > @keyValue) end @@ -697,7 +708,7 @@ Error_LSMVersionMismatch: goto Exit_Procedure; Exit_Procedure: -end +end go --------------------------------------------------------------------------------------------------- @@ -730,12 +741,12 @@ begin -- find shard map declare @currentShardMapId uniqueidentifier - - select - @currentShardMapId = ShardMapId - from + + select + @currentShardMapId = ShardMapId + from __ShardManagement.ShardMapsLocal - where + where ShardMapId = @shardMapId if (@currentShardMapId is null) @@ -743,13 +754,13 @@ begin declare @m_status_current int - select + select @m_status_current = Status from __ShardManagement.ShardMappingsLocal where ShardMapId = @shardMapId and MappingId = @mappingId - + if (@m_status_current is null) goto Error_MappingDoesNotExist; @@ -782,7 +793,7 @@ Error_LSMVersionMismatch: goto Exit_Procedure; Exit_Procedure: -end +end go --------------------------------------------------------------------------------------------------- @@ -805,7 +816,7 @@ begin @shardVersion uniqueidentifier -- get operation information as well as number of steps information - select + select @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @@ -813,7 +824,7 @@ begin @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @shardId = x.value('(Shard/Id)[1]', 'uniqueidentifier'), @shardVersion = x.value('(Shard/Version)[1]', 'uniqueidentifier') - from + from @input.nodes('/BulkOperationShardMappingsLocal') as t(x) if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @operationId is null or @stepsCount is null or @shardMapId is null or @shardId is null or @shardVersion is null) @@ -824,7 +835,7 @@ begin -- check for reentrancy if exists ( - select + select ShardId from __ShardManagement.ShardsLocal @@ -847,9 +858,9 @@ begin while (@stepIndex <= @stepsCount) begin - select - @currentStep = x.query('(./Step[@Id = sql:variable("@stepIndex")])[1]') - from + select + @currentStep = x.query('(./Step[@Id = sql:variable(""@stepIndex"")])[1]') + from @input.nodes('/BulkOperationShardMappingsLocal/Steps') as t(x) -- Identify the step type. @@ -858,7 +869,7 @@ begin @stepMappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier') from @currentStep.nodes('./Step') as t(x) - + if (@stepType is null or @stepMappingId is null) goto Error_MissingParameters; @@ -878,9 +889,9 @@ begin @stepMappingStatus int -- AddMapping - select + select @stepMinValue = convert(varbinary(128), x.value('(Mapping/MinValue)[1]', 'varchar(258)'), 1), - @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null="0"])[1]', 'varchar(258)'), 1), + @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null=""0""])[1]', 'varchar(258)'), 1), @stepMappingStatus = x.value('(Mapping/Status)[1]', 'int') from @currentStep.nodes('./Step') as t(x) @@ -891,19 +902,19 @@ begin -- add mapping insert into __ShardManagement.ShardMappingsLocal - (MappingId, - ShardId, - ShardMapId, - MinValue, - MaxValue, + (MappingId, + ShardId, + ShardMapId, + MinValue, + MaxValue, Status, LastOperationId) values - (@stepMappingId, - @shardId, - @shardMapId, - @stepMinValue, - @stepMaxValue, + (@stepMappingId, + @shardId, + @shardMapId, + @stepMinValue, + @stepMaxValue, @stepMappingStatus, @operationId) @@ -934,9 +945,9 @@ Error_LSMVersionMismatch: Success_Exit: set @result = 1 goto Exit_Procedure; - + Exit_Procedure: -end +end go --------------------------------------------------------------------------------------------------- @@ -953,11 +964,11 @@ begin @patternForKill nvarchar(128) -- get operation information as well as number of steps information - select + select @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int'), @patternForKill = x.value('(Pattern)[1]', 'nvarchar(128)') - from + from @input.nodes('/KillSessionsForShardMappingLocal') as t(x) if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @patternForKill is null) @@ -969,31 +980,31 @@ begin declare @tvKillCommands table (spid smallint primary key, commandForKill nvarchar(10)) -- insert empty row - insert into - @tvKillCommands (spid, commandForKill) - values + insert into + @tvKillCommands (spid, commandForKill) + values (0, N'') - insert into - @tvKillCommands(spid, commandForKill) - select + insert into + @tvKillCommands(spid, commandForKill) + select session_id, 'kill ' + convert(nvarchar(10), session_id) - from - sys.dm_exec_sessions - where + from + sys.dm_exec_sessions + where session_id > 50 and program_name like '%' + @patternForKill + '%' - declare @currentSpid int, + declare @currentSpid int, @currentCommandForKill nvarchar(10) declare @current_error int - select top 1 - @currentSpid = spid, - @currentCommandForKill = commandForKill - from - @tvKillCommands - order by + select top 1 + @currentSpid = spid, + @currentCommandForKill = commandForKill + from + @tvKillCommands + order by spid desc while (@currentSpid > 0) @@ -1003,18 +1014,18 @@ begin exec (@currentCommandForKill) -- remove the current row - delete - @tvKillCommands - where + delete + @tvKillCommands + where spid = @currentSpid -- get next row - select top 1 - @currentSpid = spid, - @currentCommandForKill = commandForKill - from - @tvKillCommands - order by + select top 1 + @currentSpid = spid, + @currentCommandForKill = commandForKill + from + @tvKillCommands + order by spid desc end try begin catch @@ -1026,7 +1037,7 @@ begin set @result = 1 goto Exit_Procedure; - + Error_UnableToKillSessions: set @result = 305 goto Exit_Procedure; @@ -1042,9 +1053,12 @@ Error_LSMVersionMismatch: goto Exit_Procedure; Exit_Procedure: -end +end go -- update version as 1.1 insert into __ShardManagement.ShardMapManagerLocal values (1, 1) go +"); + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.1To1.2.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.1To1.2.cs similarity index 89% rename from Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.1To1.2.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.1To1.2.cs index eb79a4b..2c35633 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.1To1.2.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1.1To1.2.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal static readonly UpgradeScript UpgradeShardMapManagerLocalFrom1_1To1_2 = new UpgradeScript(1, 1, @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -10,19 +21,19 @@ if object_id(N'__ShardManagement.spUpdateShardLocal', N'P') is not null begin drop procedure __ShardManagement.spUpdateShardLocal -end +end go if object_id(N'__ShardManagement.spBulkOperationShardMappingsLocal', N'P') is not null begin drop procedure __ShardManagement.spBulkOperationShardMappingsLocal -end +end go if object_id(N'__ShardManagement.spAddShardLocal', N'P') is not null begin drop procedure __ShardManagement.spAddShardLocal -end +end go -- create new objects for version 1.2 @@ -36,7 +47,7 @@ create procedure __ShardManagement.spUpdateShardLocal @result int output as begin - declare @lsmVersionMajorClient int, + declare @lsmVersionMajorClient int, @lsmVersionMinorClient int, @operationId uniqueidentifier, @shardMapId uniqueidentifier, @@ -48,7 +59,7 @@ begin @databaseName nvarchar(128), @shardStatus int - select + select @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @@ -60,10 +71,10 @@ begin @port = x.value('(Shard/Location/Port)[1]', 'int'), @databaseName = x.value('(Shard/Location/DatabaseName)[1]', 'nvarchar(128)'), @shardStatus = x.value('(Shard/Status)[1]', 'int') - from + from @input.nodes('/UpdateShardLocal') as t(x) - if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @operationId is null or + if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @operationId is null or @shardMapId is null or @shardId is null or @shardVersion is null or @shardStatus is null or @protocol is null or @serverName is null or @port is null or @databaseName is null) goto Error_MissingParameters; @@ -71,7 +82,7 @@ begin if (@lsmVersionMajorClient <> __ShardManagement.fnGetStoreVersionMajorLocal()) goto Error_LSMVersionMismatch; - update + update __ShardManagement.ShardsLocal set Version = @shardVersion, @@ -105,7 +116,7 @@ Error_ShardDoesNotExist: goto Exit_Procedure; Exit_Procedure: -end +end go --------------------------------------------------------------------------------------------------- @@ -129,7 +140,7 @@ begin @shardVersion uniqueidentifier -- get operation information as well as number of steps information - select + select @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @@ -138,7 +149,7 @@ begin @shardMapId = x.value('(ShardMap/Id)[1]', 'uniqueidentifier'), @shardId = x.value('(Shard/Id)[1]', 'uniqueidentifier'), @shardVersion = x.value('(Shard/Version)[1]', 'uniqueidentifier') - from + from @input.nodes('/BulkOperationShardMappingsLocal') as t(x) if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @operationId is null or @stepsCount is null or @shardMapId is null or @shardId is null or @shardVersion is null) @@ -149,7 +160,7 @@ begin -- check for reentrancy if exists ( - select + select ShardId from __ShardManagement.ShardsLocal @@ -172,9 +183,9 @@ begin while (@stepIndex <= @stepsCount) begin - select - @currentStep = x.query('(./Step[@Id = sql:variable("@stepIndex")])[1]') - from + select + @currentStep = x.query('(./Step[@Id = sql:variable(""@stepIndex"")])[1]') + from @input.nodes('/BulkOperationShardMappingsLocal/Steps') as t(x) -- Identify the step type. @@ -183,7 +194,7 @@ begin @stepMappingId = x.value('(Mapping/Id)[1]', 'uniqueidentifier') from @currentStep.nodes('./Step') as t(x) - + if (@stepType is null or @stepMappingId is null) goto Error_MissingParameters; @@ -203,9 +214,9 @@ begin @stepMappingStatus int -- AddMapping - select + select @stepMinValue = convert(varbinary(128), x.value('(Mapping/MinValue)[1]', 'varchar(258)'), 1), - @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null="0"])[1]', 'varchar(258)'), 1), + @stepMaxValue = convert(varbinary(128), x.value('(Mapping/MaxValue[@Null=""0""])[1]', 'varchar(258)'), 1), @stepMappingStatus = x.value('(Mapping/Status)[1]', 'int') from @currentStep.nodes('./Step') as t(x) @@ -217,19 +228,19 @@ begin begin try insert into __ShardManagement.ShardMappingsLocal - (MappingId, - ShardId, - ShardMapId, - MinValue, - MaxValue, + (MappingId, + ShardId, + ShardMapId, + MinValue, + MaxValue, Status, LastOperationId) values - (@stepMappingId, - @shardId, - @shardMapId, - @stepMinValue, - @stepMaxValue, + (@stepMappingId, + @shardId, + @shardMapId, + @stepMinValue, + @stepMaxValue, @stepMappingStatus, @operationId) end try @@ -242,7 +253,7 @@ begin @errorState int = error_state(), @errorLine int = error_line(), @errorProcedure nvarchar(128) = isnull(error_procedure(), '-'); - + select @errorMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, Message: ' + @errorMessage raiserror (@errorMessage, @errorSeverity, 1, @errorNumber, @errorSeverity, @errorState, @errorProcedure, @errorLine); rollback transaction; -- To avoid extra error message in response. @@ -282,9 +293,9 @@ Error_UnexpectedError: Success_Exit: set @result = 1 goto Exit_Procedure; - + Exit_Procedure: -end +end go --------------------------------------------------------------------------------------------------- @@ -296,7 +307,7 @@ create procedure __ShardManagement.spAddShardLocal @result int output as begin - declare @lsmVersionMajorClient int, + declare @lsmVersionMajorClient int, @lsmVersionMinorClient int, @operationId uniqueidentifier, @undo int, @@ -317,8 +328,8 @@ begin @errorState int, @errorLine int, @errorProcedure nvarchar(128) - select - @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), + select + @lsmVersionMajorClient = x.value('(LsmVersion/MajorVersion)[1]', 'int'), @lsmVersionMinorClient = x.value('(LsmVersion/MinorVersion)[1]', 'int'), @operationId = x.value('(@OperationId)[1]', 'uniqueidentifier'), @undo = x.value('(@Undo)[1]', 'int'), @@ -333,11 +344,11 @@ begin @port = x.value('(Shard/Location/Port)[1]', 'int'), @databaseName = x.value('(Shard/Location/DatabaseName)[1]', 'nvarchar(128)'), @shardStatus = x.value('(Shard/Status)[1]', 'int') - from + from @input.nodes('/AddShardLocal') as t(x) - if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @shardMapId is null or @operationId is null or @name is null or @sm_kind is null or @sm_keykind is null or - @shardId is null or @shardVersion is null or @protocol is null or @serverName is null or + if (@lsmVersionMajorClient is null or @lsmVersionMinorClient is null or @shardMapId is null or @operationId is null or @name is null or @sm_kind is null or @sm_keykind is null or + @shardId is null or @shardVersion is null or @protocol is null or @serverName is null or @port is null or @databaseName is null or @shardStatus is null) goto Error_MissingParameters; @@ -346,7 +357,7 @@ begin -- check for reentrancy if exists ( - select + select ShardMapId from __ShardManagement.ShardMapsLocal @@ -356,10 +367,10 @@ begin -- add shard map row, ignore duplicate inserts in this is part of undo operation begin try - insert into - __ShardManagement.ShardMapsLocal + insert into + __ShardManagement.ShardMapsLocal (ShardMapId, Name, MapType, KeyType, LastOperationId) - values + values (@shardMapId, @name, @sm_kind, @sm_keykind, @operationId) end try begin catch @@ -370,7 +381,7 @@ begin set @errorSeverity = error_severity(); set @errorState = error_state(); set @errorLine = error_line(); - set @errorProcedure = isnull(error_procedure(), '-'); + set @errorProcedure = isnull(error_procedure(), '-'); select @errorMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, Message: ' + @errorMessage raiserror (@errorMessage, @errorSeverity, 1, @errorNumber, @errorSeverity, @errorState, @errorProcedure, @errorLine); rollback transaction; -- To avoid extra error message in response. @@ -380,25 +391,25 @@ begin -- add shard row, ignore duplicate inserts if this is part of undo operation begin try - insert into + insert into __ShardManagement.ShardsLocal( - ShardId, - Version, - ShardMapId, - Protocol, - ServerName, - Port, - DatabaseName, + ShardId, + Version, + ShardMapId, + Protocol, + ServerName, + Port, + DatabaseName, Status, LastOperationId) values ( - @shardId, - @shardVersion, + @shardId, + @shardVersion, @shardMapId, - @protocol, - @serverName, - @port, - @databaseName, + @protocol, + @serverName, + @port, + @databaseName, @shardStatus, @operationId) end try @@ -411,13 +422,13 @@ begin set @errorState = error_state(); set @errorLine = error_line(); set @errorProcedure = isnull(error_procedure(), '-'); - + select @errorMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, Message: ' + @errorMessage raiserror (@errorMessage, @errorSeverity, 1, @errorNumber, @errorSeverity, @errorState, @errorProcedure, @errorLine); rollback transaction; -- To avoid extra error message in response. goto Error_UnexpectedError; end - end catch + end catch goto Success_Exit; @@ -438,16 +449,19 @@ Error_UnexpectedError: Success_Exit: set @result = 1 goto Exit_Procedure; - + Exit_Procedure: -end +end go -- update version as 1.2 update - __ShardManagement.ShardMapManagerLocal -set + __ShardManagement.ShardMapManagerLocal +set StoreVersionMinor = 2 where StoreVersionMajor = 1 and StoreVersionMinor = 1 go +"); + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1000.0To1000.1.sql b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1000.0To1000.1.cs similarity index 59% rename from Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1000.0To1000.1.sql rename to Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1000.0To1000.1.cs index cddae48..1083907 100644 --- a/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1000.0To1000.1.sql +++ b/Src/ElasticScale.Client/ShardManagement/Scripts/UpgradeShardMapManagerLocalFrom1000.0To1000.1.cs @@ -1,3 +1,14 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement +{ + /// + /// Utility properties and methods used for managing scripts and errors. + /// + internal static partial class Scripts + { + internal static readonly UpgradeScript UpgradeShardMapManagerLocalFrom1000_0To1000_1 = new UpgradeScript(1000, 0, @" -- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -11,3 +22,6 @@ begin alter table __ShardManagement.ShardMapManagerLocal drop column UpgradeLock end go +"); + } +} \ No newline at end of file diff --git a/Src/ElasticScale.Client/ShardManagement/Shard/ShardLocation.cs b/Src/ElasticScale.Client/ShardManagement/Shard/ShardLocation.cs index 3d37236..7adcec2 100644 --- a/Src/ElasticScale.Client/ShardManagement/Shard/ShardLocation.cs +++ b/Src/ElasticScale.Client/ShardManagement/Shard/ShardLocation.cs @@ -243,9 +243,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement { int h; - h = ShardKey.QPHash(this.Protocol.GetHashCode(), this.DataSource.ToUpper(CultureInfo.InvariantCulture).GetHashCode()); + h = ShardKey.QPHash(this.Protocol.GetHashCode(), this.DataSource.ToUpperInvariant().GetHashCode()); h = ShardKey.QPHash(h, this.Port.GetHashCode()); - h = ShardKey.QPHash(h, this.Database.ToUpper(CultureInfo.InvariantCulture).GetHashCode()); + h = ShardKey.QPHash(h, this.Database.ToUpperInvariant().GetHashCode()); return h; } diff --git a/Src/ElasticScale.Client/ShardManagement/ShardMapManager/ShardManagementException.cs b/Src/ElasticScale.Client/ShardManagement/ShardMapManager/ShardManagementException.cs index 9e8eb36..086efed 100644 --- a/Src/ElasticScale.Client/ShardManagement/ShardMapManager/ShardManagementException.cs +++ b/Src/ElasticScale.Client/ShardManagement/ShardMapManager/ShardManagementException.cs @@ -319,6 +319,8 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement this.ErrorCode = code; } + #region Serialization Support + /// /// Initializes a new instance with serialized data. /// @@ -331,7 +333,6 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement this.ErrorCode = (ShardManagementErrorCode)info.GetValue("ErrorCode", typeof(ShardManagementErrorCode)); } - #region Serialization Support /// /// Populates a SerializationInfo with the data needed to serialize the target object. diff --git a/Src/ElasticScale.Client/ShardManagement/SqlStore/SqlResults.cs b/Src/ElasticScale.Client/ShardManagement/SqlStore/SqlResults.cs index 1a65304..54a36c4 100644 --- a/Src/ElasticScale.Client/ShardManagement/SqlStore/SqlResults.cs +++ b/Src/ElasticScale.Client/ShardManagement/SqlStore/SqlResults.cs @@ -104,7 +104,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement { if (reader.FieldCount > 0) { - SqlResultType resultType = SqlResults.SqlResultTypeFromColumnName(reader.GetSchemaTable().Rows[1]["ColumnName"].ToString()); + SqlResultType resultType = SqlResults.SqlResultTypeFromColumnName(reader.GetName(1)); switch (resultType) { @@ -179,7 +179,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement { if (reader.FieldCount > 0) { - SqlResultType resultType = SqlResults.SqlResultTypeFromColumnName(reader.GetSchemaTable().Rows[1]["ColumnName"].ToString()); + SqlResultType resultType = SqlResults.SqlResultTypeFromColumnName(reader.GetName(1)); switch (resultType) { diff --git a/Src/ElasticScale.Client/ShardManagement/SqlStore/SqlStore.cs b/Src/ElasticScale.Client/ShardManagement/SqlStore/SqlStore.cs deleted file mode 100644 index 24b07bd..0000000 --- a/Src/ElasticScale.Client/ShardManagement/SqlStore/SqlStore.cs +++ /dev/null @@ -1,3863 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Data.SqlTypes; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Xml.Linq; -using Microsoft.Azure.SqlDatabase.ElasticScale.Common.TransientFaultHandling.Implementation; -using System.Xml; - -namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement -{ - /// - /// SQL based data store that persists ShardMapManager data structures. - /// - internal class SqlStore : IStore - { - /// - /// GSM version of store supported by this library. - /// - internal const int SqlStoreGsmVersion = 1; - - /// - /// LSM Minor version of store supported by this library. - /// - internal const int SqlStoreLsmVersion = 1; - - /// - /// Regular expression for go tokens. - /// - private static readonly Regex GoTokenRegularExpression = new Regex( - @"^\s*go\s*$", - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - - /// - /// Regular expression for comment lines. - /// - private static readonly Regex CommentLineRegularExpression = new Regex( - @"^\s*--", - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - - /// - /// Parsed representation of GSM existence check script. - /// - private static readonly IEnumerable CheckIfExistsGlobalScript = SqlStore.SplitScriptCommands(Scripts.CheckShardMapManagerGlobal); - - /// - /// Parsed representation of GSM creation script. - /// - private static readonly IEnumerable CreateGlobalScript = SqlStore.SplitScriptCommands(Scripts.CreateShardMapManagerGlobal); - - /// - /// Parsed representation of GSM drop script. - /// - private static readonly IEnumerable DropGlobalScript = SqlStore.SplitScriptCommands(Scripts.DropShardMapManagerGlobal); - - /// - /// Parsed represenation of Schema Info Collection script. - /// - private static readonly IEnumerable CreateSchemaInfoScript = SqlStore.SplitScriptCommands(Scripts.CreateSchemaInfoCollectionGlobal); - - /// - /// Parsed represenation of Schema Info Collection script. - /// - private static readonly IEnumerable DropSchemaInfoScript = SqlStore.SplitScriptCommands(Scripts.DropSchemaInfoCollectionGlobal); - - /// - /// Parsed representation of LSM existence check script. - /// - private static readonly IEnumerable CheckIfExistsLocalScript = SqlStore.SplitScriptCommands(Scripts.CheckShardMapManagerLocal); - - /// - /// Parsed representation of LSM creation script. - /// - private static readonly IEnumerable CreateLocalScript = SqlStore.SplitScriptCommands(Scripts.CreateShardMapManagerLocal); - - /// - /// Parsed representation of LSM drop script. - /// - private static readonly IEnumerable DropLocalScript = SqlStore.SplitScriptCommands(Scripts.DropShardMapManagerLocal); - - /// - /// SQL transient fault detection strategy. - /// - private static SqlDatabaseTransientErrorDetectionStrategy sqlTransientErrorDetector = new SqlDatabaseTransientErrorDetectionStrategy(); - - /// - /// Transient failure detector function. - /// - private static Func transientErrorDetector = (e) => - { - ShardMapManagerException smmException = null; - StoreException storeException = null; - SqlException sqlException = null; - - smmException = e as ShardMapManagerException; - - if (smmException != null) - { - storeException = smmException.InnerException as StoreException; - } - else - { - storeException = e as StoreException; - } - - if (storeException != null) - { - sqlException = storeException.InnerException as SqlException; - } - else - { - sqlException = e as SqlException; - } - - if (sqlException != null) - { - return sqlTransientErrorDetector.IsTransient(sqlException); - } - - return false; - }; - - /// - /// Credentials for store operations. - /// - private readonly SqlShardMapManagerCredentials credentials; - -#if DEBUG - - /// - /// Event to be raised on disposing global transaction scope. - /// This event is used for internal testing purpose only. - /// - internal event EventHandler SqlStoreEventGlobal; - - /// - /// Event to be raised on disposing local transaction scope. - /// This event is used for internal testing purpose only. - /// - internal event EventHandler SqlStoreEventLocal; - -#endif // DEBUG - - /// - /// Instantiates a store object using the credentials provided by the user. - /// - /// Credentials for store operations. - protected internal SqlStore(SqlShardMapManagerCredentials credentials) - { - Debug.Assert(credentials != null); - this.credentials = credentials; - } - - #region Transient Error Detection - - /// - /// Returns a function that is capable of detecting transient errors for the store. - /// - /// Delegate that can detect transient failure for the store. - public virtual Func GetTransientErrorDetector() - { - return SqlStore.transientErrorDetector; - } - - #endregion Transient Error Detection - - #region Transaction Management - - /// - /// Connects to the Global ShardMapManager data source and starts a transaction. When disposed - /// based on the state of Success property, either the transaction will be committed or it will - /// be aborted. - /// - /// Batch scope object. - /// Use the disposable pattern with the object returned from this method. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", - Justification = "Callers take care of disposal")] - public virtual IStoreTransactionScope GetTransactionScopeGlobal() - { - try - { - SqlTransactionScopeGlobal txnScopeGlobal = new SqlTransactionScopeGlobal(this.credentials.ConnectionStringShardMapManager); - -#if DEBUG - EventHandler handler = this.SqlStoreEventGlobal; - if (handler != null) - { - // If there are any subscribers for SqlStoreEventGlobal event, then register a subscriber function with SqlTransactionScopeGlobal - // - txnScopeGlobal.TxnScopeGlobalDisposeEvent += TxnScopeGlobalEventHandler; - } -#endif // DEBUG - - return txnScopeGlobal; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_GetTransactionScopeGlobal_SqlException, - se); - } - } - - /// - /// Connects to the Local ShardMapManager data source and starts a transaction. When disposed - /// based on the state of Success property, either the transaction will be committed or it will - /// be aborted. - /// - /// Batch scope object. - /// Use the disposable pattern with the object returned from this method. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", - Justification = "Callers take care of disposal")] - public virtual IStoreTransactionScope GetTransactionScopeLocal(ShardLocation location) - { - try - { - SqlTransactionScopeLocal txnScopeLocal = new SqlTransactionScopeLocal(location, this.credentials.ConnectionStringShard); - -#if DEBUG - EventHandler handler = this.SqlStoreEventLocal; - if (handler != null) - { - // If there are any subscribers for SqlStoreEventLocal event, then register a subscriber function with SqlTransactionScopeGlobal - // - txnScopeLocal.TxnScopeLocalDisposeEvent += TxnScopeLocalEventHandler; - } -#endif // DEBUG - - return txnScopeLocal; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_GetTransactionScopeLocal_SqlException, - se, - location); - } - } - - #endregion Transaction Management - - #region Storage Structures - - /// - /// Check if global shard map manager data structures already exist. - /// - /// true if data structures already exist, false otherwise. - public virtual bool CheckIfExistGlobal() - { - try - { - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - return SqlStore.CheckIfExistsHelper(cmd, SqlStore.CheckIfExistsGlobalScript); - } - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_CheckIfExistsGlobal_SqlException, - se); - } - } - - /// - /// Create the global shard map manager data structures for persistence. - /// - public virtual void CreateGlobal() - { - try - { - SqlStore.ExecuteSqlScriptGlobalHelper(SqlStore.CreateGlobalScript); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_CreateDropGlobal_SqlException, - se, - "Create"); - } - } - - /// - /// Delete the global shard map manager data structures. - /// - public virtual void DropGlobal() - { - try - { - SqlStore.ExecuteSqlScriptGlobalHelper(SqlStore.DropGlobalScript); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_CreateDropGlobal_SqlException, - se, - "Delete"); - } - } - - /// - /// Create Schema Info Collection global data structures for persistence. - /// - public void CreateSchemaInfoCollectionGlobal() - { - try - { - SqlStore.ExecuteSqlScriptGlobalHelper(SqlStore.CreateSchemaInfoScript); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_CreateDropSchemaInfoCollectionGlobal_SqlException, - se, - "Create", - "CreateSchemaInfoScript"); - } - } - - /// - /// Drop any Schema Info Collection global data structures. - /// - public void DropSchemaInfoCollectionGlobal() - { - try - { - SqlStore.ExecuteSqlScriptGlobalHelper(SqlStore.DropSchemaInfoScript); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_CreateDropSchemaInfoCollectionGlobal_SqlException, - se, - "Delete", - "DropSchemaInfoScript"); - } - } - - /// - /// Checks if local shard map manager data structures already exist at . - /// - /// Location of shard. - /// true if data structures already exist, false otherwise. - public virtual bool CheckIfExistLocal(ShardLocation location) - { - try - { - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(location)) - { - return SqlStore.CheckIfExistsHelper(cmd, SqlStore.CheckIfExistsLocalScript); - } - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_CheckIfExistsLocal_SqlException, - se, - location); - } - } - - /// - /// Create the local shard map manager data structures for persistence and consistency at . - /// - /// Location of shard. - public virtual void CreateLocal(ShardLocation location) - { - try - { - SqlStore.ExecuteSqlScriptLocalHelper(location, SqlStore.CreateLocalScript); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_CreateDropLocal_SqlException, - se, - "Create", - location); - } - } - - /// - /// Delete the local shard map manager data structures at given . - /// - /// Location of shard. - public virtual void DropLocal(ShardLocation location) - { - try - { - SqlStore.ExecuteSqlScriptLocalHelper(location, SqlStore.DropLocalScript); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_CreateDropLocal_SqlException, - se, - "Delete", - location); - } - } - - #endregion Storage Structures - - #region ShardMapInterfaces - - /// - /// Obtains all the ShardMaps from the Global ShardMapManager data source. - /// - /// Result of the execution. - public virtual IStoreResults GetShardMapsGlobal() - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_getAllShardMapsGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_GetAllShardMapsGlobal_SqlException, - se); - } - } - - /// - /// Adds a shard map entry to Global ShardMapManager data source. - /// - /// ShardMap to be added. - /// Storage operation result. - public virtual IStoreResults AddShardMapGlobal(IStoreShardMap ssm) - { - return SqlStore.AddAttachShardMapGlobalHelper(ssm, false); - } - - /// - /// Attaches a shard map entry to Global ShardMapManager data source. - /// - /// ShardMap to be added. - /// Storage operation result. - public virtual IStoreResults AttachShardMapGlobal(IStoreShardMap ssm) - { - return SqlStore.AddAttachShardMapGlobalHelper(ssm, true); - } - - /// - /// Removes a shard map entry from Global ShardMapManager data source. - /// - /// ShardMap to be removed. - public virtual IStoreResults RemoveShardMapGlobal(IStoreShardMap ssm) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_removeShardMapGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_version", ssm.Version.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMapManager_GlobalOperation_SqlException, - se, - "Remove"); - } - } - - /// - /// Updates a shard map entry in Global ShardMapManager data source. - /// - /// ShardMap information for update. - /// Storage operation result. - public virtual IStoreResults UpdateShardMapGlobal(IStoreShardMap ssm) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_updateShardMapGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_kind", ((int)ssm.Kind).ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("sm_status", ((int)ssm.Status).ToString()), - new XElement("sm_keykind", ((int)ssm.KeyKind).ToString()), - new XElement("sm_hashkind", ((int)ssm.HashKind).ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMapManager_GlobalOperation_SqlException, - se, - "Update"); - } - } - - /// - /// Looksup a shard map from Global ShardMapManager data source. - /// - /// Name of the shard map. - /// Storage operation result. - public virtual IStoreResults FindShardMapByNameGlobal(string shardMapName) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_findShardMapByNameGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_name", shardMapName) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMapManager_GlobalOperation_SqlException, - se, - "FindByName"); - } - } - - /// - /// Looks up a shard map from Global ShardMapManager data source. - /// - /// Id of the shard map. - /// Storage operation result. - public virtual IStoreResults FindShardMapByIdGlobal(Guid smId) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_findShardMapByIdGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", smId.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMapManager_GlobalOperation_SqlException, - se, - "FindById"); - } - } - - /// - /// Obtains all the ShardMaps from the Local ShardMapManager data source. - /// - /// Location of shard. - /// Result of the execution. - public virtual IStoreResults GetShardMapsLocal(ShardLocation location) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(location)) - { - cmd.CommandText = @"__ShardManagement.smm_getAllShardMapsLocal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("lsm_version", SqlStoreLsmVersion.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_GetShardMapsLocal_SqlException, - se, - location); - } - } - - - /// - /// Adds a shard map entry to Local Shard data source. - /// - /// Shard where shard map is being added. - /// ShardMap to be added. - /// Storage operation result. - public virtual IStoreResults AddShardMapLocal(IStoreShard ss, IStoreShardMap ssm) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(ss.Location)) - { - cmd.CommandText = @"__ShardManagement.smm_addShardMapLocal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("lsm_version", SqlStoreLsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_name", ssm.Name), - new XElement("sm_kind", ((int)ssm.Kind).ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("sm_status", ((int)ssm.Status).ToString()), - new XElement("sm_keykind", ((int)ssm.KeyKind).ToString()), - new XElement("sm_hashkind", ((int)ssm.HashKind).ToString()), - new XElement("s_id", ss.Id.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_LocalOperation_SqlException, - se, - "Add", - ssm.Name, - ss.Location); - } - } - - /// - /// Removes a shard map entry from Local Shard data source. - /// - /// Shard where shard map is being removed. - /// ShardMap to be removed. - /// Storage operation result. - public virtual IStoreResults RemoveShardMapLocal(IStoreShard ss, IStoreShardMap ssm) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(ss.Location)) - { - cmd.CommandText = @"__ShardManagement.smm_removeShardMapLocal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("lsm_version", SqlStoreLsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("s_id", ss.Id.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_LocalOperation_SqlException, - se, - "Remove", - ssm.Name, - ss.Location); - } - } - - #endregion ShardMapInterfaces - - #region ShardInterfaces - - /// - /// Obtains shards from the Global ShardMapManager data - /// source for a given shard map which specify the given status. - /// - /// Shard map to get shards for. - /// Optional number of shards to get. - /// Optional shard status to be matched. - /// Storage operation result. - public virtual IStoreResults GetShardsGlobal(IStoreShardMap ssm, int? numShards, int? status) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_getShardsGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("num_shards", - numShards.HasValue ? numShards.ToString() : null, - new XAttribute("is_null", numShards.HasValue ? "false" : "true") - ), - new XElement("s_status", - status.HasValue ? status.ToString() : null, - new XAttribute("is_null", status.HasValue ? "false" : "true") - ) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_GetShardsGlobal_SqlException, - se, - ssm.Name); - } - } - - /// - /// Obtains a Shard given the location. - /// - /// Shard map to get shard for. - /// Location of the shard. - /// Storage operation result. - public virtual IStoreResults GetShardByLocationGlobal(IStoreShardMap ssm, ShardLocation location) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_getShardByLocationGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("s_datasource", location.DataSource), - new XElement("s_database", location.Database) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_GetShardByLocationGlobal_SqlException, - se, - location, - ssm.Name); - } - } - - /// - /// Adds a shard to Global ShardMap. - /// - /// Shard map to add shard to. - /// Shard to store. - /// Storage operation result. - public virtual IStoreResults AddShardGlobal(IStoreShardMap ssm, IStoreShard ss) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_addShardGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("s_id", ss.Id.ToString()), - new XElement("s_datasource", ss.Location.DataSource), - new XElement("s_database", ss.Location.Database), - new XElement("s_version", ss.Version.ToString()), - new XElement("s_status", ss.Status.ToString()), - new XElement("s_custom", (ss.Custom == null) ? null : StringUtils.ByteArrayToString(ss.Custom), - new XAttribute("is_null", (ss.Custom == null) ? "true" : "false") - ) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_GlobalOperation_SqlException, - se, - "Add", - ssm.Name); - } - } - - /// - /// Removes a shard from Global ShardMap. - /// - /// Shard map to remove shard from. - /// Shard to remove - /// Storage operation result. - public virtual IStoreResults RemoveShardGlobal(IStoreShardMap ssm, IStoreShard ss) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_removeShardGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("s_id", ss.Id.ToString()), - new XElement("s_version", ss.Version.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_GlobalOperation_SqlException, - se, - "Remove", - ssm.Name); - } - } - - /// - /// Detaches a shard from Global ShardMap. - /// - /// Location of the shard. - /// Optional string to filter on shardmapName - /// Storage operation result. - public virtual IStoreResults DetachShardGlobal(ShardLocation location, string shardmapName = null) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_detachShardGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_name", shardmapName, - new XAttribute("is_null", (null == shardmapName) ? "true" : "false") - ), - new XElement("s_datasource", location.DataSource), - new XElement("s_database", location.Database) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMapManager_GlobalOperation_SqlException, - se, - "DetachShard"); - } - } - - /// - /// Updates a shard in Global ShardMap. - /// - /// Shard map to update shard in. - /// Old snapshot of the shard in the cache before update. - /// Updated shard. - /// Storage operation result. - public virtual IStoreResults UpdateShardGlobal(IStoreShardMap ssm, IStoreShard ssOld, IStoreShard ssNew) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_updateShardGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("s_id", ssNew.Id.ToString()), - new XElement("s_original_version", ssOld.Version.ToString()), - new XElement("s_status", ssNew.Status.ToString()), - new XElement("s_custom", (ssNew.Custom == null) ? null : StringUtils.ByteArrayToString(ssNew.Custom), - new XAttribute("is_null", (ssNew.Custom == null) ? "true" : "false") - ) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_GlobalOperation_SqlException, - se, - "Update", - ssm.Name); - } - } - - /// - /// Validate the version of a shard and it's containing shard map. - /// - /// Shard map that owns the shard. - /// Shard to validate. - /// Storage operation result. - public virtual IStoreResults ValidateShardGlobal(IStoreShardMap ssm, IStoreShard ss) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_validateShardGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("s_id", ss.Id.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ValidateShard_SqlException, - se, - ss.Location, - ssm.Name); - } - } - - #endregion ShardInterfaces - - #region SchemaInfoInterfaces - - /// - /// Create sharding schma info with a given name. This information can be used during Split\Merge or - /// any any other operation that requires such metadata. - /// - /// Name associated with the schema info. - /// The schma info in XML format. - /// Storage operation result. - public IStoreResults AddShardingSchemaInfo(string name, SqlXml si) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_setShardingSchemaInfo"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("metadata_name", name), - new XElement("schema_info", - XElement.Load(si.CreateReader()))); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_SchemaInfo_SqlException, - se, - "creating", - name); - } - } - - /// - /// Update sharding schma info with a given name. - /// - /// Name associated with the schma info. - /// The schma info in XML format. - /// Storage operation result. - public IStoreResults UpdateShardingSchemaInfo(string name, SqlXml si) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_updateShardingSchemaInfo"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("metadata_name", name), - new XElement("schema_info", - XElement.Load(si.CreateReader()))); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_SchemaInfo_SqlException, - se, - "updating", - name); - } - } - - /// - /// Fetch sharding schma info with a given name. - /// - /// Name associated with the schma info. - /// The schma info in XML format. - /// Storage operation result. - public IStoreResults GetShardingSchemaInfo(string name, out SqlXml si) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_getShardingSchemaInfo"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("metadata_name", name)); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - result.Result = (StoreResult)resultParam.Value; - si = (StoreResult.Success == result.Result) ? result.StoreSchemaInfoCollection.Single().ShardingSchemaInfo : null; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_SchemaInfo_SqlException, - se, - "retrieving", - name); - } - } - - /// - /// Fetch all the schema info. - /// - /// The schema info collection. - /// Storage operation result. - public IStoreResults GetShardingSchemaInfoAll(out Dictionary siCollection) - { - siCollection = new Dictionary(); - - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_getAllShardingSchemaInfo"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString())); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - result.Result = (StoreResult)resultParam.Value; - - - foreach (IStoreSchemaInfo si in result.StoreSchemaInfoCollection) - { - siCollection.Add(si.Name, si.ShardingSchemaInfo); - } - - return result; - } - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_SchemaInfo_SqlException, - se, - "retrieving", - "all persisted names"); - } - } - - /// - /// Delete a schma info entry with a given name. - /// - /// Name associated with the schma info. - /// Storage operation result. - public IStoreResults DeleteShardingSchemaInfo(string name) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_deleteShardingSchemaInfo"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("metadata_name", name)); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_SchemaInfo_SqlException, - se, - "deleting", - name); - } - } - - #endregion - - #region MappingInterfaces - - #region PointMappingInterfaces - -#if FUTUREWORK - /// - /// Add point mapping to Global ShardMap. - /// - /// Shard map to add mapping to. - /// Shard mapping to store. - /// Storage operation result. - public virtual IStoreResults AddPointMappingsLocal(ShardLocation location, IEnumerable sms) - { - try - { - return SqlStore.BulkAddMappingLocalHelper(location, sms); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingLocal_SqlException, - se, - "AddMappings", - "Point", - location); - } - } - - /// - /// Bulk add point mappings to Global ShardMap without consistency checks. - /// - /// Shard map to add mapping to. - /// Shard mappings to store. - /// Storage operation result. - public virtual IStoreResults AddPointMappingsGlobal(IStoreShardMap ssm, IEnumerable sms) - { - try - { - return SqlStore.BulkAddMappingGlobalHelper(ssm, sms); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingGlobal_SqlException, - se, - "AddMappings", - "Point", - ssm.Name); - } - } -#endif - - /// - /// Add point mapping to Global ShardMap. - /// - /// Shard map to add mapping to. - /// Shard mapping to store. - /// Storage operation result. - public virtual IStoreResults AddPointMappingGlobal(IStoreShardMap ssm, IStoreMapping sm) - { - try - { - return SqlStore.AddMappingGlobalHelper(ssm, sm, @"__ShardManagement.smm_addPointShardMappingGlobal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingGlobal_SqlException, - se, - "AddMapping", - "Point", - ssm.Name); - } - } - - /// - /// Removes point mapping from Global ShardMap. - /// - /// Shard map to remove mapping from. - /// Shard mapping to remove. - /// Whether to ignore the Online status. - /// Storage operation result. - public virtual IStoreResults RemovePointMappingGlobal(IStoreShardMap ssm, IStoreMapping sm, bool force = false) - { - try - { - return SqlStore.RemoveMappingGlobalHelper(ssm, sm, force, @"__ShardManagement.smm_removePointShardMappingGlobal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingGlobal_SqlException, - se, - "RemoveMapping", - "Point", - ssm.Name); - } - - } - - /// - /// Finds point mapping which contain the given key for the given ShardMap. - /// - /// Shard map to find mappings in. - /// ShardKey being searched. - /// Storage operation result. - public virtual IStoreResults FindPointMappingByKeyGlobal(IStoreShardMap ssm, ShardKey shardKey) - { - try - { - return SqlStore.FindMappingByKeyGlobalHelper(ssm, shardKey.RawValue, @"__ShardManagement.smm_findPointMappingByKeyGlobal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingGlobal_SqlException, - se, - "FindMappingByKey", - "Point", - ssm.Name); - } - } - - /// - /// Finds point mapping which contain the given range for the shard map. - /// If range is not given: - /// If shard is given, finds all mappings for the shard. - /// If shard is also not given, finds all the mappings. - /// If range is given: - /// If shard is given, finds all mappings for the shard in the range. - /// If shard is not given, finds all the mappings in the range. - /// - /// Shard map to find mappings in. - /// Optional range to find mappings in. - /// Option shard to find mappings in. - /// Storage operation result. - public virtual IStoreResults FindPointMappingByRangeGlobal(IStoreShardMap ssm, ShardRange range, IStoreShard shard) - { - try - { - return SqlStore.FindMappingByRangeGlobalHelper(ssm, range, shard, @"__ShardManagement.smm_getAllPointShardMappingsGlobal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingGlobal_SqlException, - se, - "FindMappingsForRange", - "Point", - ssm.Name); - } - } - - /// - /// Add point mapping to local ShardMap. - /// - /// Location of shard. - /// Shard mapping to store. - /// Storage operation result. - public virtual IStoreResults AddPointMappingLocal(ShardLocation location, IStoreMapping sm) - { - try - { - return SqlStore.AddMappingLocalHelper(location, sm, @"__ShardManagement.smm_addPointShardMappingLocal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingLocal_SqlException, - se, - "AddMapping", - "Point", - location); - } - } - - /// - /// Removes point mapping from local ShardMap. - /// - /// Location of shard. - /// Shard mapping to remove. - /// Whether to force removal of mapping irrespective of status. - /// Storage operation result. - public virtual IStoreResults RemovePointMappingLocal(ShardLocation location, IStoreMapping sm, bool force) - { - try - { - return SqlStore.RemoveMappingLocalHelper(location, sm, force, @"__ShardManagement.smm_removePointShardMappingLocal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingLocal_SqlException, - se, - "RemoveMapping", - "Point", - location); - } - } - - /// - /// Finds point mapping which contain the given range for the shard map. - /// If range is not given: - /// If shard is given, finds all mappings for the shard. - /// If shard is also not given, finds all the mappings. - /// If range is given: - /// If shard is given, finds all mappings for the shard in the range. - /// If shard is not given, finds all the mappings in the range. - /// - /// Shard map to find mappings in. - /// Optional range to find mappings in. - /// Shard to find mappings in. - /// Storage operation result. - public virtual IStoreResults FindPointMappingByRangeLocal(IStoreShardMap ssm, ShardRange range, IStoreShard shard) - { - try - { - return SqlStore.FindMappingByRangeLocalHelper(ssm, range, shard, @"__ShardManagement.smm_getAllPointShardMappingsLocal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingLocal_SqlException, - se, - "FindMappingsForRange", - "Point", - shard.Location); - } - } - - /// - /// Finds point mapping which contain the given range for the shard map. - /// - /// Shard map to find mappings in. - /// Key to which a corresponding mapping should be found. - /// Shard container requiring Id and ShardLocation. - /// Storage operation result. - public virtual IStoreResults FindPointMappingByKeyLocal(IStoreShardMap ssm, ShardKey key, IStoreShard shard) - { - try - { - return SqlStore.FindMappingByKeyLocalHelper(ssm, key, shard); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingLocal_SqlException, - se, - "FindMappingForKey", - "Point", - shard.Location); - } - } - - #endregion PointMappingInterfaces - - #region RangeMappingInterfaces - -#if FUTUREWORK - /// - /// Bulk add range mappings to Global ShardMap without consistency checks. - /// - /// Shard map to add mapping to. - /// List of shard mapping to store. - /// Storage operation result. - public virtual IStoreResults AddRangeMappingsGlobal(IStoreShardMap ssm, IEnumerable sms) - { - try - { - return SqlStore.BulkAddMappingGlobalHelper(ssm, sms); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingGlobal_SqlException, - se, - "AddMappings", - "Range", - ssm.Name); - } - } -#endif - - /// - /// Add range mapping to Global ShardMap. - /// - /// Shard map to add mapping to. - /// Shard mapping to store. - /// Storage operation result. - public virtual IStoreResults AddRangeMappingGlobal(IStoreShardMap ssm, IStoreMapping sm) - { - try - { - return SqlStore.AddMappingGlobalHelper(ssm, sm, @"__ShardManagement.smm_addRangeShardMappingGlobal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingGlobal_SqlException, - se, - "AddMapping", - "Range", - ssm.Name); - } - } - - /// - /// Add range mapping to Global ShardMap within existing range mapping. - /// - /// Shard map to add mapping to. - /// Shard mapping to store. - /// Range to add. - /// Lock owner id of this mapping - /// Storage operation result. - public virtual IStoreResults AddRangeWithinRangeMappingGlobal(IStoreShardMap ssm, IStoreMapping sm, ShardRange range, Guid lockOwnerId) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_addRangeShardMappingWithinRangeGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", sm.ShardMapId.ToString()), - new XElement("lo_id", lockOwnerId.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("m_id", sm.Id.ToString()), - new XElement("m_min_value", StringUtils.ByteArrayToString(range.Low.RawValue)), - new XElement("m_max_value", - (range.High == null) ? null : StringUtils.ByteArrayToString(range.High.RawValue), - new XAttribute("is_null", (range.High == null) ? "true" : "false") - ), - new XElement("m_version", sm.Version.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_RangeShardMap_AddRemoveRange_SqlException, - se, - "AddRange", - ssm.Name); - } - } - - /// - /// Removes range mapping from Global ShardMap. - /// - /// Shard map to remove mapping from. - /// Shard mapping to remove. - /// Lock owner id of this mapping - /// Whether to ignore Online status - /// Storage operation result. - public virtual IStoreResults RemoveRangeMappingGlobal(IStoreShardMap ssm, IStoreMapping sm, Guid lockOwnerId, bool force = true) - { - try - { - return SqlStore.RemoveMappingGlobalHelper(ssm, sm, force, @"__ShardManagement.smm_removeRangeShardMappingGlobal", true, lockOwnerId); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingGlobal_SqlException, - se, - "RemoveMapping", - "Range", - ssm.Name); - } - } - - /// - /// Removes range mapping within existing range mapping. - /// - /// Shard map to remove range mapping to. - /// Shard mapping to remove range from. - /// Range to remove. - /// Lock owner id of this mapping - /// Storage operation result. - public virtual IStoreResults RemoveRangeWithinRangeMappingGlobal(IStoreShardMap ssm, IStoreMapping sm, ShardRange range, Guid lockOwnerId) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_removeRangeShardMappingWithinRangeGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", sm.ShardMapId.ToString()), - new XElement("lo_id", lockOwnerId.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("m_id", sm.Id.ToString()), - new XElement("m_min_value", StringUtils.ByteArrayToString(range.Low.RawValue)), - new XElement("m_max_value", - (range.High == null) ? null : StringUtils.ByteArrayToString(range.High.RawValue), - new XAttribute("is_null", (range.High == null) ? "true" : "false") - ), - new XElement("m_version", sm.Version.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_RangeShardMap_AddRemoveRange_SqlException, - se, - "RemoveRange", - ssm.Name); - } - } - - /// - /// Splits given range mapping into 2 new mappings. - /// - /// Shard map to find mappings in. - /// Store mapping to split. - /// Split point in the mapping. - /// Lock owner id of this mapping - /// Storage operation result. - public virtual IStoreResults SplitRangeMappingGlobal(IStoreShardMap ssm, IStoreMapping sm, ShardKey splitPoint, Guid lockOwnerId) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_splitRangeShardMappingGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("lo_id", lockOwnerId.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("m_id", sm.Id.ToString()), - new XElement("m_version", sm.Version.ToString()), - new XElement("split_point", StringUtils.ByteArrayToString(splitPoint.RawValue)) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_RangeShardMap_SplitMerge_SqlException, - se, - "Split", - ssm.Name); - } - } - - /// - /// Merges the given range mappings into a single mapping. - /// - /// Shard map to find mappings in. - /// Left store mapping to merge. - /// Right store mapping to merge. - /// Left mapping lock owner id - /// Right mapping lock owner id - /// Storage operation result. - public virtual IStoreResults MergeRangeMappingsGlobal(IStoreShardMap ssm, IStoreMapping smLeft, IStoreMapping smRight, - Guid leftLockOwnerId, Guid rightLockOwnerId) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_mergeRangeShardMappingsGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("m_id_left", smLeft.Id.ToString()), - new XElement("m_version_left", smLeft.Version.ToString()), - new XElement("lo_id_left", leftLockOwnerId.ToString()), - new XElement("m_id_right", smRight.Id.ToString()), - new XElement("m_version_right", smRight.Version.ToString()), - new XElement("lo_id_right", rightLockOwnerId.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_RangeShardMap_SplitMerge_SqlException, - se, - "Merge", - ssm.Name); - } - } - - /// - /// Finds range mapping which contain the given key for the given ShardMap. - /// - /// Shard map to find mappings in. - /// ShardKey being searched. - /// Storage operation result. - public virtual IStoreResults FindRangeMappingByKeyGlobal(IStoreShardMap ssm, ShardKey shardKey) - { - try - { - return SqlStore.FindMappingByKeyGlobalHelper(ssm, shardKey.RawValue, @"__ShardManagement.smm_findRangeMappingByKeyGlobal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingGlobal_SqlException, - se, - "FindMappingByKey", - "Range", - ssm.Name); - } - } - - /// - /// Finds range mapping which contain the given range for the shard map. - /// If range is not given: - /// If shard is given, finds all mappings for the shard. - /// If shard is also not given, finds all the mappings. - /// If range is given: - /// If shard is given, finds all mappings for the shard in the range. - /// If shard is not given, finds all the mappings in the range. - /// - /// Shard map to find mappings in. - /// Optional range to find mappings in. - /// Option shard to find mappings in. - /// Storage operation result. - public virtual IStoreResults FindRangeMappingByRangeGlobal(IStoreShardMap ssm, ShardRange range, IStoreShard shard) - { - try - { - return SqlStore.FindMappingByRangeGlobalHelper(ssm, range, shard, @"__ShardManagement.smm_getAllRangeShardMappingsGlobal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingGlobal_SqlException, - se, - "FindMappingsForRange", - "Range", - ssm.Name); - } - } - - /// - /// Locks or unlocks the given range mapping - /// - /// Shard map to add mapping to. - /// Shard mapping to store. - /// The lock owner id of this mapping - /// Operation to perform on this mapping with the given lockOwnerId - /// - public virtual IStoreResults LockOrUnlockRangeMappingGlobal(IStoreShardMap ssm, IStoreMapping sm, Guid lockOwnerId, LockOwnerIdOpType lockOwnerIdOpType) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_lockOrUnlockShardMappingGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("m_id", sm.Id.ToString()), - new XElement("sm_id", sm.ShardMapId.ToString()), - new XElement("lo_id", lockOwnerId.ToString()), - new XElement("s_id", sm.StoreShard.Id.ToString()), - new XElement("m_version", sm.Version.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("lo_id_op_type", (int)lockOwnerIdOpType)); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_UpdateMappingGlobal_SqlException, - se, - "LockOrUnlockMapping", - sm.StoreShard.Location, - ssm.Name); - } - } - - /// - /// Unlocks all mappings in the specified map that - /// belong to the given lock owner id - /// - /// Shard map to add mapping to. - /// The lock owner id of this mapping - /// - public virtual IStoreResults UnlockAllMappingsWithLockOwnerIdGobal(IStoreShardMap ssm, Guid lockOwnerId) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_unlockAllMappingsWithLockIdGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("lo_id", lockOwnerId.ToString()), - new XElement("s_id", ssm.ShardId.ToString()), - new XElement("sm_version", ssm.Version.ToString())); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_UnlockAllMappingsWithLockOwnerId_SqlException, - se, - lockOwnerId, - ssm.Name); - } - } - - /// - /// Add range mapping to local ShardMap. - /// - /// Location of shard. - /// Shard mapping to store. - /// Storage operation result. - public virtual IStoreResults AddRangeMappingLocal(ShardLocation location, IStoreMapping sm) - { - try - { - return SqlStore.AddMappingLocalHelper(location, sm, @"__ShardManagement.smm_addRangeShardMappingLocal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingLocal_SqlException, - se, - "AddMapping", - "Range", - location); - } - } - - /// - /// Replace range mapping in Local ShardMap with upto 3 new mappings. - /// - /// Location of shard. - /// Original store mapping. - /// List of store mappings to add. - /// Storage operation result. - public virtual IStoreResults ReplaceRangeMappingLocal(ShardLocation location, IStoreMapping smOld, IEnumerable smList) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(location)) - { - XElement[] xe = new XElement[3]; - - using (IEnumerator smEnum = smList.GetEnumerator()) - { - for (int i = 1; i <= 3; i++) - { - string index = i.ToString(CultureInfo.InvariantCulture); - - IStoreMapping mapping = smEnum.MoveNext() ? smEnum.Current : null; - - xe[i - 1] = new XElement("root", - new XElement("m_id_" + index, (mapping == null) ? null : mapping.Id.ToString(), - new XAttribute("is_null", (mapping == null) ? "true" : "false" ) - ), - new XElement("m_min_value_" + index, (mapping == null) ? null : StringUtils.ByteArrayToString(mapping.MinValue), - new XAttribute("is_null", (mapping == null) ? "true" : "false" ) - ), - new XElement("m_max_value_" + index, (mapping == null) ? null : ((mapping.MaxValue == null) ? null : StringUtils.ByteArrayToString(mapping.MaxValue)), - new XAttribute("is_null", (mapping == null) ? "true" : ((mapping.MaxValue == null) ? "true" : "false" )) - ) - ); - } - } - - cmd.CommandText = @"__ShardManagement.smm_replaceRangeShardMappingsLocal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("lsm_version", SqlStoreLsmVersion.ToString()), - new XElement("sm_id", smOld.ShardMapId.ToString()), - new XElement("m_id", smOld.Id.ToString()), - new XElement("m_version", smOld.Version.ToString()), - xe[0].Elements(), - xe[1].Elements(), - xe[2].Elements() - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_RangeShardMap_MergeReplaceLocal_SqlException, - se, - "ReplaceRangeMappings", - location); - } - } - - /// - /// Removes range mapping from local ShardMap. - /// - /// Location of shard. - /// Shard mapping to remove. - /// Whether to force removal of mapping irrespective of status. - /// Storage operation result. - public virtual IStoreResults RemoveRangeMappingLocal(ShardLocation location, IStoreMapping sm, bool force) - { - try - { - return SqlStore.RemoveMappingLocalHelper(location, sm, force, @"__ShardManagement.smm_removeRangeShardMappingLocal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingLocal_SqlException, - se, - "RemoveMapping", - "Range", - location); - } - } - - /// - /// Merges the given range mappings into a single mapping. - /// - /// Location of shard. - /// Left store mapping to merge. - /// Right store mapping to merge. - /// Store mapping resulting from merge operation. - /// Storage operation result. - public virtual IStoreResults MergeRangeMappingsLocal(ShardLocation location, IStoreMapping smLeft, IStoreMapping smRight, IStoreMapping smMerged) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(location)) - { - cmd.CommandText = @"__ShardManagement.smm_mergeRangeShardMappingsLocal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", smLeft.ShardMapId.ToString()), - new XElement("m_id_left", smLeft.Id.ToString()), - new XElement("m_version_left", smLeft.Version.ToString()), - new XElement("m_id_right", smRight.Id.ToString()), - new XElement("m_version_right", smRight.Version.ToString()), - new XElement("m_id_new", smMerged.Id.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_RangeShardMap_MergeReplaceLocal_SqlException, - se, - "MergeRangeMappings", - location); - } - } - - /// - /// Finds range mapping which contain the given range for the shard map. - /// If range is not given: - /// If shard is given, finds all mappings for the shard. - /// If shard is also not given, finds all the mappings. - /// If range is given: - /// If shard is given, finds all mappings for the shard in the range. - /// If shard is not given, finds all the mappings in the range. - /// - /// Shard map to find mappings in. - /// Optional range to find mappings in. - /// Shard to find mappings in. - /// Storage operation result. - public virtual IStoreResults FindRangeMappingByRangeLocal(IStoreShardMap ssm, ShardRange range, IStoreShard shard) - { - try - { - return SqlStore.FindMappingByRangeLocalHelper(ssm, range, shard, @"__ShardManagement.smm_getAllRangeShardMappingsLocal"); - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMap_AddRemoveUpdateFindMappingLocal_SqlException, - se, - "FindMappingsForRange", - "Range", - shard.Location); - } - } - - #endregion RangeMappingInterfaces - - /// - /// Update mapping in Global ShardMap. - /// - /// Shard map to update mapping in. - /// Old snapshot of shard mapping in cache before update. - /// Updated shard mapping. - /// Lock owner id of this mapping - /// Storage operation result. - public virtual IStoreResults UpdateMappingGlobal(IStoreShardMap ssm, IStoreMapping smOld, IStoreMapping smNew, Guid lockOwnerId = default(Guid)) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_updateShardMappingGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", smNew.ShardMapId.ToString()), - new XElement("lo_id", lockOwnerId.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("s_id", smNew.StoreShard.Id.ToString()), - new XElement("m_id", smNew.Id.ToString()), - new XElement("m_old_version", smOld.Version.ToString()), - new XElement("m_min_value", StringUtils.ByteArrayToString(smNew.MinValue)), - new XElement("m_max_value", - (smNew.MaxValue == null) ? null : StringUtils.ByteArrayToString(smNew.MaxValue), - new XAttribute("is_null", (smNew.MaxValue == null) ? "true" : "false") - ), - new XElement("m_version", null, - new XAttribute("is_null", "true") - ), - new XElement("m_status", smNew.Status.ToString()), - new XElement("m_custom", (smNew.Custom == null) ? null : StringUtils.ByteArrayToString(smNew.Custom), - new XAttribute("is_null", (smNew.Custom == null) ? "true" : "false") - ) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_UpdateMappingGlobal_SqlException, - se, - "UpdateMapping", - smOld.StoreShard.Location, - ssm.Name); - } - } - - /// - /// Update mapping in local ShardMap. - /// - /// Location of shard. - /// Old snapshot of shard mapping in cache before update. - /// Updated shard mapping. - /// Storage operation result. - public virtual IStoreResults UpdateMappingLocal(ShardLocation location, IStoreMapping smOld, IStoreMapping smNew) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(location)) - { - cmd.CommandText = @"__ShardManagement.smm_updateShardMappingLocal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("lsm_version", SqlStoreLsmVersion.ToString()), - new XElement("sm_id", smNew.ShardMapId.ToString()), - new XElement("s_id", smNew.StoreShard.Id.ToString()), - new XElement("m_id", smNew.Id.ToString()), - new XElement("m_old_version", smOld.Version.ToString()), - new XElement("m_min_value", StringUtils.ByteArrayToString(smNew.MinValue)), - new XElement("m_max_value", - (smNew.MaxValue == null) ? null : StringUtils.ByteArrayToString(smNew.MaxValue), - new XAttribute("is_null", (smNew.MaxValue == null) ? "true" : "false") - ), - new XElement("m_version", smNew.Version.ToString()), - new XElement("m_status", smNew.Status.ToString()), - new XElement("m_custom", (smNew.Custom == null) ? null : StringUtils.ByteArrayToString(smNew.Custom), - new XAttribute("is_null", (smNew.Custom == null) ? "true" : "false") - ) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_UpdateMappingLocal_SqlException, - se, - "UpdateMapping", - location); - } - } - - /// - /// Validates that the given mapping exists in local shard map. - /// - /// Mapping being validated. - /// Storage operation result. - public virtual IStoreResults ValidateMappingGlobal(IStoreMapping sm) - { - try - { - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - return SqlStore.ValidateMappingHelper(cmd, sm, @"__ShardManagement.smm_validateShardMappingGlobal"); - } - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ValidateMappingGlobal_SqlException, - se, - sm.StoreShard.Location); - } - } - - /// - /// Validates that the given mapping exists in local shard map. - /// - /// Connection to use for validation. - /// Mapping being validated. - /// Storage operation result. - public virtual IStoreResults ValidateMappingLocal(SqlConnection conn, IStoreMapping sm) - { - // CONSIDER(wbasheer): Check for dead connections. - Debug.Assert(conn.State == ConnectionState.Open); - - using (SqlCommand cmd = conn.CreateCommand()) - { - return SqlStore.ValidateMappingHelper(cmd, sm, @"__ShardManagement.smm_validateShardMappingLocal"); - } - } - - /// - /// Kills all local sessions at the given location whose patterns match the given - /// . - /// - /// Location at which to kill sessions. - /// Name of shard map. - /// Pattern of the mapping. - /// Result of kill operations. - public virtual IStoreResults KillSessionsForMappingLocal(ShardLocation location, string shardMapName, string mappingPattern) - { - try - { - SqlConnectionStringBuilder lcsb = new SqlConnectionStringBuilder(this.credentials.ConnectionStringShard.ConnectionString); - - lcsb.DataSource = location.DataSource; - lcsb.InitialCatalog = location.Database; - - using (SqlConnection conn = new SqlConnection(lcsb.ConnectionString)) - { - conn.Open(); - - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = conn.CreateCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_KillSessionsForMappingLocal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("lsm_version", SqlStoreLsmVersion.ToString()), - new XElement("pattern", mappingPattern)); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_KillSessionsForMapping_SqlException, - se, - location, - shardMapName); - } - } - - #endregion MappingInterfaces - - #region Upgrade and Version Interfaces - - /// - /// Obtains distinct shard locations from Global ShardMapManager. - /// - /// Result of the execution. - public virtual IStoreResults GetDistinctShardLocationsGlobal() - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_getDistinctLocationsGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_GetDistinctLocationsGlobal_SqlException, - se); - } - } - - #endregion Upgrade and Version Interfaces - - #region Internal Testing Events - -#if DEBUG - - /// - /// Publisher for SqlStoreEventGlobal event. - /// - /// Event argument to handle transaction finishing action - internal void OnSqlStoreEventGlobal(SqlStoreEventArgs ssArgs) - { - EventHandler handler = this.SqlStoreEventGlobal; - - if (handler != null) - { - handler(this, ssArgs); - } - } - - /// - /// Publisher for SqlStoreEventLocal event. - /// - /// Event argument to handle transaction finishing action - internal void OnSqlStoreEventLocal(SqlStoreEventArgs ssArgs) - { - EventHandler handler = this.SqlStoreEventLocal; - - if (handler != null) - { - handler(this, ssArgs); - } - } - - /// - /// Subscriber function for SqlTransactionScopeGlobal.TxnScopeGlobalDisposeEvent event. - /// This function is used for internal testing purpose only. - /// - /// sender object (SqlTransactionScopeGlobal) - /// event argument - internal void TxnScopeGlobalEventHandler(object sender, SqlStoreEventArgs arg) - { - this.OnSqlStoreEventGlobal(arg); - } - - /// - /// Subscriber function for SqlTransactionScopeLocal.TxnScopeLocalDisposeEvent event. - /// This function is used for internal testing purpose only. - /// - /// sender object (SqlTransactionScopeLocal) - /// event argument - internal void TxnScopeLocalEventHandler(object sender, SqlStoreEventArgs arg) - { - this.OnSqlStoreEventLocal(arg); - } - -#endif // DEBUG - - #endregion Internal Testing Events - - #region Helper Functions - - /// - /// Adds or Attaches a shard map entry to Global ShardMapManager data source. - /// - /// ShardMap to be added. - /// Whether we are adding or attaching. - /// Storage operation result. - private static IStoreResults AddAttachShardMapGlobalHelper(IStoreShardMap ssm, bool isAttach) - { - try - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = @"__ShardManagement.smm_addShardMapGlobal"; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(cmd.CommandText, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_name", ssm.Name), - new XElement("sm_kind", ((int)ssm.Kind).ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("sm_status", ((int)ssm.Status).ToString()), - new XElement("sm_keykind", ((int)ssm.KeyKind).ToString()), - new XElement("sm_hashkind", ((int)ssm.HashKind).ToString()), - new XElement("for_attach", isAttach.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlStore_ShardMapManager_GlobalOperation_SqlException, - se, - isAttach ? "Attach" : "Add"); - } - } - -#if FUTUREWORK - /// - /// Add mapping to global ShardMap. - /// - /// Shard map to add mapping to. - /// Shard mappings to store. (presume these are all in the same ShardLocation. - /// Storage operation result. - private static IStoreResults BulkAddMappingGlobalHelper(IStoreShardMap ssm, IEnumerable sms) - { - var result = new SqlResults(); - if (!sms.Any()) - { - result.Result = StoreResult.Failure; - return result; - } - - DataTable schema; - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = "select * from __ShardManagement.shard_mappings_global where 0 = 1"; - using (SqlDataReader reader = cmd.ExecuteReader()) - { - schema = reader.GetSchemaTable(); - } - } - - DataTable dt = new DataTable(); - - foreach (DataRow drow in schema.Rows) - { - string columnName = System.Convert.ToString(drow["ColumnName"]); - DataColumn column = new DataColumn(columnName, (Type)(drow["DataType"])); - column.Unique = (bool)drow["IsUnique"]; - column.AllowDBNull = (bool)drow["AllowDBNull"]; - column.AutoIncrement = (bool)drow["IsAutoIncrement"]; - dt.Columns.Add(column); - } - - foreach (var sm in sms) - { - DataRow row = dt.NewRow(); - row[0] = sm.Id; - row[1] = sm.ShardMapId; - row[2] = sm.MinValue; - row[3] = sm.MaxValue; - row[4] = sm.Version; - row[5] = sm.Status; - row[6] = sm.Custom; - row[7] = sm.StoreShard.Id; - dt.Rows.Add(row); - } - - using (SqlBulkCopy bcp = SqlTransactionScopeGlobal.CreateBulkCopy()) - { - bcp.DestinationTableName = "_shard_mappings_global"; - bcp.WriteToServer(dt); - } - - result.Result = StoreResult.Success; - return result; - } - - /// - /// Add mapping to local ShardMap. - /// - /// Shard to add mappings to. - /// Shard mappings to store. (presume these are all in the same ShardLocation. - /// Storage operation result. - private static IStoreResults BulkAddMappingLocalHelper(ShardLocation location, IEnumerable sms) - { - if (!sms.Any()) - { - return StoreResult.Failure; - } - - DataTable schema; - - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(location)) - { - cmd.CommandText = "select * from __ShardManagement.shard_mappings_local where 0 = 1"; - using (SqlDataReader reader = cmd.ExecuteReader()) - { - schema = reader.GetSchemaTable(); - } - } - - DataTable dt = new DataTable(); - - foreach (DataRow drow in schema.Rows) - { - string columnName = System.Convert.ToString(drow["ColumnName"]); - DataColumn column = new DataColumn(columnName, (Type)(drow["DataType"])); - column.Unique = (bool)drow["IsUnique"]; - column.AllowDBNull = (bool)drow["AllowDBNull"]; - column.AutoIncrement = (bool)drow["IsAutoIncrement"]; - dt.Columns.Add(column); - } - - foreach (var sm in sms) - { - Debug.Assert(sm.StoreShard.Location == location); - DataRow row = dt.NewRow(); - row[0] = sm.Id; - row[1] = sm.ShardMapId; - row[2] = sm.MinValue; - row[3] = sm.MaxValue; - row[4] = sm.Version; - row[5] = sm.Status; - row[6] = sm.Custom; - row[7] = sm.StoreShard.Id; - dt.Rows.Add(row); - } - - using (SqlBulkCopy bcp = SqlTransactionScopeLocal.CreateBulkCopy(location)) - { - bcp.DestinationTableName = "_shard_mappings_local"; - bcp.WriteToServer(dt); - } - - return StoreResult.Success; - } -#endif - - /// - /// Add mapping to Global ShardMap. - /// - /// Shard map to add mapping to. - /// Shard mapping to store. - /// Name of stored proc to execute - /// Storage operation result. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", - "CA2100:Review SQL queries for security vulnerabilities", Justification = - "StoredProcName does not come from user input")] - private static IStoreResults AddMappingGlobalHelper(IStoreShardMap ssm, IStoreMapping sm, string storedProcName) - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = storedProcName; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(storedProcName, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("s_id", sm.StoreShard.Id.ToString()), - new XElement("m_id", sm.Id.ToString()), - new XElement("m_min_value", StringUtils.ByteArrayToString(sm.MinValue)), - new XElement("m_max_value", - (sm.MaxValue == null) ? null : StringUtils.ByteArrayToString(sm.MaxValue), - new XAttribute ("is_null", (sm.MaxValue == null) ? "true" : "false") - ), - new XElement("m_version", sm.Version.ToString()), - new XElement("m_status", sm.Status.ToString()), - new XElement("m_custom", (sm.Custom == null) ? null : StringUtils.ByteArrayToString(sm.Custom), - new XAttribute("is_null", (sm.Custom == null) ? "true" : "false") - ) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - - /// - /// Removes mapping from Global ShardMap. - /// - /// Shard map to remove mapping from. - /// Shard mapping to remove. - /// Whether to ignore the Online status - /// Name of stored proc to execute - /// Whether this is a range mapping - /// Lock owner id of this mapping - /// Storage operation result. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", - "CA2100:Review SQL queries for security vulnerabilities", Justification = - "StoredProcName does not come from user input")] - private static IStoreResults RemoveMappingGlobalHelper(IStoreShardMap ssm, IStoreMapping sm, bool force, string storedProcName, - bool isRangeMapping = false, Guid lockOwnerId = default(Guid)) - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = storedProcName; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(storedProcName, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("m_id", sm.Id.ToString()), - new XElement("m_version", sm.Version.ToString()), - new XElement("force_remove", force ? "1" : "0") - ); - - if (isRangeMapping) - { - input.Add(new XElement("lo_id", lockOwnerId.ToString())); - } - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - - /// - /// find mappings in Global ShardMap. - /// - /// Shard map to find mappings in. - /// Optional range to find mappings in. - /// Option shard to find mappings in. - /// Name of stored proc to execute. - /// Storage operation result. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", - "CA2100:Review SQL queries for security vulnerabilities", Justification = - "StoredProcName does not come from user input")] - private static IStoreResults FindMappingByRangeGlobalHelper(IStoreShardMap ssm, ShardRange range, IStoreShard shard, string storedProcName) - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = storedProcName; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(storedProcName, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("s_id", shard == null ? null : shard.Id.ToString(), - new XAttribute("is_null", (shard == null) ? "true" : "false") - ), - new XElement("m_min_value", range == null ? null : StringUtils.ByteArrayToString(range.Low.RawValue), - new XAttribute("is_null", (range == null) ? "true" : "false") - ), - new XElement("m_max_value", (range == null) ? null : StringUtils.ByteArrayToString(range.High.RawValue), - new XAttribute("is_null", (range == null) ? "true" : "false") - ) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - - /// - /// find mappings in Local ShardMap. - /// - /// Shard map to find mappings in. - /// Optional range to find mappings in. - /// Shard to find mappings in. - /// Name of stored proc to execute. - /// Storage operation result. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", - "CA2100:Review SQL queries for security vulnerabilities", Justification = - "StoredProcName does not come from user input")] - private static IStoreResults FindMappingByRangeLocalHelper(IStoreShardMap ssm, ShardRange range, IStoreShard shard, string storedProcName) - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(shard.Location)) - { - cmd.CommandText = storedProcName; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(storedProcName, - new XElement("lsm_version", SqlStoreLsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("s_id", shard == null ? null : shard.Id.ToString(), - new XAttribute("is_null", (shard == null) ? "true" : "false") - ), - new XElement("m_min_value", range == null ? null : StringUtils.ByteArrayToString(range.Low.RawValue), - new XAttribute("is_null", (range == null) ? "true" : "false") - ), - new XElement("m_max_value", (range == null) ? null : StringUtils.ByteArrayToString(range.High.RawValue), - new XAttribute("is_null", (range == null) ? "true" : "false") - ) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - - /// - /// find mappings in Local ShardMap. - /// - /// Shard map to find mappings in. - /// Key corresponding to a point mapping. - /// Shard to find mappings in. - /// Storage operation result. - private static IStoreResults FindMappingByKeyLocalHelper(IStoreShardMap ssm, ShardKey key, IStoreShard shard) - { - string storedProcName = "__ShardManagement.smm_getPointShardMappingLocal"; - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(shard.Location)) - { - cmd.CommandText = storedProcName; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(storedProcName, - new XElement("lsm_version", SqlStoreLsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("s_id", shard.Id.ToString()), - new XElement("m_value", StringUtils.ByteArrayToString(key.RawValue)) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - - - /// - /// Add mapping to local ShardMap. - /// - /// Location of shard. - /// Shard mapping to store. - /// Name of stored proc to execute - /// Storage operation result. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", - "CA2100:Review SQL queries for security vulnerabilities", Justification = - "StoredProcName does not come from user input")] - private static IStoreResults AddMappingLocalHelper(ShardLocation location, IStoreMapping sm, string storedProcName) - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(location)) - { - cmd.CommandText = storedProcName; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(storedProcName, - new XElement("lsm_version", SqlStoreLsmVersion.ToString()), - new XElement("sm_id", sm.ShardMapId.ToString()), - new XElement("s_id", sm.StoreShard.Id.ToString()), - new XElement("m_id", sm.Id.ToString()), - new XElement("m_min_value", StringUtils.ByteArrayToString(sm.MinValue)), - new XElement("m_max_value", - (sm.MaxValue == null) ? null : StringUtils.ByteArrayToString(sm.MaxValue), - new XAttribute("is_null", (sm.MaxValue == null) ? "true" : "false") - ), - new XElement("m_version", sm.Version.ToString()), - new XElement("m_status", sm.Status.ToString()), - new XElement("m_custom", (sm.Custom == null) ? null : StringUtils.ByteArrayToString(sm.Custom), - new XAttribute("is_null", (sm.Custom == null) ? "true" : "false") - ) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - - /// - /// Removes mapping from local ShardMap. - /// - /// Location of shard. - /// Shard mapping to remove. - /// Name of stored proc to execute - /// Force the removal of mapping irrespective of the status. - /// Storage operation result. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", - "CA2100:Review SQL queries for security vulnerabilities", Justification = - "StoredProcName does not come from user input")] - private static IStoreResults RemoveMappingLocalHelper(ShardLocation location, IStoreMapping sm, bool force, string storedProcName) - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(location)) - { - cmd.CommandText = storedProcName; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(storedProcName, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", sm.ShardMapId.ToString()), - new XElement("m_id", sm.Id.ToString()), - new XElement("m_version", sm.Version.ToString()), - new XElement("force_remove", force ? "1" : "0") - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - - /// - /// Finds mapping which contain the given key for the given ShardMap. - /// - /// Shard map to find mappings in. - /// ShardKey being searched. - /// Name of stored proc to execute - /// Storage operation result. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", - "CA2100:Review SQL queries for security vulnerabilities", Justification = - "StoredProcName does not come from user input")] - private static IStoreResults FindMappingByKeyGlobalHelper(IStoreShardMap ssm, byte[] shardKey, string storedProcName) - { - SqlResults result = new SqlResults(); - - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = storedProcName; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(storedProcName, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", ssm.Id.ToString()), - new XElement("sm_version", ssm.Version.ToString()), - new XElement("s_key", StringUtils.ByteArrayToString(shardKey)) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - } - - return result; - } - - /// - /// Validates that the given mapping exists in the shard map. - /// - /// Command to use for validation. - /// Mapping being validated. - /// Name of stored proc to execute. - /// Storage operation result. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", - "CA2100:Review SQL queries for security vulnerabilities", Justification = - "StoredProcName does not come from user input")] - private static IStoreResults ValidateMappingHelper(SqlCommand cmd, IStoreMapping sm, string storedProcName) - { - SqlResults result = new SqlResults(); - - cmd.CommandText = storedProcName; - cmd.CommandType = CommandType.StoredProcedure; - - XElement input = new XElement(storedProcName, - new XElement("gsm_version", SqlStoreGsmVersion.ToString()), - new XElement("sm_id", sm.ShardMapId.ToString()), - new XElement("m_id", sm.Id.ToString()), - new XElement("m_version", sm.Version.ToString()) - ); - - SqlStore.AddCommandParameter(cmd, "@input", SqlDbType.Xml, ParameterDirection.Input, 0, input.ToString()); - SqlParameter resultParam = SqlStore.AddCommandParameter(cmd, "@result", SqlDbType.Int, ParameterDirection.Output, 0, 0); - - using (SqlDataReader reader = cmd.ExecuteReader()) - { - result.Fetch(reader); - } - - // Output parameter will be used to specify the outcome. - result.Result = (StoreResult)resultParam.Value; - - return result; - } - - /// - /// Gets the result of execution of existence check for shard map manager. - /// - /// Command object used for executing the request. - /// Script to execute. - /// true if check succeeds, false otherwise. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", - "CA2100:Review SQL queries for security vulnerabilities", Justification = - "StoredProcName does not come from user input")] - private static bool CheckIfExistsHelper(SqlCommand cmd, IEnumerable script) - { - bool exists = false; - - cmd.CommandText = script.Single().ToString(); - cmd.CommandType = CommandType.Text; - - using (SqlDataReader rdr = cmd.ExecuteReader()) - { - exists = rdr.HasRows; - } - - return exists; - } - - /// - /// Executes the given script on global shard map manager data source. - /// - /// Script to execute - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", - "CA2100:Review SQL queries for security vulnerabilities", Justification = - "StoredProcName does not come from user input")] - private static void ExecuteSqlScriptGlobalHelper(IEnumerable script) - { - foreach (StringBuilder batch in script) - { - using (SqlCommand cmd = SqlTransactionScopeGlobal.CreateSqlCommand()) - { - cmd.CommandText = batch.ToString(); - cmd.CommandType = CommandType.Text; - - cmd.ExecuteNonQuery(); - } - } - } - - /// - /// Executes the given script on local shard map manager data source. - /// - /// Location of local data source. - /// Script to execute - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", - "CA2100:Review SQL queries for security vulnerabilities", Justification = - "StoredProcName does not come from user input")] - private static void ExecuteSqlScriptLocalHelper(ShardLocation location, IEnumerable script) - { - foreach (StringBuilder batch in script) - { - using (SqlCommand cmd = SqlTransactionScopeLocal.CreateSqlCommand(location)) - { - cmd.CommandText = batch.ToString(); - cmd.CommandType = CommandType.Text; - - cmd.ExecuteNonQuery(); - } - } - } - - /// - /// Splits the input script into batches of individual commands, the go token is - /// considered the separation boundary. Also skips comment lines. - /// - /// Input script. - /// Collection of string builder that represent batches of commands. - private static IEnumerable SplitScriptCommands(string script) - { - List batches = new List(); - - using (StringReader sr = new StringReader(script)) - { - StringBuilder current = new StringBuilder(); - string currentLine; - - while ((currentLine = sr.ReadLine()) != null) - { - // Break at the go token boundary. - if (SqlStore.GoTokenRegularExpression.IsMatch(currentLine)) - { - batches.Add(current); - current = new StringBuilder(); - } - else if (!SqlStore.CommentLineRegularExpression.IsMatch(currentLine)) - { - // Add the line to the batch if it is not a comment. - current.AppendLine(currentLine); - } - } - } - - return batches; - } - - /// - /// Adds parameter to given command. - /// - /// Command to add parameter to. - /// Parameter name. - /// Parameter type. - /// Parameter direction. - /// Size of parameter, useful for variable length types only. - /// Parameter value. - /// Parameter object this created. - private static SqlParameter AddCommandParameter( - SqlCommand cmd, - string parameterName, - SqlDbType dbType, - ParameterDirection direction, - int size, - object value) - { - SqlParameter p = new SqlParameter(parameterName, dbType) - { - Direction = direction, - Value = value ?? DBNull.Value - }; - - if ((dbType == SqlDbType.NVarChar) || (dbType == SqlDbType.VarBinary)) - { - p.Size = size; - } - - cmd.Parameters.Add(p); - - return p; - } - - #endregion Helper Functions - } - - /// - /// Represents a global transaction scope. Opens a new connection and starts - /// a transaction on that connection. - /// - internal class SqlTransactionScopeGlobal : IStoreTransactionScope - { - /// - /// Whether the object has already been disposed. - /// - private bool disposed; - - /// - /// Connection used for accessing database. - /// - private SqlConnection conn; - - /// - /// Transaction under which operations happen on the connection. - /// - private SqlTransaction tran; - - /// - /// Current transaction scope. - /// - [ThreadStatic] - private static SqlTransactionScopeGlobal current; - - /// - /// Constructs a new instance of the transaction scope. Uses the - /// credentials scope for obtaining the credentials. - /// - /// Credentials for accessing shard map manager database. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", - "CA2000:Dispose objects before losing scope", Justification = - "Connection is disposed when this is disposed")] - protected internal SqlTransactionScopeGlobal(SqlConnectionStringBuilder shardMapManagerConnectionString) - { - Debug.Assert(SqlTransactionScopeGlobal.current == null); - - SqlConnection conn = new SqlConnection(shardMapManagerConnectionString.ConnectionString); - - conn.Open(); - - SqlTransaction tran = conn.BeginTransaction(IsolationLevel.Serializable); - - this.conn = conn; - this.tran = tran; - SqlTransactionScopeGlobal.current = this; - } - - /// - /// Indicator for whether to commit or rollback transaction. - /// - public bool Success - { - get; - set; - } - -#if DEBUG - /// - /// Event raised by Dispose() method. - /// This event is used for internal testing purpose only. - /// - internal event EventHandler TxnScopeGlobalDisposeEvent; - -#endif // DEBUG - - /// - /// Disposes off the scope. - /// - public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(this); - } - -#if FUTUREWORK - /// - /// Create a command object for executing requests. The command - /// is associated with the underlying connection and transaction - /// objects. - /// - /// Command object which is used for executing requests. - internal static SqlBulkCopy CreateBulkCopy(SqlBulkCopyOptions options = SqlBulkCopyOptions.Default) - { - SqlTransactionScopeGlobal tsGlobal = SqlTransactionScopeGlobal.GetAmbientTransactionScopeGlobal(); - SqlBulkCopy bcp = new SqlBulkCopy(tsGlobal.conn, options, tsGlobal.tran); - return bcp; - } -#endif - - /// - /// Create a command object for executing requests. The command - /// is associated with the underlying connection and transaction - /// objects. - /// - /// Command object which is used for executing requests. - internal static SqlCommand CreateSqlCommand() - { - SqlTransactionScopeGlobal tsGlobal = SqlTransactionScopeGlobal.GetAmbientTransactionScopeGlobal(); - - SqlCommand cmd = tsGlobal.conn.CreateCommand(); - cmd.Transaction = tsGlobal.tran; - return cmd; - } - - /// - /// Protected implementation of Dispose pattern. - /// - /// Whether the object is being Disposed. - protected virtual void Dispose(bool disposing) - { - if (this.disposed) - { - return; - } - - if (disposing) - { - this.FinishTransaction(); - } - - this.disposed = true; - } - - /// - /// Completes the currently active transaction. - /// - internal void FinishTransaction() - { - Debug.Assert(this.conn != null); - Debug.Assert(this.tran != null); - try - { -#if DEBUG - // Raise event and check if current transaction should be aborted. - // - SqlStoreEventArgs eventArgs = new SqlStoreEventArgs(); - - OnDisposeEvent(eventArgs); - - if (eventArgs.action == SqlStoreEventArgs.SqlStoreTxnFinishAction.TxnAbort) - { - throw new StoreException( - Errors.SqlTransactionScopeGlobal_SqlException, - this.Success ? "Commit" : "Rollback"); - } - else -#endif // DEBUG - { - if (this.Success) - { - this.tran.Commit(); - } - else - { - this.tran.Rollback(); - } - } - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlTransactionScopeGlobal_SqlException, - se, - this.Success ? "Commit" : "Rollback"); - } - finally - { - this.tran.Dispose(); - this.conn.Dispose(); - SqlTransactionScopeGlobal.current = null; - } - } - -#if DEBUG - /// - /// Publisher function for TxnScopeGlobalDisposeEvent event. - /// This function is used for internal testing purpose only. - /// - /// Argument to capture transaction finish action - protected void OnDisposeEvent(SqlStoreEventArgs args) - { - EventHandler handler = TxnScopeGlobalDisposeEvent; - if (handler != null) - { - handler(this, args); - } - } - -#endif // DEBUG - - /// - /// Ensures that there is an ambient global transaction scope in the thread. - /// - private static SqlTransactionScopeGlobal GetAmbientTransactionScopeGlobal() - { - SqlTransactionScopeGlobal tsGlobal = SqlTransactionScopeGlobal.current as SqlTransactionScopeGlobal; - - if (tsGlobal == null) - { - throw new StoreException(Errors.SqlStore_TransactionScope_DoesNotExist); - } - - return tsGlobal; - } - } - - /// - /// Represents a local transaction scope. Opens a new connection and starts - /// a transaction on that connection. - /// - internal class SqlTransactionScopeLocal : IStoreTransactionScope - { - /// - /// Whether the object has already been disposed. - /// - private bool disposed; - - /// - /// Connection used for accessing database. - /// - private SqlConnection conn; - - /// - /// Transaction under which operations happen on the connection. - /// - private SqlTransaction tran; - - /// - /// Current transaction scope. - /// - [ThreadStatic] - private static SqlTransactionScopeLocal current; - - /// - /// Constructs a new instance of the transaction scope. Uses the - /// credentials scope for obtaining the credentials. - /// - /// Location of local shard. - /// Credentials for accessing a shard. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", - "CA2000:Dispose objects before losing scope", Justification = - "Connection is disposed when this is disposed")] - protected internal SqlTransactionScopeLocal(ShardLocation location, SqlConnectionStringBuilder shardConnectionString) - { - Debug.Assert(SqlTransactionScopeLocal.current == null); - Debug.Assert(location != null); - Debug.Assert(location.DataSource != null); - Debug.Assert(location.Database != null); - - // Copy the builder. - SqlConnectionStringBuilder lcsb = new SqlConnectionStringBuilder(shardConnectionString.ConnectionString); - - lcsb.DataSource = location.DataSource; - lcsb.InitialCatalog = location.Database; - - SqlConnection conn = new SqlConnection(lcsb.ConnectionString); - - conn.Open(); - - SqlTransaction tran = conn.BeginTransaction(IsolationLevel.Serializable); - - this.Location = location; - this.conn = conn; - this.tran = tran; - SqlTransactionScopeLocal.current = this; - } - - /// - /// Indicator for whether to commit or rollback transaction. - /// - public bool Success - { - get; - set; - } - - /// - /// Location of data source against which operations are to be performed. - /// - private ShardLocation Location - { - get; - set; - } - -#if DEBUG - /// - /// Event raised by Dispose() method. - /// This event is used for internal testing purpose only. - /// - internal event EventHandler TxnScopeLocalDisposeEvent; - -#endif // DEBUG - - /// - /// Disposes off the scope, makes decision on commit or rollback based - /// on the Success property. - /// - public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Create a command object for executing requests. The command - /// is associated with the underlying connection and transaction - /// objects. - /// - /// Target location. Only useful for local operations. - /// Command object which is used for executing requests. - internal static SqlCommand CreateSqlCommand(ShardLocation location) - { - SqlTransactionScopeLocal tsLocal = SqlTransactionScopeLocal.GetAmbientTransactionScopeLocal(location); - - SqlCommand cmd = tsLocal.conn.CreateCommand(); - cmd.Transaction = tsLocal.tran; - return cmd; - } - -#if FUTUREWORK - /// - /// Create a command object for executing requests. The command - /// is associated with the underlying connection and transaction - /// objects. - /// - /// Target location. Only useful for local operations. - /// Command object which is used for executing requests. - internal static SqlBulkCopy CreateBulkCopy(ShardLocation location, SqlBulkCopyOptions options = SqlBulkCopyOptions.Default) - { - SqlTransactionScopeLocal tsLocal = SqlTransactionScopeLocal.GetAmbientTransactionScopeLocal(location); - - SqlBulkCopy bcp = new SqlBulkCopy(tsLocal.conn, options, tsLocal.tran); - return bcp; - } -#endif - - /// - /// Protected implementation of Dispose pattern. - /// - /// Whether the object is being Disposed. - protected virtual void Dispose(bool disposing) - { - if (this.disposed) - { - return; - } - - if (disposing) - { - this.FinishTransaction(); - } - - this.disposed = true; - } - - /// - /// Completes the currently active transaction. - /// - internal void FinishTransaction() - { - Debug.Assert(this.conn != null); - Debug.Assert(this.tran != null); - try - { -#if DEBUG - // Raise event and check if current transaction should be aborted. - // - SqlStoreEventArgs eventArgs = new SqlStoreEventArgs(); - - OnDisposeEvent(eventArgs); - - if (eventArgs.action == SqlStoreEventArgs.SqlStoreTxnFinishAction.TxnAbort) - { - throw new StoreException( - Errors.SqlTransactionScopeLocal_SqlException, - this.Success ? "Commit" : "Rollback", - this.Location); - } - else -#endif // DEBUG - { - if (this.Success) - { - this.tran.Commit(); - } - else - { - this.tran.Rollback(); - } - } - } - catch (SqlException se) - { - throw new StoreException( - Errors.SqlTransactionScopeLocal_SqlException, - se, - this.Success ? "Commit" : "Rollback", - this.Location); - } - finally - { - this.tran.Dispose(); - this.conn.Dispose(); - SqlTransactionScopeLocal.current = null; - } - } - -#if DEBUG - /// - /// Publisher function for TxnScopeGlobalDisposeEvent event. - /// This function is used for internal testing purpose only. - /// - /// Argument to capture transaction finish action - protected void OnDisposeEvent(SqlStoreEventArgs args) - { - EventHandler handler = TxnScopeLocalDisposeEvent; - if (handler != null) - { - handler(this, args); - } - } - -#endif // DEBUG - - /// - /// Ensures that there is an ambient local transaction scope in the thread. - /// - private static SqlTransactionScopeLocal GetAmbientTransactionScopeLocal(ShardLocation location) - { - SqlTransactionScopeLocal tsLocal = SqlTransactionScopeLocal.current as SqlTransactionScopeLocal; - if (tsLocal == null) - { - throw new StoreException(Errors.SqlStore_TransactionScope_DoesNotExist); - } - - if (!tsLocal.Location.Equals(location)) - { - throw new StoreException( - Errors.SqlStore_TransactionScope_LocationMismatch, - tsLocal.Location, - location); - } - - return tsLocal; - } - } - -#if DEBUG - - /// - /// Internal class to handle arguments for SqlStore Events - /// - internal sealed class SqlStoreEventArgs : EventArgs - { - /// - /// Action to be performed on active GSM transaction - /// - internal enum SqlStoreTxnFinishAction - { - None, - TxnAbort, - }; - - /// - /// Default constructor. - /// - internal SqlStoreEventArgs() - { - action = SqlStoreTxnFinishAction.None; - } - - /// - /// Constructor accepting txnFinishAction. - /// - /// Action to be taken for active GSM transaction - internal SqlStoreEventArgs(SqlStoreTxnFinishAction txnAction) - { - action = txnAction; - } - - /// - /// SqlStoreTxnFinishAction variable that will be updated by Subscriber of events. - /// - internal SqlStoreTxnFinishAction action; - } -#endif // DEBUG -} diff --git a/Src/ElasticScale.Client/ShardManagement/Utils/ReflectionUtils.cs b/Src/ElasticScale.Client/ShardManagement/Utils/ReflectionUtils.cs new file mode 100644 index 0000000..b593d5e --- /dev/null +++ b/Src/ElasticScale.Client/ShardManagement/Utils/ReflectionUtils.cs @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Reflection; + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.Utils +{ + internal static class ReflectionUtils + { + public static Assembly GetAssembly(this Type type) + { +#if NETFRAMEWORK + return type.Assembly; +#else + return type.GetTypeInfo().Assembly; +#endif + } + } +} diff --git a/Src/ElasticScale.Client/ShardManagement/Utils/SqlUtils.cs b/Src/ElasticScale.Client/ShardManagement/Utils/SqlUtils.cs index 34e3d32..07487f4 100644 --- a/Src/ElasticScale.Client/ShardManagement/Utils/SqlUtils.cs +++ b/Src/ElasticScale.Client/ShardManagement/Utils/SqlUtils.cs @@ -10,6 +10,7 @@ using System.Data.SqlTypes; using System.Diagnostics; using System.IO; using System.Linq; +using System.Reflection; using System.Resources; using System.Text; using System.Text.RegularExpressions; @@ -491,38 +492,13 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement { List upgradeSteps = new List(); - ResourceSet rs = Scripts.ResourceManager.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture, true, true); + IEnumerable upgradeScripts = parseLocal ? Scripts.UpgradeLocalScripts : Scripts.UpgradeGlobalScripts; - string upgradeFileNameFilter = @"^UpgradeShardMapManagerGlobalFrom(\d*).(\d*)"; - - if (parseLocal) + foreach (var entry in upgradeScripts) { - upgradeFileNameFilter = upgradeFileNameFilter.Replace("Global", "Local"); - } - - Regex fileNameRegEx = new Regex( - upgradeFileNameFilter, - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - - // Filter upgrade scripts based on file name and order by initial Major.Minor version - var upgradeScriptObjects = from r in rs.Cast() - let m = fileNameRegEx.Match(r.Key.ToString()) - where - m.Success - orderby new Version(Convert.ToInt32(m.Groups[1].Value), Convert.ToInt32(m.Groups[2].Value)) - select new - { - Key = r.Key, - Value = r.Value, - initialMajorVersion = Convert.ToInt32(m.Groups[1].Value), - initialMinorVersion = Convert.ToInt32(m.Groups[2].Value) - }; - - foreach (var entry in upgradeScriptObjects) - { - foreach (StringBuilder cmd in SplitScriptCommands(entry.Value.ToString())) + foreach (StringBuilder cmd in SplitScriptCommands(entry.Script)) { - upgradeSteps.Add(new UpgradeSteps(entry.initialMajorVersion, entry.initialMinorVersion, cmd)); + upgradeSteps.Add(new UpgradeSteps(entry.InitialMajorVersion, entry.InitialMinorVersion, cmd)); } } diff --git a/Src/build.props b/Src/build.props deleted file mode 100644 index 6635cb9..0000000 --- a/Src/build.props +++ /dev/null @@ -1,10 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - - - Product\$(RelativeOutputPath) - - - diff --git a/Src/dirs.proj b/Src/dirs.proj deleted file mode 100644 index 013fa37..0000000 --- a/Src/dirs.proj +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/Test/ElasticScale.ClientTestCommon/AssertExtensions.cs b/Test/ElasticScale.ClientTestCommon/AssertExtensions.cs index 7daba23..a743a0b 100644 --- a/Test/ElasticScale.ClientTestCommon/AssertExtensions.cs +++ b/Test/ElasticScale.ClientTestCommon/AssertExtensions.cs @@ -274,8 +274,6 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Test.Common return; } - Trace.TraceError("Expected: [{0}]", expectedArray.ToCommaSeparatedString()); - Trace.TraceError("Actual: [{0}]", actualArray.ToCommaSeparatedString()); Assert.Fail( "Sequences were not equal. Message: {0}. Expected sequence had {1} elements, actual had {2}. Comma separated contents for expected: <{3}>, for actual: <{4}>", message, @@ -320,8 +318,6 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Test.Common } } - Trace.TraceError("Expected: [{0}]", expectedArray.ToCommaSeparatedString()); - Trace.TraceError("Actual: [{0}]", actualArray.ToCommaSeparatedString()); Assert.Fail( "Sequences were not equivalent. Message: {0}. Expected sequence had {1} elements, actual had {2}. Comma separated contents for expected: <{3}>, for actual: <{4}>", message, diff --git a/Test/ElasticScale.ClientTestCommon/CommonTestUtils.cs b/Test/ElasticScale.ClientTestCommon/CommonTestUtils.cs new file mode 100644 index 0000000..b5785ea --- /dev/null +++ b/Test/ElasticScale.ClientTestCommon/CommonTestUtils.cs @@ -0,0 +1,22 @@ +using System; +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.Test.Common +{ + public static class CommonTestUtils + { + public static T SerializeDeserialize(T originalException) where T : Exception + { + using (MemoryStream memStream = new MemoryStream()) + { + BinaryFormatter formatter = new BinaryFormatter(); + + formatter.Serialize(memStream, originalException); + memStream.Seek(0, SeekOrigin.Begin); + + return (T)formatter.Deserialize(memStream); + } + } + } +} diff --git a/Test/ElasticScale.ClientTestCommon/ElasticScale.ClientTestCommon.csproj b/Test/ElasticScale.ClientTestCommon/ElasticScale.ClientTestCommon.csproj deleted file mode 100644 index c031f58..0000000 --- a/Test/ElasticScale.ClientTestCommon/ElasticScale.ClientTestCommon.csproj +++ /dev/null @@ -1,49 +0,0 @@ - - - - {13200c7c-8606-47b8-a004-570b56e3a9a8} - Library - Properties - Microsoft.Azure.SqlDatabase.ElasticScale.ClientTestCommon - Microsoft.Azure.SqlDatabase.ElasticScale.ClientTestCommon - 512 - - - - AnyCPU - true - full - false - $(DefineConstants);DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - $(DefineConstants);TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - diff --git a/Test/ElasticScale.ClientTestCommon/Microsoft.Azure.SqlDatabase.ElasticScale.ClientTestCommon.csproj b/Test/ElasticScale.ClientTestCommon/Microsoft.Azure.SqlDatabase.ElasticScale.ClientTestCommon.csproj new file mode 100644 index 0000000..58c7ed3 --- /dev/null +++ b/Test/ElasticScale.ClientTestCommon/Microsoft.Azure.SqlDatabase.ElasticScale.ClientTestCommon.csproj @@ -0,0 +1,9 @@ + + + net451;netstandard2.0 + + + + + + \ No newline at end of file diff --git a/Test/ElasticScale.ClientTestCommon/Properties/AssemblyInfo.cs b/Test/ElasticScale.ClientTestCommon/Properties/AssemblyInfo.cs index 42c013a..b389366 100644 --- a/Test/ElasticScale.ClientTestCommon/Properties/AssemblyInfo.cs +++ b/Test/ElasticScale.ClientTestCommon/Properties/AssemblyInfo.cs @@ -4,30 +4,9 @@ using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ElasticScale.Test.Common")] -[assembly: AssemblyDescription("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] - [assembly: CLSCompliant(true)] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -// [assembly: AssemblyVersion("1.0.0.0")] -// [assembly: AssemblyFileVersion("1.0.0.0")] - [assembly: NeutralResourcesLanguage("en-US")] diff --git a/Test/ElasticScale.Query.UnitTests/DataSetExtensions.cs b/Test/ElasticScale.Query.UnitTests/DataSetExtensions.cs new file mode 100644 index 0000000..c8a7ef7 --- /dev/null +++ b/Test/ElasticScale.Query.UnitTests/DataSetExtensions.cs @@ -0,0 +1,14 @@ +using System.Data; + +namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests +{ +#if !NET451 + static class DataSetExtensions + { + public static T Field(this DataRow dataSet, int index) + { + return (T)dataSet[index]; + } + } +#endif +} diff --git a/Test/ElasticScale.Query.UnitTests/ElasticScale.Query.UnitTests.csproj b/Test/ElasticScale.Query.UnitTests/ElasticScale.Query.UnitTests.csproj deleted file mode 100644 index 0db3219..0000000 --- a/Test/ElasticScale.Query.UnitTests/ElasticScale.Query.UnitTests.csproj +++ /dev/null @@ -1,115 +0,0 @@ - - - - {56DDEC7E-0B14-4636-B287-DB38DEC55192} - Library - Properties - Microsoft.Azure.SqlDatabase.ElasticScale.Query - Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - False - UnitTest - - - - AnyCPU - true - full - false - $(DefineConstants);DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - $(DefineConstants);TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - Component - - - Component - - - - - - - - - - - - Designer - - - - - - - - - {13200c7c-8606-47b8-a004-570b56e3a9a8} - ClientTestCommon - - - - - {663D22BB-483A-46B0-A504-861C5335DAD1} - Microsoft.Azure.SqlDatabase.ElasticScale.Client - - - - - - - False - - - False - - - False - - - False - - - - - - - - \ No newline at end of file diff --git a/Test/ElasticScale.Query.UnitTests/Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests.csproj b/Test/ElasticScale.Query.UnitTests/Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests.csproj new file mode 100644 index 0000000..d191170 --- /dev/null +++ b/Test/ElasticScale.Query.UnitTests/Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests.csproj @@ -0,0 +1,17 @@ + + + net452;netcoreapp2.0 + false + + + + + + + + + + + + + \ No newline at end of file diff --git a/Test/ElasticScale.Query.UnitTests/MockSqlConnection.cs b/Test/ElasticScale.Query.UnitTests/MockSqlConnection.cs index ead8723..dfe6dcc 100644 --- a/Test/ElasticScale.Query.UnitTests/MockSqlConnection.cs +++ b/Test/ElasticScale.Query.UnitTests/MockSqlConnection.cs @@ -167,15 +167,6 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests throw new NotSupportedException(); } - /// - /// - /// - /// - public override void EnlistTransaction(System.Transactions.Transaction transaction) - { - throw new NotSupportedException(); - } - /// /// /// diff --git a/Test/ElasticScale.Query.UnitTests/MockSqlDataReader.cs b/Test/ElasticScale.Query.UnitTests/MockSqlDataReader.cs index 03b12e5..8a4eaab 100644 --- a/Test/ElasticScale.Query.UnitTests/MockSqlDataReader.cs +++ b/Test/ElasticScale.Query.UnitTests/MockSqlDataReader.cs @@ -10,7 +10,9 @@ using System.Collections; using System.Data; using System.Data.Common; using System.IO; +#if NETFRAMEWORK using System.Runtime.Remoting; +#endif using System.Threading; using System.Threading.Tasks; @@ -52,7 +54,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests } /// - /// Gets the number of columns in the current row. + /// Gets the number of columns in the current row. /// public override int FieldCount { @@ -60,7 +62,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests } /// - /// Gets a value that indicates whether this DbDataReader contains one or more rows. + /// Gets a value that indicates whether this DbDataReader contains one or more rows. /// public override bool HasRows { @@ -99,7 +101,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests } /// - /// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement. + /// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement. /// /// /// However, from the SqlDataReader source, it looks like the property is updated before the reader is closed @@ -154,6 +156,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests _isClosed = false; } +#if NETFRAMEWORK /// /// Not implemented /// @@ -161,6 +164,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests { throw new NotImplementedException(); } +#endif /// /// Gets the value of the specified column as a Boolean. @@ -183,7 +187,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests } /// - /// Reads a stream of bytes from the specified column, starting at location indicated by dataOffset, into the + /// Reads a stream of bytes from the specified column, starting at location indicated by dataOffset, into the /// buffer, starting at the location indicated by bufferOffset. /// /// The zero-based column ordinal. @@ -208,7 +212,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests } /// - /// Reads a stream of characters from the specified column, starting at location indicated by dataOffset, into + /// Reads a stream of characters from the specified column, starting at location indicated by dataOffset, into /// the buffer, starting at the location indicated by bufferOffset. /// /// The zero-based column ordinal. @@ -243,7 +247,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests } /// - /// Returns a DbDataReader object for the requested column ordinal that can be overridden with a + /// Returns a DbDataReader object for the requested column ordinal that can be overridden with a /// provider-specific implementation. /// /// The zero-based column ordinal. @@ -544,6 +548,6 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests base.Dispose(disposing); } - #endregion +#endregion } } diff --git a/Test/ElasticScale.Query.UnitTests/MultiShardDataReaderTests.cs b/Test/ElasticScale.Query.UnitTests/MultiShardDataReaderTests.cs index 8240f38..c149928 100644 --- a/Test/ElasticScale.Query.UnitTests/MultiShardDataReaderTests.cs +++ b/Test/ElasticScale.Query.UnitTests/MultiShardDataReaderTests.cs @@ -2,14 +2,14 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // Purpose: -// Basic unit testing for the MultiShardDataReader class. Will integrate with +// Basic unit testing for the MultiShardDataReader class. Will integrate with // build at a later date. // // Notes: // Aim is to integrate this within a broader cleint-side wrapper framework. // As a result, unit testing will likely be relatively significantly // restructured once we have the rest of the wrapper classes in place. -// *NOTE: Unit tests currently assume that a sql server instance is +// *NOTE: Unit tests currently assume that a sql server instance is // accessible on localhost. // *NOTE: Unit tests will blow away and recreate databases called Test1, Test2, // and Test3. Should change these database names to guids at some point, but @@ -29,7 +29,9 @@ using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Diagnostics; +#if NETFRAMEWORK using System.Runtime.Remoting; +#endif using System.IO; using System.Threading.Tasks; using System.Threading; @@ -37,7 +39,7 @@ using System.Threading; namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests { /// - /// Very basic unit tests for the MultiShardDataReader class. + /// Very basic unit tests for the MultiShardDataReader class. /// Just enough to ensure that simple scenarios working as expected. /// [TestClass] @@ -71,7 +73,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests /// public TestContext TestContext { get; set; } - #region Additional test attributes +#region Additional test attributes /// /// Sets up our three test databases that we drive the unit testing off of. @@ -146,7 +148,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests } } - #endregion +#endregion /// /// Validate MultiShardDataReader can be supplied as argument to DataTable.Load @@ -328,8 +330,8 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests } /// - /// Check that we collect an exception and expose it on the ShardedReader - /// when encountering schema mismatches across result sets due to different + /// Check that we collect an exception and expose it on the ShardedReader + /// when encountering schema mismatches across result sets due to different /// column names. /// [TestMethod] @@ -337,7 +339,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests public void TestMismatchedSchemasWrongColumnName() { // What we're doing: - // Issue different queries to readers 1 & 2 so that we have the same column count and types but we have a + // Issue different queries to readers 1 & 2 so that we have the same column count and types but we have a // column name mismatch. // Try to load them into a MultiShardDataReader. // Should see an exception on the MultiShardDataReader. @@ -373,7 +375,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests } /// - /// Check that we throw as expected when encountering schema mismatches across result sets due to different + /// Check that we throw as expected when encountering schema mismatches across result sets due to different /// column types. /// [TestMethod] @@ -381,7 +383,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests public void TestMismatchedSchemasWrongType() { // What we're doing: - // Issue different queries to readers 1 & 2 so that we have the same column count and names but we have a + // Issue different queries to readers 1 & 2 so that we have the same column count and names but we have a // column type mismatch. // Try to load them into a MultiShardDataReader. // Should see an exception on the MultiShardDataReader. @@ -495,9 +497,9 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests } /// - /// Validate ReadAsync() behavior when multiple data readers are involved. This test is same as existing test TestMiddleResultEmptyOnSelect + /// Validate ReadAsync() behavior when multiple data readers are involved. This test is same as existing test TestMiddleResultEmptyOnSelect /// except that we are using ReadAsync() in this case instead of Read() to read individual rows. - /// + /// /// NOTE: We needn't replicate every single Read() test for ReadAsync() since Read() ends up calling ReadAsync().Result under the /// hood. So, by validating Read(), we are also validating ReadAsync() indirectly. /// @@ -575,7 +577,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests // Create a new task that would try to read rows off the second shard while they are locked by the previous task // and block therefore. - Task readToBlockTask = Task.Factory.StartNew(() => + Task readToBlockTask = Task.Factory.StartNew(() => { string selectSql = string.Format( "SELECT dbNameField, Test_int_Field, Test_bigint_Field FROM ConsistentShardedTable WHERE dbNameField='{0}'", @@ -604,7 +606,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests Assert.IsTrue(ex != null, "A task canceled exception was not received upon cancellation."); } - + // Set the event signaling the first task to rollback its update transaction. rollback.Set(); @@ -620,8 +622,8 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests { // The code below exposes a flaw in our current implementation related to // CompleteResults semantics and the internal c-tor. The flaw does not - // leak out to customers because the MultiShardCommand object manages the - // necessary logic, but we need to patch the flaw so it doesn't end up + // leak out to customers because the MultiShardCommand object manages the + // necessary logic, but we need to patch the flaw so it doesn't end up // inadvertently leaking out to customers. // See VSTS 2616238 (i believe). Philip will be modofying logic and // augmenting tests to deal with this issue. @@ -656,8 +658,8 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests { // The code below exposes a flaw in our current implementation related to // CompleteResults semantics and the internal c-tor. The flaw does not - // leak out to customers because the MultiShardCommand object manages the - // necessary logic, but we need to patch the flaw so it doesn't end up + // leak out to customers because the MultiShardCommand object manages the + // necessary logic, but we need to patch the flaw so it doesn't end up // inadvertently leaking out to customers. // See VSTS 2616238 (i believe). Philip will be modofying logic and // augmenting tests to deal with this issue. @@ -686,7 +688,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests /// /// Validate that we throw an exception and invalidate the - /// MultiShardDataReader when we encounter a reader that has + /// MultiShardDataReader when we encounter a reader that has /// multiple result sets /// [TestMethod] @@ -791,8 +793,8 @@ SELECT dbNameField, Test_int_Field, Test_bigint_Field FROM ConsistentShardedTab { // The code below exposes a flaw in our current implementation related to // CompleteResults semantics and the internal c-tor. The flaw does not - // leak out to customers because the MultiShardCommand object manages the - // necessary logic, but we need to patch the flaw so it doesn't end up + // leak out to customers because the MultiShardCommand object manages the + // necessary logic, but we need to patch the flaw so it doesn't end up // inadvertently leaking out to customers. // See VSTS 2616238 (i believe). Philip will be modofying logic and // augmenting tests to deal with this issue. @@ -858,9 +860,9 @@ SELECT dbNameField, Test_int_Field, Test_bigint_Field FROM ConsistentShardedTab LabeledDbDataReader[] readers = new LabeledDbDataReader[0]; using (MultiShardDataReader sdr = new MultiShardDataReader( - _dummyCommand, + _dummyCommand, readers, - MultiShardExecutionPolicy.CompleteResults, + MultiShardExecutionPolicy.CompleteResults, addShardNamePseudoColumn: true, expectedReaderCount: connections.Count)) { @@ -900,7 +902,7 @@ SELECT dbNameField, Test_int_Field, Test_bigint_Field FROM ConsistentShardedTab } /// - /// Check that we successfuly support the asynchronous addition of readers while we are in the process of reading, when we start + /// Check that we successfuly support the asynchronous addition of readers while we are in the process of reading, when we start /// with some readers already added. /// [TestMethod] @@ -917,9 +919,9 @@ SELECT dbNameField, Test_int_Field, Test_bigint_Field FROM ConsistentShardedTab }; using (MultiShardDataReader sdr = new MultiShardDataReader( - _dummyCommand, - readers, - MultiShardExecutionPolicy.CompleteResults, + _dummyCommand, + readers, + MultiShardExecutionPolicy.CompleteResults, addShardNamePseudoColumn: true, expectedReaderCount: connections.Count)) { @@ -1035,7 +1037,7 @@ SELECT dbNameField, Test_int_Field, Test_bigint_Field FROM ConsistentShardedTab } } - +#if NETFRAMEWORK /// /// Check that we throw as expected when trying to call CreateObjRef. /// @@ -1056,6 +1058,7 @@ SELECT dbNameField, Test_int_Field, Test_bigint_Field FROM ConsistentShardedTab sdr.CreateObjRef(typeof(MultiShardDataReader)); } } +#endif /// /// Check that we can iterate through the result sets as expected comparing all the values @@ -1158,7 +1161,7 @@ SELECT dbNameField, Test_int_Field, Test_bigint_Field FROM ConsistentShardedTab } } - #region Helpers +#region Helpers private void ExpectException(Func func, int ordinal) where T : Exception { @@ -1207,14 +1210,14 @@ SELECT dbNameField, Test_int_Field, Test_bigint_Field FROM ConsistentShardedTab private void VerifyAllGettersPositiveCases(MultiShardDataReader reader, MutliShardTestCaseColumn column, int ordinal) { // General pattern here: - // Grab the value through the regular getter, through the getValue, - // through the sync GetFieldValue, and through the async GetFieldValue to ensure we are + // Grab the value through the regular getter, through the getValue, + // through the sync GetFieldValue, and through the async GetFieldValue to ensure we are // getting back the same thing from all calls. // // Then grab through the Sql getter to make sure it works. (should we compare again?) // // Then verify that the field types are as we expect. - // + // // Note: For the array-based getters we can't do the sync/async comparison. // @@ -1237,7 +1240,7 @@ SELECT dbNameField, Test_int_Field, Test_bigint_Field FROM ConsistentShardedTab // And these are indexes into our SQL type array. - // + // int SqlValueResult = 0; int SqlGetResult = 1; object[] sqlResults = new object[SqlGetResult + 1]; @@ -1649,6 +1652,6 @@ SELECT dbNameField, Test_int_Field, Test_bigint_Field FROM ConsistentShardedTab return sdr; } - #endregion Helpers +#endregion Helpers } } diff --git a/Test/ElasticScale.Query.UnitTests/MultiShardTestUtils.cs b/Test/ElasticScale.Query.UnitTests/MultiShardTestUtils.cs index 3624189..934c2de 100644 --- a/Test/ElasticScale.Query.UnitTests/MultiShardTestUtils.cs +++ b/Test/ElasticScale.Query.UnitTests/MultiShardTestUtils.cs @@ -45,12 +45,6 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests /// private static string s_dbNameField = "dbNameField"; - /// - /// SqlCredential encapsulating the testUserId and testPassword that we will use - /// when opening connections to shards when issuing a fanout query. - /// - private static SqlCredential s_testCredential = GenerateDefaultSqlCredential(); - /// /// Connection string for local shard user. /// @@ -166,15 +160,6 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests ExecuteNonQueries("master", commands); } - /// - /// Simple helper to obtain the SqlCredential to use in running our tests. - /// - /// The test username and password packaged up into a SqlCredential object. - internal static SqlCredential GetTestSqlCredential() - { - return s_testCredential; - } - /// /// Helper method that alters the column name on one of our test tables in one of our test databases. /// Useful for inducing a schema mismatch to test our failure handling. @@ -251,26 +236,6 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests return rVal; } - /// - /// Static helper that populates our defualt password into a SecureString. - /// - /// The default password encoded in a SecureString. - private static SqlCredential GenerateDefaultSqlCredential() - { - SecureString ss = new SecureString(); - char[] pwdChars = s_testPassword.ToCharArray(); - for (int i = 0; i < pwdChars.Length; i++) - { - ss.AppendChar(pwdChars[i]); - } - - // Need to mark it as read only to avoid an ArgumentException in the SqlCredential c-tor. - // - ss.MakeReadOnly(); - - return new SqlCredential(s_testUserId, ss); - } - /// /// Helper to populate a list with our test database names. /// diff --git a/Test/ElasticScale.Query.UnitTests/MultiShardUnitTests.cs b/Test/ElasticScale.Query.UnitTests/MultiShardUnitTests.cs index 40ad87f..d398962 100644 --- a/Test/ElasticScale.Query.UnitTests/MultiShardUnitTests.cs +++ b/Test/ElasticScale.Query.UnitTests/MultiShardUnitTests.cs @@ -14,12 +14,11 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Data.Common; -using System.IO; using System.Linq; -using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement; +using Microsoft.Azure.SqlDatabase.ElasticScale.Test.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests @@ -570,9 +569,14 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests MultiShardAggregateException aggEx = new MultiShardAggregateException(exList); - TestSerialization(innerEx1); - TestSerialization(innerEx2); - TestSerialization(aggEx); + MultiShardException deserialized1 = CommonTestUtils.SerializeDeserialize(innerEx1); + CompareForEquality(innerEx1, deserialized1); + + MultiShardException deserialized2 = CommonTestUtils.SerializeDeserialize(innerEx2); + CompareForEquality(innerEx2, deserialized2); + + MultiShardAggregateException deserialized3 = CommonTestUtils.SerializeDeserialize(aggEx); + CompareForEquality(aggEx, deserialized3); } /// @@ -737,20 +741,6 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests #endregion - private void TestSerialization(T originalException) where T : Exception - { - MemoryStream memStream = new MemoryStream(); - BinaryFormatter formatter = new BinaryFormatter(); - - formatter.Serialize(memStream, originalException); - memStream.Seek(0, SeekOrigin.Begin); - - T deserializedException = (T)formatter.Deserialize(memStream); - memStream.Close(); - - CompareForEquality(originalException, deserializedException); - } - private void CompareForEquality(Exception first, Exception second) { Assert.AreEqual(first.GetType(), second.GetType()); diff --git a/Test/ElasticScale.Query.UnitTests/Properties/AssemblyInfo.cs b/Test/ElasticScale.Query.UnitTests/Properties/AssemblyInfo.cs index aa8d0be..5048da1 100644 --- a/Test/ElasticScale.Query.UnitTests/Properties/AssemblyInfo.cs +++ b/Test/ElasticScale.Query.UnitTests/Properties/AssemblyInfo.cs @@ -5,14 +5,8 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Microsoft.Azure.SqlDatabase.ElasticScale.Query.UnitTests")] -[assembly: AssemblyDescription("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] diff --git a/Test/ElasticScale.ShardManagement.LoadTests/ElasticScale.ShardManagement.LoadTests.csproj b/Test/ElasticScale.ShardManagement.LoadTests/ElasticScale.ShardManagement.LoadTests.csproj index 7526091..228b3f9 100644 --- a/Test/ElasticScale.ShardManagement.LoadTests/ElasticScale.ShardManagement.LoadTests.csproj +++ b/Test/ElasticScale.ShardManagement.LoadTests/ElasticScale.ShardManagement.LoadTests.csproj @@ -14,7 +14,6 @@ WebTest False - true full @@ -69,7 +68,7 @@ - - \ No newline at end of file diff --git a/Test/ElasticScale.ShardManagement.UnitTests/Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests.csproj b/Test/ElasticScale.ShardManagement.UnitTests/Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests.csproj new file mode 100644 index 0000000..c73b138 --- /dev/null +++ b/Test/ElasticScale.ShardManagement.UnitTests/Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests.csproj @@ -0,0 +1,17 @@ + + + net451;netcoreapp2.0 + false + + + + + + + + + + + + + \ No newline at end of file diff --git a/Test/ElasticScale.ShardManagement.UnitTests/Properties/AssemblyInfo.cs b/Test/ElasticScale.ShardManagement.UnitTests/Properties/AssemblyInfo.cs index 7123ea3..50841aa 100644 --- a/Test/ElasticScale.ShardManagement.UnitTests/Properties/AssemblyInfo.cs +++ b/Test/ElasticScale.ShardManagement.UnitTests/Properties/AssemblyInfo.cs @@ -5,14 +5,8 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ShardMapManagerUnitTests")] -[assembly: AssemblyDescription("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] diff --git a/Test/ElasticScale.ShardManagement.UnitTests/ScenarioTests.cs b/Test/ElasticScale.ShardManagement.UnitTests/ScenarioTests.cs index 0100fed..2f5b719 100644 --- a/Test/ElasticScale.ShardManagement.UnitTests/ScenarioTests.cs +++ b/Test/ElasticScale.ShardManagement.UnitTests/ScenarioTests.cs @@ -1344,6 +1344,7 @@ end", s_testUser); [TestCategory("ExcludeFromGatedCheckin")] public void ListShardMapPerformanceCounterValidation() { +#if NETFRAMEWORK if (PerfCounterInstance.HasCreatePerformanceCategoryPermissions()) { string shardMapName = "PerTenantShardMap"; @@ -1454,8 +1455,10 @@ end", s_testUser); { Assert.Inconclusive("Do not have permissions to create performance counter category, test skipped"); } +#endif } +#if NETFRAMEWORK private bool ValidateNonZeroCounterValue(string instanceName, PerformanceCounterName counterName) { string counterdisplayName = (from c in PerfCounterInstance.counterList @@ -1486,6 +1489,7 @@ end", s_testUser); { return PerformanceCounterCategory.InstanceExists(instanceName, PerformanceCounters.ShardManagementPerformanceCounterCategory); } +#endif private RangeMapping MarkMappingOfflineAndUpdateShard(RangeShardMap map, RangeMapping mapping, Shard newShard) { diff --git a/Test/ElasticScale.ShardManagement.UnitTests/SchemaInfoCollectionTests.cs b/Test/ElasticScale.ShardManagement.UnitTests/SchemaInfoCollectionTests.cs index 0b76eee..bbc686f 100644 --- a/Test/ElasticScale.ShardManagement.UnitTests/SchemaInfoCollectionTests.cs +++ b/Test/ElasticScale.ShardManagement.UnitTests/SchemaInfoCollectionTests.cs @@ -328,6 +328,18 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests Assert.AreEqual(3, i); } + [TestMethod] + [TestCategory("ExcludeFromGatedCheckin")] + public void TestSchemaInfoExceptionSerializability() + { + SchemaInfoException ex = new SchemaInfoException(SchemaInfoErrorCode.SchemaInfoNameConflict, "message"); + SchemaInfoException deserialized = CommonTestUtils.SerializeDeserialize(ex); + + // Validate + Assert.AreEqual(ex.ErrorCode, deserialized.ErrorCode, "ErrorCode"); + Assert.AreEqual(ex.ToString(), deserialized.ToString(), "ToString()"); + } + /// /// Verifies that the serialization format of matches the serialization format /// from v1.0.0. If this fails, then an older version of EDCL v1.0.0 will not be able to successfully diff --git a/Test/ElasticScale.ShardManagement.UnitTests/ShardMapFaultHandlingTests.cs b/Test/ElasticScale.ShardManagement.UnitTests/ShardMapFaultHandlingTests.cs index b5243c6..85930ca 100644 --- a/Test/ElasticScale.ShardManagement.UnitTests/ShardMapFaultHandlingTests.cs +++ b/Test/ElasticScale.ShardManagement.UnitTests/ShardMapFaultHandlingTests.cs @@ -1481,11 +1481,16 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests private static SqlException CreateSqlException() { - ConstructorInfo ciSqlError = typeof(SqlError) - .GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic) - .Single(c => c.GetParameters().Length == 7); + ConstructorInfo[] cisSqlError = typeof(SqlError) + .GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic); +#if NETFRAMEWORK + ConstructorInfo ciSqlError = cisSqlError.Single(c => c.GetParameters().Length == 7); SqlError se = (SqlError)ciSqlError.Invoke(new object[] { (int)10928, (byte)0, (byte)0, "", "", "", (int)0 }); +#else + ConstructorInfo ciSqlError = cisSqlError.Single(c => c.GetParameters().Length == 8); + SqlError se = (SqlError)ciSqlError.Invoke(new object[] { (int)10928, (byte)0, (byte)0, "", "", "", (int)0, null }); +#endif ConstructorInfo ciSqlErrorCollection = typeof(SqlErrorCollection) .GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Single(); diff --git a/Test/ElasticScale.ShardManagement.UnitTests/ShardMapManagerLoadTests.cs b/Test/ElasticScale.ShardManagement.UnitTests/ShardMapManagerLoadTests.cs index 7b33726..769417a 100644 --- a/Test/ElasticScale.ShardManagement.UnitTests/ShardMapManagerLoadTests.cs +++ b/Test/ElasticScale.ShardManagement.UnitTests/ShardMapManagerLoadTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.SqlDatabase.ElasticScale; using Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.Recovery; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; @@ -8,8 +9,6 @@ using System.Collections.Generic; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; -using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling; -using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.SqlAzure; namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests { @@ -114,7 +113,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests /// /// Retry policy used for DDR in unit tests. /// - private static RetryPolicy s_retryPolicy; + private static TransientFaultHandling.RetryPolicy s_retryPolicy; #region CommonMethods @@ -215,8 +214,8 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests } // Initialize retry policy - s_retryPolicy = new RetryPolicy( - new ExponentialBackoff(5, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(100))); + s_retryPolicy = new TransientFaultHandling.RetryPolicy( + new TransientFaultHandling.ExponentialBackoff(5, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(100))); } /// diff --git a/Test/ElasticScale.ShardManagement.UnitTests/ShardMapManagerTests.cs b/Test/ElasticScale.ShardManagement.UnitTests/ShardMapManagerTests.cs index 5a8fff7..0b0bd10 100644 --- a/Test/ElasticScale.ShardManagement.UnitTests/ShardMapManagerTests.cs +++ b/Test/ElasticScale.ShardManagement.UnitTests/ShardMapManagerTests.cs @@ -91,7 +91,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests } catch (ShardManagementException smme) { - Assert.IsTrue(smme.ErrorCode == ShardManagementErrorCode.ShardMapLookupFailure); + Assert.AreEqual(ShardManagementErrorCode.ShardMapLookupFailure, smme.ErrorCode); } } @@ -111,7 +111,7 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests } catch (ShardManagementException smme) { - Assert.IsTrue(smme.ErrorCode == ShardManagementErrorCode.ShardMapLookupFailure); + Assert.AreEqual(ShardManagementErrorCode.ShardMapLookupFailure, smme.ErrorCode); } } @@ -364,24 +364,12 @@ namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests var errorCode = ShardManagementErrorCode.ShardMapDoesNotExist; ShardManagementException ex = new ShardManagementException(errorCategory, errorCode, "Testing"); - string exceptionToString = ex.ToString(); - - // Serialize and de-serialize with a BinaryFormatter - BinaryFormatter bf = new BinaryFormatter(); - using (MemoryStream ms = new MemoryStream()) - { - // Serialize - bf.Serialize(ms, ex); - - // Deserialize - ms.Seek(0, 0); - ex = (ShardManagementException)bf.Deserialize(ms); - } + ShardManagementException deserialized = CommonTestUtils.SerializeDeserialize(ex); // Validate - Assert.AreEqual(ex.ErrorCode, errorCode, "ErrorCode"); - Assert.AreEqual(ex.ErrorCategory, errorCategory, "ErrorCategory"); - Assert.AreEqual(exceptionToString, ex.ToString(), "ToString()"); + Assert.AreEqual(ex.ErrorCode, deserialized.ErrorCode, "ErrorCode"); + Assert.AreEqual(ex.ErrorCategory, deserialized.ErrorCategory, "ErrorCategory"); + Assert.AreEqual(ex.ToString(), deserialized.ToString(), "ToString()"); } #region GsmAbortTests diff --git a/Test/build.props b/Test/build.props deleted file mode 100644 index 0744f34..0000000 --- a/Test/build.props +++ /dev/null @@ -1,10 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - - - Test\$(RelativeOutputPath) - - - diff --git a/Test/dirs.proj b/Test/dirs.proj deleted file mode 100644 index ad559cb..0000000 --- a/Test/dirs.proj +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/build.cmd b/build.cmd deleted file mode 100644 index 3ede296..0000000 --- a/build.cmd +++ /dev/null @@ -1,31 +0,0 @@ -@ECHO OFF - -SETLOCAL - -SET CACHED_NUGET=%LocalAppData%\NuGet\NuGet.exe -SET SOLUTION_PATH="%~dp0ElasticDatabaseTools.sln" -SET MSBUILD12_TOOLS_PATH="%ProgramFiles(x86)%\MSBuild\12.0\bin\MSBuild.exe" -SET MSBUILD14_TOOLS_PATH="%ProgramFiles(x86)%\MSBuild\14.0\bin\MSBuild.exe" -SET BUILD_TOOLS_PATH=%MSBUILD14_TOOLS_PATH% - -IF EXIST %MSBUILD14_TOOLS_PATH% ( - SET BUILD_TOOLS_PATH=%MSBUILD14_TOOLS_PATH% -) else if exist %MSBUILD12_TOOLS_PATH% ( - SET BUILD_TOOLS_PATH=%MSBUILD12_TOOLS_PATH% -) else ( - echo Could not find MSBuild in any of the following locations: - echo %MSBUILD14_TOOLS_PATH% - echo %MSBUILD12_TOOLS_PATH% - exit /b 1 -) - -IF EXIST %CACHED_NUGET% goto restore -echo Downloading latest version of NuGet.exe... -IF NOT EXIST %LocalAppData%\NuGet md %LocalAppData%\NuGet -@powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://www.nuget.org/nuget.exe' -OutFile '%CACHED_NUGET%'" - -:restore -IF NOT EXIST src\packages md src\packages -%CACHED_NUGET% restore %SOLUTION_PATH% - -%BUILD_TOOLS_PATH% %SOLUTION_PATH% /nologo /m /v:m /flp:verbosity=normal %* \ No newline at end of file diff --git a/build.props b/build.props index 2fbc0d8..ff755bf 100644 --- a/build.props +++ b/build.props @@ -1,52 +1,5 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + + + $(DefineConstants);NETFRAMEWORK - - - true - false - - - - - - prompt - 4 - $(DefineConstants);STANDALONE_BUILD - v4.5.1 - - Debug - - - $(MSBuildThisFileDirectory)\obj\$(MSBuildProjectFile) - $(MSBuildThisFileDirectory)\bin - $(BaseOutputPath)\$(Configuration)\$(AssemblyName) - $(MSBuildThisFileDirectory)\packages - - - - false - full - $(DefineConstants),DEBUG,TRACE,CODE_ANALYSIS - - - - true - pdbonly - $(DefineConstants),TRACE - - - - - true - - - + \ No newline at end of file diff --git a/dirs.proj b/dirs.proj deleted file mode 100644 index 2030bea..0000000 --- a/dirs.proj +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/global.json b/global.json new file mode 100644 index 0000000..043b94e --- /dev/null +++ b/global.json @@ -0,0 +1,3 @@ +{ + "projects": [ "Src" ] +} \ No newline at end of file