Referencing a non-existing node

In addition to the previous issue, you can also insert a relation into an edge table that uses node_ids that don't exist at all. For instance, in the table used in this chapter, there are no nodes with the ID of 45 and 65, and thus the next statement should not work:

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

However, the result of the previous statement does not look like an error message, as shown in the following code:

(1 row affected)

As you might guess, to prevent this, you can use a trigger. The following code creates a trigger that does not allow you to reference a non-existing node in an edge table:

CREATE TRIGGER dbo.TG2 ON dbo.Follows
FOR INSERT, UPDATE
AS
BEGIN
IF NOT EXISTS(SELECT 1 FROM inserted
INNER JOIN dbo.TwitterUser tu ON inserted.$from_id = tu.$node_id
INNER JOIN dbo.TwitterUser tu2 ON inserted.$to_id = tu2.$node_id
)
BEGIN
RAISERROR('At least one node does not exist!',16,1);
ROLLBACK TRAN;
END
END

Now, you can try to insert a relation for non-existing nodes:

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

As you expected, you'll get an error:

Msg 50000, Level 16, State 1, Procedure TG2, Line 10 [Batch Start Line 0]
At least one node does not exist!
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.

If you specify a non-existing node table, the INSERT will fail:

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

The preceding INSERT statement fails with the following error message:

Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'from_obj_id_CAD229E5EB9443328A3F0291CEEF166C', table 'SqlGraphDb.dbo.Follows'; column does not allow nulls. INSERT fails.
The statement has been terminated.

This issue is prevented by design and you don't need to use a trigger.

..................Content has been hidden....................

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