dpc2007 mysql stored routines for php developers (roland bouman)
DESCRIPTION
Dutch PHP ConferenceTRANSCRIPT
1Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Amsterdam, June 16 2007● MySQL: Quick Introduction● MySQL Stored Routines for PHP developers● Questions and Discussion
2Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Roland Bouman (rpbouman.blogspot.com)Certification DeveloperMySQL AB, Leiden
● MySQL Community Contributor since 2005● Joined MySQL AB in July 2006
● Certification Developer:● MySQL 5.1 Cluster DBA exam (CMCDBA)● MySQL Associate exam (CMA)
● Attained:● CMDEV● CMDBA
● Formerly: Consultant & Application Developer (mostly Oracle, some MS SQL)
3Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Amsterdam, June 16 2007● MySQL: Quick Introduction● MySQL Stored Routines for PHP developers● Questions and Discussion
4Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL: Quick Introduction
● MySQL Software Products● RDBMS (Database)● Monitoring and Advisory Service ● Drivers and APIs● Client (GUI) Tools & Utilities
● MySQL Professional Services● Technical Support● Consulting● Training● Certification● Indemnification
5Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
● Generally Available, Stable Releases● MySQL 5.0 Server Community Edition
● Patches from community
● MySQL 5.0 Server Enterprise Edition● Stablility and Robustness, Early Bugfixes● Monitoring and Advisory Service● Binaries
● Development Releases:● MySQL 5.1 (New: Events, Partitioning)● MySQL 6.0 (New: Falcon)
● Other RDBMS Products: ● MySQL Cluster / Carrier Grade Edition● Embedded● MaxDB (SAP Certified)
MySQL Open Source RDBMS Products
6Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Monitoring and Advisory Service
7Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
● For PHP● ext/mysql: “MySQL Functions”● ext/mysqli: “MySQL Improved Extension”● mysqlnd: “MySQL native driver for PHP”
● Beta 5.● Built Into PHP 5; PHP 6● Replaces libmysql
● Other:● ODBC: Connector/ODBC● JDBC: Connector/J● ADO.NET: Connector/.NET
MySQL Drivers and APIs
8Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Amsterdam, June 16 2007● MySQL: Quick Introduction● MySQL Stored Routines for PHP developers● Questions and Discussion
9Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routines
● Overview of MySQL Stored Routines● MySQL Stored Routine Language● PHP Techniques● Use cases● Best Practices
10Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routines● Overview of MySQL Stored Routines:
● Terminology, Purpose, Application
● MySQL Stored Routine Language● Block Structure, Parameters and Variables, Flow Control
Constructs, SQL inside stored routines.
● PHP Techniques● Creating and Calling Stored Procedures, Processing
Result set, Handling Multiple Result sets.
● Use cases● Best Practices
● What to do on the client, and what on the server● What to do in PHP, and what in Stored Routines.● Performance: how MySQL Stored Routines can help or
hurt performance.
11Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routines: Overview● Programs as Database Schema Objects
● Executed in-process with the Database
● Types of Stored Routines:● Procedures● Functions● Triggers● Events (Temporal triggers; new in MySQL 5.1)
● Language: ● Subset of Standard SQL:2003 SQL/PSM● Procedural, Block structured● Do not confuse with User Defined Functions (UDF)!
● Available as of MySQL 5.0 (October 2005)
12Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routine Types: Overview● Stored Procedures & Functions
● Encapsulate tasks or Calculations for reuse● Single point of definition for Business Logic● Source Safely stored and backed up● Added layer of Security
● Triggers● Data-Driven● Enforce Data quality through Basic validation● Enforce complex Business Rules● Automatically Update Aggregate tables
● Events (MySQL Server 5.1 beta)● Schedule Code Execution in time.
● Use instead of cron or windows event scheduler
● Automatically Update Aggregate tables
13Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routines: Purpose / Advantages● Performance
● Save network roundtrips, lower latency
● Portability and Reuse● Single point of definition● Reusable from many application contexts
● Security● DEFINER versus INVOKER
● Grant only Execution Privilege
● Ease of Maintenance● Code stored in the database
● Browse using information_schema database
● 'Headless' administrative tasks● No additional runtime environment required
14Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routines: Caveat / Disadvantages● Performance
● Overhead may result in higher latency● Increased usage of database server computing power may
negatively affect throughput
● Portability and Reuse● Which point of view?
● Database portability ?● Or Application portability?
15Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routines● Overview of MySQL Stored Routines:
● Terminology, Purpose, Application
● MySQL Stored Routine Language● Block Structure, Parameters and Variables, Flow Control
Constructs, SQL inside stored routines.
● PHP Techniques● Creating and Calling Stored Procedures, Processing
Result set, Handling Multiple Result sets.
● Use cases● Best Practices
● What to do on the client, and what on the server● What to do in PHP, and what in Stored Routines.● How MySQL Stored Routines can help or hurt
performance.
16Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routine Language● Subset of Standard SQL “Persistent Stored
Modules” (SQL/PSM)● Procedural constructs with embedded SQL
● Parameters and (Local) variables● Manipulate values
● Statement Sequence● execute statements in order
● Choice● conditionally execute a particular sequence
● Repetition● execute a particular sequence multiple times
● A bit like Pascal with embedded SQL statements● Valid inside all stored routine types● Can be mixed with most SQL statements
17Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Creating a MySQL Stored Procedure
CREATE PROCEDURE sp_hello( p_who VARCHAR(32))SELECT CONCAT('Hello, ',v_what,'!!');
• CREATE PROCEDURE DDL statement
• Created in the current schema (= database)• Name (sp_hello) must be unique with in the
schema, may be qualified (my_db.sp_hello)
• Parameter (p_who): IN parameter by default
• Procedure body is one single statement, in this case, an ordinary SQL SELECT statement.
• Prerequisite: CREATE ROUTINE and ALTER ROUTINE privileges
18Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Calling a MySQL Stored Procedure
CALL sp_hello('PHP');
• CALL statement
• Name identifies the procedure within the schema, and maybe qualified: CALL my_schema.sp_hello('PHP')
• Must pass a parameter value
Result:
Hello, PHP!
• Result set returned to the client
• Prerequisite: EXECUTE ROUTINE privilege
19Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Generic Statement Sequence: BEGIN...END
CREATE PROCEDURE sp_greating( p_who VARCHAR(32), p_what VARCHAR(32))BEGIN SELECT CONCAT('Hello ', p_who); SELECT CONCAT(p_what,'!');END
• BEGIN...END is a compound statement; it may contain multiple other statements.
• Contained statements executed Sequentially (in order of appearance)
• (Sidenote: 2 result sets are returned to the client)
20Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Variables and Parameters
CREATE PROCEDURE sp_fibonacci( INOUT p_m INT, INOUT p_n INT, OUT p_s DOUBLE) BEGIN DECLARE v_m INT DEFAULT COALESCE(p_m,0); DECLARE v_n INT DEFAULT COALESCE(p_n,1);
SET p_m := v_n; single assignment SET p_n := v_m + v_n multiple , p_s := p_m/p_n; assignments
SELECT p_m, p_n, p_s;END;
• IN, OUT and INOUT parameters• DECLARE local variables, optionally assign a default value
• Use SET to assign values to one or more variables
21Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Variables and Parameters
call sp_fibonacci(@m,@n,@s);++++| p_m | p_n | p_s |++++| 1 | 1 | 1 |++++call sp_fibonacci(@m,@n,@s);++++| p_m | p_n | p_s |++++| 1 | 2 | 0.5 |++++call sp_fibonacci(@m,@n,@s);++++| p_m | p_n | p_s |++++| 2 | 3 | 0.666666666 |++++
22Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Variable Scope / Visibility
BEGIN DECLARE v_script, v_http VARCHAR(32); SET v_script := 'PHP', v_http := 'Apache'; SELECT v_script, v_http; BEGIN DECLARE v_http VARCHAR(32); SET v_http := 'lighttpd'; SELECT v_script, v_http; END; SELECT v_script, v_http;END;
• Variables are visible only inside the declaring block• Nearest Scope: inner declarations mask outer ones
23Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Choice Constructs
● Compound statements● IF...END IF statement
● Simple test of a single condition● Conditionally start a sequence of statements (branch)● Optionally, chooses between two branches
● Don't confuse with the IF() function!
● CASE...END CASE statement● Conditionally starts one out of multiple branches
● Simple CASE statement
● Just like switch in PHP
● Searched CASE statement
● Just like nested if...elseif...else in PHP
● Don't confuse with the CASE..END expression!
24Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Syntax: IF...END IF● Tests condition, branches when TRUE
● Conditional branch can contain a sequence
//main, unconditional branchIF <condition> THEN <statements> “true” branchEND IF;
● Optionally, include a branch for the other case:
IF <condition> THEN <statements> ”true” branchELSE <statements> ”false” branchEND IF;
25Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
IF CURRENT_TIME < '12:00:00' THEN SELECT 'Good Morning';ELSE SELECT 'Good Afternoon';END IF;
IF statement vs IF function
SELECT IF(CURRENT_TIME < '12:00:00' , 'Good Morning' , 'Good Afternoon' );
● An IF statement chooses between sequences of statements
● IF function chooses between expressions
26Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Syntax: Simple CASE..END CASE● Evaluate expression and compare● Conditional branch can contain a sequence ● Optional ELSE branch
● Just like switch...case in PHP
CASE <expression> WHEN <expression1> THEN <statements> WHEN <expression2> THEN <statements> ELSE <statements> END CASE;
27Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Syntax: Searched CASE..END CASE● Search first TRUE condition, then branch
● Conditional branch can contain a sequence ● Optional ELSE branch
● Just like if...elsif...else in PHP
CASE WHEN <condition> THEN <statements> WHEN <expression> THEN <statements> ELSE <statements> END CASE;
28Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Repetition● Unstructured Loop
● No explicit logic to end the loop
● Structured● Logic to end the loop is part of the construct
LOOP <statement> END LOOP;
WHILE <condition>DO <statement>END WHILE;
REPEAT <statement>UNTIL <condition>END REPEAT;
● Iterate: ● Leave: exit the current block
29Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
TriggersCREATE [DEFINER = { <username> | CURRENT_USER }]TRIGGER <triggername> {BEFORE | AFTER} {INSERT | UPDATE | DELETE}ON <tablename>FOR EACH ROW <singlestatement>
● Automatically executed in response to row-level events occurring on table
● Can refer to OLD and NEW pseudo-records● INSERT: NEW● DELETE: OLD● UPDATE: both OLD and NEW
● Executed as part of transaction
30Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Event Scheduler (Temporal Triggers)● New in MySQL 5.1● Automatically executed according to time
schedule● Can be recurring● Can be scheduled to start in the future● Can be instructed to clean itself up
31Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routines● Overview of MySQL Stored Routines:
● Terminology, Purpose, Application
● MySQL Stored Routine Language● Block Structure, Parameters and Variables, Flow Control
Constructs, SQL inside stored routines.
● PHP Techniques● Creating and Calling Stored Procedures, Processing
Result Set, Handling Multiple Result Sets.
● Use cases● Best Practices
● What to do on the client, and what on the server● What to do in PHP, and what in Stored Routines.● How MySQL Stored Routines can help or hurt
performance.
32Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
PHP and MySQL Stored Routines● Two relevant PHP extensions● MySQL Functions (ext/mysql)
● CREATE PROCEDURE and CALL work fine
● Just use the PHP function mysql_query()
● However, obtaining a result set is impossible
● MySQL Improved extension (ext/mysqli)● use mysqli_query() for one result set
● For multiple resultsets, use● mysqli_multi_query()
● mysqli_use_result()
● mysqli_store_result()
● mysqli_next_result()
● mysqli_more_results()
33Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
mysql_query() and Stored Routines<?php $db = mysql_connect($host,$usr,$pwd); mysql_select_db('test',$db); $result = mysql_query( "CALL sp_hello('PHP')",$db ); $num_rows = mysql_affected_rows($db); echo '<br/>num: ', $num_rows; echo '<br/>msg: ', mysql_error($db); echo '<br/>no: ', mysql_errno($db);?>
num: 1msg: PROCEDURE test.sp_hello can't return a result set in the given context
no: 1312
34Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
mysqli_query() and Stored Routines<?php $db = mysqli_connect($host,$usr,$pwd); $db>select_db('test'); $result = mysqli_query( $db,"CALL sp_hello('PHP')" ); $row = mysqli_fetch_row($result); echo $row[0];?>
Hello, PHP!
35Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Handling Multiple result sets<?php $db = mysqli_connect($host,$usr,$pwd); $db>select_db('test'); $db>multi_query( "CALL sp_greating('PHP','Good Morning')" ); while($result = $db>store_result()) { while ($row = $result>fetch_row()) { echo $row[0]; } $result>close(); $db>next_result(); }?>
Hello PHP, Good Morning!
36Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routines● Overview of MySQL Stored Routines:
● Terminology, Purpose, Application
● MySQL Stored Routine Language● Block Structure, Parameters and Variables, Flow Control
Constructs, SQL inside stored routines.
● PHP Techniques● Creating and Calling Stored Procedures, Processing
Result set, Handling Multiple Result sets.
● Use Cases● Best Practices
● What to do on the client, and what on the server● What to do in PHP, and what in Stored Routines.● How MySQL Stored Routines can help or hurt
performance.
37Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routine Use Cases● Stored Procedures
● subtypes and vertical partitioning● data intensive transformation
● Stored Functions● domain specific calculations● data transformation
● Triggers● Auditing● Automatically Aggregate tables
● Events● Logging status● Updating aggregate tables “Materialized views”● ETL processes
38Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Routines● Overview of MySQL Stored Routines:
● Terminology, Purpose, Application
● MySQL Stored Routine Language● Block Structure, Parameters and Variables, Flow Control
Constructs, SQL inside stored routines.
● PHP Techniques● Creating and Calling Stored Procedures, Processing
Result set, Handling Multiple Result sets.
● Use Cases● Best Practices
● What to do on the client, and what on the server● What to do in PHP, and what in Stored Routines.● How MySQL Stored Routines can help or hurt
performance.
39Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Stored Procedures: Best Practices● Use pure SQL when you can● Use stored procedures for data-intensive
operations● Don't use stored procedures for complex
computation● Don't use stored procedures for single layer
encapsulation● Simple CRUD layers don't scale● Stored Procedure should add significant functionality
● Return multiple result sets from stored procedures to reduce network roundtrips
40Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
MySQL Triggers: Best Practices● Use triggers to enforce integrity of data● Using triggers does not mean the application can
forget about validation
41Copyright 2007 MySQL AB The World’s Most Popular Open Source Database
Amsterdam, June 16 2007
● MySQL: Quick Introduction● MySQL Stored Routines for PHP developers● Questions and Discussion
42Copyright 2007 MySQL AB The World’s Most Popular Open Source Database