You are on page 1of 16

M y S Q L lir r I)a ta b a sAd n i i n i s tra ro rs e

Chapter14 TRIGGERSAND EVENTS

$\sg

M"SQL firr l)atabascAdnlinistrators

Chaptcr l;t - Triggcrs anclIivcnts

l4.Triggers Events and


Learning Objectives
This chapte:r introcluccs Trigger and Events in NI'SQL. In this chaptcr. voLtwill lcarn to: . o . o o . o . o o o 'l-ri-cgcr c()nccpts I ) i l ' l c r c n ll y p c s o l ' t r i s g c r s Syntax to crcatc and dnrp trigscrs privilcgcs J'rig-ccr R c : . r s o l lts ) u s c t | i g g c r s ( TriSscrliltlitlttitttl: What lrvcnts arc S y n t a x f i r r c r c a t i n u . l r o r p i n s n d a l t c r i n gc v c n t s c a l ) c t a i l s o l ' c v c n t c x c c u t i o ns c h c c l u l i n g P r i v i l c g c sl n c l c v c n t s S t a t u sv a r i a b l e s c r t u r r r i n u( )c v c n t s p t

$\ffiE

i \ .{

P a g c1 4 - 1

MySQL firr I)atabascAclntinistrators

Chlptcr l-l - Triggcrs ancl[lr,cnts

14.1. Triggers

@
l4. l. l. T ri g g e r C o n c e p ts
[)atabasctriggcrs arc tlittttccl databascobjccts that arc nraintainccl ithin 1 clrtahtsc arc rctivate{ r,l lllcl r,l,hcn clatawithin a tlblc is Inoclil'icd. Hach tri-qficr within that clatahusc nrust havcr clif'l'crcnt a niintc. A t r i g g c r i s d c l ' i n c ctlo t c t i ' n l t c ' l r c t t p a r t i c u l a rk i n d o l ' c v c n t o c c u r s l i t r a g i v c t a b l c .( O n 6 c c a s i g . w a ,11u ) n r i g h t s c c i t s a i d t h a t a t r i g g c r " l ' i r e s . "l ' h i s t r a i n i n g g u i t l c u s c s t h c t c r n t . ' a c t i v ' a t c s . " - h c t r i g g c r t l c f - i n i t i o n l i n c l u d c s r t a L c n 'ne t o b c c r c c u t c d w h c n t h e t r i g g c r a c t i rl t c s . s lt Thc evcrlts firr which tri-ugcrscan bc dcfinecl arc trNSERT. DELETE. ancl UPDATE. A givcn rriugcr is d c l ' i n c clli l r o n l y o n c o f ' t h c s cc r c l t t s . b u t y o u c u d c f i n c r n u l t i p l c t r i g g c r sl i l r a t u b l c .o n c t r i g g e r p c t ' t y p c 9 l t cvcnt. Tri-sgcrscan bc dcl'inedto activatccithcr bclirre or af'terthe cvcnt. 'fhis nicans thcrc can hc two triggcrs pcr cven[ (firr cxaniplc. otlc triggcr to activatc bc./rtrcan UFDATE ancl onc t activatc uficr). Thcrcfirrc. thcrc c a n b c u p t o s i x t r i g c c r sp c r t a h l c .

11.1.2. Creating Triggers Ttl def ine a trigscr lirr a tablc. usc thc CREATE TRIGGER statcntcnt.i'nhichhas thc lirlIrwi:] svnti.tx: CREATE { TRIGGER t rigger _?ame DELETE i I AFTER } { INSERT I UPDATE I ON t.abLe _name FOR EACH RO}g triggered statement tsEFORE

triqqer-name i s t h c l t a n t ct o , u i v c t h c t r i g - u e ra n c l t ; b i e _ ; t : r i t - . i s t h c :t a h l c w i t h w h i c h t o a s s o c i r t c . thc triegcr. BEfoRE or AFTER indicatcswhether thc tricser activrtcs bclorc or af'tcrthc triggcring cvcnt, and INSERT. UPDATE. or DELETE indicate what that cvenr is. s Thc lilllowint cxantplc crcatcs a triggcr nanrcd DeletedCit-l' that activatcson clclcteslisni thc Cit.v tablc (f'rom thc world databilsc): CREATE FOR TRTGGER ROVS Cit.y_AD AFTER DELETE ON Ciry

EACH

INSERT INTO DeJ.etedCit.y Name } { ID, (OLD . ID, VALUES OLD . Name) ; Note: Thc artil'icialtablc nantcs(sornctinres calleclt,tcutlorct'ortl.s) OLD and NEWcan bc useci accessthe tcl ctrlunrn contcnts as thcv wcrc/are bcf'orc t>ru.ficr thc actual row opcriltlon.

';Ji..
ftsg {

P agc14- 2

A MySQt. lirr [)atabasc clministrators

Chapter l:1 - Triggcrs ancllrvents

14.1.3. Trigger Events " w T r i g g c r s a r c a s s o c i a t c c l i t h i n d i v i c l u a lt a b l c s .T h c n r c t h o dl i r r a c t i r . a t i n g r i g g c r s i s c a l l e c l c v c n t s " a n d t h c t l i r l l o w i n s l i s t d c s c r i b c s h o s ca v a i l a b l c : t o BEF'ORE - thcsc typcs ol'cvcnts arc bascclon activation tinrcs that takc placc bcfirrc changcs to 'l'hersc thc clata in thc tahlc arc writtcn to thc unclcrlvins clatabasc. typcs of' cvcnts can capturc intpropcr data cntrics attclcorrcct thcni or re'.jcct prior to storing thcnt. Thcrc arc thrcc activltion v c v c n t sa s s o c i a t c d r ' i t ht h c B E F O R E a c t i v a t i o nt i n r c : . o BEE'ORE TNSERT - this cvcnt is triggcrcd prior to ncu clatabcing adclccl thc tablc. to BEPCIRE UPDATE t h i s c v c n t i s t r i s s c r c c lp r i o r t o e x i s l i n g d a t a b c i n g u p d a t c c l( o r

ruvcrwritlcn w ith ncw clata. I o BEFORE DELETE - this cvcnt is triggcrcd prior to data bcing dclcte:cl I'ronithc tablc.

A F T E R - t h c s c t v l r c so f ' c v c n t s a r c b a s c d o n a c t i v a t i o nt i r n c st h a t t a k c p l a c c a l ' t c rc h a n g e st o t h c clata in the table arc r.l'rittcnto thc undcrlying databasc.Thcse tvpcs of' cvcnts can be ussd lirr l o g g i n u r l r a u d i t i n gt h c n r o d i fi c a t i o no l - c l a t a v i t h i n t h c c l a t a b a s c s .h c r c a r c t h r c c a c t i v a t i o ne v c n t s l T r . r s s o s i t gi{t h t h c A F T E R a el i \ i . r l r o ni l l r c : t "l o AFTER" INSERT - this cvcnt is triggered af'tcrncw data was rdded to thc tablc. o AFTER UPDATE this cvcnt is triggcrccl aficr cxistins data has bccn updatccl (or ovrrrwrittcnI vn rrcw data. ith

AFTER DELETE - this cvcnt is triggcrcd al'tcrdata has bcen dclctcclf'rontthc tablcs.

Forcign kcys with cascadingbchavior cllrrcntlv do NOT activatetrig-sers.

Othcr strtcnrcnts that havc a clircct cf'lcct on thc datt ill thc tablcs. likc REtrLACE and LOAD DATA T N F I L E . c a n a l s o t r i q s e r t h c a s s o c i . r tc v c n t s . cd

Thc trrggcr action docs not havc to bc a purc SQL slate:nrcnt. nlost slorcclproccdurc statcnrcnts likc CA.L are also supportecl.Thc tsEGTN" . . END conrtrutttl strtcr-nent may also bc uscd firr thc trigscr uction statem(]nt order to cxccutc a scclucncc in ol'stiltcmcnts.

Page 4-3 1

$\sg

MySQL lirr I)atabase: Adnrinistri-ltors

Chaptcr l-l - Triggcrs anclHvents

Inline Lab l4-A


In th i sc x c rc i s c o u w i l l c rc l tc tri ggcr. y a A CT IO N (Yo u D o )
L F i r s t .c h c c k t o s c c i f ' w h i c h r r i g g c r sr c s i c l c n t h c i currcnt schcnta:

CON{PUTERRESPONSE/ Cornments
{n cnrpty'sc1is rcturncclas tltcrc aren't anv triggcrs vct.

meysqJ-> SHOI{ TRIGGERS\G Ernpty set {CI.6 sec} ). A tablc shoultl bc crcatcclto conti.rin data thc c o l l e c t e dl ' r o n it h e t r i g l c r r : CREATE TABLE DeletedCity A tablcis crcatcd

mysql>

3.

C r c a t c t h e a c t u a lt r i g l c r . u s i n g t h c u p p r o p r i a t c n a n t ca c c o r d i n gt o t h c t v p c o l ' c v c n t . H e r c i t i s "AI)" for AFTER DELETE. Thc FOR. EACII RCIWin the syntax ntcansthal cxceutitrn oeeurs oncc "lill'cach nlw dclctccl."not "firr cach row' c u r r c n t l y i n t h c t a b l c . ":

rnysqS> *> _}

CREATE TRIGGER City_AD AFTER DBLETE ON Cty

FOR EACH ROW *)ts INSERT fNTO DeletedCity *> (ID, Name) VAIUES -)! (OLD . ID , OLD . Narne ) ;

1 . C o n l - i n l rt h a t t h e C i t r _ A l ) t r i _ e g cn o w ' c x i s t s r rnysql> SHOW TRIGGERS\G

{ row is rcturncd slrowilrg the propcrtiesancl l c l ' i n i t i o no l ' t h c t r i g g e r rows arc dclcted.

-5. Pcrlirrm DELETE on rhcCity tablc.This a ca u s c th c tri g g c r b c c x c c u tc d. aci ng s to pl row si n t h cD e l e te d C i ty ta b l e : rnysg}> *> DELETE F&.M City W H ER E N a me = ' L o ndon' ;

{e

!"jr.

1 Pagc 4-4

B\SM

l \ l r S Q L l i r r | ) a t u h r sA r l r t t i n i s t n r t o l ' s c

C h a p t c r l ; 1- T r i g g c r s a n d f t v c n t s

ACTION(YouDo)
6. Perfirrnr qLrcrv n thc City_AI) tritgcr table a o . Noticc that Lonclonhas bccn aclclccl thc table to ff?ysql-)2 SELECI' *

COMP[ITER RESPONSEComments / +------+----*---+ l I D N N a m e l +------+--------+ 456 | Lor:don I | I L820 [ London I +------+*-------+

14.1.4. Reasons to t.lse Triggers A t r i g g c r p r o v i c l c s l l n c a n s t ( ) c x c c u t c a n S Q L s t a t c n r c n o r s c t o l ' s t a t c r . n c r nws c n y o u i n s c r t . u p d a t c .o r i t lh 'frisgcrs providcthc lirlkrwingbencl'its: dclctcrows in a trblc. o .\ triggcr can cxullincro\\' vitlucs to hc inscrtcd or updatcd.anclit can dctcrntinc what values wcrc clclctccl what thcv r,r'crc or updatedto. ,\ triggcr can changc valucs helirrc thcv are inscrteclinto rtahlc or uscd to update a table. fior cxatlplc. vou culchcck lirr out-ol'-boundsvalucs ancl nrodil'v thcnt to bc within bounds. This c a p a h i l i t vc n a b l e t h c u s c o f ' t r i g g c r sa s d a t a l - i l t c r s . s You cut nroclil,v hou' INSERT. DELETE, or UPDATE work. l-rlr cxanrplc.durin_u trNSERT. you an c a n p r o v i d c a c l c f t u l t v a l u c t h a t i s h a s c do n t h c c u r r c n t t i r n c f i r r c o l u m n s w i t h a n y t c m p o r a l d a t a i t y r c .N o r n l a l l v . o n l v T I M E S T & I ' { Fc o l u n r n sc a n b c i n i t i a l i z c dt o t l i c c u r r c n l t i l n c a u t o m a t i c a l l y .

14.1.5. Trigger Error Handling H r r r l r sd u r i n g t r r g r : c r x c eu t i o l t a r c h a n d l c da s f i l l l o w s : c o o Il-a BEFORE trisscr cvcnt lrils. thc opcration on thc corresponding row is not pcrlilrmcd. Art AFTER trigscr cvcnt is cxccutcd only il'thc BEFORE triggcr cvcnt (il'any) and thc rutw opcrationboth cxccutc successl'ully. Fttr transactionaltahlcs. lrilurcof a trigger (and thus thc wholc statcmcnt)shoulclctusc rollhack ol'all changespcrlirrrncclby thc statcmcnt. For non-transactional tablcs. such rollhack cannot bc donc, so although the statcnrent lrils. any changespcrlirrmcd prior to thc point ol'the error rcmain in cl'li'ct.

14.1.6. Dropping Triggers This statcntcnt clropsa triggcr. Howcvcr. whcn a tablc is dclctecl.all thc triggcrs associatcd with that table arc also derlctccl.

$\dTg

'i" r{

P age14- 5

MySQL lirr I )atabase Aclntinistrators

Chaptcr l-1- Triggcrs anclHvents

W h e n u s i n gD R " O FT R I G G E R . t h c s c r v c rw , i l l k r o k f i r r t h a t t r i t g c r n a n t c i n t h c c u r r c n ts c h c n t a . f ' t h c I , r : i . r ' t ' , i - . - i , , ' r '.'t h a t i s b c i n - g l c l c t c ds i n a n o t h c rs c h c r n at,h c i s s u c l ' o f ' t h c t r t c n t cc a n i n c l u d ct h c c i s nt schcnlt lltnlc. DROP TRTGGER Lisc IF I rF EXrsrs ] [ schema_name . ] trigger__ ane;

EXISTS to prcvcnt an crror f'ntnl occLrrring firr a trisser that cklcs not cxist. A NOTE is gcneratccl l i r l 'L tl t t r t t - c r i s l c ttllt' i : l g c lr't l l c n u s i n CI F E X I S T S .

Note: Il'rou clropa databasc. thc triggcrs of'all its tablcs arc i.tut()nli.tticall_v clroppccl also.

14.1.7. Restrictions on Triggers 'l'riggers

bring a level of' powcr and sccurity clown to thc inclividual record scts ol' clata within a tablc. Htrwcvcr. thcrc arc lintitutirtt.r triggers.Thc lirllowing arc not allor,r,,cd: t() o o o (pREPARE. EXECUTE, DEALLCICATE PREPARE). SQI- prcparcd strtcnrcnts Statcmrcnts that clo cxplicit or implicit COMMIT or ROLTBACK. Statctllclltsthat rctunt a rcsult sct. This includcs SELECT statct'ncllts that do rr.r havc an INTO

''lu,'::r,ti;'l':JH,"^,,.':hi;";'J"'ili:ilJ:'u" with _-,*,'l:'':: sct cithcr SELECT

o o

F'LUSHstatcrtrcnts. 'fri-g-ger rccursior:You cannot rc-trigger thc triuger I'rontinside the tricgcr

In additioll. trigscrs are not l.ired in rcsponseto updatcs or deletcs that arc causcd bl, cascading fbrcign kcys. 14.1.8. Privileges Required for Triggers T() crcate 0r dcstrov tri-sgcrsr.vithCpgAfe TRIGGER or DROP TRIGGER, yOu must havc thc TRIGGER privifcgc. (Prirr to 5.1 SUPERtrivilcga i.srcquirctl.fttr tlrcsc.l(utur(.\.) Il'thc triggcrcd statcmcntusesoLD orNEV{,thcrc arc additional privilcgc rcquircntcnts: o T t r a s s i g nt h e v a l u e o l ' a c o l u n i n w i t h S E T N E w . c o l - _ _ n a m e = UPDATE prir,,ilcgc thc colul.nn. lirr vaJue. you nrust havc thc

Ttl usc NEW" col-name in an cxpressionto rcl'cr to thc ncw vrlucof't ct>luntn.y()u nrust have thc SELECT privilcec fbr thc column.

t, t'4. $) \'

$wrJ

'

P a g c1 4 -

M y S Q L l i r r l ) a t a b a s cA d n i i n i s t r a t o r s

Chaptcr l-1- Triggers ancllrvcnts

Inline Lab ll-B


In this crcrcisc vou 'uvill crcatc tablcs rncl thcn create triggers on thc tablcs crcatccl.

.{CTION (\'ou Do)


l. In thc M,SQl- cgtltttltttclc clicnt. typc: li USE worLd;

COMPLTTER RESPONSE Comments /


Thc clatabasc lcctcrl firr usc is llow thc world schcnra. se

?. . T v p c : SHOh? TABLES; 3. Typc: CITEATE?AtsLE d"otriggers {c o l u mn l IN T } ;


1. Typc: CREATE I'ABLE audit_triggers {oJ-.1*colrrrnn INT, ner*_colurnn INT, date cornpleted DATETIME) -5. Typc: CREATE TRIGGER dotriggers_ai AFTER TNSERT ON dotriqsers FOR EACH RO9{ INSERT INTO audit _triggers (new_colurnn / date_completed) VA,UES (NEW. coJ-umnln NOVI( ) ) ;

A l i s t o l ' t a b l c si n t h e w o r l d s c h c r n a s r c t u r n c d . i

The tablc dotriggers is creatcdw'ith onc integcr colunrn callcdcolumnl

Thc tablc audit_triggers is crcatcclw'ith threc coluntns. o l d _ c o l u m n . w h i c h i s a n i n t c r i c rc o l u n t n : n e w _ c o l u m n , w h i c h i s t l s o a n i n t c , e cc o l u m n : r date_completed. which is ol'thc clatctintc tvpc This trisgcr. dotriggers_ai. will inscrt rows into the audit_triggers table alier a rur.r, inscrtcd into thc is dotriggers tablc. nelr'_column storcs thc nc'uv cntrv adclcdto thc dotriggers tablc ancl date_completed storc tltc datc and tinic that thc row was inscrtccl.

. T y p c : INSEITT fNTO dot.riggers VALUES i 1 ) , ( 2 j , { 3 } , { 4 i, ( 5 ) , ( 6 ) ;

This statc:ntent inscrtssix nrws into the dotriggers tablc.

l. Tvpc:
SELECT * FROM dotrj-ggers;

This stltcmcnt rctums thc rows that wcrc addcclinto thc dotriggers tablc. This statcnrcntretums the six rows that werc addcd to thc audit_triggers tablc bascd on the'dotriggers_ai t,rigger. Notc that both thc inscrtcd valuc rs wcll as thc r c l c v a n td a t c t i n t c Notc: Thc colunin old_column is NULL becausctherc was no olcl clatabcins ntodil'iecl.

8. T ' y p c : S EL E C T * F R O M a u d i t

tri ggers;

9 . I n t h e M r S Q l - c o n t l n a n dl i n c c l i c n t . t y p c : DROP TRIGGER dotriggers _aJ-;

Thc dotriggers_ai triggcr is rcntovcd lionl thc world datahasc. Any l-uturc dclctcs on the dotriggers tablc w'ill rrr rccordcd in thc audit_triggers tablc. bc All the rows in thc dotriggers tablcs arc dclcted.

1 0 .T y p c : DELETE FROM dotriggers;

'.b

i'o,

P a g c1 4 - l

&sg

MySQL firr l)atabascAchlinistrators

Chaptcr l:1 - Triggcrs ancllrvcnts

A CTIO N (\' o u D o ) I l. Typc: SE L EC T * F R O Md o tri g g e rs ;

COMPLITER RESPONSE/ Comments


R c s u l t si n L u tc n r p t r ,s c t d u c t o t h c p r c v i o u sc l c l c t i o n . ' Note: Both thc dotriggers and thc audit_triggers t a b l c sw i l l r c r n a i n .u r r t i l t h c y a r c d c l c t c d ( u s i n e D R O P

TABI,E ).

,B

.1.
'!{-

Pagc 14-B

&ss

MySQL firr I)atabasc dnrinistrators A

C h a p t c r l - 1 - T r i g g c r s a n c lI r v c n t s

14.2. Events
MySQL [']vcnts arc t.tsks that run accorcling to a schcdulc. Thcrclirrc. ue sontctirncsrelcr to thent as st'ltt'tlul'tl evcnts. Whcu vou crcatc urcvcnt. you rrecrcatin-!ti.r niunccl clatablscobjcct contrilrin_s i.rn (optionally conrpouncl)SQI- (or storcclproccclurc)statcnrcr.lt thal is to bc cxccutcclat a ccrtain ntolncnt ir) t i t - t t co p t i t t n a l l ' r c c u r r i t t ga t a r c g u l a r i n t c r l ' a l .C o n c c p t u a l h ' .t h i s i s s i n r i l a rt o t h c i d c a o l ' t h c L , i n u x / L l n i x . " c r o n t a b ( l l s o k n o w n l s : . 1c r o n j o b " t o r t h c W i n c l o r . vT a s k S c h c d u l c r . s Ncw cvents are crcttccl using thc CREA.TE E1ENT svntax. Thc svntar nroclclis sivcn bclow: CREATE = i user IBEFINER I CURRENT_USER ll E1ENT

Irr

NoT EXTSTS]
schedu-i.e

eveJ?_ ?ame ON SCIIEDULE [oN []OT I pRESERIE l ON SLA\IE] I DTSABLE I DTSABLE IENAFLE ' comment' j ICOMMENT DO sgl_ statemet C0MPLETTON N o t e t h c l i r l l o w i n g n r a n d a t o r y a r i a b l cc l c n t c n t si n t h e s v n t a x : v o e\eJ?t marne: F,vcntsarc schcntaob.jccts..lust likc tahlcs. storeclproceclurcs ancl triggcrs. Thc bc cvcn_nanlc rnLtst a valicl iclcrttif-ier. it rnay bc cuotcdancl/orcualif with thc schcnia name ancl icd in thc ususal wa'. All cvcnts in a schctnasharc thc srnrc nurlcspacc. hcncc cvcnt nlllcs n-lusl trnd bc uniqucwithin tlrcschclria. schedu-Le: Thc schcdulc is a rule that spccil'icswhcn thc action that is rssocirtcd thc t:vt:nt with w i l l b c c x s c u t c d .T h i s i s c x p l a i n c di n I ' u l l d c t a i l i n a s c p a r a t c c c t i o ni n t h i s c h a p t c r . s sgf_stat.ement: t h i s i s a v a l i d S Q L s t a t e n t c n to r s t o r c c lp r o c c d u r cs t a t c m c n tt h a t w i l l b e cxccutccl as clictatcd hy thc schedulc. Gcnerallv spcakinu thc statcnrcntis subject to thc slmc lilnitati<tnsas thc slatcnrcnts that can appcar in storcclproceclures and clynanticSQL. In addition. t h c s t a t c n t c n tc a n n o t b c a s t a t c m c n t t h a t r c t u r n s a r c s u l t s c t ( s u c h a s S E L E C T o r S H O I ) . Typically'. onc wttuld usc a CA[,I. statcnlcnl1o call a proccclurc pcrlitrnl thc actual action. to Apart liorn thcsc ntandatorvclnrcnts.thcrc rrc numbcr ol'othcr clauscsthat nccclsorneexplanation: a . D E F I N E R : a s p e c i f c a t i o no f - t h c u s c r a c c o u n tw h i c h i s u s e c t o r c s o l v c r c c c sp r i v i l c g c s .T h i s c a n i l s c i t h e : rb c a n a n r c c la c c o u n t o f ' t h c l b r r n ' u s e - q _ n a m e ' Q ' h o s t n a n e r or the kcy word CURRENT -USER . which cxplicitly dcnotcs that thc privilcgcs ol' thc currcnt uscr account will b c u s c d .W h c n n o t s p c c i l ' y i n g h c D E F I N E R c l a u s c . t h c p r i v i l c g c so 1 ' t h cc u r r e n tu s e r a r c u s c d . t bchavcs in thc usual wav, and prcvcnts an crror l-ror.n r'rccurrinsin clscan o l ' t h a t n a n r ca l r c a d ye x i s t si n t h c s p c c i fi e d s c h c m a svcnt IF NOT EXISTS:

P agc14- 9

ftss

M'SQL lirr I)atabrsc Adnlinistrators

('haptcr l-l - l'riggcrs anclF.vcnts

'

CIN COMPLETfON

clausc: spccifics whcthcr tlrc c\,cnt shoulcl bc kcpt or cliscarclcdtl'tcr cotltplctitln.lll' dcl'ault.cvcnts arc cliscardcd, hut this can hc prcvcntcctb, using thc PRESEIT\,rE kcvwrlrcl. l r n a b l i n g : t h i s c l a u s e s p c c i l ' i e s ' h a t h a p p c n s w l r c n t h c s c h c r l u l ci s r n c t . F i _ r , , c l c f l u lc . c n t s a r c w tv c n a b l c d .l t l c l " u l i l l t h a t t h c i r a s s o c i r t c c l t i o n w i l l b c c x c c u t c c lU s i n s t h c D I S A B L E k c _ v w o r c l , i l l s ac . w crcatc thc cvcllt^ but not cxccutc it cvcn if'thc scl-rcclulc rnct. Thc DISAtsLE OII SLA1IE phrasc is t l t a v h c u s c c lw l r c t t u s i t t s c v e n t s i n a r c p l i c a t i o nc l u s t c r .T h i s i s u s e l ' u li n c a s c t h c a c t i o n p e r l i l r n i s w o r k . s u c h a s i n s c r t r n g l a t ai n L oa t a b l c . t h a t w i l l b c r c p l i c a t c cill l t h c u s u a l f ' a s h i o nA s i n t h i s c a s c c . a c l c l i t i t t n a lx c c u t i o n o f ' t h c c v c n t w i l l i n t c r fe r c . t h i s l l a v l r c u s c c lt o p r r r v c n t1 h cc v c n t f ' r o n rh c i l t g c c x c c u t c d .b u t o n l t ' o n t h e s l a v c s .

Oncc thc cvcnt is crcatcd. it is storccl in thc databascso it can bc cxccLrtccl accorclingto schcclulc.Thc schsdulcsol'all cvcnts are nlor.lirorecl thc so callcclcvent_schcdular br thrcad. which will start a ncw thrcacl t o a c t u a l l yc x c c u t ct h e c v c n t o l l c c t h c s c h e d u l e s m c t . i t s ' d c l a u l t . t h c c v c n - s c h c c l L r l ch r c a d i s n o t c n a b l e d .l t n r u s tb c c x p l i c i t l v c n a h l c db v n r o i l i i n g t h c v a l u e o f ' tr thc global event--scheduler s c r v c r v a r i a h l c .T h i s c a n b c c k l t c c i t h c r i n a n o p t i o n l ' i l c ( s o t h c c h a n g c takes cf'f-cct startup)rlr dvnanrically usine thc SET srntax: on = { ON I OFF,' SET GLOBAL event_ scheduler } A l t e r t h c c v c n - s c h c d u l e rt h r c a d i s c n a b l c d .i t i s v i s i b l c i r r t h c o u r p u ro f ' S H O { P R O C E S S L I S T i n f o r m a t i o n _ s c h e m a c qu i v a l c n t ,P R O C E S S L I S T ) (and the

Oncc created.EVENTs mav bc changed using t h c A L T E R E l E N T s v n r a x .l r v e r r ys i n g l c c l c m c n r o f ' t h c E\ENT maybe changcd u,ith this svnrax, and conscqucntlv. thc svntax ntodcl filr ALTER EVENT is almost idcntical to that of'thc CREATE E\IENT s t a t c m c n t : ALTER

IDEFINER = { user I CURRENT_USER }] EIIENT event r?arne ION SCEIEDLE scheduJe,] loN CCIMPLETTON [NOT] FRESER\ru1 [RENAIr4E TO new__e\ent_ name] [ENABLE I DISABLE I DISABLE ON SLAVE] ' ICOMMENT comment'l sqL_satement ] IDO Finally.cvents rnaybc dropped usingthc DROPEVENT synrax: DROP E\IENT [IF' EXISTSJ event_name

14.2.1. Schedule A scltedulr a rulc thatspccif whcn lhc actionshould cxecutcd. schedulc bc spccif in thc is ics bc The ied crn SCHtrDULHclausc ol'thc CRITATIT IiVHNT andALTHR tTVHNT stiltcme nts. Thcrcarc two typcsof'schcdulc: thoscthatars cxccutcd oncc(usingthc AT kcvword)antl thoscthatrnay (usingthc ITVHRYkcyword). bc cxccutcd rcpcatcdly For the lattcrit is lltanclatory dcl'inc intcrval to an to

T-.\
t!(. \

Page 4-10 1

E\Sg

MvSQL firr l)atabasc drninistrators A

( - l l t p t c r l J - T r i g g c r su n t l F . v c n t s

clcl'incthc l'rcqucncv.and optionallv. a tinic-winclow can he clcfincclthat clcnrarcatcs clurins what pcrioclthc cvcnt slroulcl rcpcatccl. bc 'I'he syntax lirr therSCHEDLE clruser sivcn hclo'ul,: is AT I timesarnp interval [+ INTERVAL in enral ]

EVERY

nf e^rra] I l I STARTS i"rnesamp [ + INTERVAL int.erva] IENDS imestamp [ + INTERVAL I l 'l'hc s c h e d u l c l a u s cc a n c o n t a i nt h c f i r l l o l v i n gv a r i a b l cc l c l n c n t s : c o T h i s i s a n c x p r c s s i o n l ' t h c I ) A T I T T I M I To r T I M H S T A M P t v p c . ti-nestainp: o o inerva7'. t h i s s p c c i l ' i c n s c l u r a t i o nT h c c l u r l t i o r ri s c r p l c s s c c b y s p c c i l y i n ga q u t n t i t - vl s u n a . l intcgcr fitllowcd bv a kevworcl that dcl'incsa particularkincl ol'cluration.Valid kcvworclsarc: YEAR. QUARTER. MONTI{. DAY. HOUR..MINUTE. WEEK. SECOND. YEAR_MONTH. DAY-ITOUIT. DAY-MINUSE. DAY SECOI{D. HOR MINIJTE. HOUR" SECOND. MINUTE-SECOND Irvcnts arc cxccutcclbv ther cvcnt schcduler.which is a scparatcthrcaclin ther nrysclldproccss.It chccks il'it s h o u l dc x c c u t ea n e v e n t .a n c lw h c n i t c k l c si t c r c a t c sa n c w c o n n c c t i o nt ( )c x c c u t c t h c a c t i o n . Bccituscthc schcclule triggcrs crccution ol'thc action. there is a rcscnrhluncc with table trirgcrs. Thcrclirrc. cvcr.lts kn()wn as tcnrporaltriggcrs (although that is not thc pre:lcrrccl are:illst'r tcnll). H v e n t sc a n b c u s c c lf i t r a u t o t r a t i c .p c r i o d i c a lc x e c u t i o no f ' ( n l a i n t c n l n c c ) t a s ks u c h a s u p d a t i n ga s u n l n l r y s. t a b l c o r r e l i c s h i n - u a t a b l c l ' m r r a q u c r y ( m a t c r i a l i z c d i c w c l n u l a t i o n ) " n d l i r r p c r l i t r r n i n gn i g h t l y . i o b s a v a (processingthc clal,'swork. loading a data warchousc,exporting data to I'ilc).
t a ' ; 2.2. '2' |

t't

183

The Event Scheduler r rtr r-lrrrt \) and NIySQL Privileges

T o c n a b l c o r c l i s a h l ct h e c x e c u t i o n o f ' s c h c d u l c d c v c n t s , i t i s n c e c s s a r y o s c t t h c v a l u c o l ' t h c g l o b a l t event__scheduler v a r i a b l c .l ' h i s r c q u i r c st h e S U P E Rp r i v i l c g e. T h er c i s a p r i v i l c g c s o v c r n i n g t h c c r c a t i o n .n r o d i l ' i c a t i o na n c ld c l c t i o n o f ' c v c n t s :t h c E V E N T p r i v i l c g c .T h i s . privilcgc can bc bcslowcd using GRANT. For cxaniplc, this GRANT statclncntconl'crsthc EVENT privilegc lirr thc schcrnananrcdmyschema on the uscr jon@ghidora: GRANT EIIENT ON myschema. * TO jon@ghidora;

Ttt grant this sltlcuscr thc E\IENT privilcgc on all schcnras would rccluircthc fitllowing statcnrcnt. GR.,AlfT EVENT ON * . * TO jon@ghi-dora;

Thc EVENT privilcgc has schcnla-lcvcl scopc. Therclirrc, trving t() grant it on a singlc table rcsults in an crr()r as shown: maysqJ"> GR.,ANT EVENT ON myschema . mytable TO jon@ghidora;

ib

-1.\''

ftrtg

'

P agc14- 11

MySQL firr I)atabascAclnlinrstrators

('haptcr I-l -'Iricscrs ancl[rve:nts

HRH"#ffi" X3"&& te?.*# ) : IJ-legal tReldTlRHV*g:ffi cc:rnnennd.;please t .h e m a n u a l - L * s * * w h i ch pri vl eges * & rr b* used

cnnsul*

It is inrportult r-lnderstancl an cvcnl is executeclwith t h c p r i r i l c g c s o l ' i t s d c l ' i n c r .a n c lt h a t i t c l l l n o t to that p e r l i r r n r r n v c t i o n sl i r r w h i c h i t s d c l ' i n c l ' c l o c n o t h a v c t h c r c q i r i s i t cp r i v i l c t c s . I - o r c x : . r n i p l cs u p p o s ct h a t a s . 3on@ghidora has thc EVENT privilcgc firr nnyschema. S u p p o s ca l s o t h a t t h i s r s c r h a s t h c S E L E C T p r i v i l c g c f i r r r n y s c h e m a . b u r n o o t h c r p r i v i l c g c s f i r r t h i s s c h c n l a .l t i s p o s s i b l c l i r r 3 o n $ g h 5 - d s r a t o c r c : . r t tn c w c v c n t s u c h a s t h i s o l l c : c CREATE EVERY E\IENT ]. e store ts

CIN SCIIEDT]LE SECOND

DO TNSERTrNTo myschema.myt,able vAl,uES (uNrx rrMESTgtp() );


* T h e u s c r w t i t s l i r r a l l . l i n u t c o r ' \ o . u n d t h c n p c r l i r r n r s a S E T , E C T F R O b {m y t a b l e ; q u e r ) . c x p c c t i n s t o scc scvcrllltcw rou's itl thc tablc. Instcad. hc l'inclsthat thc tahlc is clnpty. Sincc hc docs lt1lt haye thc T N S E R Tp r i v i l c g c f i r r t h e t a h l c i n q u c s t i o n . h e c v c n t h a s n o c l l e c t . t I f ' v t t u i n s p c c tt h c M y S Q L c r r r t r l t t g ( , , , . ' . r j i.i: . r i i , , , : , , . e r v) , u c a n s c c t h a t t h c c v e n t i s c x e c u t i n g .b u t t h c r ro ilction it is attcrlpting to pcrlirrnr I'ails.as indicatcdby RetCode=0: * 6*2*9 **2** ffi*29 62,*9 *6*g9 3.9 22 : 39 : 4& ?"2:39:44 22 : 39 : 5& 22:39:%& 22: &: 4 22:&*:4 ib*t.ar J iN*eel lt*ce j ili*te*l il*Lel i}*t.*J fiIff,X flXtrtrUTIhr# even* nesd*h " e f i l ' r f f i XH X H C { J ? H * e v c n * n e w d k r . * H\,'HX trXKfltITIlG evenr ::ewd"h " e f i V H X A X H C i t T g I ) * v e n L newdb " e H V H X H X H C U T E X { T v e n L n*:rd^h. e e fiVHX ffiX*UTKil *vsnr
^ ^ - - l L tlev.{ll,J " H

ItrXFF":3"l I H X F K : 3 - *1 " R e t C * d . e * * I H X F R :X " l i H K P & " :1 l . R e t . * c y d e = * In:ffiR: X" j iffiXtrR: tr-*l . ft.etf*d*=S

Sincethis uscr vcry likelv docsnot havcacccss thc errrtrlog, hc can vcrif-v to whcthcrlhc cvent's rction s t rtc rn es v a l i db v ru n n i n gt h i n l scl f' : i nt i r&ysql> INSERT INTO rnyschema . mytable VALUES tUNf X TIMESTAIVTP) ) ; ( KH.RR Lk&ft" {42**i : 3}l$ffiffi.T*srrnand deried f,e Lxser ' j e rru ' ' g h ri d # tra ' f,o r tabJ-e ' myt.ahl e ' S

l:.u

P agc14- 12

hdTg

MySQL lirr l)atabascAdlninistrators

C h r r p l c rl - l

Trisscrs ullrll-.rcnts

Inspcction tho INFORMATION_SCHEMA. ol' EVENTStablcsholl'sthat e_store_ts cxistsand is cnablccl, bul ils LAST. EXECUT'ED ctllurnnis NULL: r#ysq:-:" SELECT * FROM INFORb{ATI ON_SCHEI'{A. E\ruNTS *} WTTERfiE\TENT NAII{E= ' e store t's ' *v I\FID E\trgNT_gCHEftfA='rnyschenna ' \G
******s:"4'*'it** ******* ****,***1k L " row *.*** *.*** *****'**.*t{**'i4 ****,{.**

HturyIfT *&TFrL#t : brJtL KVHI{?'_SilHffiH4& rnys trh.erfte^ : ffinKlT _ffi&I4H: * stclce,,ts nffitrlltHR : SernSgkaed*r*. ffiVK?T ffi#*Y ; StL HLrybT aHtr:r:?r*H: :StsHRT x}T* ffiys*heerfta" rrytahl* ?:MffiSTJLh{e } } {TJWTX" i trI/KlgT ?YPH: StHt{.lRRIffiG ffiXffiCfJTffi A? : ?I"?LL }?ffiH.VAL V&L{"Ttr: 5 IH?ffiRVeL FIffiLn: NTffiRVAL Sffie*Hffi $fiL $4*trfi: ffiULt S T ' J L R T:t r * * # * * - #* : ** t *{} ffih;*g: *##*##*# *#: **: # ST&T{"}tr: ffiffiAffiLKffi FA #*F{PLHY#ffi: ha*T pRg$ffiR\rffi RffiATKn Z#S-*f;*S : L J L S T L T H ffi trf; 2 ,# 6* * k* * : L"&ST HKffi*ffTffi* : ?tlLL ffikruffiT_flM}4ffib?T : r*w n esh {#"* s*f;} fr*:3S: # 32 : 36 :* 6

vL{JHs

l) r io rl o tv l y SQL .1 .th c rc\\l \ n ()EV E N T E FIN ITfON eol urrul . E V E N T--B OD Y 5 .rrrtl contai rrctJ SQ L -D thc
statcnrcntor statst'l"lcnts bc cxcculcd. t() To rcscind the E\IENT privilcge. use thc REVOKE statcntcnt.In this cxamplc. thc EVENT privilcgc on thc schcnrr myschema is rcn.lovecl ll'onr thc jonQghidora uscr ilccourit: REVOKE E\ruNT ON myschema. * FROM jon@ghidora;

Important: Rcvokine thc EVENT privilcgc lnrm a user account does rr clelcteor clisableany cvcnts that nray have bccn crcatccl that account. by

' $\dlg

Pagc 4-13 1

M y S Q L l i r r I ) r t l r b u s cr l n r i l l l s l r r t o r r A

Chaptcr l-l - Triggcrs anclIlu'ents

I - o rc x a rn p l cs u p p o s th l t th a tu s crj on$ghdora has bcell grantcd thc EIIBNT ancl INSERT privilcgcs . e on thc myschema schcnltr. This uscrtlicncrcatcs l i r l l o w i n g c v c n t : thc CREATE E\ruNT e_insert. ON SCHEDULE E\rER.Y 7 SECCIND DO
TNSERT INTO lnyschema.rnyt,ahJ-e VATUES {T.INIX TIMHSTAMP {}) ; Howevcr, Alicr this cvcnt htsbccrt crcatccl.root rcvokes thc E\|ENT prililcge litr 3onggh:-dora. e-insert c t l n t i n L l c so g 1 g 1 c .i n s c r t i n - a n c \ \ ' r ( ) \ \ ' i n t ( ) m y t a b J - e c a c h s c v c n s c c t l l d s . t s

l r v en t d c l ' i r t i t i o r t s r c s t o r c c li n t h c m y s q l " e v e r r L t a h l c ( a c l c l c cn M y S Q L - 5 . 1 . 6 )H g w ev c r , v o u s h u l c l a il . a v o i d t o u c h i n g t h i s t a b l c d i r e c t l l , ( o r a r r y , o t h c r a b l c i n t h c m y s q l c l a r a b a sfc r r t h a t n t a t t c r ) . o t l i s c a r ca n t i T l c v t : n t ,u s e t h e I ) R O P H V I T N T s y n r a x : DROP ElENT I IF' EXISTS ] e_insert ;

Ntlt c that thc uscr that drors thc cvent rtccds to havc thc EVHNT privilegc lirr thc databasethat colttains thc cvcnt that is to bc dnrpped. l\iote: Thc nanlesplcc sclrcclulercl lirr cvcnts chanscclin M,SQL -5. Prior ro that MySeL vcrsion. dil'ltrcnt L u s c r s c o u l d c r c a t c d i l ' l c r c n tc \ c n t s h a r , i n st h e :s a m c n a n l c i n t h e s a r r e d a t a b a s c : n M y s e l , - 5 . 1a n c l l a t e r . i tltat is no lottsc:rthc casc. When upgrading to NI'SQL 5.1.12 or later from M,'SQL 5.1.1I or earlier, it is extremel' intportant to make sure that no events in the same database share the same name, trilr It tt,t'formin4 the up1rade,. LJscrs' EVENT privilcucs arc storcclin thc Event. >niv colunlns ol' thc mysqJ- . user anclmysql- . db t a b l c s . I n b t t t h c a s c s .t h i s c o l u n r n h o l d s o n c o l ' t h c v a l u c s ' Y ' o r ' N ' . ' N ' i s thc clelault. mysql .user.Event-priv i s s c t t o ' Y ' l i r r a g i v c n u s c r o n l v i f ' t h a t u s e rh a s t h c g l o h a l E V E N T p r i v i l c g c ( t h a t i s . i l ' t h c p r i v i l c g c ' u v a sh e s t o w c d u s i n g G R A N T E \ I E N T O N * . * ) . I r o r a s c h e n r a - l e v cE v E N T l privilcgc. GRANT crclttcsil ro\\ irr mysql. db and sets that row's Db column to thc nante ol'the schcnta, 'Y'. thc User citluntn Lo thc nantc ol'thc uscr. and tlrc Event_pri-v colunln to Thcre shoulclncvcr bc any necd to manipulatc tliesc tablcs dircctly. sincc thc GRANT E\IENT and REVOKE EVENT statcntt:nt pcrlirrnr the rcquircd opcrationson therl. M y S Q L 5 . 1 i n t r t t d u c e sf - i v c s t a t u s v a r i a b l e s p r o v i d i n g c o u n t s o f - c v e n t - r c l a t c c o p e r a t i o n s( b u t i r o l ' l statenlents executcdhv cvents.Thcsc arc: Com-create--event: rcstart. Com--a1ter.--event: rcstilrt. Com--drop-event: Thc nurnberol'CREATE EVENT statcntcnts cxccutcd sincc thc last scrvcr

Thc nutnbcr ol'ALTER E\IENT statcments cxecutcd sincc thc last scrvcr

Thc ttuntberol'DROP EVENT statcnrcnts exccutodsincc thc last servcr rcstart.

i.\

P a g c1 4 - 1 4

$wg

MySQL lirr l)attbasc Aclnrinistrators

!\r

fi\sg

You might also like