 
         [Token] ASC
 
-    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+    )
 
 END
 


        [Token] [int] NULL,

     CONSTRAINT [PK_Leases_1] PRIMARY KEY CLUSTERED 

    (



    SELECT @now = SYSDATETIMEOFFSET()



	BEGIN TRAN

	SELECT TOP 1 @resourceName = ResourceName 

	FROM Leases WITH (XLOCK,ROWLOCK)

	WHERE 

		Pool = @pool

			AND 

		(Expires IS NULL OR Expires < @now) 

			AND 

		DATEADD(MILLISECOND, @waitIntervalMilliseconds, LastReleased) < @now 

		ORDER BY LastReleased;

    

    UPDATE Leases

        SET LastGranted = @now,

            Expires = DATEADD(MILLISECOND, @leaseDurationMilliseconds, @now),

            Token = @token

		output inserted.[ResourceName], 

		       inserted.[Pool],

			   deleted.[LastGranted],

			   inserted.[LastReleased],

			   inserted.[Expires],

			   inserted.[Token]

        WHERE 

            ResourceName = @resourceName

			AND 

			[Pool] = @pool



    COMMIT TRAN



    END





GO



IF object_id('[Alluvial].[ExtendLease]') IS NULL

    exec('CREATE PROCEDURE [Alluvial].[ExtendLease] AS SELECT 1')

GO



ALTER PROCEDURE [Alluvial].[ExtendLease]

    @resourceName nvarchar(100),

    @byMilliseconds int, 

    @token int  

    AS

    BEGIN



    SET NOCOUNT ON;

    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE



    BEGIN TRAN



    DECLARE @expires datetimeoffset(7)



    SELECT @expires = 

    (SELECT Expires FROM Alluvial.Leases WITH (XLOCK,ROWLOCK)

        WHERE 

            ResourceName = @resourceName 

                AND 

            Token = @token)



    UPDATE Alluvial.Leases

        SET Expires = DATEADD(MILLISECOND, @byMilliseconds, @expires)

        WHERE 

            ResourceName = @resourceName 

                AND 

            Token = @token

                AND 

            Expires >= SYSDATETIMEOFFSET()



    SELECT Expires FROM Alluvial.Leases

        WHERE 

            ResourceName = @resourceName 

                AND 

            Token = @token



    IF @@ROWCOUNT = 0

        BEGIN

            ROLLBACK TRAN;

            THROW 50000, 'Lease could not be extended', 1;

        END

    ELSE

        COMMIT TRAN;

    END



GO



IF object_id('[Alluvial].[ReleaseLease]') IS NULL

    exec('CREATE PROCEDURE [Alluvial].[ReleaseLease] AS SELECT 1')

GO



ALTER PROCEDURE [Alluvial].[ReleaseLease]

    @resourceName nvarchar(100)  , 

    @token int  

    AS

    BEGIN

    SET NOCOUNT ON;



    DECLARE @now DATETIMEOFFSET(7)

    SELECT @now = SYSDATETIMEOFFSET()



    UPDATE Leases

    SET LastReleased = @now,

        Expires = null

    WHERE ResourceName = @resourceName 

