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
2025-12-20 16:02:23 +10:00
BEGIN TRANSACTION
2025-12-02 12:56:25 +10:00
BEGIN TRY
2025-12-20 16:02:23 +10:00
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-20 16:02:23 +10:00
)
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
2025-12-20 16:02:23 +10:00
)
-- Bump user account revision dates
2025-12-20 16:02:23 +10:00
EXEC [dbo].[User_BumpAccountRevisionDateByCollectionId] @CollectionId, @OrganizationId
2025-12-20 16:02:23 +10:00
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
2025-12-20 16:02:23 +10:00
SET @WasCreated = 0
2025-12-20 14:48:00 +10:00
IF @@TRANCOUNT > 0
2025-12-20 16:02:23 +10:00
ROLLBACK TRANSACTION
2025-12-20 14:48:00 +10:00
END
ELSE
BEGIN
-- Unexpected error, rollback and re-throw
IF @@TRANCOUNT > 0
2025-12-20 16:02:23 +10:00
ROLLBACK TRANSACTION
THROW
2025-12-20 14:48:00 +10:00
END
END CATCH
2025-12-02 12:56:25 +10:00
END
GO