Duplicates in an edge table

As mentioned in the first subsection, in an edge table, you can connect any two nodes in the graph, regardless of their types. Therefore, you can have relational duplicates in the table. In relational tables, this is usually prevented by creating a primary key, as in the dbo.UserFollows relational table:

CONSTRAINT PK_UserFollows PRIMARY KEY CLUSTERED(
UserId ASC,
FollowingUserId ASC)
);

The primary key constraint will not let you enter the same pair of values for UserId and FollowingUserId again, but in the dbo.Follows edge table, this will be possible. The following statement will not fail:

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

When you check the content of the edge table, using the following code:

SELECT * FROM dbo.Follows;

You can see two entries with the same node_id, as shown in the following screenshot:

Duplicate entries in an edge table

You can see that the edge entries with IDs of 0 and 29 reference the same nodes. Of course, this problem will be solved with another trigger, but before that, you have to delete the last entry in this table by using the following statement:

DELETE FROM dbo.Follows WHERE $edge_id='{"type":"edge","schema":"dbo","table":"Follows","id":29}';

Clearly, you might use another ID in the DELETE statement, when you try to execute this code on your machine.

Now, you can create a trigger to prevent duplicates in the edge table:

CREATE TRIGGER dbo.TG3 ON dbo.Follows
FOR INSERT, UPDATE
AS
BEGIN
IF (( SELECT COUNT(*) FROM inserted INNER JOIN dbo.Follows f ON inserted.$from_id = f.$from_id AND inserted.$to_id = f.$to_id ) >0)
BEGIN
RAISERROR('Duplicates not allowed!',16,1);
ROLLBACK TRAN;
END
END

Again, try the same INSERT statement using the following code:

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

This time, the INSERT statement failed, as you expected. Here is the error message:

Msg 50000, Level 16, State 1, Procedure TG3, Line 7 [Batch Start Line 11]
Duplicates not allowed!
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.143.239.44