Triggers: Born Evil or Misunderstood?

Slides:



Advertisements
Similar presentations
Yukon – What is New Rajesh Gala. Yukon – What is new.NET Framework Programming Data Types Exception Handling Batches Databases Database Engine Administration.
Advertisements

Louis Davidson drsql.org. Triggers and Tiggers have one important thing in commonTiggers Generally speaking, you are better off the fewer of them you.
1 Constraints, Triggers and Active Databases Chapter 9.
Advantage Data Dictionary. agenda Creating and Managing Data Dictionaries –Tables, Indexes, Fields, and Triggers –Defining Referential Integrity –Defining.
Introduction to Structured Query Language (SQL)
Database Design Concepts INFO1408 Term 2 week 1 Data validation and Referential integrity.
Introduction to Structured Query Language (SQL)
Working with SQL and PL/SQL/ Session 1 / 1 of 27 SQL Server Architecture.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
Chapter 7 Constraints and Triggers Spring 2011 Instructor: Hassan Khosravi.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Chapter 6: Integrity and Security Thomas Nikl 19 October, 2004 CS157B.
Database Technical Session By: Prof. Adarsh Patel.
Drsql.org How to Write a DML Trigger Louis Davidson drsql.org.
Lecture 7 Integrity & Veracity UFCE8K-15-M: Data Management.
SQL Server 7.0 Maintaining Referential Integrity.
November 6-9, Seattle, WA Triggers: Born Evil or Misunderstood? Louis Davidson.
Triggers A Quick Reference and Summary BIT 275. Triggers SQL code permits you to access only one table for an INSERT, UPDATE, or DELETE statement. The.
M1G Introduction to Database Development 2. Creating a Database.
Views Lesson 7.
Triggers. Why Triggers ? Suppose a warehouse wishes to maintain a minimum inventory of each item. Number of items kept in items table Items(name, number,...)
Data Driven Designs 99% of enterprise applications operate on database data or at least interface databases. Most common DBMS are Microsoft SQL Server,
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Fall 2001Database Systems1 Triggers Assertions –Assertions describe rules that should hold for a given database. –An assertion is checked anytime a table.
Advanced SQL: Triggers & Assertions
Constraints cis 407 Types of Constraints & Naming Key Constraints Unique Constraints Check Constraints Default Constraints Misc Rules and Defaults Triggers.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Louis Davidson drsql.org.  Introduction  Trigger Coding Basics  Designing a Trigger Solution  Advanced Trigger Concepts  Summary.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
Constraints Lesson 8. Skills Matrix Constraints Domain Integrity: A domain refers to a column in a table. Domain integrity includes data types, rules,
Session 1 Module 1: Introduction to Data Integrity
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Louis Davidson drsql.org.  Introduction  Designing a Trigger Solution  Trigger Coding Basics  Advanced Trigger Concepts  Summary SQL Saturday East.
A Guide to SQL, Eighth Edition Chapter Six Updating Data.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Constraints Advanced Database Systems Dr. AlaaEddin Almabhouh.
7.5 Using Stored-Procedure and Triggers NAME MATRIC NUM GROUP Muhammad Azwan Bin Khairul Anwar CS2305A Muhammad Faiz Bin Badrol Shah CS2305B.
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
Getting started with Accurately Storing Data
With Temporal Tables and More
Fundamentals of DBMS Notes-1.
Trigger used in PosgreSQL
Logical Database Design and the Rational Model
How to Write a DML Trigger
Chapter 6: Integrity (and Security)
Creating Database Triggers
Active Database Concepts
Instructor: Jason Carter
CIS 155 Table Relationship
Error Handling Summary of the next few pages: Error Handling Cursors.
Let Me Finish... Isolating Write Operations
Module 5: Implementing Data Integrity by Using Constraints
Normalization Referential Integrity
Prove to your boss your database is sound - Unit Testing with tSQLt
Constraints.
Advanced SQL: Views & Triggers
Microsoft SQL Server 2014 for Oracle DBAs Module 7
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Let Me Finish... Isolating Write Operations
Relational Database Design
Prof. Arfaoui. COM390 Chapter 9
SQL – Constraints & Triggers
-Transactions in SQL -Constraints and Triggers
Assertions and Triggers
Responding to Data Manipulation Via Triggers
Presentation transcript:

Triggers: Born Evil or Misunderstood? Louis Davidson

Who am I? Been in IT for over 18 years Microsoft MVP For 9 Years Corporate Data Architect Written five books on database design Ok, so they were all versions of the same book. They at least had slightly different titles each time

Brief Introduction Triggers are coded modules that are very similar to stored procedures Not called directly, but are “triggered” by certain events With “special” tools to access event data Triggers existed in Microsoft SQL Server 1.0 (far before check constraints!) Types: DML –Table/View level, fire on INSERT, UPDATE and/or DELETE to a single object Once per statement, regardless of number of rows DDL – Server or Database level, fire whenever a DDL statement is executed Login – Fire whenever a user logs into the server AD-100 - Triggers, Born Evil or Misunderstood?

Introduction - Continued Triggers execute as part of the operation statement ROLLBACK in the trigger will stop the operation (and anything else that is part of the current transaction) Can use EXECUTE AS to elevate the permissions of the trigger code (in extreme circumstances!) Never return any results from triggers Ability to do so will be removed in an upcoming SQL Server version Currently controlled with “disallow results from triggers” server setting Should operate silently AD-100 - Triggers, Born Evil or Misunderstood?

The Setup… In the following session we will put triggers on trial I will play the part of Judge, Prosecutor, and Defense Attorney I will provide many exhibits (aka Code Demos) to demonstrate my points You will play the part of Jury Member and possibly Witness AD-100 - Triggers, Born Evil or Misunderstood?

Your Part of the Process - Jury Judge triggers… You will be given the following choices, majority rules You can find them 5 - Evil 4 3 2 1 – Misunderstood (aka Awesome!) Then we discuss sentencing… AD-100 - Triggers, Born Evil or Misunderstood?

Come to order AD-100 - Triggers, Born Evil or Misunderstood?

Opening Statements - Prosecution AD-100 - Triggers, Born Evil or Misunderstood?

Triggers are dangerous Sneaky…can do weird stuff to data that isn’t obvious Performance could be affected Difficult to get right unless you are really careful Multi-row operations for DML triggers are commonly screwed up Very often the source of problems that aren’t diagnosed because they execute silently Error handling can be messy Sneaky Conniving Performance Zapping Expect to insert 100 rows, but none entered You check your WHERE clause, and it seems right… Administrators should be able to tell, but typical end users will never know better AD-100 - Triggers, Born Evil or Misunderstood?

Opening Statement - Defense AD-100 - Triggers, Born Evil or Misunderstood?

What is the overall data problem? Top Issue with Database Implementations #1 Data Quality #2 Does any other issue matter if the data quality is unsatisfactory? Obviously performance and usability is important, but still quality is the most important thing Anything we can do to manage our servers and keep the data clean the better Triggers are a VERY small part of the picture! But still a part of the picture… AD-100 - Triggers, Born Evil or Misunderstood?

Data Protection.1/3 – Start right! Start by getting the structure correct Normalization -Normalized structures are far less susceptible to data integrity issues Datatypes Match datatypes to the needs of the user Data stored in the right datatype works better for the Query Processor Make sure only the right people are modifying structures AD-100 - Triggers, Born Evil or Misunderstood?

Data Protection.2/3 - Constraints NULL: Determines if a column will accept NULL for its value. NULL constraints aren’t technically constraint objects, they behave like them. PRIMARY KEY and UNIQUE: Used to make sure your rows contain only unique combinations of values over a given set of key columns. FOREIGN KEY: Used to make sure that any migrated keys have only valid values that match the key columns they reference. DEFAULT: Used to set an acceptable default value for a column when the user doesn’t provide one. (Some people don’t count defaults as constraints, because they don’t constrain updates.) CHECK: Used to limit the values that can be entered into a single column or an entire row. AD-100 - Triggers, Born Evil or Misunderstood?

Data Protection.3/3 Determine what can be reliably done using client code Stored procedures Compiled, procedural code The key word in previous statement: “reliably” Client code is notoriously untrustworthy It gets worse when it a rule has to be enforced in multiple places Often multiple layers implementing the same rules can be useful Then come triggers…filling in gaps that can not be handled reliably in any other manner AD-100 - Triggers, Born Evil or Misunderstood?

Prosecution – Evidence AD-100 - Triggers, Born Evil or Misunderstood?

Exhibit A – Multi-row Operations DML triggers must be coded using Multi-Row operations Not getting this right can cause data to be allowed in that is actually incorrect AD-100 - Triggers, Born Evil or Misunderstood?

Exhibit B –Settings Triggers are subject to settings at the server and the database level that can change how the code works AT RUNTIME! Including: sp_serveroption— nested triggers (default ON)– Determines if a DML statement from one trigger causes other DML triggers to be executed Database option—RECURSIVE_TRIGGERS (default OFF)– Determines if an update on the table where the trigger fired causes the same triggers to fire again sp_serveroption–disallow results from triggers (default OFF): Turn this setting on will ensure that any trigger that tries to return data to the client will get an error sp_serveroption-server trigger recursion (default ON) – Determines if DDL in a server DDL trigger causes it to fire again AD-100 - Triggers, Born Evil or Misunderstood?

Exhibit C –Messy Error Handling Errors that occur in triggers can result in multiple different outcomes, depending on how they are coded AD-100 - Triggers, Born Evil or Misunderstood?

Exhibit D –Weird Things Happen DML Triggers can make the action you want to take not actually occur This can go unnoticed for long periods of time, causing data loss Even worse, sometimes triggers return results…by accident… AD-100 - Triggers, Born Evil or Misunderstood?

Prosecution – Last Minute Witnesses? AD-100 - Triggers, Born Evil or Misunderstood?

Defense – Evidence AD-100 - Triggers, Born Evil or Misunderstood?

Exhibit A –Skill and Templates… It is true, triggers are not “simple” However, the prosecution would have you believe they are impossible With caution and process, they are very possible Start from a template that sets you up for success AD-100 - Triggers, Born Evil or Misunderstood?

Exhibit B –Automatic Protection… When coded properly, prevents data that does not meet minimum standards to be stored, even if the rules are complex.. AD-100 - Triggers, Born Evil or Misunderstood?

Exhibit C – Makes Magic Happen Triggers can, when needed do validations that other types of automatic code cannot: Access data in multiple rows Access data in a different table Introduce side effects Stop DML operations Work on DDL operations Work on Login operations AD-100 - Triggers, Born Evil or Misunderstood?

Exhibit C – Example Magic Magical operations can occur with minimal coding where necessary and zero visible system impact Examples Clandestinely adding to third party systems Row metadata (last modified time) Logging changes to data AD-100 - Triggers, Born Evil or Misunderstood?

Exhibit D – Metadata Makes Life Easier There are many bits of metadata in the catalog objects that make it easier to support triggers sys.configurations: check the settings for nested triggers and results allowed sys.databases: see if recursive triggers set to on sys.triggers: list triggers and properties sys.trigger_events: list events that cause triggers to fire sys.dm_sql_referenced_entities: see objects and columns referenced in triggers AD-100 - Triggers, Born Evil or Misunderstood?

Exhibit E – Works on Any Edition Express Standard Enterprise AD-100 - Triggers, Born Evil or Misunderstood?

Defense – Last Minute Witness? AD-100 - Triggers, Born Evil or Misunderstood?

Summation - Prosecution AD-100 - Triggers, Born Evil or Misunderstood?

Summation – Prosecution Points Triggers are sneaky, devious objects Triggers are the most complex code that has to be maintained DBAs need to be cognizant of their existence of they will drive you NUTS Any positives are always prefixed with: As long as you know what you are doing AD-100 - Triggers, Born Evil or Misunderstood?

Summation - Defense AD-100 - Triggers, Born Evil or Misunderstood?

Summation – Defense Points Triggers fill a gap of data validation that cannot be done easily otherwise Multi-row validations Multi-table validations Auditing (certainly where Version < Enterprise) Complex Cascading operations Triggers allow you to make silent changes to system (the prosecution called this sneaky, I call it useful) As long as programmers/users are aware of their existence and purpose, they are helpful and useful tools AD-100 - Triggers, Born Evil or Misunderstood?

Ladies and Gentlemen of the Jury It is time, what says you? You can find them 5 - Evil 4 3 2 1 – Misunderstood (aka Awesome!) AD-100 - Triggers, Born Evil or Misunderstood?

Sentencing Quit your job before being forced to use a trigger Never use them in any case, unless your boss forces you to Only use them when absolutely necessary and you can’t come up with any other method that would work Use them in any case where they seem needed and you can’t think of any other solution Use them for everything AD-100 - Triggers, Born Evil or Misunderstood?