Validation issues in edge tables

In SQL Server 2017, it is not possible to define constraints on the edge table to restrict it from connecting any two types of nodes. That is, an edge can connect any two nodes in the graph, regardless of their types. Therefore, you can have relational duplicates in the table and thus, for instance, let the user follow him/herself. In a relational table, you can create a constraint and prevent this, as shown in the following code:

ALTER TABLE dbo.UserFollows ADD CONSTRAINT CHK_UserFollows CHECK (UserId <> FollowingUserId); 

Now, when you try to insert an entry that violates the constraints, as shown in the following code:

INSERT INTO dbo.UserFollows VALUES (1, 1);

You will be welcomed with the following error message:

Msg 547, Level 16, State 0, Line 10
The INSERT statement conflicted with the CHECK constraint "CHK_UserFollows". The conflict occurred in database "SqlGraphDb", table "dbo.UserFollows".
The statement has been terminated.

However, in an edge table, you cannot create such constraints on automatically created columns, and thus this insert would be possible. To prevent this integrity issue, you have to use triggers. The following trigger implements this:

CREATE TRIGGER dbo.TG1 ON dbo.Follows
FOR INSERT, UPDATE
AS
BEGIN
IF EXISTS(SELECT 1 FROM inserted WHERE inserted.$from_id = inserted.$to_id)
BEGIN
RAISERROR('User cannot follow himself!',16,1);
ROLLBACK TRAN;
END
END

Now, the INSERT statement that indicates that the user follows him/herself should not work:

INSERT INTO dbo.Follows  VALUES('{"type":"node","schema":"dbo","table":"TwitterUser","id":0}','{"type":"node","schema":"dbo","table":"TwitterUser","id":0}');

Indeed, when you execute the statement, you will get an error message informing you that the transaction has been aborted, as shown in the following code:

Msg 50000, Level 16, State 1, Procedure TG1, Line 7 [Batch Start Line 11]
User cannot follow himself!
Msg 3609, Level 16, State 1, Line 12
The transaction ended in the trigger. The batch has been aborted.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.163.208