Files
server/util/Migrator/DbScripts/2025-12-02_00_Collection_UpsertDefaultCollection.sql

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

83 lines
2.2 KiB
MySQL
Raw Normal View History

2025-12-02 12:56:25 +10:00
-- Create the idempotent stored procedure for creating default collections
-- This procedure prevents duplicate "My Items" collections for users by checking
-- if a default collection already exists before attempting to create one.
CREATE 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-03 12:41:28 +10:00
DECLARE @ExistingCollectionId UNIQUEIDENTIFIER;
2025-12-02 12:56:25 +10:00
-- Check if this organization user already has a default collection
2025-12-03 12:41:28 +10:00
SELECT @ExistingCollectionId = c.Id
2025-12-02 12:56:25 +10:00
FROM [dbo].[Collection] c
INNER JOIN [dbo].[CollectionUser] cu ON cu.CollectionId = c.Id
WHERE cu.OrganizationUserId = @OrganizationUserId
AND c.OrganizationId = @OrganizationId
AND c.Type = 1; -- CollectionType.DefaultUserCollection
2025-12-03 12:41:28 +10:00
-- If collection already exists, return early
IF @ExistingCollectionId IS NOT NULL
2025-12-02 12:56:25 +10:00
BEGIN
2025-12-03 12:41:28 +10:00
SET @WasCreated = 0;
RETURN;
END
2025-12-02 12:56:25 +10:00
2025-12-03 12:41:28 +10:00
-- Create new default collection
SET @WasCreated = 1;
2025-12-02 12:56:25 +10:00
2025-12-03 12:41:28 +10:00
-- Insert Collection
INSERT INTO [dbo].[Collection]
(
[Id],
[OrganizationId],
[Name],
[ExternalId],
[CreationDate],
[RevisionDate],
[DefaultUserCollectionEmail],
[Type]
)
VALUES
(
@CollectionId,
@OrganizationId,
@Name,
NULL, -- ExternalId
@CreationDate,
@RevisionDate,
NULL, -- DefaultUserCollectionEmail
1 -- CollectionType.DefaultUserCollection
);
2025-12-02 12:56:25 +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
);
-- Bump user account revision dates
EXEC [dbo].[User_BumpAccountRevisionDateByCollectionId] @CollectionId, @OrganizationId;
2025-12-02 12:56:25 +10:00
END
GO