From 307fe8424286ca2e34dc26a9d908b9e998d23254 Mon Sep 17 00:00:00 2001 From: "ulf.johansson" Date: Tue, 5 Nov 2019 09:25:55 +0100 Subject: [PATCH 1/2] Add possibility to add prefix to tables --- src/Hangfire.SqlServer/Constants.cs | 3 +- src/Hangfire.SqlServer/CountersAggregator.cs | 4 +- src/Hangfire.SqlServer/DefaultInstall.sql | 98 ++++- src/Hangfire.SqlServer/DefaultInstall.tt | 2 +- src/Hangfire.SqlServer/ExpirationManager.cs | 7 +- src/Hangfire.SqlServer/Install.sql | 358 +++++++++++------- src/Hangfire.SqlServer/SqlServerConnection.cs | 64 ++-- src/Hangfire.SqlServer/SqlServerJobQueue.cs | 8 +- .../SqlServerJobQueueMonitoringApi.cs | 8 +- .../SqlServerMonitoringApi.cs | 50 +-- .../SqlServerObjectsInstaller.cs | 15 +- src/Hangfire.SqlServer/SqlServerStorage.cs | 5 +- .../SqlServerStorageOptions.cs | 21 +- src/Hangfire.SqlServer/SqlServerTimeoutJob.cs | 6 +- .../SqlServerWriteOnlyTransaction.cs | 54 +-- .../Utils/CleanDatabaseAttribute.cs | 2 +- 16 files changed, 452 insertions(+), 253 deletions(-) diff --git a/src/Hangfire.SqlServer/Constants.cs b/src/Hangfire.SqlServer/Constants.cs index 3688b31fd..54b97d76c 100644 --- a/src/Hangfire.SqlServer/Constants.cs +++ b/src/Hangfire.SqlServer/Constants.cs @@ -3,5 +3,6 @@ internal class Constants { public static readonly string DefaultSchema = "HangFire"; - } + public static readonly string DefaultTablePrefix = string.Empty; + } } diff --git a/src/Hangfire.SqlServer/CountersAggregator.cs b/src/Hangfire.SqlServer/CountersAggregator.cs index 0d825d407..9d1336a35 100644 --- a/src/Hangfire.SqlServer/CountersAggregator.cs +++ b/src/Hangfire.SqlServer/CountersAggregator.cs @@ -100,11 +100,11 @@ BEGIN TRAN DELETE TOP (@count) C OUTPUT DELETED.[Key], DELETED.[Value], DELETED.[ExpireAt] INTO @RecordsToAggregate -FROM [{storage.SchemaName}].[Counter] C WITH (READPAST, XLOCK, INDEX(0)) +FROM [{storage.SchemaName}].[{storage.TablePrefix}Counter] C WITH (READPAST, XLOCK, INDEX(0)) SET NOCOUNT ON -;MERGE [{storage.SchemaName}].[AggregatedCounter] WITH (FORCESEEK, HOLDLOCK) AS [Target] +;MERGE [{storage.SchemaName}].[{storage.TablePrefix}AggregatedCounter] WITH (FORCESEEK, HOLDLOCK) AS [Target] USING ( SELECT [Key], SUM([Value]) as [Value], MAX([ExpireAt]) AS [ExpireAt] FROM @RecordsToAggregate GROUP BY [Key]) AS [Source] ([Key], [Value], [ExpireAt]) diff --git a/src/Hangfire.SqlServer/DefaultInstall.sql b/src/Hangfire.SqlServer/DefaultInstall.sql index 0a5ab6332..9239883a1 100644 --- a/src/Hangfire.SqlServer/DefaultInstall.sql +++ b/src/Hangfire.SqlServer/DefaultInstall.sql @@ -43,18 +43,108 @@ DECLARE @SCHEMA_ID int; SELECT @SCHEMA_ID = [schema_id] FROM [sys].[schemas] WHERE [name] = 'HangFire'; -- Create the [HangFire].Schema table if not exists -IF NOT EXISTS(SELECT [object_id] FROM [sys].[tables] - WHERE [name] = 'Schema' AND [schema_id] = @SCHEMA_ID) + +SELECT @SCHEMAColumnName = [t].[name] FROM [sys].[columns] c +INNER JOIN [sys].[tables] t ON [c].[object_id] = [t.object_id] +WHERE [c].[name] = 'Version' and [t].[name] like '%Schema' and [t].schema_id = @SCHEMA_ID + +IF NOT EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @SCHEMAColumnName AND [schema_id] = @SCHEMA_ID) BEGIN CREATE TABLE [HangFire].[Schema]( [Version] [int] NOT NULL, + [TablePrefix] varchar(20) NOT NULL DEFAULT(''), + [TablePrefixOld] varchar(20) NOT NULL DEFAULT(''), CONSTRAINT [PK_HangFire_Schema] PRIMARY KEY CLUSTERED ([Version] ASC) ); + SET @SCHEMAColumnName = '[Schema]'; PRINT 'Created table [HangFire].[Schema]'; END ELSE PRINT 'Table [HangFire].[Schema] already exists'; - + +-- Update table names if prefix has changed +DECLARE @OLDTABLEPREFIX varchar(20) = SUBSTRING(@SCHEMAColumnName, CHARINDEX('Schema', @SCHEMAColumnName), 7); + +IF '' <> @OLDTABLEPREFIX +BEGIN + DECLARE @OLDAggregatedCounterOldColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'AggregatedCounter'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDAggregatedCounterOldColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDAggregatedCounter varchar(37) = CONCAT('[HangFire].[', @OLDAggregatedCounterOldColumnName, ']'); + EXEC sp_rename @OLDAggregatedCounter, '[HangFire].[AggregatedCounter]' + END + + DECLARE @OLDCounterColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Counter'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDCounterColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDCounter varchar(27) = CONCAT('[HangFire].[', @OLDCounterColumnName, ']'); + EXEC sp_rename @OLDCounter, '[HangFire].[Counter]' + END + + DECLARE @OLDHashColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Hash'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDCounterColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDHash varchar(24) = CONCAT('[HangFire].[', @OLDHashColumnName,']'); + EXEC sp_rename @OLDHash, '[HangFire].[Hash]' + END + + DECLARE @OLDJobColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Job'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDJobColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDJob varchar(24) = CONCAT('[HangFire].[', @OLDJobColumnName, ']'); + EXEC sp_rename @OLDJob, '[HangFire].[Job]' + END + + DECLARE @OLDJobParameterColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'JobParameter'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDJobParameterColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDJobParameter varchar(24) = CONCAT('[HangFire].[', @OLDJobParameterColumnName, ']'); + EXEC sp_rename @OLDJobParameter, '[HangFire].[JobParameter]' + END + + DECLARE @OLDJobQueueColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'JobQueue'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDJobQueueColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDJobQueue varchar(24) = CONCAT('[HangFire].[', @OLDJobQueueColumnName, ']'); + EXEC sp_rename @OLDJobQueue, '[HangFire].[JobQueue]' + END + + DECLARE @OLDListColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'List'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDListColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDList varchar(24) = CONCAT('[HangFire].[', @OLDListColumnName, ']'); + EXEC sp_rename @OLDList, '[HangFire].[List]' + END + + DECLARE @OLDSchemaColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Schema'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDSchemaColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDSchema varchar(24) = CONCAT('[HangFire].[', @OLDSchemaColumnName, ']'); + EXEC sp_rename @OLDSchema, '[HangFire].[Schema]' + END + + DECLARE @OLDServerColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Server'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDServerColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDServer varchar(24) = CONCAT('[HangFire].[', @OLDServerColumnName, ']'); + EXEC sp_rename @OLDServer, '[HangFire].[Server]' + END + + DECLARE @OLDSetColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Set'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDSetColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDSet varchar(24) = CONCAT('[HangFire].[', @OLDSetColumnName, ']'); + EXEC sp_rename @OLDSet, '[HangFire].[Set]' + END + DECLARE @OLDStateColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'State'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDSetColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDState varchar(24) = CONCAT('[HangFire].[', @OLDState, ']'); + EXEC sp_rename @OLDState, '[HangFire].[State]' + END +END + + DECLARE @CURRENT_SCHEMA_VERSION int; SELECT @CURRENT_SCHEMA_VERSION = [Version] FROM [HangFire].[Schema]; @@ -443,7 +533,7 @@ BEGIN -- non-null state name. This will decrease the number of operations, when creating a background job. -- It will be recreated later in the migration. - DROP INDEX [IX_HangFire_Job_StateName] ON [HangFire].Job; + DROP INDEX [IX_HangFire_Job_StateName] ON [HangFire].[Job]; PRINT 'Dropped index [IX_HangFire_Job_StateName]'; -- Dropping foreign key constraints based on the JobId column, because we need to modify the underlying diff --git a/src/Hangfire.SqlServer/DefaultInstall.tt b/src/Hangfire.SqlServer/DefaultInstall.tt index 9d049f58c..31ae4a1c3 100644 --- a/src/Hangfire.SqlServer/DefaultInstall.tt +++ b/src/Hangfire.SqlServer/DefaultInstall.tt @@ -12,7 +12,7 @@ "Hangfire.SqlServer.Install.sql"); script = script.Replace("$(HangFireSchema)", "HangFire"); - + script = script.Replace("$(HangFireTabelPrefix)", ""); Write(script); #> diff --git a/src/Hangfire.SqlServer/ExpirationManager.cs b/src/Hangfire.SqlServer/ExpirationManager.cs index 9b9dd51a8..a8613da9c 100644 --- a/src/Hangfire.SqlServer/ExpirationManager.cs +++ b/src/Hangfire.SqlServer/ExpirationManager.cs @@ -41,7 +41,7 @@ internal class ExpirationManager : IServerComponent private static readonly string[] ProcessedTables = { "AggregatedCounter", - "Job", + "Job", "List", "Set", "Hash", @@ -61,9 +61,10 @@ public ExpirationManager(SqlServerStorage storage, TimeSpan checkInterval) public void Execute(CancellationToken cancellationToken) { - foreach (var table in ProcessedTables) + foreach (var tableNameWithOutPrefix in ProcessedTables) { - _logger.Debug($"Removing outdated records from the '{table}' table..."); + var table = _storage.TablePrefix + tableNameWithOutPrefix; + _logger.Debug($"Removing outdated records from the '{table}' table..."); UseConnectionDistributedLock(_storage, connection => { diff --git a/src/Hangfire.SqlServer/Install.sql b/src/Hangfire.SqlServer/Install.sql index 085c82285..d3b3df289 100644 --- a/src/Hangfire.SqlServer/Install.sql +++ b/src/Hangfire.SqlServer/Install.sql @@ -42,20 +42,110 @@ DECLARE @SCHEMA_ID int; SELECT @SCHEMA_ID = [schema_id] FROM [sys].[schemas] WHERE [name] = '$(HangFireSchema)'; -- Create the [$(HangFireSchema)].Schema table if not exists -IF NOT EXISTS(SELECT [object_id] FROM [sys].[tables] - WHERE [name] = 'Schema' AND [schema_id] = @SCHEMA_ID) + +SELECT @SCHEMAColumnName = [t].[name] FROM [sys].[columns] c +INNER JOIN [sys].[tables] t ON [c].[object_id] = [t.object_id] +WHERE [c].[name] = 'Version' and [t].[name] like '%Schema' and [t].schema_id = @SCHEMA_ID + +IF NOT EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @SCHEMAColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - CREATE TABLE [$(HangFireSchema)].[Schema]( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Schema]( [Version] [int] NOT NULL, + [TablePrefix] varchar(20) NOT NULL DEFAULT(''), + [TablePrefixOld] varchar(20) NOT NULL DEFAULT(''), CONSTRAINT [PK_HangFire_Schema] PRIMARY KEY CLUSTERED ([Version] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[Schema]'; + SET @SCHEMAColumnName = '[$(HangFireTabelPrefix)Schema]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)Schema]'; END ELSE - PRINT 'Table [$(HangFireSchema)].[Schema] already exists'; - + PRINT 'Table [$(HangFireSchema)].[$(HangFireTabelPrefix)Schema] already exists'; + +-- Update table names if prefix has changed +DECLARE @OLDTABLEPREFIX varchar(20) = SUBSTRING(@SCHEMAColumnName, CHARINDEX('Schema', @SCHEMAColumnName), 7); + +IF '$(HangFireTabelPrefix)' <> @OLDTABLEPREFIX +BEGIN + DECLARE @OLDAggregatedCounterOldColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'AggregatedCounter'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDAggregatedCounterOldColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDAggregatedCounter varchar(37) = CONCAT('[$(HangFireSchema)].[', @OLDAggregatedCounterOldColumnName, ']'); + EXEC sp_rename @OLDAggregatedCounter, '[$(HangFireSchema)].[$(HangFireTabelPrefix)AggregatedCounter]' + END + + DECLARE @OLDCounterColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Counter'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDCounterColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDCounter varchar(27) = CONCAT('[$(HangFireSchema)].[', @OLDCounterColumnName, ']'); + EXEC sp_rename @OLDCounter, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Counter]' + END + + DECLARE @OLDHashColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Hash'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDCounterColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDHash varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDHashColumnName,']'); + EXEC sp_rename @OLDHash, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Hash]' + END + + DECLARE @OLDJobColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Job'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDJobColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDJob varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDJobColumnName, ']'); + EXEC sp_rename @OLDJob, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Job]' + END + + DECLARE @OLDJobParameterColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'JobParameter'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDJobParameterColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDJobParameter varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDJobParameterColumnName, ']'); + EXEC sp_rename @OLDJobParameter, '[$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter]' + END + + DECLARE @OLDJobQueueColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'JobQueue'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDJobQueueColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDJobQueue varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDJobQueueColumnName, ']'); + EXEC sp_rename @OLDJobQueue, '[$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue]' + END + + DECLARE @OLDListColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'List'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDListColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDList varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDListColumnName, ']'); + EXEC sp_rename @OLDList, '[$(HangFireSchema)].[$(HangFireTabelPrefix)List]' + END + + DECLARE @OLDSchemaColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Schema'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDSchemaColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDSchema varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDSchemaColumnName, ']'); + EXEC sp_rename @OLDSchema, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Schema]' + END + + DECLARE @OLDServerColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Server'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDServerColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDServer varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDServerColumnName, ']'); + EXEC sp_rename @OLDServer, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Server]' + END + + DECLARE @OLDSetColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Set'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDSetColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDSet varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDSetColumnName, ']'); + EXEC sp_rename @OLDSet, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Set]' + END + DECLARE @OLDStateColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'State'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDSetColumnName AND [schema_id] = @SCHEMA_ID) + BEGIN + DECLARE @OLDState varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDState, ']'); + EXEC sp_rename @OLDState, '[$(HangFireSchema)].[$(HangFireTabelPrefix)State]' + END +END + + DECLARE @CURRENT_SCHEMA_VERSION int; -SELECT @CURRENT_SCHEMA_VERSION = [Version] FROM [$(HangFireSchema)].[Schema]; +SELECT @CURRENT_SCHEMA_VERSION = [Version] FROM [$(HangFireSchema)].[$(HangFireTabelPrefix)Schema]; PRINT 'Current Hangfire schema version: ' + CASE WHEN @CURRENT_SCHEMA_VERSION IS NULL THEN 'none' ELSE CONVERT(nvarchar, @CURRENT_SCHEMA_VERSION) END; @@ -80,7 +170,7 @@ BEGIN PRINT 'Installing schema version 1'; -- Create job tables - CREATE TABLE [$(HangFireSchema)].[Job] ( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ( [Id] [int] IDENTITY(1,1) NOT NULL, [StateId] [int] NULL, [StateName] [nvarchar](20) NULL, -- To speed-up queries. @@ -91,14 +181,14 @@ BEGIN CONSTRAINT [PK_HangFire_Job] PRIMARY KEY CLUSTERED ([Id] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[Job]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)Job]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_Job_StateName] ON [$(HangFireSchema)].[Job] ([StateName] ASC); + CREATE NONCLUSTERED INDEX [IX_HangFire_Job_StateName] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ([StateName] ASC); PRINT 'Created index [IX_HangFire_Job_StateName]'; -- Job history table - CREATE TABLE [$(HangFireSchema)].[State] ( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)State] ( [Id] [int] IDENTITY(1,1) NOT NULL, [JobId] [int] NOT NULL, [Name] [nvarchar](20) NOT NULL, @@ -108,20 +198,20 @@ BEGIN CONSTRAINT [PK_HangFire_State] PRIMARY KEY CLUSTERED ([Id] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[State]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)State]'; - ALTER TABLE [$(HangFireSchema)].[State] ADD CONSTRAINT [FK_HangFire_State_Job] FOREIGN KEY([JobId]) - REFERENCES [$(HangFireSchema)].[Job] ([Id]) + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)State] ADD CONSTRAINT [FK_HangFire_State_Job] FOREIGN KEY([JobId]) + REFERENCES [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ([Id]) ON UPDATE CASCADE ON DELETE CASCADE; PRINT 'Created constraint [FK_HangFire_State_Job]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_State_JobId] ON [$(HangFireSchema)].[State] ([JobId] ASC); + CREATE NONCLUSTERED INDEX [IX_HangFire_State_JobId] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)State] ([JobId] ASC); PRINT 'Created index [IX_HangFire_State_JobId]'; -- Job parameters table - CREATE TABLE [$(HangFireSchema)].[JobParameter]( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter]( [Id] [int] IDENTITY(1,1) NOT NULL, [JobId] [int] NOT NULL, [Name] [nvarchar](40) NOT NULL, @@ -129,15 +219,15 @@ BEGIN CONSTRAINT [PK_HangFire_JobParameter] PRIMARY KEY CLUSTERED ([Id] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[JobParameter]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter]'; - ALTER TABLE [$(HangFireSchema)].[JobParameter] ADD CONSTRAINT [FK_HangFire_JobParameter_Job] FOREIGN KEY([JobId]) - REFERENCES [$(HangFireSchema)].[Job] ([Id]) + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter] ADD CONSTRAINT [FK_HangFire_JobParameter_Job] FOREIGN KEY([JobId]) + REFERENCES [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ([Id]) ON UPDATE CASCADE ON DELETE CASCADE; PRINT 'Created constraint [FK_HangFire_JobParameter_Job]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_JobParameter_JobIdAndName] ON [$(HangFireSchema)].[JobParameter] ( + CREATE NONCLUSTERED INDEX [IX_HangFire_JobParameter_JobIdAndName] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter] ( [JobId] ASC, [Name] ASC ); @@ -145,7 +235,7 @@ BEGIN -- Job queue table - CREATE TABLE [$(HangFireSchema)].[JobQueue]( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue]( [Id] [int] IDENTITY(1,1) NOT NULL, [JobId] [int] NOT NULL, [Queue] [nvarchar](20) NOT NULL, @@ -153,15 +243,15 @@ BEGIN CONSTRAINT [PK_HangFire_JobQueue] PRIMARY KEY CLUSTERED ([Id] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[JobQueue]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_JobQueue_JobIdAndQueue] ON [$(HangFireSchema)].[JobQueue] ( + CREATE NONCLUSTERED INDEX [IX_HangFire_JobQueue_JobIdAndQueue] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue] ( [JobId] ASC, [Queue] ASC ); PRINT 'Created index [IX_HangFire_JobQueue_JobIdAndQueue]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_JobQueue_QueueAndFetchedAt] ON [$(HangFireSchema)].[JobQueue] ( + CREATE NONCLUSTERED INDEX [IX_HangFire_JobQueue_QueueAndFetchedAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue] ( [Queue] ASC, [FetchedAt] ASC ); @@ -169,18 +259,18 @@ BEGIN -- Servers table - CREATE TABLE [$(HangFireSchema)].[Server]( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Server]( [Id] [nvarchar](50) NOT NULL, [Data] [nvarchar](max) NULL, [LastHeartbeat] [datetime] NULL, CONSTRAINT [PK_HangFire_Server] PRIMARY KEY CLUSTERED ([Id] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[Server]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)Server]'; -- Extension tables - CREATE TABLE [$(HangFireSchema)].[Hash]( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash]( [Id] [int] IDENTITY(1,1) NOT NULL, [Key] [nvarchar](100) NOT NULL, [Name] [nvarchar](40) NOT NULL, @@ -190,15 +280,15 @@ BEGIN CONSTRAINT [PK_HangFire_Hash] PRIMARY KEY CLUSTERED ([Id] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[Hash]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash]'; - CREATE UNIQUE NONCLUSTERED INDEX [UX_HangFire_Hash_KeyAndName] ON [$(HangFireSchema)].[Hash] ( + CREATE UNIQUE NONCLUSTERED INDEX [UX_HangFire_Hash_KeyAndName] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash] ( [Key] ASC, [Name] ASC ); PRINT 'Created index [UX_HangFire_Hash_KeyAndName]'; - CREATE TABLE [$(HangFireSchema)].[List]( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)List]( [Id] [int] IDENTITY(1,1) NOT NULL, [Key] [nvarchar](100) NOT NULL, [Value] [nvarchar](max) NULL, @@ -206,9 +296,9 @@ BEGIN CONSTRAINT [PK_HangFire_List] PRIMARY KEY CLUSTERED ([Id] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[List]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)List]'; - CREATE TABLE [$(HangFireSchema)].[Set]( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Set]( [Id] [int] IDENTITY(1,1) NOT NULL, [Key] [nvarchar](100) NOT NULL, [Score] [float] NOT NULL, @@ -217,15 +307,15 @@ BEGIN CONSTRAINT [PK_HangFire_Set] PRIMARY KEY CLUSTERED ([Id] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[Set]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)Set]'; - CREATE UNIQUE NONCLUSTERED INDEX [UX_HangFire_Set_KeyAndValue] ON [$(HangFireSchema)].[Set] ( + CREATE UNIQUE NONCLUSTERED INDEX [UX_HangFire_Set_KeyAndValue] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Set] ( [Key] ASC, [Value] ASC ); PRINT 'Created index [UX_HangFire_Set_KeyAndValue]'; - CREATE TABLE [$(HangFireSchema)].[Value]( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Value]( [Id] [int] IDENTITY(1,1) NOT NULL, [Key] [nvarchar](100) NOT NULL, [StringValue] [nvarchar](max) NULL, @@ -236,14 +326,14 @@ BEGIN [Id] ASC ) ); - PRINT 'Created table [$(HangFireSchema)].[Value]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)Value]'; - CREATE UNIQUE NONCLUSTERED INDEX [UX_HangFire_Value_Key] ON [$(HangFireSchema)].[Value] ( + CREATE UNIQUE NONCLUSTERED INDEX [UX_HangFire_Value_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Value] ( [Key] ASC ); PRINT 'Created index [UX_HangFire_Value_Key]'; - CREATE TABLE [$(HangFireSchema)].[Counter]( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Counter]( [Id] [int] IDENTITY(1,1) NOT NULL, [Key] [nvarchar](100) NOT NULL, [Value] [tinyint] NOT NULL, @@ -251,9 +341,9 @@ BEGIN CONSTRAINT [PK_HangFire_Counter] PRIMARY KEY CLUSTERED ([Id] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[Counter]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)Counter]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_Counter_Key] ON [$(HangFireSchema)].[Counter] ([Key] ASC) + CREATE NONCLUSTERED INDEX [IX_HangFire_Counter_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Counter] ([Key] ASC) INCLUDE ([Value]); PRINT 'Created index [IX_HangFire_Counter_Key]'; @@ -266,20 +356,20 @@ BEGIN -- https://github.com/odinserj/HangFire/issues/83 - DROP INDEX [IX_HangFire_Counter_Key] ON [$(HangFireSchema)].[Counter]; + DROP INDEX [IX_HangFire_Counter_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Counter]; - ALTER TABLE [$(HangFireSchema)].[Counter] ALTER COLUMN [Value] SMALLINT NOT NULL; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Counter] ALTER COLUMN [Value] SMALLINT NOT NULL; - CREATE NONCLUSTERED INDEX [IX_HangFire_Counter_Key] ON [$(HangFireSchema)].[Counter] ([Key] ASC) + CREATE NONCLUSTERED INDEX [IX_HangFire_Counter_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Counter] ([Key] ASC) INCLUDE ([Value]); PRINT 'Index [IX_HangFire_Counter_Key] re-created'; - DROP TABLE [$(HangFireSchema)].[Value]; - DROP TABLE [$(HangFireSchema)].[Hash]; - PRINT 'Dropped tables [$(HangFireSchema)].[Value] and [$(HangFireSchema)].[Hash]' + DROP TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Value]; + DROP TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash]; + PRINT 'Dropped tables [$(HangFireSchema)].[Value] and [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash]' - DELETE FROM [$(HangFireSchema)].[Server] WHERE [LastHeartbeat] IS NULL; - ALTER TABLE [$(HangFireSchema)].[Server] ALTER COLUMN [LastHeartbeat] DATETIME NOT NULL; + DELETE FROM [$(HangFireSchema)].[$(HangFireTabelPrefix)Server] WHERE [LastHeartbeat] IS NULL; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Server] ALTER COLUMN [LastHeartbeat] DATETIME NOT NULL; SET @CURRENT_SCHEMA_VERSION = 2; END @@ -288,10 +378,10 @@ IF @CURRENT_SCHEMA_VERSION = 2 BEGIN PRINT 'Installing schema version 3'; - DROP INDEX [IX_HangFire_JobQueue_JobIdAndQueue] ON [$(HangFireSchema)].[JobQueue]; + DROP INDEX [IX_HangFire_JobQueue_JobIdAndQueue] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue]; PRINT 'Dropped index [IX_HangFire_JobQueue_JobIdAndQueue]'; - CREATE TABLE [$(HangFireSchema)].[Hash]( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash]( [Id] [int] IDENTITY(1,1) NOT NULL, [Key] [nvarchar](100) NOT NULL, [Field] [nvarchar](100) NOT NULL, @@ -300,9 +390,9 @@ BEGIN CONSTRAINT [PK_HangFire_Hash] PRIMARY KEY CLUSTERED ([Id] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[Hash]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash]'; - CREATE UNIQUE NONCLUSTERED INDEX [UX_HangFire_Hash_Key_Field] ON [$(HangFireSchema)].[Hash] ( + CREATE UNIQUE NONCLUSTERED INDEX [UX_HangFire_Hash_Key_Field] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash] ( [Key] ASC, [Field] ASC ); @@ -315,7 +405,7 @@ IF @CURRENT_SCHEMA_VERSION = 3 BEGIN PRINT 'Installing schema version 4'; - CREATE TABLE [$(HangFireSchema)].[AggregatedCounter] ( + CREATE TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)AggregatedCounter] ( [Id] [int] IDENTITY(1,1) NOT NULL, [Key] [nvarchar](100) NOT NULL, [Value] [bigint] NOT NULL, @@ -323,36 +413,36 @@ BEGIN CONSTRAINT [PK_HangFire_CounterAggregated] PRIMARY KEY CLUSTERED ([Id] ASC) ); - PRINT 'Created table [$(HangFireSchema)].[AggregatedCounter]'; + PRINT 'Created table [$(HangFireSchema)].[$(HangFireTabelPrefix)AggregatedCounter]'; - CREATE UNIQUE NONCLUSTERED INDEX [UX_HangFire_CounterAggregated_Key] ON [$(HangFireSchema)].[AggregatedCounter] ( + CREATE UNIQUE NONCLUSTERED INDEX [UX_HangFire_CounterAggregated_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)AggregatedCounter] ( [Key] ASC ) INCLUDE ([Value]); PRINT 'Created index [UX_HangFire_CounterAggregated_Key]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_Hash_ExpireAt] ON [$(HangFireSchema)].[Hash] ([ExpireAt]) + CREATE NONCLUSTERED INDEX [IX_HangFire_Hash_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash] ([ExpireAt]) INCLUDE ([Id]); - CREATE NONCLUSTERED INDEX [IX_HangFire_Job_ExpireAt] ON [$(HangFireSchema)].[Job] ([ExpireAt]) + CREATE NONCLUSTERED INDEX [IX_HangFire_Job_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ([ExpireAt]) INCLUDE ([Id]); - CREATE NONCLUSTERED INDEX [IX_HangFire_List_ExpireAt] ON [$(HangFireSchema)].[List] ([ExpireAt]) + CREATE NONCLUSTERED INDEX [IX_HangFire_List_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)List] ([ExpireAt]) INCLUDE ([Id]); - CREATE NONCLUSTERED INDEX [IX_HangFire_Set_ExpireAt] ON [$(HangFireSchema)].[Set] ([ExpireAt]) + CREATE NONCLUSTERED INDEX [IX_HangFire_Set_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Set] ([ExpireAt]) INCLUDE ([Id]); PRINT 'Created indexes for [ExpireAt] columns'; - CREATE NONCLUSTERED INDEX [IX_HangFire_Hash_Key] ON [$(HangFireSchema)].[Hash] ([Key] ASC) + CREATE NONCLUSTERED INDEX [IX_HangFire_Hash_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash] ([Key] ASC) INCLUDE ([ExpireAt]); PRINT 'Created index [IX_HangFire_Hash_Key]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_List_Key] ON [$(HangFireSchema)].[List] ([Key] ASC) + CREATE NONCLUSTERED INDEX [IX_HangFire_List_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)List] ([Key] ASC) INCLUDE ([ExpireAt], [Value]); PRINT 'Created index [IX_HangFire_List_Key]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_Set_Key] ON [$(HangFireSchema)].[Set] ([Key] ASC) + CREATE NONCLUSTERED INDEX [IX_HangFire_Set_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Set] ([Key] ASC) INCLUDE ([ExpireAt], [Value]); PRINT 'Created index [IX_HangFire_Set_Key]'; @@ -363,25 +453,25 @@ IF @CURRENT_SCHEMA_VERSION = 4 BEGIN PRINT 'Installing schema version 5'; - DROP INDEX [IX_HangFire_JobQueue_QueueAndFetchedAt] ON [$(HangFireSchema)].[JobQueue]; - PRINT 'Dropped index [IX_HangFire_JobQueue_QueueAndFetchedAt] to modify the [$(HangFireSchema)].[JobQueue].[Queue] column'; + DROP INDEX [IX_HangFire_JobQueue_QueueAndFetchedAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue]; + PRINT 'Dropped index [IX_HangFire_JobQueue_QueueAndFetchedAt] to modify the [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue].[Queue] column'; - ALTER TABLE [$(HangFireSchema)].[JobQueue] ALTER COLUMN [Queue] NVARCHAR (50) NOT NULL; - PRINT 'Modified [$(HangFireSchema)].[JobQueue].[Queue] length to 50'; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue] ALTER COLUMN [Queue] NVARCHAR (50) NOT NULL; + PRINT 'Modified [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue].[Queue] length to 50'; - CREATE NONCLUSTERED INDEX [IX_HangFire_JobQueue_QueueAndFetchedAt] ON [$(HangFireSchema)].[JobQueue] ( + CREATE NONCLUSTERED INDEX [IX_HangFire_JobQueue_QueueAndFetchedAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue] ( [Queue] ASC, [FetchedAt] ASC ); PRINT 'Re-created index [IX_HangFire_JobQueue_QueueAndFetchedAt]'; - ALTER TABLE [$(HangFireSchema)].[Server] DROP CONSTRAINT [PK_HangFire_Server] + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Server] DROP CONSTRAINT [PK_HangFire_Server] PRINT 'Dropped constraint [PK_HangFire_Server] to modify the [HangFire].[Server].[Id] column'; - ALTER TABLE [$(HangFireSchema)].[Server] ALTER COLUMN [Id] NVARCHAR (100) NOT NULL; - PRINT 'Modified [$(HangFireSchema)].[Server].[Id] length to 100'; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Server] ALTER COLUMN [Id] NVARCHAR (100) NOT NULL; + PRINT 'Modified [$(HangFireSchema)].[$(HangFireTabelPrefix)Server].[Id] length to 100'; - ALTER TABLE [$(HangFireSchema)].[Server] ADD CONSTRAINT [PK_HangFire_Server] PRIMARY KEY CLUSTERED + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Server] ADD CONSTRAINT [PK_HangFire_Server] PRIMARY KEY CLUSTERED ( [Id] ASC ); @@ -413,15 +503,15 @@ BEGIN AND i.index_id <> 0 AND o.is_ms_shipped = 0 AND SCHEMA_NAME(o.[schema_id]) = '$(HangFireSchema)' - AND o.name = 'Set'; + AND o.name = '$(HangFireTabelPrefix)Set'; EXEC sp_executesql @dropIndexSql; - PRINT 'Dropped all secondary indexes on the [Set] table'; + PRINT 'Dropped all secondary indexes on the [$(HangFireTabelPrefix)Set] table'; -- Next, we'll remove the unnecessary indexes. They were unnecessary in the previous schema, -- and are unnecessary in the new schema as well. We'll not re-create them. - DROP INDEX [IX_HangFire_Hash_Key] ON [$(HangFireSchema)].[Hash]; + DROP INDEX [IX_HangFire_Hash_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash]; PRINT 'Dropped unnecessary index [IX_HangFire_Hash_Key]'; -- Next, all the indexes that cover expiration will be filtered, to include only non-null values. This @@ -429,176 +519,176 @@ BEGIN -- expiration time. Also, they include the Id column by a mistake. So we'll re-create them later in the -- migration. - DROP INDEX [IX_HangFire_Hash_ExpireAt] ON [$(HangFireSchema)].[Hash]; + DROP INDEX [IX_HangFire_Hash_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash]; PRINT 'Dropped index [IX_HangFire_Hash_ExpireAt]'; - DROP INDEX [IX_HangFire_Job_ExpireAt] ON [$(HangFireSchema)].[Job]; + DROP INDEX [IX_HangFire_Job_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Job]; PRINT 'Dropped index [IX_HangFire_Job_ExpireAt]'; - DROP INDEX [IX_HangFire_List_ExpireAt] ON [$(HangFireSchema)].[List]; + DROP INDEX [IX_HangFire_List_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)List]; PRINT 'Dropped index [IX_HangFire_List_ExpireAt]'; -- IX_HangFire_Job_StateName index can also be optimized, since we are querying it only with a -- non-null state name. This will decrease the number of operations, when creating a background job. -- It will be recreated later in the migration. - DROP INDEX [IX_HangFire_Job_StateName] ON [$(HangFireSchema)].Job; + DROP INDEX [IX_HangFire_Job_StateName] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Job]; PRINT 'Dropped index [IX_HangFire_Job_StateName]'; -- Dropping foreign key constraints based on the JobId column, because we need to modify the underlying -- column type of the clustered index to BIGINT. We'll recreate them later in the migration. - ALTER TABLE [$(HangFireSchema)].[JobParameter] DROP CONSTRAINT [FK_HangFire_JobParameter_Job]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter] DROP CONSTRAINT [FK_HangFire_JobParameter_Job]; PRINT 'Dropped constraint [FK_HangFire_JobParameter_Job]'; - ALTER TABLE [$(HangFireSchema)].[State] DROP CONSTRAINT [FK_HangFire_State_Job]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)State] DROP CONSTRAINT [FK_HangFire_State_Job]; PRINT 'Dropped constraint [FK_HangFire_State_Job]'; -- We are going to create composite clustered indexes that are more natural for the following tables, -- so the following indexes will be unnecessary. Natural sorting will keep related data close to each -- other, and simplify the index modifications by the cost of fragmentation and additional page splits. - DROP INDEX [UX_HangFire_CounterAggregated_Key] ON [$(HangFireSchema)].[AggregatedCounter]; + DROP INDEX [UX_HangFire_CounterAggregated_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)AggregatedCounter]; PRINT 'Dropped index [UX_HangFire_CounterAggregated_Key]'; - DROP INDEX [IX_HangFire_Counter_Key] ON [$(HangFireSchema)].[Counter]; + DROP INDEX [IX_HangFire_Counter_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Counter]; PRINT 'Dropped index [IX_HangFire_Counter_Key]'; - DROP INDEX [IX_HangFire_JobParameter_JobIdAndName] ON [$(HangFireSchema)].[JobParameter]; + DROP INDEX [IX_HangFire_JobParameter_JobIdAndName] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter]; PRINT 'Dropped index [IX_HangFire_JobParameter_JobIdAndName]'; - DROP INDEX [IX_HangFire_JobQueue_QueueAndFetchedAt] ON [$(HangFireSchema)].[JobQueue]; + DROP INDEX [IX_HangFire_JobQueue_QueueAndFetchedAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue]; PRINT 'Dropped index [IX_HangFire_JobQueue_QueueAndFetchedAt]'; - DROP INDEX [UX_HangFire_Hash_Key_Field] ON [$(HangFireSchema)].[Hash]; + DROP INDEX [UX_HangFire_Hash_Key_Field] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash]; PRINT 'Dropped index [UX_HangFire_Hash_Key_Field]'; - DROP INDEX [IX_HangFire_List_Key] ON [$(HangFireSchema)].[List]; + DROP INDEX [IX_HangFire_List_Key] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)List]; PRINT 'Dropped index [IX_HangFire_List_Key]'; - DROP INDEX [IX_HangFire_State_JobId] ON [$(HangFireSchema)].[State]; + DROP INDEX [IX_HangFire_State_JobId] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)State]; PRINT 'Dropped index [IX_HangFire_State_JobId]'; -- Then, we need to drop the primary key constraints, to modify id columns to the BIGINT type. Some of them -- will be re-created later in the migration. But some of them would be removed forever, because their -- uniqueness property sometimes unnecessary. - ALTER TABLE [$(HangFireSchema)].[AggregatedCounter] DROP CONSTRAINT [PK_HangFire_CounterAggregated]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)AggregatedCounter] DROP CONSTRAINT [PK_HangFire_CounterAggregated]; PRINT 'Dropped constraint [PK_HangFire_CounterAggregated]'; - ALTER TABLE [$(HangFireSchema)].[Counter] DROP CONSTRAINT [PK_HangFire_Counter]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Counter] DROP CONSTRAINT [PK_HangFire_Counter]; PRINT 'Dropped constraint [PK_HangFire_Counter]'; - ALTER TABLE [$(HangFireSchema)].[Hash] DROP CONSTRAINT [PK_HangFire_Hash]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash] DROP CONSTRAINT [PK_HangFire_Hash]; PRINT 'Dropped constraint [PK_HangFire_Hash]'; - ALTER TABLE [$(HangFireSchema)].[Job] DROP CONSTRAINT [PK_HangFire_Job]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] DROP CONSTRAINT [PK_HangFire_Job]; PRINT 'Dropped constraint [PK_HangFire_Job]'; - ALTER TABLE [$(HangFireSchema)].[JobParameter] DROP CONSTRAINT [PK_HangFire_JobParameter]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter] DROP CONSTRAINT [PK_HangFire_JobParameter]; PRINT 'Dropped constraint [PK_HangFire_JobParameter]'; - ALTER TABLE [$(HangFireSchema)].[JobQueue] DROP CONSTRAINT [PK_HangFire_JobQueue]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue] DROP CONSTRAINT [PK_HangFire_JobQueue]; PRINT 'Dropped constraint [PK_HangFire_JobQueue]'; - ALTER TABLE [$(HangFireSchema)].[List] DROP CONSTRAINT [PK_HangFire_List]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)List] DROP CONSTRAINT [PK_HangFire_List]; PRINT 'Dropped constraint [PK_HangFire_List]'; - ALTER TABLE [$(HangFireSchema)].[Set] DROP CONSTRAINT [PK_HangFire_Set]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Set] DROP CONSTRAINT [PK_HangFire_Set]; PRINT 'Dropped constraint [PK_HangFire_Set]'; - ALTER TABLE [$(HangFireSchema)].[State] DROP CONSTRAINT [PK_HangFire_State]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)State] DROP CONSTRAINT [PK_HangFire_State]; PRINT 'Dropped constraint [PK_HangFire_State]'; -- We are removing identity columns of the following tables completely, their clustered -- index will be based on natural values. So, instead of modifying them to BIGINT, we -- are dropping them. - ALTER TABLE [$(HangFireSchema)].[AggregatedCounter] DROP COLUMN [Id]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)AggregatedCounter] DROP COLUMN [Id]; PRINT 'Dropped [AggregatedCounter].[Id] column, we will cluster on [Key] column with uniqufier'; - ALTER TABLE [$(HangFireSchema)].[Counter] DROP COLUMN [Id]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Counter] DROP COLUMN [Id]; PRINT 'Dropped [Counter].[Id] column, we will cluster on [Key] column'; - ALTER TABLE [$(HangFireSchema)].[Hash] DROP COLUMN [Id]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash] DROP COLUMN [Id]; PRINT 'Dropped [Hash].[Id] column, we will cluster on [Key]/[Field] columns'; - ALTER TABLE [$(HangFireSchema)].[Set] DROP COLUMN [Id]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Set] DROP COLUMN [Id]; PRINT 'Dropped [Set].[Id] column, we will cluster on [Key]/[Value] columns'; - ALTER TABLE [$(HangFireSchema)].[JobParameter] DROP COLUMN [Id]; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter] DROP COLUMN [Id]; PRINT 'Dropped [JobParameter].[Id] column, we will cluster on [JobId]/[Name] columns'; -- Then we need to modify all the remaining Id columns to be of type BIGINT. - ALTER TABLE [$(HangFireSchema)].[List] ALTER COLUMN [Id] BIGINT NOT NULL; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)List] ALTER COLUMN [Id] BIGINT NOT NULL; PRINT 'Modified [List].[Id] type to BIGINT'; - ALTER TABLE [$(HangFireSchema)].[Job] ALTER COLUMN [Id] BIGINT NOT NULL; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ALTER COLUMN [Id] BIGINT NOT NULL; PRINT 'Modified [Job].[Id] type to BIGINT'; - ALTER TABLE [$(HangFireSchema)].[Job] ALTER COLUMN [StateId] BIGINT NULL; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ALTER COLUMN [StateId] BIGINT NULL; PRINT 'Modified [Job].[StateId] type to BIGINT'; - ALTER TABLE [$(HangFireSchema)].[JobParameter] ALTER COLUMN [JobId] BIGINT NOT NULL; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter] ALTER COLUMN [JobId] BIGINT NOT NULL; PRINT 'Modified [JobParameter].[JobId] type to BIGINT'; - ALTER TABLE [$(HangFireSchema)].[JobQueue] ALTER COLUMN [JobId] BIGINT NOT NULL; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue] ALTER COLUMN [JobId] BIGINT NOT NULL; PRINT 'Modified [JobQueue].[JobId] type to BIGINT'; - ALTER TABLE [$(HangFireSchema)].[State] ALTER COLUMN [Id] BIGINT NOT NULL; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)State] ALTER COLUMN [Id] BIGINT NOT NULL; PRINT 'Modified [State].[Id] type to BIGINT'; - ALTER TABLE [$(HangFireSchema)].[State] ALTER COLUMN [JobId] BIGINT NOT NULL; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)State] ALTER COLUMN [JobId] BIGINT NOT NULL; PRINT 'Modified [State].[JobId] type to BIGINT'; - ALTER TABLE [$(HangFireSchema)].[Counter] ALTER COLUMN [Value] INT NOT NULL; + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Counter] ALTER COLUMN [Value] INT NOT NULL; PRINT 'Modified [Counter].[Value] type to INT'; -- Adding back all the Primary Key constraints or clustered indexes where PKs aren't appropriate. - ALTER TABLE [$(HangFireSchema)].[AggregatedCounter] ADD CONSTRAINT [PK_HangFire_CounterAggregated] PRIMARY KEY CLUSTERED ( + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)AggregatedCounter] ADD CONSTRAINT [PK_HangFire_CounterAggregated] PRIMARY KEY CLUSTERED ( [Key] ASC ); PRINT 'Re-created constraint [PK_HangFire_CounterAggregated]'; - CREATE CLUSTERED INDEX [CX_HangFire_Counter] ON [$(HangFireSchema)].[Counter] ([Key]); + CREATE CLUSTERED INDEX [CX_HangFire_Counter] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Counter] ([Key]); PRINT 'Created clustered index [CX_HangFire_Counter]'; - ALTER TABLE [$(HangFireSchema)].[Hash] ADD CONSTRAINT [PK_HangFire_Hash] PRIMARY KEY CLUSTERED ( + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash] ADD CONSTRAINT [PK_HangFire_Hash] PRIMARY KEY CLUSTERED ( [Key] ASC, [Field] ASC ); PRINT 'Re-created constraint [PK_HangFire_Hash]'; - ALTER TABLE [$(HangFireSchema)].[Job] ADD CONSTRAINT [PK_HangFire_Job] PRIMARY KEY CLUSTERED ([Id] ASC); + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ADD CONSTRAINT [PK_HangFire_Job] PRIMARY KEY CLUSTERED ([Id] ASC); PRINT 'Re-created constraint [PK_HangFire_Job]'; - ALTER TABLE [$(HangFireSchema)].[JobParameter] ADD CONSTRAINT [PK_HangFire_JobParameter] PRIMARY KEY CLUSTERED ( + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter] ADD CONSTRAINT [PK_HangFire_JobParameter] PRIMARY KEY CLUSTERED ( [JobId] ASC, [Name] ASC ); PRINT 'Re-created constraint [PK_HangFire_JobParameter]'; - ALTER TABLE [$(HangFireSchema)].[JobQueue] ADD CONSTRAINT [PK_HangFire_JobQueue] PRIMARY KEY CLUSTERED ( + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue] ADD CONSTRAINT [PK_HangFire_JobQueue] PRIMARY KEY CLUSTERED ( [Queue] ASC, [Id] ASC ); PRINT 'Re-created constraint [PK_HangFire_JobQueue]'; - ALTER TABLE [$(HangFireSchema)].[List] ADD CONSTRAINT [PK_HangFire_List] PRIMARY KEY CLUSTERED ( + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)List] ADD CONSTRAINT [PK_HangFire_List] PRIMARY KEY CLUSTERED ( [Key] ASC, [Id] ASC ); PRINT 'Re-created constraint [PK_HangFire_List]'; - ALTER TABLE [$(HangFireSchema)].[Set] ADD CONSTRAINT [PK_HangFire_Set] PRIMARY KEY CLUSTERED ( + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)Set] ADD CONSTRAINT [PK_HangFire_Set] PRIMARY KEY CLUSTERED ( [Key] ASC, [Value] ASC ); PRINT 'Re-created constraint [PK_HangFire_Set]'; - ALTER TABLE [$(HangFireSchema)].[State] ADD CONSTRAINT [PK_HangFire_State] PRIMARY KEY CLUSTERED ( + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)State] ADD CONSTRAINT [PK_HangFire_State] PRIMARY KEY CLUSTERED ( [JobId] ASC, [Id] ); @@ -606,50 +696,50 @@ BEGIN -- Creating secondary, nonclustered indexes - CREATE NONCLUSTERED INDEX [IX_HangFire_Job_StateName] ON [$(HangFireSchema)].[Job] ([StateName]) + CREATE NONCLUSTERED INDEX [IX_HangFire_Job_StateName] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ([StateName]) WHERE [StateName] IS NOT NULL; PRINT 'Re-created index [IX_HangFire_Job_StateName]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_Set_Score] ON [$(HangFireSchema)].[Set] ([Score]) + CREATE NONCLUSTERED INDEX [IX_HangFire_Set_Score] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Set] ([Score]) WHERE [Score] IS NOT NULL; PRINT 'Created index [IX_HangFire_Set_Score]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_Server_LastHeartbeat] ON [$(HangFireSchema)].[Server] ([LastHeartbeat]); + CREATE NONCLUSTERED INDEX [IX_HangFire_Server_LastHeartbeat] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Server] ([LastHeartbeat]); PRINT 'Created index [IX_HangFire_Server_LastHeartbeat]'; -- Creating filtered indexes for ExpireAt columns - CREATE NONCLUSTERED INDEX [IX_HangFire_AggregatedCounter_ExpireAt] ON [$(HangFireSchema)].[AggregatedCounter] ([ExpireAt]) + CREATE NONCLUSTERED INDEX [IX_HangFire_AggregatedCounter_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)AggregatedCounter] ([ExpireAt]) WHERE [ExpireAt] IS NOT NULL; PRINT 'Created index [IX_HangFire_AggregatedCounter_ExpireAt]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_Hash_ExpireAt] ON [$(HangFireSchema)].[Hash] ([ExpireAt]) + CREATE NONCLUSTERED INDEX [IX_HangFire_Hash_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Hash] ([ExpireAt]) WHERE [ExpireAt] IS NOT NULL; PRINT 'Re-created index [IX_HangFire_Hash_ExpireAt]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_Job_ExpireAt] ON [$(HangFireSchema)].[Job] ([ExpireAt]) + CREATE NONCLUSTERED INDEX [IX_HangFire_Job_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ([ExpireAt]) INCLUDE ([StateName]) WHERE [ExpireAt] IS NOT NULL; PRINT 'Re-created index [IX_HangFire_Job_ExpireAt]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_List_ExpireAt] ON [$(HangFireSchema)].[List] ([ExpireAt]) + CREATE NONCLUSTERED INDEX [IX_HangFire_List_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)List] ([ExpireAt]) WHERE [ExpireAt] IS NOT NULL; PRINT 'Re-created index [IX_HangFire_List_ExpireAt]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_Set_ExpireAt] ON [$(HangFireSchema)].[Set] ([ExpireAt]) + CREATE NONCLUSTERED INDEX [IX_HangFire_Set_ExpireAt] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Set] ([ExpireAt]) WHERE [ExpireAt] IS NOT NULL; PRINT 'Re-created index [IX_HangFire_Set_ExpireAt]'; -- Restoring foreign keys - ALTER TABLE [$(HangFireSchema)].[State] ADD CONSTRAINT [FK_HangFire_State_Job] FOREIGN KEY([JobId]) - REFERENCES [$(HangFireSchema)].[Job] ([Id]) + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)State] ADD CONSTRAINT [FK_HangFire_State_Job] FOREIGN KEY([JobId]) + REFERENCES [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ([Id]) ON UPDATE CASCADE ON DELETE CASCADE; PRINT 'Re-created constraint [FK_HangFire_State_Job]'; - ALTER TABLE [$(HangFireSchema)].[JobParameter] ADD CONSTRAINT [FK_HangFire_JobParameter_Job] FOREIGN KEY([JobId]) - REFERENCES [$(HangFireSchema)].[Job] ([Id]) + ALTER TABLE [$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter] ADD CONSTRAINT [FK_HangFire_JobParameter_Job] FOREIGN KEY([JobId]) + REFERENCES [$(HangFireSchema)].[$(HangFireTabelPrefix)Job] ([Id]) ON UPDATE CASCADE ON DELETE CASCADE; PRINT 'Re-created constraint [FK_HangFire_JobParameter_Job]'; @@ -661,10 +751,10 @@ IF @CURRENT_SCHEMA_VERSION = 6 BEGIN PRINT 'Installing schema version 7'; - DROP INDEX [IX_HangFire_Set_Score] ON [$(HangFireSchema)].[Set]; + DROP INDEX [IX_HangFire_Set_Score] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Set]; PRINT 'Dropped index [IX_HangFire_Set_Score]'; - CREATE NONCLUSTERED INDEX [IX_HangFire_Set_Score] ON [$(HangFireSchema)].[Set] ([Key], [Score]); + CREATE NONCLUSTERED INDEX [IX_HangFire_Set_Score] ON [$(HangFireSchema)].[$(HangFireTabelPrefix)Set] ([Key], [Score]); PRINT 'Created index [IX_HangFire_Set_Score] with the proper composite key'; SET @CURRENT_SCHEMA_VERSION = 7; @@ -679,9 +769,9 @@ BEGIN SET @CURRENT_SCHEMA_VERSION = 8; END*/ -UPDATE [$(HangFireSchema)].[Schema] SET [Version] = @CURRENT_SCHEMA_VERSION +UPDATE [$(HangFireSchema)].[$(HangFireTabelPrefix)Schema] SET [Version] = @CURRENT_SCHEMA_VERSION IF @@ROWCOUNT = 0 - INSERT INTO [$(HangFireSchema)].[Schema] ([Version]) VALUES (@CURRENT_SCHEMA_VERSION) + INSERT INTO [$(HangFireSchema)].[$(HangFireTabelPrefix)Schema] ([Version]) VALUES (@CURRENT_SCHEMA_VERSION) PRINT 'Hangfire database schema installed'; diff --git a/src/Hangfire.SqlServer/SqlServerConnection.cs b/src/Hangfire.SqlServer/SqlServerConnection.cs index 19af29c59..2dcbcb566 100644 --- a/src/Hangfire.SqlServer/SqlServerConnection.cs +++ b/src/Hangfire.SqlServer/SqlServerConnection.cs @@ -91,7 +91,7 @@ public override string CreateExpiredJob( if (parameters == null) throw new ArgumentNullException(nameof(parameters)); var queryString = -$@"insert into [{_storage.SchemaName}].Job (InvocationData, Arguments, CreatedAt, ExpireAt) +$@"insert into [{_storage.SchemaName}].{_storage.TablePrefix}Job (InvocationData, Arguments, CreatedAt, ExpireAt) output inserted.Id values (@invocationData, @arguments, @createdAt, @expireAt)"; @@ -113,9 +113,9 @@ output inserted.Id queryString = $@" set xact_abort on; set nocount on; declare @jobId bigint; begin tran; -insert into [{_storage.SchemaName}].Job (InvocationData, Arguments, CreatedAt, ExpireAt) values (@invocationData, @arguments, @createdAt, @expireAt); +insert into [{_storage.SchemaName}].{_storage.TablePrefix}Job (InvocationData, Arguments, CreatedAt, ExpireAt) values (@invocationData, @arguments, @createdAt, @expireAt); select @jobId = scope_identity(); select @jobId; -insert into [{_storage.SchemaName}].JobParameter (JobId, Name, Value) values (@jobId, @name, @value); +insert into [{_storage.SchemaName}].{_storage.TablePrefix}JobParameter (JobId, Name, Value) values (@jobId, @name, @value); commit tran;"; queryParameters.Add("@name", parametersArray[0].Key, DbType.String, size: 40); queryParameters.Add("@value", parametersArray[0].Value, DbType.String, size: -1); @@ -125,9 +125,9 @@ output inserted.Id queryString = $@" set xact_abort on; set nocount on; declare @jobId bigint; begin tran; -insert into [{_storage.SchemaName}].Job (InvocationData, Arguments, CreatedAt, ExpireAt) values (@invocationData, @arguments, @createdAt, @expireAt); +insert into [{_storage.SchemaName}].{_storage.TablePrefix}Job (InvocationData, Arguments, CreatedAt, ExpireAt) values (@invocationData, @arguments, @createdAt, @expireAt); select @jobId = scope_identity(); select @jobId; -insert into [{_storage.SchemaName}].JobParameter (JobId, Name, Value) values (@jobId, @name1, @value1), (@jobId, @name2, @value2); +insert into [{_storage.SchemaName}].{_storage.TablePrefix}JobParameter (JobId, Name, Value) values (@jobId, @name1, @value1), (@jobId, @name2, @value2); commit tran;"; queryParameters.Add("@name1", parametersArray[0].Key, DbType.String, size: 40); queryParameters.Add("@value1", parametersArray[0].Value, DbType.String, size: -1); @@ -149,7 +149,7 @@ output inserted.Id commandTimeout: _storage.CommandTimeout).ToString(); var insertParameterSql = -$@"insert into [{_storage.SchemaName}].JobParameter (JobId, Name, Value) values (@jobId, @name, @value)"; +$@"insert into [{_storage.SchemaName}].{_storage.TablePrefix}JobParameter (JobId, Name, Value) values (@jobId, @name, @value)"; using (var commandBatch = new SqlCommandBatch(connection, transaction, preferBatching: _storage.CommandBatchMaxTimeout.HasValue)) { @@ -176,7 +176,7 @@ public override JobData GetJobData(string id) if (id == null) throw new ArgumentNullException(nameof(id)); string sql = -$@"select InvocationData, StateName, Arguments, CreatedAt from [{_storage.SchemaName}].Job with (readcommittedlock, forceseek) where Id = @id"; +$@"select InvocationData, StateName, Arguments, CreatedAt from [{_storage.SchemaName}].{_storage.TablePrefix}Job with (readcommittedlock, forceseek) where Id = @id"; return _storage.UseConnection(_dedicatedConnection, connection => { @@ -221,8 +221,8 @@ public override StateData GetStateData(string jobId) string sql = $@"select s.Name, s.Reason, s.Data -from [{_storage.SchemaName}].State s with (readcommittedlock, forceseek) -inner join [{_storage.SchemaName}].Job j with (readcommittedlock, forceseek) on j.StateId = s.Id and j.Id = s.JobId +from [{_storage.SchemaName}].{_storage.TablePrefix}State s with (readcommittedlock, forceseek) +inner join [{_storage.SchemaName}].{_storage.TablePrefix}Job j with (readcommittedlock, forceseek) on j.StateId = s.Id and j.Id = s.JobId where j.Id = @jobId"; return _storage.UseConnection(_dedicatedConnection, connection => @@ -254,7 +254,7 @@ public override void SetJobParameter(string id, string name, string value) _storage.UseConnection(_dedicatedConnection, connection => { connection.Execute( -$@";merge [{_storage.SchemaName}].JobParameter with (holdlock, forceseek) as Target +$@";merge [{_storage.SchemaName}].{_storage.TablePrefix}JobParameter with (holdlock, forceseek) as Target using (VALUES (@jobId, @name, @value)) as Source (JobId, Name, Value) on Target.JobId = Source.JobId AND Target.Name = Source.Name when matched then update set Value = Source.Value @@ -270,7 +270,7 @@ public override string GetJobParameter(string id, string name) if (name == null) throw new ArgumentNullException(nameof(name)); return _storage.UseConnection(_dedicatedConnection, connection => connection.ExecuteScalar( - $@"select top (1) Value from [{_storage.SchemaName}].JobParameter with (readcommittedlock, forceseek) where JobId = @id and Name = @name", + $@"select top (1) Value from [{_storage.SchemaName}].{_storage.TablePrefix}JobParameter with (readcommittedlock, forceseek) where JobId = @id and Name = @name", new { id = long.Parse(id), name = name }, commandTimeout: _storage.CommandTimeout)); } @@ -282,7 +282,7 @@ public override HashSet GetAllItemsFromSet(string key) return _storage.UseConnection(_dedicatedConnection, connection => { var result = connection.Query( - $@"select Value from [{_storage.SchemaName}].[Set] with (readcommittedlock, forceseek) where [Key] = @key", + $@"select Value from [{_storage.SchemaName}].[{_storage.TablePrefix}Set] with (readcommittedlock, forceseek) where [Key] = @key", new { key }, commandTimeout: _storage.CommandTimeout); @@ -304,7 +304,7 @@ public override List GetFirstByLowestScoreFromSet(string key, double fro return _storage.UseConnection(_dedicatedConnection, connection => { var result = connection.Query( - $@"select top (@count) Value from [{_storage.SchemaName}].[Set] with (readcommittedlock, forceseek) where [Key] = @key and Score between @from and @to order by Score", + $@"select top (@count) Value from [{_storage.SchemaName}].[{_storage.TablePrefix}Set] with (readcommittedlock, forceseek) where [Key] = @key and Score between @from and @to order by Score", new { count = count, key, from = fromScore, to = toScore }, commandTimeout: _storage.CommandTimeout); @@ -318,13 +318,13 @@ public override void SetRangeInHash(string key, IEnumerable { @@ -367,7 +367,7 @@ public override Dictionary GetAllEntriesFromHash(string key) return _storage.UseConnection(_dedicatedConnection, connection => { var result = connection.Query( - $"select Field, Value from [{_storage.SchemaName}].Hash with (forceseek, readcommittedlock) where [Key] = @key", + $"select Field, Value from [{_storage.SchemaName}].{_storage.TablePrefix}Hash with (forceseek, readcommittedlock) where [Key] = @key", new { key }, commandTimeout: _storage.CommandTimeout) .ToDictionary(x => x.Field, x => x.Value); @@ -391,7 +391,7 @@ public override void AnnounceServer(string serverId, ServerContext context) _storage.UseConnection(_dedicatedConnection, connection => { connection.Execute( -$@";merge [{_storage.SchemaName}].Server with (holdlock) as Target +$@";merge [{_storage.SchemaName}].{_storage.TablePrefix}Server with (holdlock) as Target using (VALUES (@id, @data, @heartbeat)) as Source (Id, Data, Heartbeat) on Target.Id = Source.Id when matched then update set Data = Source.Data, LastHeartbeat = Source.Heartbeat @@ -408,7 +408,7 @@ public override void RemoveServer(string serverId) _storage.UseConnection(_dedicatedConnection, connection => { connection.Execute( - $@"delete from [{_storage.SchemaName}].Server where Id = @id", + $@"delete from [{_storage.SchemaName}].{_storage.TablePrefix}Server where Id = @id", new { id = serverId }, commandTimeout: _storage.CommandTimeout); }); @@ -421,7 +421,7 @@ public override void Heartbeat(string serverId) _storage.UseConnection(_dedicatedConnection, connection => { var affected = connection.Execute( - $@"update [{_storage.SchemaName}].Server set LastHeartbeat = @now where Id = @id", + $@"update [{_storage.SchemaName}].{_storage.TablePrefix}Server set LastHeartbeat = @now where Id = @id", new { now = DateTime.UtcNow, id = serverId }, commandTimeout: _storage.CommandTimeout); @@ -440,7 +440,7 @@ public override int RemoveTimedOutServers(TimeSpan timeOut) } return _storage.UseConnection(_dedicatedConnection, connection => connection.Execute( - $@"delete from [{_storage.SchemaName}].Server where LastHeartbeat < @timeOutAt", + $@"delete from [{_storage.SchemaName}].{_storage.TablePrefix}Server where LastHeartbeat < @timeOutAt", new { timeOutAt = DateTime.UtcNow.Add(timeOut.Negate()) }, commandTimeout: _storage.CommandTimeout)); } @@ -450,7 +450,7 @@ public override long GetSetCount(string key) if (key == null) throw new ArgumentNullException(nameof(key)); return _storage.UseConnection(_dedicatedConnection, connection => connection.Query( - $"select count(*) from [{_storage.SchemaName}].[Set] with (readcommittedlock, forceseek) where [Key] = @key", + $"select count(*) from [{_storage.SchemaName}].[{_storage.TablePrefix}Set] with (readcommittedlock, forceseek) where [Key] = @key", new { key = key }, commandTimeout: _storage.CommandTimeout).First()); } @@ -462,7 +462,7 @@ public override List GetRangeFromSet(string key, int startingFrom, int e string query = $@"select [Value] from ( select [Value], row_number() over (order by [Score] ASC) as row_num - from [{_storage.SchemaName}].[Set] with (readcommittedlock, forceseek) + from [{_storage.SchemaName}].[{_storage.TablePrefix}Set] with (readcommittedlock, forceseek) where [Key] = @key ) as s where s.row_num between @startingFrom and @endingAt"; @@ -475,7 +475,7 @@ public override TimeSpan GetSetTtl(string key) { if (key == null) throw new ArgumentNullException(nameof(key)); - string query = $@"select min([ExpireAt]) from [{_storage.SchemaName}].[Set] with (readcommittedlock, forceseek) where [Key] = @key"; + string query = $@"select min([ExpireAt]) from [{_storage.SchemaName}].[{_storage.TablePrefix}Set] with (readcommittedlock, forceseek) where [Key] = @key"; return _storage.UseConnection(_dedicatedConnection, connection => { @@ -491,10 +491,10 @@ public override long GetCounter(string key) if (key == null) throw new ArgumentNullException(nameof(key)); string query = -$@"select sum(s.[Value]) from (select sum([Value]) as [Value] from [{_storage.SchemaName}].Counter with (readcommittedlock, forceseek) +$@"select sum(s.[Value]) from (select sum([Value]) as [Value] from [{_storage.SchemaName}].{_storage.TablePrefix}Counter with (readcommittedlock, forceseek) where [Key] = @key union all -select [Value] from [{_storage.SchemaName}].AggregatedCounter with (readcommittedlock, forceseek) +select [Value] from [{_storage.SchemaName}].{_storage.TablePrefix}AggregatedCounter with (readcommittedlock, forceseek) where [Key] = @key) as s"; return _storage.UseConnection(_dedicatedConnection, connection => @@ -505,7 +505,7 @@ public override long GetHashCount(string key) { if (key == null) throw new ArgumentNullException(nameof(key)); - string query = $@"select count(*) from [{_storage.SchemaName}].Hash with (readcommittedlock, forceseek) where [Key] = @key"; + string query = $@"select count(*) from [{_storage.SchemaName}].{_storage.TablePrefix}Hash with (readcommittedlock, forceseek) where [Key] = @key"; return _storage.UseConnection(_dedicatedConnection, connection => connection.ExecuteScalar(query, new { key = key }, commandTimeout: _storage.CommandTimeout)); @@ -515,7 +515,7 @@ public override TimeSpan GetHashTtl(string key) { if (key == null) throw new ArgumentNullException(nameof(key)); - string query = $@"select min([ExpireAt]) from [{_storage.SchemaName}].Hash with (readcommittedlock, forceseek) where [Key] = @key"; + string query = $@"select min([ExpireAt]) from [{_storage.SchemaName}].{_storage.TablePrefix}Hash with (readcommittedlock, forceseek) where [Key] = @key"; return _storage.UseConnection(_dedicatedConnection, connection => { @@ -532,7 +532,7 @@ public override string GetValueFromHash(string key, string name) if (name == null) throw new ArgumentNullException(nameof(name)); string query = -$@"select [Value] from [{_storage.SchemaName}].Hash with (readcommittedlock, forceseek) +$@"select [Value] from [{_storage.SchemaName}].{_storage.TablePrefix}Hash with (readcommittedlock, forceseek) where [Key] = @key and [Field] = @field"; return _storage.UseConnection(_dedicatedConnection, connection => connection @@ -544,7 +544,7 @@ public override long GetListCount(string key) if (key == null) throw new ArgumentNullException(nameof(key)); string query = -$@"select count(*) from [{_storage.SchemaName}].List with (readcommittedlock, forceseek) +$@"select count(*) from [{_storage.SchemaName}].{_storage.TablePrefix}List with (readcommittedlock, forceseek) where [Key] = @key"; return _storage.UseConnection(_dedicatedConnection, connection => @@ -556,7 +556,7 @@ public override TimeSpan GetListTtl(string key) if (key == null) throw new ArgumentNullException(nameof(key)); string query = -$@"select min([ExpireAt]) from [{_storage.SchemaName}].List with (readcommittedlock, forceseek) +$@"select min([ExpireAt]) from [{_storage.SchemaName}].{_storage.TablePrefix}List with (readcommittedlock, forceseek) where [Key] = @key"; return _storage.UseConnection(_dedicatedConnection, connection => @@ -575,7 +575,7 @@ public override List GetRangeFromList(string key, int startingFrom, int string query = $@"select [Value] from ( select [Value], row_number() over (order by [Id] desc) as row_num - from [{_storage.SchemaName}].List with (readcommittedlock, forceseek) + from [{_storage.SchemaName}].{_storage.TablePrefix}List with (readcommittedlock, forceseek) where [Key] = @key ) as s where s.row_num between @startingFrom and @endingAt"; @@ -589,7 +589,7 @@ public override List GetAllItemsFromList(string key) if (key == null) throw new ArgumentNullException(nameof(key)); string query = -$@"select [Value] from [{_storage.SchemaName}].List with (readcommittedlock, forceseek) +$@"select [Value] from [{_storage.SchemaName}].{_storage.TablePrefix}List with (readcommittedlock, forceseek) where [Key] = @key order by [Id] desc"; diff --git a/src/Hangfire.SqlServer/SqlServerJobQueue.cs b/src/Hangfire.SqlServer/SqlServerJobQueue.cs index 7b261652b..1684770c1 100644 --- a/src/Hangfire.SqlServer/SqlServerJobQueue.cs +++ b/src/Hangfire.SqlServer/SqlServerJobQueue.cs @@ -73,7 +73,7 @@ public void Enqueue(DbConnection connection, DbTransaction transaction, string q #endif { string enqueueJobSql = -$@"insert into [{_storage.SchemaName}].JobQueue (JobId, Queue) values (@jobId, @queue)"; +$@"insert into [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue (JobId, Queue) values (@jobId, @queue)"; connection.Execute( enqueueJobSql, @@ -169,7 +169,7 @@ private string GetNonBlockingFetchSql() update top (1) JQ set FetchedAt = GETUTCDATE() output INSERTED.Id, INSERTED.JobId, INSERTED.Queue, INSERTED.FetchedAt -from [{_storage.SchemaName}].JobQueue JQ with ({GetSlidingFetchTableHints()}) +from [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue JQ with ({GetSlidingFetchTableHints()}) where Queue in @queues and (FetchedAt is null or FetchedAt < DATEADD(second, @timeout, GETUTCDATE()));"; } @@ -194,7 +194,7 @@ private string GetBlockingFetchSql() update top (1) JQ set FetchedAt = @now output INSERTED.Id, INSERTED.JobId, INSERTED.Queue, INSERTED.FetchedAt - from [{_storage.SchemaName}].JobQueue JQ with ({GetSlidingFetchTableHints()}) + from [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue JQ with ({GetSlidingFetchTableHints()}) where Queue in @queues and (FetchedAt is null or FetchedAt < DATEADD(second, @timeout, @now)); @@ -231,7 +231,7 @@ private SqlServerTransactionJob DequeueUsingTransaction(string[] queues, Cancell string fetchJobSqlTemplate = $@"delete top (1) JQ output DELETED.Id, DELETED.JobId, DELETED.Queue -from [{_storage.SchemaName}].JobQueue JQ with (readpast, updlock, rowlock, forceseek) +from [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue JQ with (readpast, updlock, rowlock, forceseek) where Queue in @queues and (FetchedAt is null or FetchedAt < DATEADD(second, @timeout, GETUTCDATE()))"; var pollInterval = _options.QueuePollInterval > TimeSpan.Zero diff --git a/src/Hangfire.SqlServer/SqlServerJobQueueMonitoringApi.cs b/src/Hangfire.SqlServer/SqlServerJobQueueMonitoringApi.cs index 1e0c4f9b0..3f21a3012 100644 --- a/src/Hangfire.SqlServer/SqlServerJobQueueMonitoringApi.cs +++ b/src/Hangfire.SqlServer/SqlServerJobQueueMonitoringApi.cs @@ -49,7 +49,7 @@ public SqlServerJobQueueMonitoringApi([NotNull] SqlServerStorage storage) public IEnumerable GetQueues() { - string sqlQuery = $@"select distinct(Queue) from [{_storage.SchemaName}].JobQueue with (nolock)"; + string sqlQuery = $@"select distinct(Queue) from [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue with (nolock)"; lock (_cacheLock) { @@ -73,7 +73,7 @@ public IEnumerable GetEnqueuedJobIds(string queue, int @from, int perPage) var sqlQuery = $@"select r.JobId from ( select jq.JobId, row_number() over (order by jq.Id) as row_num - from [{_storage.SchemaName}].JobQueue jq with (nolock, forceseek) + from [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue jq with (nolock, forceseek) where jq.Queue = @queue and jq.FetchedAt is null ) as r where r.row_num between @start and @end"; @@ -95,7 +95,7 @@ public IEnumerable GetFetchedJobIds(string queue, int @from, int perPage) var fetchedJobsSql = $@" select r.JobId from ( select jq.JobId, jq.FetchedAt, row_number() over (order by jq.Id) as row_num - from [{_storage.SchemaName}].JobQueue jq with (nolock, forceseek) + from [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue jq with (nolock, forceseek) where jq.Queue = @queue and jq.FetchedAt is not null ) as r where r.row_num between @start and @end"; @@ -119,7 +119,7 @@ select sum(Enqueued) as EnqueuedCount, sum(Fetched) as FetchedCount select case when FetchedAt is null then 1 else 0 end as Enqueued, case when FetchedAt is not null then 1 else 0 end as Fetched - from [{_storage.SchemaName}].JobQueue with (nolock, forceseek) + from [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue with (nolock, forceseek) where Queue = @queue ) q"; diff --git a/src/Hangfire.SqlServer/SqlServerMonitoringApi.cs b/src/Hangfire.SqlServer/SqlServerMonitoringApi.cs index 9ee0652a7..89599def7 100644 --- a/src/Hangfire.SqlServer/SqlServerMonitoringApi.cs +++ b/src/Hangfire.SqlServer/SqlServerMonitoringApi.cs @@ -124,7 +124,7 @@ public IList Servers() return UseConnection>(connection => { var servers = connection.Query( - $@"select * from [{_storage.SchemaName}].Server with (nolock)", commandTimeout: _storage.CommandTimeout) + $@"select * from [{_storage.SchemaName}].{_storage.TablePrefix}Server with (nolock)", commandTimeout: _storage.CommandTimeout) .ToList(); var result = new List(); @@ -270,9 +270,9 @@ public JobDetailsDto JobDetails(string jobId) return UseConnection(connection => { string sql = $@" -select * from [{_storage.SchemaName}].Job with (nolock, forceseek) where Id = @id -select * from [{_storage.SchemaName}].JobParameter with (nolock, forceseek) where JobId = @id -select * from [{_storage.SchemaName}].State with (nolock, forceseek) where JobId = @id order by Id desc"; +select * from [{_storage.SchemaName}].{_storage.TablePrefix}Job with (nolock, forceseek) where Id = @id +select * from [{_storage.SchemaName}].{_storage.TablePrefix}JobParameter with (nolock, forceseek) where JobId = @id +select * from [{_storage.SchemaName}].{_storage.TablePrefix}State with (nolock, forceseek) where JobId = @id order by Id desc"; using (var multi = connection.QueryMultiple(sql, new { id = jobId }, commandTimeout: _storage.CommandTimeout)) { @@ -322,24 +322,24 @@ public StatisticsDto GetStatistics() { string sql = String.Format(@" set transaction isolation level read committed; -select count(Id) from [{0}].Job with (nolock, forceseek) where StateName = N'Enqueued'; -select count(Id) from [{0}].Job with (nolock, forceseek) where StateName = N'Failed'; -select count(Id) from [{0}].Job with (nolock, forceseek) where StateName = N'Processing'; -select count(Id) from [{0}].Job with (nolock, forceseek) where StateName = N'Scheduled'; -select count(Id) from [{0}].Server with (nolock); +select count(Id) from [{0}].{1}Job with (nolock, forceseek) where StateName = N'Enqueued'; +select count(Id) from [{0}].{1}Job with (nolock, forceseek) where StateName = N'Failed'; +select count(Id) from [{0}].{1}Job with (nolock, forceseek) where StateName = N'Processing'; +select count(Id) from [{0}].{1}Job with (nolock, forceseek) where StateName = N'Scheduled'; +select count(Id) from [{0}].{1}Server with (nolock); select sum(s.[Value]) from ( - select sum([Value]) as [Value] from [{0}].Counter with (nolock, forceseek) where [Key] = N'stats:succeeded' + select sum([Value]) as [Value] from [{0}].{1}Counter with (nolock, forceseek) where [Key] = N'stats:succeeded' union all - select [Value] from [{0}].AggregatedCounter with (nolock, forceseek) where [Key] = N'stats:succeeded' + select [Value] from [{0}].{1}AggregatedCounter with (nolock, forceseek) where [Key] = N'stats:succeeded' ) as s; select sum(s.[Value]) from ( - select sum([Value]) as [Value] from [{0}].Counter with (nolock, forceseek) where [Key] = N'stats:deleted' + select sum([Value]) as [Value] from [{0}].{1}Counter with (nolock, forceseek) where [Key] = N'stats:deleted' union all - select [Value] from [{0}].AggregatedCounter with (nolock, forceseek) where [Key] = N'stats:deleted' + select [Value] from [{0}].{1}AggregatedCounter with (nolock, forceseek) where [Key] = N'stats:deleted' ) as s; -select count(*) from [{0}].[Set] with (nolock, forceseek) where [Key] = N'recurring-jobs'; - ", _storage.SchemaName); +select count(*) from [{0}].{1}[Set] with (nolock, forceseek) where [Key] = N'recurring-jobs'; + ", _storage.SchemaName, _storage.TablePrefix); var statistics = UseConnection(connection => { @@ -403,7 +403,7 @@ private Dictionary GetTimelineStats( IDictionary keyMaps) { string sqlQuery = -$@"select [Key], [Value] as [Count] from [{_storage.SchemaName}].AggregatedCounter with (nolock, forceseek) +$@"select [Key], [Value] as [Count] from [{_storage.SchemaName}].{_storage.TablePrefix}AggregatedCounter with (nolock, forceseek) where [Key] in @keys"; var valuesMap = connection.Query( @@ -444,8 +444,8 @@ private JobList EnqueuedJobs(DbConnection connection, long[] job { string enqueuedJobsSql = $@"select j.*, s.Reason as StateReason, s.Data as StateData, s.CreatedAt as StateChanged -from [{_storage.SchemaName}].Job j with (nolock, forceseek) -left join [{_storage.SchemaName}].State s with (nolock, forceseek) on s.Id = j.StateId and s.JobId = j.Id +from [{_storage.SchemaName}].{_storage.TablePrefix}Job j with (nolock, forceseek) +left join [{_storage.SchemaName}].{_storage.TablePrefix}State s with (nolock, forceseek) on s.Id = j.StateId and s.JobId = j.Id where j.Id in @jobIds"; var jobs = connection.Query( @@ -474,8 +474,8 @@ private JobList EnqueuedJobs(DbConnection connection, long[] job private long GetNumberOfJobsByStateName(DbConnection connection, string stateName) { var sqlQuery = _jobListLimit.HasValue - ? $@"select count(j.Id) from (select top (@limit) Id from [{_storage.SchemaName}].Job with (nolock, forceseek) where StateName = @state) as j" - : $@"select count(Id) from [{_storage.SchemaName}].Job with (nolock, forceseek) where StateName = @state"; + ? $@"select count(j.Id) from (select top (@limit) Id from [{_storage.SchemaName}]{_storage.TablePrefix}.Job with (nolock, forceseek) where StateName = @state) as j" + : $@"select count(Id) from [{_storage.SchemaName}].{_storage.TablePrefix}Job with (nolock, forceseek) where StateName = @state"; var count = connection.ExecuteScalar( sqlQuery, @@ -515,13 +515,13 @@ private JobList GetJobs( $@";with cte as ( select j.Id, row_number() over (order by j.Id desc) as row_num - from [{_storage.SchemaName}].Job j with (nolock, forceseek) + from [{_storage.SchemaName}].{_storage.TablePrefix}Job j with (nolock, forceseek) where j.StateName = @stateName ) select j.*, s.Reason as StateReason, s.Data as StateData, s.CreatedAt as StateChanged -from [{_storage.SchemaName}].Job j with (nolock, forceseek) +from [{_storage.SchemaName}].{_storage.TablePrefix}Job j with (nolock, forceseek) inner join cte on cte.Id = j.Id -left join [{_storage.SchemaName}].State s with (nolock, forceseek) on j.StateId = s.Id and j.Id = s.JobId +left join [{_storage.SchemaName}].{_storage.TablePrefix}State s with (nolock, forceseek) on j.StateId = s.Id and j.Id = s.JobId where cte.row_num between @start and @end order by j.Id desc"; @@ -566,8 +566,8 @@ private JobList FetchedJobs(DbConnection connection, IEnumerable< { string fetchedJobsSql = $@"select j.*, s.Reason as StateReason, s.Data as StateData -from [{_storage.SchemaName}].Job j with (nolock, forceseek) -left join [{_storage.SchemaName}].State s with (nolock, forceseek) on s.Id = j.StateId and s.JobId = j.Id +from [{_storage.SchemaName}].{_storage.TablePrefix}Job j with (nolock, forceseek) +left join [{_storage.SchemaName}].{_storage.TablePrefix}State s with (nolock, forceseek) on s.Id = j.StateId and s.JobId = j.Id where j.Id in @jobIds"; var jobs = connection.Query( diff --git a/src/Hangfire.SqlServer/SqlServerObjectsInstaller.cs b/src/Hangfire.SqlServer/SqlServerObjectsInstaller.cs index 0c392e34b..df7300f59 100644 --- a/src/Hangfire.SqlServer/SqlServerObjectsInstaller.cs +++ b/src/Hangfire.SqlServer/SqlServerObjectsInstaller.cs @@ -30,32 +30,33 @@ public static class SqlServerObjectsInstaller public static void Install(DbConnection connection) { - Install(connection, null); + Install(connection, null, null); } - public static void Install(DbConnection connection, string schema) + public static void Install(DbConnection connection, string schema, string tablePrefix) { - Install(connection, schema, false); + Install(connection, schema, tablePrefix, false); } - public static void Install(DbConnection connection, string schema, bool enableHeavyMigrations) + public static void Install(DbConnection connection, string schema, string tablePrefix, bool enableHeavyMigrations) { if (connection == null) throw new ArgumentNullException(nameof(connection)); - var script = GetInstallScript(schema, enableHeavyMigrations); + var script = GetInstallScript(schema, tablePrefix, enableHeavyMigrations); connection.Execute(script, commandTimeout: 0); } - public static string GetInstallScript(string schema, bool enableHeavyMigrations) + public static string GetInstallScript(string schema, string tablePrefix, bool enableHeavyMigrations) { var script = GetStringResource( typeof(SqlServerObjectsInstaller).GetTypeInfo().Assembly, "Hangfire.SqlServer.Install.sql"); script = script.Replace("$(HangFireSchema)", !string.IsNullOrWhiteSpace(schema) ? schema : Constants.DefaultSchema); + script = script.Replace("$(HangFireTabelPrefix)", !string.IsNullOrWhiteSpace(tablePrefix) ? tablePrefix : Constants.DefaultTablePrefix); - if (!enableHeavyMigrations) + if (!enableHeavyMigrations) { script = script.Replace("--SET @DISABLE_HEAVY_MIGRATIONS = 1;", "SET @DISABLE_HEAVY_MIGRATIONS = 1;"); } diff --git a/src/Hangfire.SqlServer/SqlServerStorage.cs b/src/Hangfire.SqlServer/SqlServerStorage.cs index 9da7f7fdb..d3dfbbf19 100644 --- a/src/Hangfire.SqlServer/SqlServerStorage.cs +++ b/src/Hangfire.SqlServer/SqlServerStorage.cs @@ -131,7 +131,8 @@ public SqlServerStorage([NotNull] Func connectionFactory, [NotNull public override bool LinearizableReads => true; internal string SchemaName => _escapedSchemaName; - internal int? CommandTimeout => _options.CommandTimeout.HasValue ? (int)_options.CommandTimeout.Value.TotalSeconds : (int?)null; + internal string TablePrefix => _options.TablePrefix; + internal int? CommandTimeout => _options.CommandTimeout.HasValue ? (int)_options.CommandTimeout.Value.TotalSeconds : (int?)null; internal int? CommandBatchMaxTimeout => _options.CommandBatchMaxTimeout.HasValue ? (int)_options.CommandBatchMaxTimeout.Value.TotalSeconds : (int?)null; internal TimeSpan? SlidingInvisibilityTimeout => _options.SlidingInvisibilityTimeout; internal SqlServerStorageOptions Options => _options; @@ -323,7 +324,7 @@ private void Initialize() { UseConnection(null, connection => { - SqlServerObjectsInstaller.Install(connection, _options.SchemaName, _options.EnableHeavyMigrations); + SqlServerObjectsInstaller.Install(connection, _options.SchemaName, _options.TablePrefix, _options.EnableHeavyMigrations); }); lastException = null; diff --git a/src/Hangfire.SqlServer/SqlServerStorageOptions.cs b/src/Hangfire.SqlServer/SqlServerStorageOptions.cs index daf419935..113459dd2 100644 --- a/src/Hangfire.SqlServer/SqlServerStorageOptions.cs +++ b/src/Hangfire.SqlServer/SqlServerStorageOptions.cs @@ -27,7 +27,8 @@ public class SqlServerStorageOptions { private TimeSpan _queuePollInterval; private string _schemaName; - private TimeSpan _jobExpirationCheckInterval; + private string _tablePrefix; + private TimeSpan _jobExpirationCheckInterval; private TimeSpan? _slidingInvisibilityTimeout; public SqlServerStorageOptions() @@ -42,7 +43,8 @@ public SqlServerStorageOptions() PrepareSchemaIfNecessary = true; DashboardJobListLimit = 10000; _schemaName = Constants.DefaultSchema; - TransactionTimeout = TimeSpan.FromMinutes(1); + _tablePrefix = Constants.DefaultTablePrefix; + TransactionTimeout = TimeSpan.FromMinutes(1); DisableGlobalLocks = false; UsePageLocksOnDequeue = false; } @@ -117,7 +119,20 @@ public string SchemaName } } - public Func ImpersonationFunc { get; set; } + public string TablePrefix + { + get { return _tablePrefix; } + set + { + if (string.IsNullOrWhiteSpace(_tablePrefix)) + { + throw new ArgumentException(_tablePrefix, nameof(value)); + } + _tablePrefix = value; + } + } + + public Func ImpersonationFunc { get; set; } public bool DisableGlobalLocks { get; set; } public bool UsePageLocksOnDequeue { get; set; } public bool UseRecommendedIsolationLevel { get; set; } diff --git a/src/Hangfire.SqlServer/SqlServerTimeoutJob.cs b/src/Hangfire.SqlServer/SqlServerTimeoutJob.cs index 5e77725be..831887b51 100644 --- a/src/Hangfire.SqlServer/SqlServerTimeoutJob.cs +++ b/src/Hangfire.SqlServer/SqlServerTimeoutJob.cs @@ -60,7 +60,7 @@ public void RemoveFromQueue() _storage.UseConnection(null, connection => { connection.Execute( - $"delete JQ from [{_storage.SchemaName}].JobQueue JQ with ({GetTableHints()}) where Queue = @queue and Id = @id and FetchedAt = @fetchedAt", + $"delete JQ from [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue JQ with ({GetTableHints()}) where Queue = @queue and Id = @id and FetchedAt = @fetchedAt", new { queue = Queue, id = Id, fetchedAt = FetchedAt }, commandTimeout: _storage.CommandTimeout); }); @@ -78,7 +78,7 @@ public void Requeue() _storage.UseConnection(null, connection => { connection.Execute( - $"update JQ set FetchedAt = null from [{_storage.SchemaName}].JobQueue JQ with ({GetTableHints()}) where Queue = @queue and Id = @id and FetchedAt = @fetchedAt", + $"update JQ set FetchedAt = null from [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue JQ with ({GetTableHints()}) where Queue = @queue and Id = @id and FetchedAt = @fetchedAt", new { queue = Queue, id = Id, fetchedAt = FetchedAt }, commandTimeout: _storage.CommandTimeout); }); @@ -127,7 +127,7 @@ private void ExecuteKeepAliveQuery(object obj) _storage.UseConnection(null, connection => { FetchedAt = connection.ExecuteScalar( - $"update JQ set FetchedAt = getutcdate() output INSERTED.FetchedAt from [{_storage.SchemaName}].JobQueue JQ with ({GetTableHints()}) where Queue = @queue and Id = @id and FetchedAt = @fetchedAt", + $"update JQ set FetchedAt = getutcdate() output INSERTED.FetchedAt from [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue JQ with ({GetTableHints()}) where Queue = @queue and Id = @id and FetchedAt = @fetchedAt", new { queue = Queue, id = Id, fetchedAt = FetchedAt }, commandTimeout: _storage.CommandTimeout); }); diff --git a/src/Hangfire.SqlServer/SqlServerWriteOnlyTransaction.cs b/src/Hangfire.SqlServer/SqlServerWriteOnlyTransaction.cs index da2e3aa02..4649fe1bc 100644 --- a/src/Hangfire.SqlServer/SqlServerWriteOnlyTransaction.cs +++ b/src/Hangfire.SqlServer/SqlServerWriteOnlyTransaction.cs @@ -101,7 +101,7 @@ public override void ExpireJob(string jobId, TimeSpan expireIn) AddCommand( _jobCommands, long.Parse(jobId), - $@"update J set ExpireAt = @expireAt from [{_storage.SchemaName}].Job J with (forceseek) where Id = @id;", + $@"update J set ExpireAt = @expireAt from [{_storage.SchemaName}].{_storage.TablePrefix}Job J with (forceseek) where Id = @id;", new SqlCommandBatchParameter("@expireAt", DbType.DateTime) { Value = DateTime.UtcNow.Add(expireIn) }, new SqlCommandBatchParameter("@id", DbType.Int64) { Value = long.Parse(jobId) }); } @@ -111,16 +111,16 @@ public override void PersistJob(string jobId) AddCommand( _jobCommands, long.Parse(jobId), - $@"update J set ExpireAt = NULL from [{_storage.SchemaName}].Job J with (forceseek) where Id = @id;", + $@"update J set ExpireAt = NULL from [{_storage.SchemaName}].{_storage.TablePrefix}Job J with (forceseek) where Id = @id;", new SqlCommandBatchParameter("@id", DbType.Int64) { Value = long.Parse(jobId) }); } public override void SetJobState(string jobId, IState state) { string addAndSetStateSql = -$@"insert into [{_storage.SchemaName}].State (JobId, Name, Reason, CreatedAt, Data) +$@"insert into [{_storage.SchemaName}].{_storage.TablePrefix}State (JobId, Name, Reason, CreatedAt, Data) values (@jobId, @name, @reason, @createdAt, @data); -update [{_storage.SchemaName}].Job set StateId = SCOPE_IDENTITY(), StateName = @name where Id = @jobId;"; +update [{_storage.SchemaName}].{_storage.TablePrefix}Job set StateId = SCOPE_IDENTITY(), StateName = @name where Id = @jobId;"; AddCommand( _jobCommands, @@ -136,7 +136,7 @@ public override void SetJobState(string jobId, IState state) public override void AddJobState(string jobId, IState state) { string addStateSql = -$@"insert into [{_storage.SchemaName}].State (JobId, Name, Reason, CreatedAt, Data) +$@"insert into [{_storage.SchemaName}].{_storage.TablePrefix}State (JobId, Name, Reason, CreatedAt, Data) values (@jobId, @name, @reason, @createdAt, @data)"; AddCommand( @@ -160,7 +160,7 @@ public override void AddToQueue(string queue, string jobId) AddCommand( _queueCommands, queue, - $@"insert into [{_storage.SchemaName}].JobQueue (JobId, Queue) values (@jobId, @queue)", + $@"insert into [{_storage.SchemaName}].{_storage.TablePrefix}JobQueue (JobId, Queue) values (@jobId, @queue)", new SqlCommandBatchParameter("@jobId", DbType.Int64) { Value = long.Parse(jobId) }, new SqlCommandBatchParameter("@queue", DbType.String, 50) { Value = queue }); @@ -183,7 +183,7 @@ public override void IncrementCounter(string key) AddCommand( _counterCommands, key, - $@"insert into [{_storage.SchemaName}].Counter ([Key], [Value]) values (@key, @value)", + $@"insert into [{_storage.SchemaName}].{_storage.TablePrefix}Counter ([Key], [Value]) values (@key, @value)", new SqlCommandBatchParameter("@key", DbType.String, 100) { Value = key }, new SqlCommandBatchParameter("@value", DbType.Int32) { Value = +1 }); } @@ -193,7 +193,7 @@ public override void IncrementCounter(string key, TimeSpan expireIn) AddCommand( _counterCommands, key, - $@"insert into [{_storage.SchemaName}].Counter ([Key], [Value], [ExpireAt]) values (@key, @value, @expireAt)", + $@"insert into [{_storage.SchemaName}].{_storage.TablePrefix}Counter ([Key], [Value], [ExpireAt]) values (@key, @value, @expireAt)", new SqlCommandBatchParameter("@key", DbType.String, 100) { Value = key }, new SqlCommandBatchParameter("@value", DbType.Int32) { Value = +1 }, new SqlCommandBatchParameter("@expireAt", DbType.DateTime) { Value = DateTime.UtcNow.Add(expireIn) }); @@ -204,7 +204,7 @@ public override void DecrementCounter(string key) AddCommand( _counterCommands, key, - $@"insert into [{_storage.SchemaName}].Counter ([Key], [Value]) values (@key, @value)", + $@"insert into [{_storage.SchemaName}].{_storage.TablePrefix}Counter ([Key], [Value]) values (@key, @value)", new SqlCommandBatchParameter("@key", DbType.String, 100) { Value = key }, new SqlCommandBatchParameter("@value", DbType.Int32) { Value = -1 }); } @@ -214,7 +214,7 @@ public override void DecrementCounter(string key, TimeSpan expireIn) AddCommand( _counterCommands, key, - $@"insert into [{_storage.SchemaName}].Counter ([Key], [Value], [ExpireAt]) values (@key, @value, @expireAt)", + $@"insert into [{_storage.SchemaName}].{_storage.TablePrefix}Counter ([Key], [Value], [ExpireAt]) values (@key, @value, @expireAt)", new SqlCommandBatchParameter("@key", DbType.String, 100) { Value = key }, new SqlCommandBatchParameter("@value", DbType.Int32) { Value = -1 }, new SqlCommandBatchParameter("@expireAt", DbType.DateTime) { Value = DateTime.UtcNow.Add(expireIn) }); @@ -228,7 +228,7 @@ public override void AddToSet(string key, string value) public override void AddToSet(string key, string value, double score) { string addSql = -$@";merge [{_storage.SchemaName}].[Set] with (holdlock) as Target +$@";merge [{_storage.SchemaName}].[{_storage.TablePrefix}Set] with (holdlock) as Target using (VALUES (@key, @value, @score)) as Source ([Key], Value, Score) on Target.[Key] = Source.[Key] and Target.Value = Source.Value when matched then update set Score = Source.Score @@ -246,7 +246,7 @@ public override void AddToSet(string key, string value, double score) public override void RemoveFromSet(string key, string value) { - string query = $@"delete from [{_storage.SchemaName}].[Set] where [Key] = @key and Value = @value"; + string query = $@"delete from [{_storage.SchemaName}].[{_storage.TablePrefix}Set] where [Key] = @key and Value = @value"; AcquireSetLock(key); AddCommand( @@ -264,9 +264,9 @@ public override void InsertToList(string key, string value) _listCommands, key, $@" -select [Key] from [{_storage.SchemaName}].List with (xlock) +select [Key] from [{_storage.SchemaName}].{_storage.TablePrefix}List with (xlock) where [Key] = @key; -insert into [{_storage.SchemaName}].List ([Key], Value) values (@key, @value);", +insert into [{_storage.SchemaName}].{_storage.TablePrefix}List ([Key], Value) values (@key, @value);", new SqlCommandBatchParameter("@key", DbType.String, 100) { Value = key }, new SqlCommandBatchParameter("@value", DbType.String, -1) { Value = value }); } @@ -277,7 +277,7 @@ public override void RemoveFromList(string key, string value) AddCommand( _listCommands, key, - $@"delete from [{_storage.SchemaName}].List where [Key] = @key and Value = @value", + $@"delete from [{_storage.SchemaName}].{_storage.TablePrefix}List where [Key] = @key and Value = @value", new SqlCommandBatchParameter("@key", DbType.String, 100) { Value = key }, new SqlCommandBatchParameter("@value", DbType.String, -1) { Value = value }); } @@ -287,7 +287,7 @@ public override void TrimList(string key, int keepStartingFrom, int keepEndingAt string trimSql = $@";with cte as ( select row_number() over (order by Id desc) as row_num - from [{_storage.SchemaName}].List with (xlock) + from [{_storage.SchemaName}].{_storage.TablePrefix}List with (xlock) where [Key] = @key) delete from cte where row_num not between @start and @end"; @@ -308,7 +308,7 @@ public override void SetRangeInHash(string key, IEnumerable items) // TODO: Rewrite using the `MERGE` statement. string query = -$@"insert into [{_storage.SchemaName}].[Set] ([Key], Value, Score) +$@"insert into [{_storage.SchemaName}].[{_storage.TablePrefix}Set] ([Key], Value, Score) values (@key, @value, 0.0)"; AcquireSetLock(key); @@ -362,7 +362,7 @@ public override void RemoveSet(string key) { if (key == null) throw new ArgumentNullException(nameof(key)); - string query = $@"delete from [{_storage.SchemaName}].[Set] where [Key] = @key"; + string query = $@"delete from [{_storage.SchemaName}].[{_storage.TablePrefix}Set] where [Key] = @key"; AcquireSetLock(key); AddCommand(_setCommands, key, query, new SqlCommandBatchParameter("@key", DbType.String, 100) { Value = key }); @@ -373,7 +373,7 @@ public override void ExpireHash(string key, TimeSpan expireIn) if (key == null) throw new ArgumentNullException(nameof(key)); string query = $@" -update [{_storage.SchemaName}].[Hash] set ExpireAt = @expireAt where [Key] = @key"; +update [{_storage.SchemaName}].[{_storage.TablePrefix}Hash] set ExpireAt = @expireAt where [Key] = @key"; AcquireHashLock(key); AddCommand(_hashCommands, key, query, @@ -386,7 +386,7 @@ public override void ExpireSet(string key, TimeSpan expireIn) if (key == null) throw new ArgumentNullException(nameof(key)); string query = $@" -update [{_storage.SchemaName}].[Set] set ExpireAt = @expireAt where [Key] = @key"; +update [{_storage.SchemaName}].[{_storage.TablePrefix}Set] set ExpireAt = @expireAt where [Key] = @key"; AcquireSetLock(key); AddCommand(_setCommands, key, query, @@ -399,7 +399,7 @@ public override void ExpireList(string key, TimeSpan expireIn) if (key == null) throw new ArgumentNullException(nameof(key)); string query = $@" -update [{_storage.SchemaName}].[List] set ExpireAt = @expireAt where [Key] = @key"; +update [{_storage.SchemaName}].[{_storage.TablePrefix}List] set ExpireAt = @expireAt where [Key] = @key"; AcquireListLock(key); AddCommand(_listCommands, key, query, @@ -412,7 +412,7 @@ public override void PersistHash(string key) if (key == null) throw new ArgumentNullException(nameof(key)); string query = $@" -update [{_storage.SchemaName}].Hash set ExpireAt = null where [Key] = @key"; +update [{_storage.SchemaName}].{_storage.TablePrefix}Hash set ExpireAt = null where [Key] = @key"; AcquireHashLock(key); AddCommand(_hashCommands, key, query, new SqlCommandBatchParameter("@key", DbType.String, 100) { Value = key }); @@ -423,7 +423,7 @@ public override void PersistSet(string key) if (key == null) throw new ArgumentNullException(nameof(key)); string query = $@" -update [{_storage.SchemaName}].[Set] set ExpireAt = null where [Key] = @key"; +update [{_storage.SchemaName}].[{_storage.TablePrefix}Set] set ExpireAt = null where [Key] = @key"; AcquireSetLock(key); AddCommand(_setCommands, key, query, new SqlCommandBatchParameter("@key", DbType.String, 100) { Value = key }); @@ -434,7 +434,7 @@ public override void PersistList(string key) if (key == null) throw new ArgumentNullException(nameof(key)); string query = $@" -update [{_storage.SchemaName}].[List] set ExpireAt = null where [Key] = @key"; +update [{_storage.SchemaName}].[{_storage.TablePrefix}List] set ExpireAt = null where [Key] = @key"; AcquireListLock(key); AddCommand(_listCommands, key, query, new SqlCommandBatchParameter("@key", DbType.String, 100) { Value = key }); @@ -489,7 +489,7 @@ private void AcquireLock(string resource) { if (!_storage.Options.DisableGlobalLocks || _storage.Options.UseFineGrainedLocks) { - _lockedResources.Add($"{_storage.SchemaName}:{resource}:Lock"); + _lockedResources.Add($"{_storage.SchemaName}:{_storage.TablePrefix}{resource}:Lock"); } } } diff --git a/tests/Hangfire.SqlServer.Tests/Utils/CleanDatabaseAttribute.cs b/tests/Hangfire.SqlServer.Tests/Utils/CleanDatabaseAttribute.cs index 0ae50c718..9b9e305ab 100644 --- a/tests/Hangfire.SqlServer.Tests/Utils/CleanDatabaseAttribute.cs +++ b/tests/Hangfire.SqlServer.Tests/Utils/CleanDatabaseAttribute.cs @@ -71,7 +71,7 @@ private static void CreateAndInitializeDatabaseIfNotExists() using (var connection = new SqlConnection( ConnectionUtils.GetConnectionString())) { - SqlServerObjectsInstaller.Install(connection, null, true); + SqlServerObjectsInstaller.Install(connection, null, null, true); } } } From 478d966e3cc74ae45655f08f8918b48ea178589c Mon Sep 17 00:00:00 2001 From: "ulf.johansson" Date: Tue, 5 Nov 2019 13:24:52 +0100 Subject: [PATCH 2/2] Finished with changes TablePrefix --- src/Hangfire.SqlServer/Install.sql | 75 ++++++++++--------- src/Hangfire.SqlServer/SqlServerStorage.cs | 21 +++++- .../SqlServerStorageOptions.cs | 11 +-- 3 files changed, 63 insertions(+), 44 deletions(-) diff --git a/src/Hangfire.SqlServer/Install.sql b/src/Hangfire.SqlServer/Install.sql index d3b3df289..df0d37faf 100644 --- a/src/Hangfire.SqlServer/Install.sql +++ b/src/Hangfire.SqlServer/Install.sql @@ -43,8 +43,9 @@ SELECT @SCHEMA_ID = [schema_id] FROM [sys].[schemas] WHERE [name] = '$(HangFireS -- Create the [$(HangFireSchema)].Schema table if not exists +DECLARE @SCHEMAColumnName nvarchar(128); SELECT @SCHEMAColumnName = [t].[name] FROM [sys].[columns] c -INNER JOIN [sys].[tables] t ON [c].[object_id] = [t.object_id] +INNER JOIN [sys].[tables] t ON [c].[object_id] = [t].[object_id] WHERE [c].[name] = 'Version' and [t].[name] like '%Schema' and [t].schema_id = @SCHEMA_ID IF NOT EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @SCHEMAColumnName AND [schema_id] = @SCHEMA_ID) @@ -62,84 +63,84 @@ ELSE PRINT 'Table [$(HangFireSchema)].[$(HangFireTabelPrefix)Schema] already exists'; -- Update table names if prefix has changed -DECLARE @OLDTABLEPREFIX varchar(20) = SUBSTRING(@SCHEMAColumnName, CHARINDEX('Schema', @SCHEMAColumnName), 7); +DECLARE @OLDTABLEPREFIX varchar(111) = SUBSTRING(@SCHEMAColumnName, 0, CHARINDEX('Schema', @SCHEMAColumnName)); IF '$(HangFireTabelPrefix)' <> @OLDTABLEPREFIX BEGIN - DECLARE @OLDAggregatedCounterOldColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'AggregatedCounter'); + DECLARE @OLDAggregatedCounterOldColumnName varchar(128) = CONCAT(@OLDTABLEPREFIX, 'AggregatedCounter'); IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDAggregatedCounterOldColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - DECLARE @OLDAggregatedCounter varchar(37) = CONCAT('[$(HangFireSchema)].[', @OLDAggregatedCounterOldColumnName, ']'); - EXEC sp_rename @OLDAggregatedCounter, '[$(HangFireSchema)].[$(HangFireTabelPrefix)AggregatedCounter]' + DECLARE @OLDAggregatedCounter varchar(261) = CONCAT('[$(HangFireSchema)].[', @OLDAggregatedCounterOldColumnName, ']'); + EXEC sp_rename @OLDAggregatedCounter, '$(HangFireTabelPrefix)AggregatedCounter' END - DECLARE @OLDCounterColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Counter'); + DECLARE @OLDCounterColumnName varchar(128) = CONCAT(@OLDTABLEPREFIX, 'Counter'); IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDCounterColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - DECLARE @OLDCounter varchar(27) = CONCAT('[$(HangFireSchema)].[', @OLDCounterColumnName, ']'); - EXEC sp_rename @OLDCounter, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Counter]' + DECLARE @OLDCounter varchar(261) = CONCAT('[$(HangFireSchema)].[', @OLDCounterColumnName, ']'); + EXEC sp_rename @OLDCounter, '$(HangFireTabelPrefix)Counter' END - DECLARE @OLDHashColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Hash'); - IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDCounterColumnName AND [schema_id] = @SCHEMA_ID) + DECLARE @OLDHashColumnName varchar(128) = CONCAT(@OLDTABLEPREFIX, 'Hash'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDHashColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - DECLARE @OLDHash varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDHashColumnName,']'); - EXEC sp_rename @OLDHash, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Hash]' + DECLARE @OLDHash varchar(261) = CONCAT('[$(HangFireSchema)].[', @OLDHashColumnName,']'); + EXEC sp_rename @OLDHash, '$(HangFireTabelPrefix)Hash' END - DECLARE @OLDJobColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Job'); + DECLARE @OLDJobColumnName varchar(128) = CONCAT(@OLDTABLEPREFIX, 'Job'); IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDJobColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - DECLARE @OLDJob varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDJobColumnName, ']'); - EXEC sp_rename @OLDJob, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Job]' + DECLARE @OLDJob varchar(261) = CONCAT('[$(HangFireSchema)].[', @OLDJobColumnName, ']'); + EXEC sp_rename @OLDJob, '$(HangFireTabelPrefix)Job' END - DECLARE @OLDJobParameterColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'JobParameter'); + DECLARE @OLDJobParameterColumnName varchar(128) = CONCAT(@OLDTABLEPREFIX, 'JobParameter'); IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDJobParameterColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - DECLARE @OLDJobParameter varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDJobParameterColumnName, ']'); - EXEC sp_rename @OLDJobParameter, '[$(HangFireSchema)].[$(HangFireTabelPrefix)JobParameter]' + DECLARE @OLDJobParameter varchar(261) = CONCAT('[$(HangFireSchema)].[', @OLDJobParameterColumnName, ']'); + EXEC sp_rename @OLDJobParameter, '$(HangFireTabelPrefix)JobParameter' END - DECLARE @OLDJobQueueColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'JobQueue'); + DECLARE @OLDJobQueueColumnName varchar(128) = CONCAT(@OLDTABLEPREFIX, 'JobQueue'); IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDJobQueueColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - DECLARE @OLDJobQueue varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDJobQueueColumnName, ']'); - EXEC sp_rename @OLDJobQueue, '[$(HangFireSchema)].[$(HangFireTabelPrefix)JobQueue]' + DECLARE @OLDJobQueue varchar(261) = CONCAT('[$(HangFireSchema)].[', @OLDJobQueueColumnName, ']'); + EXEC sp_rename @OLDJobQueue, '$(HangFireTabelPrefix)JobQueue' END - DECLARE @OLDListColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'List'); + DECLARE @OLDListColumnName varchar(128) = CONCAT(@OLDTABLEPREFIX, 'List'); IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDListColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - DECLARE @OLDList varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDListColumnName, ']'); - EXEC sp_rename @OLDList, '[$(HangFireSchema)].[$(HangFireTabelPrefix)List]' + DECLARE @OLDList varchar(261) = CONCAT('[$(HangFireSchema)].[', @OLDListColumnName, ']'); + EXEC sp_rename @OLDList, '$(HangFireTabelPrefix)List' END - DECLARE @OLDSchemaColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Schema'); + DECLARE @OLDSchemaColumnName varchar(128) = CONCAT(@OLDTABLEPREFIX, 'Schema'); IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDSchemaColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - DECLARE @OLDSchema varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDSchemaColumnName, ']'); - EXEC sp_rename @OLDSchema, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Schema]' + DECLARE @OLDSchema varchar(261) = CONCAT('[$(HangFireSchema)].[', @OLDSchemaColumnName, ']'); + EXEC sp_rename @OLDSchema, '$(HangFireTabelPrefix)Schema' END - DECLARE @OLDServerColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Server'); + DECLARE @OLDServerColumnName varchar(128) = CONCAT(@OLDTABLEPREFIX, 'Server'); IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDServerColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - DECLARE @OLDServer varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDServerColumnName, ']'); - EXEC sp_rename @OLDServer, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Server]' + DECLARE @OLDServer varchar(261) = CONCAT('[$(HangFireSchema)].[', @OLDServerColumnName, ']'); + EXEC sp_rename @OLDServer, '$(HangFireTabelPrefix)Server' END - DECLARE @OLDSetColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'Set'); + DECLARE @OLDSetColumnName varchar(128) = CONCAT(@OLDTABLEPREFIX, 'Set'); IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDSetColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - DECLARE @OLDSet varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDSetColumnName, ']'); - EXEC sp_rename @OLDSet, '[$(HangFireSchema)].[$(HangFireTabelPrefix)Set]' + DECLARE @OLDSet varchar(261) = CONCAT('[$(HangFireSchema)].[', @OLDSetColumnName, ']'); + EXEC sp_rename @OLDSet, '$(HangFireTabelPrefix)Set' END - DECLARE @OLDStateColumnName varchar(37) = CONCAT(@OLDTABLEPREFIX, 'State'); - IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDSetColumnName AND [schema_id] = @SCHEMA_ID) + DECLARE @OLDStateColumnName varchar(128) = CONCAT(@OLDTABLEPREFIX, 'State'); + IF EXISTS(SELECT [object_id] FROM [sys].[tables] WHERE [name] = @OLDStateColumnName AND [schema_id] = @SCHEMA_ID) BEGIN - DECLARE @OLDState varchar(24) = CONCAT('[$(HangFireSchema)].[', @OLDState, ']'); - EXEC sp_rename @OLDState, '[$(HangFireSchema)].[$(HangFireTabelPrefix)State]' + DECLARE @OLDState varchar(261) = CONCAT('[$(HangFireSchema)].[', @OLDStateColumnName, ']'); + EXEC sp_rename @OLDState, '$(HangFireTabelPrefix)State' END END diff --git a/src/Hangfire.SqlServer/SqlServerStorage.cs b/src/Hangfire.SqlServer/SqlServerStorage.cs index d3dfbbf19..ec9572737 100644 --- a/src/Hangfire.SqlServer/SqlServerStorage.cs +++ b/src/Hangfire.SqlServer/SqlServerStorage.cs @@ -347,10 +347,27 @@ private void Initialize() } } - InitializeQueueProviders(); + ValidateTablePrefix(); + InitializeQueueProviders(); } - private void InitializeQueueProviders() + private void ValidateTablePrefix() + { + UseConnection(null, connection => + { + var tableCount = connection.Query(string.Format(@" + SELECT COUNT(1) from [sys].[tables] AS t + INNER JOIN [sys].[schemas] AS s ON t.schema_id = s.schema_id + WHERE s.name = '{0}' AND t.name = '{1}Schema'", + Options.SchemaName, Options.TablePrefix) + ).FirstOrDefault(); + + if (tableCount == 0) + throw new ArgumentException("TablePrefix does not match with database, use PrepareSchemaIfNecessary = true if it should be changed at Initialize."); + }); + } + + private void InitializeQueueProviders() { var defaultQueueProvider = new SqlServerJobQueueProvider(this, _options); QueueProviders = new PersistentJobQueueProviderCollection(defaultQueueProvider); diff --git a/src/Hangfire.SqlServer/SqlServerStorageOptions.cs b/src/Hangfire.SqlServer/SqlServerStorageOptions.cs index 113459dd2..a49fd7dcb 100644 --- a/src/Hangfire.SqlServer/SqlServerStorageOptions.cs +++ b/src/Hangfire.SqlServer/SqlServerStorageOptions.cs @@ -124,11 +124,12 @@ public string TablePrefix get { return _tablePrefix; } set { - if (string.IsNullOrWhiteSpace(_tablePrefix)) - { - throw new ArgumentException(_tablePrefix, nameof(value)); - } - _tablePrefix = value; + if (value == null) + _tablePrefix = Constants.DefaultTablePrefix; + else if (value.Length > 111) + throw new ArgumentException(_schemaName, nameof(value)); + else + _tablePrefix = value; } }