Files
server/util/Migrator/DbScripts/2025-12-20_01_Collection_UpsertDefaultCollection.sql

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

90 lines
2.5 KiB
MySQL
Raw Normal View History

2025-12-02 12:56:25 +10:00
-- Create the idempotent stored procedure for creating default collections
2025-12-20 14:48:00 +10:00
-- This procedure prevents duplicate "My Items" collections for users using
-- a filtered unique constraint on (DefaultCollectionOwner, OrganizationId, Type) WHERE Type = 1.
2025-12-02 12:56:25 +10:00
2025-12-03 13:36:58 +10:00
CREATE OR ALTER PROCEDURE [dbo].[Collection_UpsertDefaultCollection]
2025-12-03 12:41:28 +10:00
@CollectionId UNIQUEIDENTIFIER,
2025-12-02 12:56:25 +10:00
@OrganizationId UNIQUEIDENTIFIER,
@OrganizationUserId UNIQUEIDENTIFIER,
@Name VARCHAR(MAX),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@WasCreated BIT OUTPUT
AS
BEGIN
SET NOCOUNT ON
BEGIN TRANSACTION;
2025-12-02 12:56:25 +10:00
BEGIN TRY
SET @WasCreated = 1;
2025-12-02 12:56:25 +10:00
2025-12-20 14:48:00 +10:00
-- Insert Collection with DefaultCollectionOwner populated for constraint enforcement
INSERT INTO [dbo].[Collection]
(
[Id],
[OrganizationId],
[Name],
[ExternalId],
[CreationDate],
[RevisionDate],
[DefaultUserCollectionEmail],
2025-12-20 14:48:00 +10:00
[Type],
[DefaultCollectionOwner]
)
VALUES
(
@CollectionId,
@OrganizationId,
@Name,
NULL, -- ExternalId
@CreationDate,
@RevisionDate,
NULL, -- DefaultUserCollectionEmail
2025-12-20 14:48:00 +10:00
1, -- CollectionType.DefaultUserCollection
@OrganizationUserId
);
2025-12-03 12:41:28 +10:00
-- Insert CollectionUser
INSERT INTO [dbo].[CollectionUser]
(
[CollectionId],
[OrganizationUserId],
[ReadOnly],
[HidePasswords],
[Manage]
)
VALUES
(
@CollectionId,
@OrganizationUserId,
0, -- ReadOnly = false
0, -- HidePasswords = false
1 -- Manage = true
);
-- Bump user account revision dates
EXEC [dbo].[User_BumpAccountRevisionDateByCollectionId] @CollectionId, @OrganizationId;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
2025-12-20 14:48:00 +10:00
-- Check if error is unique constraint violation (error 2601 or 2627)
IF ERROR_NUMBER() IN (2601, 2627)
BEGIN
-- Collection already exists, return gracefully
SET @WasCreated = 0;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END
ELSE
BEGIN
-- Unexpected error, rollback and re-throw
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
THROW;
END
END CATCH
2025-12-02 12:56:25 +10:00
END
GO