Triggers

In any database, when data is inserted, updated, or deleted, you can have the table launch a trigger. For example, if a user inserts a record, you could launch a trigger to make sure that the record meets some specified criteria—no null values. Spatial databases allow you to use the same triggers. You can create these in several languages, including Python and SQL. The following example will use PL/pgsql.

You create triggers using SQL expressions. The following code will create a trigger to prevent entering an incomplete incident:

query=('CREATE FUNCTION newcrime()'+'
'
'RETURNS trigger' +' '
'AS $newcrime$' +' '
'BEGIN' +' '
'IF NEW.crimetype IS NULL THEN'+' '
'RAISE EXCEPTION' +" '% Must Include Crime Type', NEW.address;"+' '
'END IF;'+' '
'RETURN NEW;'+' '
'END;'+' '
'$newcrime$'+' '
'LANGUAGE 'plpgsql';'
)
cursor.execute(query)

The previous code creates a new function named newcrime(). The function is an if statement that checks if the NEW.crimetype is null. If it is, the record is not added, and an exception is raised. The exception will state that NEW.address must include a crime type. The assumption is being made that the address is not null.

Now that you have a function, you can create a trigger that calls that function. The following code shows you how:

query=('CREATE TRIGGER newcrime BEFORE INSERT OR UPDATE ON incidents FOR EACH ROW EXECUTE PROCEDURE newcrime()')
cursor.execute(query)
connection.commit()

The previous code executes the SQL statement that creates the trigger. It is created BEFORE INSERT OR UPDATE. To test the trigger, let's insert a point with no crime type. The following code will attempt to enter the incident:

p=Point([-106,35])
address="123 Sesame St"
cursor.execute("INSERT INTO incidents (address, geom) VALUES ('{}', ST_GeomFromText('{}'))".format(address, p.wkt))

The previous code creates an incident with only an address and a geom. The result of executing the previous code is shown in the following screenshot:

In the previous screenshot, the InternalError states that 123 Sesame St Must Include Crime Type. Our trigger successfully blocked bad data from being entered. To double-check, we can query for "123 Sesame St." The results are shown in the following screenshot:

A trigger can be used to prevent bad data from being loaded for emailing or texting when changes have occurred. For example, you could allow users to enter polygons they are interested in, and their phone number. On a new incident being added to the database, you could see if it is within a polygon, and if so, text the phone number associated with the polygon. 

To install other languages for triggers, open Stack Builder and add the add-on shown in the following screenshot:

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

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