SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON; GO IF COL_LENGTH(N'dbo.NativeReviewImports',N'DocumentGuid') IS NULL ALTER TABLE dbo.NativeReviewImports ADD DocumentGuid uniqueidentifier NULL,ObservationRevision bigint NULL,ChapterStart int NULL,ChapterEnd int NULL,ScenePositionsJson nvarchar(max) NULL; GO CREATE OR ALTER PROCEDURE dbo.NativeReviewSource_Save @UserID int,@ReviewID uniqueidentifier,@EncryptedSource nvarchar(max),@ObservedRevision bigint=NULL AS BEGIN SET NOCOUNT ON; IF DATALENGTH(@EncryptedSource)>8388608 THROW 51000,'Source capture too large',1; UPDATE dbo.NativeChapterReviews SET EncryptedSource=@EncryptedSource,ResultJson=CASE WHEN @ObservedRevision IS NOT NULL THEN JSON_MODIFY(ResultJson,'$.DocumentRevision',@ObservedRevision) ELSE ResultJson END WHERE ReviewID=@ReviewID AND UserID=@UserID AND EncryptedSource IS NULL; END; GO CREATE OR ALTER TRIGGER dbo.NativeReviewImports_CapturePositions ON dbo.NativeReviewImports AFTER INSERT AS BEGIN SET NOCOUNT ON; UPDATE n SET DocumentGuid=r.ManuscriptID,ObservationRevision=TRY_CONVERT(bigint,JSON_VALUE(r.ResultJson,'$.DocumentRevision')),ChapterStart=r.ChapterStart,ChapterEnd=r.ChapterEnd, ScenePositionsJson=(SELECT p.Start,p.[End],m.SceneID,n.ChapterID FROM OPENJSON(r.ResultJson,'$.Scenes') WITH(Start int,[End] int) p JOIN dbo.OnboardingManuscriptBuildSceneMap m ON m.OnboardingManuscriptBuildID=n.BuildID AND m.TemporarySceneKey=CONCAT(n.ChapterKey,':',p.Start) FOR JSON PATH) FROM dbo.NativeReviewImports n JOIN inserted i ON i.BookID=n.BookID AND i.ChapterKey=n.ChapterKey JOIN dbo.NativeChapterReviews r ON r.ReviewID=n.ReviewID; IF EXISTS(SELECT 1 FROM dbo.NativeReviewImports n JOIN inserted i ON i.BookID=n.BookID AND i.ChapterKey=n.ChapterKey JOIN dbo.NativeReviewImports other ON other.BookID=n.BookID AND other.DocumentGuid=n.DocumentGuid AND other.ChapterKey<>n.ChapterKey AND other.ChapterStart=s.Start AND @Position=n.ChapterStart AND @Position