SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
www.syntegris.de
Der perfekte 12c
Trigger
Author: Sven Weller
NEW 12C FEATURES
Der perfekte 12c T r i gger
Autor: Sven Weller, Syntegris, Neu-Isenburg
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
BEFORE ROW INSERT TRIGGER
Der perfekte 12c Trigger
Feuert beim Insert
Für jede Zeile
Setzt Spaltenwerte
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
ID AND AUDIT COLUMNS
Traditional Trigger
1
2
3
4
5
6
7
8
9
10
11FOR EACH ROW
12 BEGIN
13 -- record needs always a key
14IF :new.id IS NULL 15
16
17
18
19
20
21
22
23
create table swe_demo (id number primary key
,col1 number
,col2 varchar2(30)
,inserted_date date not null
,inserted_from varchar2(30) not null);
create sequence swe_demo_seq cache 10000;
create or replace trigger swe_demo_bri_trg
BEFORE INSERT ON swe_demo
THEN
:new.id := swe_demo_seq.NEXTVAL;
END IF;
-- timestamp of the last changes
:new.inserted_date := SYSDATE;
:new.inserted_from := NVL(v('APP_USER'),
END swe_demo_bri_trg;
/
user);
1
2
3
4
5
6
7
8
create table swe_demo (id number primary key
,col1 number
,col2 varchar2(30)
,inserted_date date not null
,inserted_from varchar2(30) not null);
create sequence swe_demo_seq cache 10000;
1
2
3
4
5
create table swe_demo (id number primary key
,col1 number
,col2 varchar2(30)
,inserted_date date not null
,inserted_from varchar2(30) not null);
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
Der perfekte 12c Trigger
TOPICS
Der “perfekte” Trigger
=
?
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
TOPICS
Neue 12c Features
Performance
Tipps und Tricks
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
Der perfekte 12c Trigger
SYNTAX
Identity column (12R1)
”ID”
oder
”ID”
generated always as identity
generated by default on null as identity
Sequence wird automatisch erzeugt und verwaltet
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
SYNTAX
Default value columns (12R1)
expression => sequence.nextval
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
ENTSCHEIDUNG
Default value auch für andere non-ID Spalten
Identity Columns haben mehr “Nebeneffekte”
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
Default value oder Identity?
1
2
3
4
5
6
7
8
9
10
set serveroutput on
declare
v_id demo@remoteDB.id%type;
begin
insert into demo@remoteDB (col1)
values ('abc')
returning id into v_id;
dbms_output.put_line('new ID='||v_id);
end;
/
ORA-22816: unsupported feature with RETURNING clause
ORA-06512: at line 4
22816. 00000 - "unsupported feature with RETURNING clause"
*Cause: RETURNING clause is currently not supported for object type columns, LONG
columns, remote tables, INSERT with subquery,
and INSTEAD OF Triggers.
*Action: Use separate select statement to get the values.
DEFAULT COLUMNS
12c solution (ohne trigger)
create sequence swe_demo_seq cache 10000;
create table swe_demo
(id number default on null swe_demo_seq.nextval
,col1 number
,col2 varchar2(30)
primary key
,inserted_date date default sysdate
,inserted_from varchar2(30) default
not null
NVL(v('APP_USER'), user) not null);
Tipp: user => langsam
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
SYS_CONTEXT
Was ist ein Kontext?
Lokale oder globale “Variable”
vordefiniert: USERENV
Security Feature
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
USERENV
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
Aktueller Benutzer
SYS_CONTEXT('USERENV', ' p a r a m e t e r' )
Parameter Beschreibung
client_identifier Returns an identifier that is set by the application through the
DBMS_SESSION.SET_IDENTIFIER procedure, the OCI attribute
OCI_ATTR_CLIENT_IDENTIFIER, or the Java class
Oracle.jdbc.OracleConnection.setClientIdentifier. This attribute is used by various
database components to identify lightweight application users who authenticate as
the same database user.
current_schema Name of the default schema being used in the current schema. This value can be
changed during the session with an ALTER SESSION SET CURRENT_SCHEMA
statement.
current_user Deprecated – Use the SESSION_USER parameter instead.
session_user For enterprises users, returns the schema. For other users, returns the database user
name by which the current user is authenticated. This value remains the same
throughout the duration of the session.
dblink_info Returns the source of a database link session. Specifically, it returns a string of the
form:SOURCE_GLOBAL_NAME=dblink_src_global_name,
DBLINK_NAME=dblink_name,
SOURCE_AUDIT_SESSIONID=dblink_src_audit_sessionid
APEX KONTEXTE
SYS_CONTEXT('APEX$SESSION','APP_USER')
SYS_CONTEXT('APEX$SESSION','APP_SESSION')
SYS_CONTEXT('APEX$SESSION','WORKSPACE_ID')
neu in Apex 5
Extrem performant
Aktueller Benutzer
SYS_CONTEXT('USERENV','client_identifier')
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
APP_USER:APP_SESSION => SVEN:0123456789
DEFAULT COLUMNS + KONTEXT
12c Ergebnis - ohne Trigger
create sequence swe_demo_seq cache 10000;
create table swe_demo
(id number default on null swe_demo_seq.nextval primary key
,col1 number
,col2 varchar2(30)
,inserted_date date default sysdate not null
,inserted_from varchar2(30) default coalesce(
sys_context('APEX$SESSION','app_user'
)
,regexp_substr(sys_context('userenv','client_identifier'),'^[^:]*'
)
,sys_context('userenv','session_user')
)
not null);
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
VORTEILE
Weniger Code
Performance
Sequence mit Tabelle verbunden
12c ohne Trigger
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
www.syntegris.de
Fragen?
BEFORE ROW UPDATE TRIGGER
Keine 12c Alternative bisher!
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
Sonstiges
Neuer Syntax Vorschlag: DEFAULT ON UPDATE
https://community.oracle.com/ideas/15760
PERFORMANCE TEST - TC1
Sonstiges
1
2
3
4
5
6
7
8
9
10
set time on
set timing on
declare
v_result
begin
for i in
varchar2(100);
1..1000000 loop
v_result
end loop;
end;
/
:= ##EXPRESSION##;
Test
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
Skript
PERFORMANCE TEST - TC1
Sonstiges
1 set time on
2 set timing on Test S
3 declare
4 v_result varchar2(100);
5 begin
6 for i in 1..1000000 loop
7 v_result := ##EXPRESSION##;
8 end loop;
9 end;
10 /
kript
Expression Time (in s)
sys_context('userenv','client_identifier') 2,4
substr(sys_context('userenv','client_identifier'),1
,instr(sys_context('userenv','client_identifier'),':')-1)
4,3
substr(sys_context('userenv','client_identifier'),1,
coalesce(nullif(instr(sys_context('userenv','client_identifier'),':'),0)-1,
length(sys_context('userenv','client_identifier'))))
6,3
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
regexp_substr(sys_context('userenv','client_identifier'),'^[^:]*') 3,5
translate(sys_context('userenv','client_identifier'),'A0123456789','A') 5,6
user 20,6
sys_context('APEX$SESSION','app_user') 1,5
v('APP_USER') 5,6
CONTEXT WITH DBLINK
# Beschreibung Inserted From
1 apex remote insert SVEN
2 apex local insert SVEN
5 direct remote insert REMOTE_B
6 direct local insert LOCAL_A
7 direct insert current_schema IAMDBA
Sonstiges
App User Apex Session Client Identifier
– – SVEN:4628609689353
SVEN SVEN SVEN:4628609689353
– – –
– – –
– – –
© SYNTEGRIS INFORMATION SOLUTIONS GMBH
# Current
Schema
Current
User
User Session
User
Authenticated
Identity
1 DEMO DEMO REMOTE_B REMOTE_B REMOTE_B
2 DEMO DEMO APEX_PUBLIC_USER APEX_PUBLIC_USER APEX_PUBLIC_USER
5 DEMO DEMO REMOTE_B REMOTE_B REMOTE_B
6 DEMO DEMO LOCAL_A LOCAL_A LOCAL_A
7 DEMO DEMO IAMDBA IAMDBA IAMDBA
www.syntegris.de
The End!

Weitere ähnliche Inhalte

Was ist angesagt?

Calculator code with scientific functions in java
Calculator code with scientific functions in java Calculator code with scientific functions in java
Calculator code with scientific functions in java Amna Nawazish
 
Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...
Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...
Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...Andrés Viedma Peláez
 
Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016Svet Ivantchev
 
Introduction To Testing With Perl
Introduction To Testing With PerlIntroduction To Testing With Perl
Introduction To Testing With Perljoshua.mcadams
 
Hashing enderecamento aberto bean - bean
Hashing enderecamento aberto bean - beanHashing enderecamento aberto bean - bean
Hashing enderecamento aberto bean - beanElaine Cecília Gatto
 
PyconKR 2018 Deep dive into Coroutine
PyconKR 2018 Deep dive into CoroutinePyconKR 2018 Deep dive into Coroutine
PyconKR 2018 Deep dive into CoroutineDaehee Kim
 
C++ program: All tasks .cpp
C++ program: All tasks .cppC++ program: All tasks .cpp
C++ program: All tasks .cppKhalid Waleed
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsGlobalLogic Ukraine
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga beginsDaniel Franz
 
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018Codemotion
 
Standford 2015 week9
Standford 2015 week9Standford 2015 week9
Standford 2015 week9彼得潘 Pan
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereSergey Platonov
 
Hashing endereçamento aberto - main
Hashing endereçamento aberto - mainHashing endereçamento aberto - main
Hashing endereçamento aberto - mainElaine Cecília Gatto
 

Was ist angesagt? (20)

Calculator code with scientific functions in java
Calculator code with scientific functions in java Calculator code with scientific functions in java
Calculator code with scientific functions in java
 
Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...
Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...
Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...
 
Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016
 
Side effects-con-redux
Side effects-con-reduxSide effects-con-redux
Side effects-con-redux
 
Introduction To Testing With Perl
Introduction To Testing With PerlIntroduction To Testing With Perl
Introduction To Testing With Perl
 
Hashing enderecamento aberto bean - bean
Hashing enderecamento aberto bean - beanHashing enderecamento aberto bean - bean
Hashing enderecamento aberto bean - bean
 
PyconKR 2018 Deep dive into Coroutine
PyconKR 2018 Deep dive into CoroutinePyconKR 2018 Deep dive into Coroutine
PyconKR 2018 Deep dive into Coroutine
 
Performance tests - it's a trap
Performance tests - it's a trapPerformance tests - it's a trap
Performance tests - it's a trap
 
C++ program: All tasks .cpp
C++ program: All tasks .cppC++ program: All tasks .cpp
C++ program: All tasks .cpp
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side Effects
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
 
YCAM Workshop Part 3
YCAM Workshop Part 3YCAM Workshop Part 3
YCAM Workshop Part 3
 
C sharp 8
C sharp 8C sharp 8
C sharp 8
 
Static and const members
Static and const membersStatic and const members
Static and const members
 
Standford 2015 week9
Standford 2015 week9Standford 2015 week9
Standford 2015 week9
 
Promise is a Promise
Promise is a PromisePromise is a Promise
Promise is a Promise
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
Hashing endereçamento aberto - main
Hashing endereçamento aberto - mainHashing endereçamento aberto - main
Hashing endereçamento aberto - main
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
 

Andere mochten auch

Інформація щодо фактичного використання бюджетних коштів у 2016 році по відді...
Інформація щодо фактичного використання бюджетних коштів у 2016 році по відді...Інформація щодо фактичного використання бюджетних коштів у 2016 році по відді...
Інформація щодо фактичного використання бюджетних коштів у 2016 році по відді...Иришка Ой
 
M2828_Marketing Analytics Brochure_5-26-2016.pdf
M2828_Marketing Analytics Brochure_5-26-2016.pdfM2828_Marketing Analytics Brochure_5-26-2016.pdf
M2828_Marketing Analytics Brochure_5-26-2016.pdfEdmund-Graham Balogun
 
презентація уроку 8 клас технологія критичного мислення
презентація уроку 8 клас технологія критичного мисленняпрезентація уроку 8 клас технологія критичного мислення
презентація уроку 8 клас технологія критичного мисленняanna1691
 
Is cloud secure or not
Is cloud secure or notIs cloud secure or not
Is cloud secure or notebuc
 
Top global mega trends
Top global mega trends Top global mega trends
Top global mega trends ebuc
 
Овідій - великий поет. 8 клас
Овідій - великий поет. 8  класОвідій - великий поет. 8  клас
Овідій - великий поет. 8 класdfktynbyf15
 
FLORA DAN FAUNA
FLORA DAN FAUNAFLORA DAN FAUNA
FLORA DAN FAUNARfr Egha
 
Розвантаження та оновлення програм початкової школи
Розвантаження та оновлення програм початкової школиРозвантаження та оновлення програм початкової школи
Розвантаження та оновлення програм початкової школиНаталія Касарда
 
Календарне планування з рос. мови для 5 кл. ІІ семестр (перший рік вивчення м...
Календарне планування з рос. мови для 5 кл. ІІ семестр (перший рік вивчення м...Календарне планування з рос. мови для 5 кл. ІІ семестр (перший рік вивчення м...
Календарне планування з рос. мови для 5 кл. ІІ семестр (перший рік вивчення м...Adriana Himinets
 
My Top Five DevOps Learnings
My Top Five DevOps LearningsMy Top Five DevOps Learnings
My Top Five DevOps LearningsPredix
 
наказ № 133 від 05.04.2016 про результативність в обласних олімпіадах копія
наказ № 133 від 05.04.2016 про результативність в обласних олімпіадах   копіянаказ № 133 від 05.04.2016 про результативність в обласних олімпіадах   копія
наказ № 133 від 05.04.2016 про результативність в обласних олімпіадах копіяolena2605
 
Результати олімпіади з біології
Результати олімпіади з біологіїРезультати олімпіади з біології
Результати олімпіади з біологіїЮрій Романушко
 
08.12.2015 ІІ етап олімпіади хімія
08.12.2015 ІІ етап олімпіади хімія08.12.2015 ІІ етап олімпіади хімія
08.12.2015 ІІ етап олімпіади хіміяЮрій Романушко
 
"Через віки з любов'ю". Позакласний захід
"Через віки з любов'ю". Позакласний захід"Через віки з любов'ю". Позакласний захід
"Через віки з любов'ю". Позакласний західAdriana Himinets
 
PAM3: Machine Learning in the Railway Industry ( Predix Transform 2016)
PAM3: Machine Learning in the Railway Industry ( Predix Transform 2016)PAM3: Machine Learning in the Railway Industry ( Predix Transform 2016)
PAM3: Machine Learning in the Railway Industry ( Predix Transform 2016)Predix
 
Образ Гобсека. Презентація
Образ Гобсека. ПрезентаціяОбраз Гобсека. Презентація
Образ Гобсека. ПрезентаціяAdriana Himinets
 
2 mm a_ua
2 mm a_ua2 mm a_ua
2 mm a_ua4book
 
Data Lake, Virtual Database, or Data Hub - How to Choose?
Data Lake, Virtual Database, or Data Hub - How to Choose?Data Lake, Virtual Database, or Data Hub - How to Choose?
Data Lake, Virtual Database, or Data Hub - How to Choose?DATAVERSITY
 
A Practical Guide to Selecting a Stream Processing Technology
A Practical Guide to Selecting a Stream Processing Technology A Practical Guide to Selecting a Stream Processing Technology
A Practical Guide to Selecting a Stream Processing Technology confluent
 

Andere mochten auch (20)

Інформація щодо фактичного використання бюджетних коштів у 2016 році по відді...
Інформація щодо фактичного використання бюджетних коштів у 2016 році по відді...Інформація щодо фактичного використання бюджетних коштів у 2016 році по відді...
Інформація щодо фактичного використання бюджетних коштів у 2016 році по відді...
 
ПЛАН – СІТКА
ПЛАН – СІТКА ПЛАН – СІТКА
ПЛАН – СІТКА
 
M2828_Marketing Analytics Brochure_5-26-2016.pdf
M2828_Marketing Analytics Brochure_5-26-2016.pdfM2828_Marketing Analytics Brochure_5-26-2016.pdf
M2828_Marketing Analytics Brochure_5-26-2016.pdf
 
презентація уроку 8 клас технологія критичного мислення
презентація уроку 8 клас технологія критичного мисленняпрезентація уроку 8 клас технологія критичного мислення
презентація уроку 8 клас технологія критичного мислення
 
Is cloud secure or not
Is cloud secure or notIs cloud secure or not
Is cloud secure or not
 
Top global mega trends
Top global mega trends Top global mega trends
Top global mega trends
 
Овідій - великий поет. 8 клас
Овідій - великий поет. 8  класОвідій - великий поет. 8  клас
Овідій - великий поет. 8 клас
 
FLORA DAN FAUNA
FLORA DAN FAUNAFLORA DAN FAUNA
FLORA DAN FAUNA
 
Розвантаження та оновлення програм початкової школи
Розвантаження та оновлення програм початкової школиРозвантаження та оновлення програм початкової школи
Розвантаження та оновлення програм початкової школи
 
Календарне планування з рос. мови для 5 кл. ІІ семестр (перший рік вивчення м...
Календарне планування з рос. мови для 5 кл. ІІ семестр (перший рік вивчення м...Календарне планування з рос. мови для 5 кл. ІІ семестр (перший рік вивчення м...
Календарне планування з рос. мови для 5 кл. ІІ семестр (перший рік вивчення м...
 
My Top Five DevOps Learnings
My Top Five DevOps LearningsMy Top Five DevOps Learnings
My Top Five DevOps Learnings
 
наказ № 133 від 05.04.2016 про результативність в обласних олімпіадах копія
наказ № 133 від 05.04.2016 про результативність в обласних олімпіадах   копіянаказ № 133 від 05.04.2016 про результативність в обласних олімпіадах   копія
наказ № 133 від 05.04.2016 про результативність в обласних олімпіадах копія
 
Результати олімпіади з біології
Результати олімпіади з біологіїРезультати олімпіади з біології
Результати олімпіади з біології
 
08.12.2015 ІІ етап олімпіади хімія
08.12.2015 ІІ етап олімпіади хімія08.12.2015 ІІ етап олімпіади хімія
08.12.2015 ІІ етап олімпіади хімія
 
"Через віки з любов'ю". Позакласний захід
"Через віки з любов'ю". Позакласний захід"Через віки з любов'ю". Позакласний захід
"Через віки з любов'ю". Позакласний захід
 
PAM3: Machine Learning in the Railway Industry ( Predix Transform 2016)
PAM3: Machine Learning in the Railway Industry ( Predix Transform 2016)PAM3: Machine Learning in the Railway Industry ( Predix Transform 2016)
PAM3: Machine Learning in the Railway Industry ( Predix Transform 2016)
 
Образ Гобсека. Презентація
Образ Гобсека. ПрезентаціяОбраз Гобсека. Презентація
Образ Гобсека. Презентація
 
2 mm a_ua
2 mm a_ua2 mm a_ua
2 mm a_ua
 
Data Lake, Virtual Database, or Data Hub - How to Choose?
Data Lake, Virtual Database, or Data Hub - How to Choose?Data Lake, Virtual Database, or Data Hub - How to Choose?
Data Lake, Virtual Database, or Data Hub - How to Choose?
 
A Practical Guide to Selecting a Stream Processing Technology
A Practical Guide to Selecting a Stream Processing Technology A Practical Guide to Selecting a Stream Processing Technology
A Practical Guide to Selecting a Stream Processing Technology
 

Ähnlich wie Der perfekte 12c trigger

The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181Mahmoud Samir Fayed
 
Oracle 11g new features for developers
Oracle 11g new features for developersOracle 11g new features for developers
Oracle 11g new features for developersScott Wesley
 
8 bit single cycle processor
8 bit single cycle processor8 bit single cycle processor
8 bit single cycle processorDhaval Kaneria
 
利用Init connect做mysql clients stat 用户审计
 利用Init connect做mysql clients stat 用户审计 利用Init connect做mysql clients stat 用户审计
利用Init connect做mysql clients stat 用户审计Dehua Yang
 
The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88Mahmoud Samir Fayed
 
OpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developersOpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developersConnor McDonald
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기Ji Hun Kim
 
Sangam 19 - PLSQL still the coolest
Sangam 19 - PLSQL still the coolestSangam 19 - PLSQL still the coolest
Sangam 19 - PLSQL still the coolestConnor McDonald
 
A New View of Database Views
A New View of Database ViewsA New View of Database Views
A New View of Database ViewsMichael Rosenblum
 
The Ring programming language version 1.4 book - Part 21 of 30
The Ring programming language version 1.4 book - Part 21 of 30The Ring programming language version 1.4 book - Part 21 of 30
The Ring programming language version 1.4 book - Part 21 of 30Mahmoud Samir Fayed
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowAlex Zaballa
 
Cdr stats-vo ip-analytics_solution_mongodb_meetup
Cdr stats-vo ip-analytics_solution_mongodb_meetupCdr stats-vo ip-analytics_solution_mongodb_meetup
Cdr stats-vo ip-analytics_solution_mongodb_meetupchristkv
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive? Tomasz Kowalczewski
 
How I Built a Power Debugger Out of the Standard Library and Things I Found o...
How I Built a Power Debugger Out of the Standard Library and Things I Found o...How I Built a Power Debugger Out of the Standard Library and Things I Found o...
How I Built a Power Debugger Out of the Standard Library and Things I Found o...doughellmann
 
Session 6 sv_randomization
Session 6 sv_randomizationSession 6 sv_randomization
Session 6 sv_randomizationNirav Desai
 

Ähnlich wie Der perfekte 12c trigger (20)

The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181
 
Oracle 11g new features for developers
Oracle 11g new features for developersOracle 11g new features for developers
Oracle 11g new features for developers
 
8 bit single cycle processor
8 bit single cycle processor8 bit single cycle processor
8 bit single cycle processor
 
利用Init connect做mysql clients stat 用户审计
 利用Init connect做mysql clients stat 用户审计 利用Init connect做mysql clients stat 用户审计
利用Init connect做mysql clients stat 用户审计
 
The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88
 
alexnet.pdf
alexnet.pdfalexnet.pdf
alexnet.pdf
 
OpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developersOpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developers
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
 
Sangam 19 - PLSQL still the coolest
Sangam 19 - PLSQL still the coolestSangam 19 - PLSQL still the coolest
Sangam 19 - PLSQL still the coolest
 
Triggers and Stored Procedures
Triggers and Stored ProceduresTriggers and Stored Procedures
Triggers and Stored Procedures
 
A New View of Database Views
A New View of Database ViewsA New View of Database Views
A New View of Database Views
 
The Ring programming language version 1.4 book - Part 21 of 30
The Ring programming language version 1.4 book - Part 21 of 30The Ring programming language version 1.4 book - Part 21 of 30
The Ring programming language version 1.4 book - Part 21 of 30
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should Know
 
Unit 4
Unit 4Unit 4
Unit 4
 
Cdc
CdcCdc
Cdc
 
Cdr stats-vo ip-analytics_solution_mongodb_meetup
Cdr stats-vo ip-analytics_solution_mongodb_meetupCdr stats-vo ip-analytics_solution_mongodb_meetup
Cdr stats-vo ip-analytics_solution_mongodb_meetup
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive?
 
How I Built a Power Debugger Out of the Standard Library and Things I Found o...
How I Built a Power Debugger Out of the Standard Library and Things I Found o...How I Built a Power Debugger Out of the Standard Library and Things I Found o...
How I Built a Power Debugger Out of the Standard Library and Things I Found o...
 
Less09 Data
Less09 DataLess09 Data
Less09 Data
 
Session 6 sv_randomization
Session 6 sv_randomizationSession 6 sv_randomization
Session 6 sv_randomization
 

Kürzlich hochgeladen

UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 

Kürzlich hochgeladen (20)

UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 

Der perfekte 12c trigger

  • 2. NEW 12C FEATURES Der perfekte 12c T r i gger Autor: Sven Weller, Syntegris, Neu-Isenburg © SYNTEGRIS INFORMATION SOLUTIONS GMBH
  • 3. BEFORE ROW INSERT TRIGGER Der perfekte 12c Trigger Feuert beim Insert Für jede Zeile Setzt Spaltenwerte © SYNTEGRIS INFORMATION SOLUTIONS GMBH
  • 4. ID AND AUDIT COLUMNS Traditional Trigger 1 2 3 4 5 6 7 8 9 10 11FOR EACH ROW 12 BEGIN 13 -- record needs always a key 14IF :new.id IS NULL 15 16 17 18 19 20 21 22 23 create table swe_demo (id number primary key ,col1 number ,col2 varchar2(30) ,inserted_date date not null ,inserted_from varchar2(30) not null); create sequence swe_demo_seq cache 10000; create or replace trigger swe_demo_bri_trg BEFORE INSERT ON swe_demo THEN :new.id := swe_demo_seq.NEXTVAL; END IF; -- timestamp of the last changes :new.inserted_date := SYSDATE; :new.inserted_from := NVL(v('APP_USER'), END swe_demo_bri_trg; / user); 1 2 3 4 5 6 7 8 create table swe_demo (id number primary key ,col1 number ,col2 varchar2(30) ,inserted_date date not null ,inserted_from varchar2(30) not null); create sequence swe_demo_seq cache 10000; 1 2 3 4 5 create table swe_demo (id number primary key ,col1 number ,col2 varchar2(30) ,inserted_date date not null ,inserted_from varchar2(30) not null); © SYNTEGRIS INFORMATION SOLUTIONS GMBH
  • 5. Der perfekte 12c Trigger TOPICS Der “perfekte” Trigger = ? © SYNTEGRIS INFORMATION SOLUTIONS GMBH
  • 6. TOPICS Neue 12c Features Performance Tipps und Tricks © SYNTEGRIS INFORMATION SOLUTIONS GMBH Der perfekte 12c Trigger
  • 7. SYNTAX Identity column (12R1) ”ID” oder ”ID” generated always as identity generated by default on null as identity Sequence wird automatisch erzeugt und verwaltet © SYNTEGRIS INFORMATION SOLUTIONS GMBH
  • 8. SYNTAX Default value columns (12R1) expression => sequence.nextval © SYNTEGRIS INFORMATION SOLUTIONS GMBH
  • 9. ENTSCHEIDUNG Default value auch für andere non-ID Spalten Identity Columns haben mehr “Nebeneffekte” © SYNTEGRIS INFORMATION SOLUTIONS GMBH Default value oder Identity? 1 2 3 4 5 6 7 8 9 10 set serveroutput on declare v_id demo@remoteDB.id%type; begin insert into demo@remoteDB (col1) values ('abc') returning id into v_id; dbms_output.put_line('new ID='||v_id); end; / ORA-22816: unsupported feature with RETURNING clause ORA-06512: at line 4 22816. 00000 - "unsupported feature with RETURNING clause" *Cause: RETURNING clause is currently not supported for object type columns, LONG columns, remote tables, INSERT with subquery, and INSTEAD OF Triggers. *Action: Use separate select statement to get the values.
  • 10. DEFAULT COLUMNS 12c solution (ohne trigger) create sequence swe_demo_seq cache 10000; create table swe_demo (id number default on null swe_demo_seq.nextval ,col1 number ,col2 varchar2(30) primary key ,inserted_date date default sysdate ,inserted_from varchar2(30) default not null NVL(v('APP_USER'), user) not null); Tipp: user => langsam © SYNTEGRIS INFORMATION SOLUTIONS GMBH
  • 11. SYS_CONTEXT Was ist ein Kontext? Lokale oder globale “Variable” vordefiniert: USERENV Security Feature © SYNTEGRIS INFORMATION SOLUTIONS GMBH
  • 12. USERENV © SYNTEGRIS INFORMATION SOLUTIONS GMBH Aktueller Benutzer SYS_CONTEXT('USERENV', ' p a r a m e t e r' ) Parameter Beschreibung client_identifier Returns an identifier that is set by the application through the DBMS_SESSION.SET_IDENTIFIER procedure, the OCI attribute OCI_ATTR_CLIENT_IDENTIFIER, or the Java class Oracle.jdbc.OracleConnection.setClientIdentifier. This attribute is used by various database components to identify lightweight application users who authenticate as the same database user. current_schema Name of the default schema being used in the current schema. This value can be changed during the session with an ALTER SESSION SET CURRENT_SCHEMA statement. current_user Deprecated – Use the SESSION_USER parameter instead. session_user For enterprises users, returns the schema. For other users, returns the database user name by which the current user is authenticated. This value remains the same throughout the duration of the session. dblink_info Returns the source of a database link session. Specifically, it returns a string of the form:SOURCE_GLOBAL_NAME=dblink_src_global_name, DBLINK_NAME=dblink_name, SOURCE_AUDIT_SESSIONID=dblink_src_audit_sessionid
  • 13. APEX KONTEXTE SYS_CONTEXT('APEX$SESSION','APP_USER') SYS_CONTEXT('APEX$SESSION','APP_SESSION') SYS_CONTEXT('APEX$SESSION','WORKSPACE_ID') neu in Apex 5 Extrem performant Aktueller Benutzer SYS_CONTEXT('USERENV','client_identifier') © SYNTEGRIS INFORMATION SOLUTIONS GMBH APP_USER:APP_SESSION => SVEN:0123456789
  • 14. DEFAULT COLUMNS + KONTEXT 12c Ergebnis - ohne Trigger create sequence swe_demo_seq cache 10000; create table swe_demo (id number default on null swe_demo_seq.nextval primary key ,col1 number ,col2 varchar2(30) ,inserted_date date default sysdate not null ,inserted_from varchar2(30) default coalesce( sys_context('APEX$SESSION','app_user' ) ,regexp_substr(sys_context('userenv','client_identifier'),'^[^:]*' ) ,sys_context('userenv','session_user') ) not null); © SYNTEGRIS INFORMATION SOLUTIONS GMBH
  • 15. VORTEILE Weniger Code Performance Sequence mit Tabelle verbunden 12c ohne Trigger © SYNTEGRIS INFORMATION SOLUTIONS GMBH
  • 17. BEFORE ROW UPDATE TRIGGER Keine 12c Alternative bisher! © SYNTEGRIS INFORMATION SOLUTIONS GMBH Sonstiges Neuer Syntax Vorschlag: DEFAULT ON UPDATE https://community.oracle.com/ideas/15760
  • 18. PERFORMANCE TEST - TC1 Sonstiges 1 2 3 4 5 6 7 8 9 10 set time on set timing on declare v_result begin for i in varchar2(100); 1..1000000 loop v_result end loop; end; / := ##EXPRESSION##; Test © SYNTEGRIS INFORMATION SOLUTIONS GMBH Skript
  • 19. PERFORMANCE TEST - TC1 Sonstiges 1 set time on 2 set timing on Test S 3 declare 4 v_result varchar2(100); 5 begin 6 for i in 1..1000000 loop 7 v_result := ##EXPRESSION##; 8 end loop; 9 end; 10 / kript Expression Time (in s) sys_context('userenv','client_identifier') 2,4 substr(sys_context('userenv','client_identifier'),1 ,instr(sys_context('userenv','client_identifier'),':')-1) 4,3 substr(sys_context('userenv','client_identifier'),1, coalesce(nullif(instr(sys_context('userenv','client_identifier'),':'),0)-1, length(sys_context('userenv','client_identifier')))) 6,3 © SYNTEGRIS INFORMATION SOLUTIONS GMBH regexp_substr(sys_context('userenv','client_identifier'),'^[^:]*') 3,5 translate(sys_context('userenv','client_identifier'),'A0123456789','A') 5,6 user 20,6 sys_context('APEX$SESSION','app_user') 1,5 v('APP_USER') 5,6
  • 20. CONTEXT WITH DBLINK # Beschreibung Inserted From 1 apex remote insert SVEN 2 apex local insert SVEN 5 direct remote insert REMOTE_B 6 direct local insert LOCAL_A 7 direct insert current_schema IAMDBA Sonstiges App User Apex Session Client Identifier – – SVEN:4628609689353 SVEN SVEN SVEN:4628609689353 – – – – – – – – – © SYNTEGRIS INFORMATION SOLUTIONS GMBH # Current Schema Current User User Session User Authenticated Identity 1 DEMO DEMO REMOTE_B REMOTE_B REMOTE_B 2 DEMO DEMO APEX_PUBLIC_USER APEX_PUBLIC_USER APEX_PUBLIC_USER 5 DEMO DEMO REMOTE_B REMOTE_B REMOTE_B 6 DEMO DEMO LOCAL_A LOCAL_A LOCAL_A 7 DEMO DEMO IAMDBA IAMDBA IAMDBA