]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/adodb/docs/tips_portable_sql.htm
Upgrade adodb
[SourceForge/phpwiki.git] / lib / WikiDB / adodb / docs / tips_portable_sql.htm
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\r
2 \r
3 <html>\r
4 <head>\r
5         <title>Tips on Writing Portable SQL for Multiple Databases for PHP</title>\r
6 </head>\r
7 \r
8 <body bgcolor=white>\r
9 <table width=100% border=0><tr><td><h2>Tips on Writing Portable SQL &nbsp;</h2></td><td>\r
10  <div align=right><img src="cute_icons_for_site/adodb.gif"></div></td></tr></table>\r
11   <p>Updated 6 Oct 2006. Added OffsetDate example.\r
12   <p>Updated 18 Sep 2003. Added Portable Native SQL section.\r
13 <p>\r
14 \r
15  If you are writing an application that is used in multiple environments and \r
16   operating systems, you need to plan to support multiple databases. This article \r
17   is based on my experiences with multiple database systems, stretching from 4th \r
18   Dimension in my Mac days, to the databases I currently use, which are: Oracle, \r
19   FoxPro, Access, MS SQL Server and MySQL. Although most of the advice here applies \r
20   to using SQL with Perl, Python and other programming languages, I will focus on PHP and how \r
21   the <a href="http://adodb.sourceforge.net/">ADOdb</a> database abstraction library \r
22   offers some solutions.<p></p>\r
23 <p>Most database vendors practice product lock-in. The best or fastest way to \r
24   do things is often implemented using proprietary extensions to SQL. This makes \r
25   it extremely hard to write portable SQL code that performs well under all conditions. \r
26   When the first ANSI committee got together in 1984 to standardize SQL, the database \r
27   vendors had such different implementations that they could only agree on the \r
28   core functionality of SQL. Many important application specific requirements \r
29   were not standardized, and after so many years since the ANSI effort began, \r
30   it looks as if much useful database functionality will never be standardized. \r
31   Even though ANSI-92 SQL has codified much more, we still have to implement portability \r
32   at the application level.</p>\r
33 <h3><b>Selects</b></h3>\r
34 <p>The SELECT statement has been standardized to a great degree. Nearly every \r
35   database supports the following:</p>\r
36 <p>SELECT [cols] FROM [tables]<br>\r
37   &nbsp;&nbsp;[WHERE conditions]<br>\r
38   &nbsp; [GROUP BY cols]<br>\r
39   &nbsp; [HAVING conditions] <br>\r
40   &nbsp; [ORDER BY cols]</p>\r
41 <p>But so many useful techniques can only be implemented by using proprietary \r
42   extensions. For example, when writing SQL to retrieve the first 10 rows for \r
43   paging, you could write...</p>\r
44 <table width="80%" border="1" cellspacing="0" cellpadding="0" align="center">\r
45   <tr> \r
46         <td><b>Database</b></td>\r
47         <td><b>SQL Syntax</b></td>\r
48   </tr>\r
49   <tr> \r
50         <td>DB2</td>\r
51         <td>select * from table fetch first 10 rows only</td>\r
52   </tr>\r
53   <tr> \r
54         <td>Informix</td>\r
55         <td>select first 10 * from table</td>\r
56   </tr>\r
57   <tr> \r
58         <td>Microsoft SQL Server and Access</td>\r
59         <td>select top 10 * from table</td>\r
60   </tr>\r
61   <tr> \r
62         <td>MySQL and PostgreSQL</td>\r
63         <td>select * from table limit 10</td>\r
64   </tr>\r
65   <tr> \r
66         <td>Oracle 8i</td>\r
67         <td>select * from (select * from table) where rownum &lt;= 10</td>\r
68   </tr>\r
69 </table>\r
70 <p>This feature of getting a subset of data is so useful that in the PHP class \r
71   library ADOdb, we have a SelectLimit( ) function that allows you to hide the \r
72   implementation details within a function that will rewrite your SQL for you:</p>\r
73 <pre>$connection-&gt;SelectLimit('select * from table', 10);\r
74 </pre>\r
75 <p><b>Selects: Fetch Modes</b></p>\r
76 <p>PHP allows you to retrieve database records as arrays. You can choose to have \r
77   the arrays indexed by field name or number. However different low-level PHP \r
78   database drivers are inconsistent in their indexing efforts. ADOdb allows you \r
79   to determine your prefered mode. You set this by setting the variable $ADODB_FETCH_MODE \r
80   to either of the constants ADODB_FETCH_NUM (for numeric indexes) or ADODB_FETCH_ASSOC \r
81   (using field names as an associative index).</p>\r
82 <p>The default behaviour of ADOdb varies depending on the database you are using. \r
83   For consistency, set the fetch mode to either ADODB_FETCH_NUM (for speed) or \r
84   ADODB_FETCH_ASSOC (for convenience) at the beginning of your code. </p>\r
85 <p><b>Selects: Counting Records</b></p>\r
86 <p>Another problem with SELECTs is that some databases do not return the number \r
87   of rows retrieved from a select statement. This is because the highest performance \r
88   databases will return records to you even before the last record has been found. \r
89 </p>\r
90 <p>In ADOdb, RecordCount( ) returns the number of rows returned, or will emulate \r
91   it by buffering the rows and returning the count after all rows have been returned. \r
92   This can be disabled for performance reasons when retrieving large recordsets \r
93   by setting the global variable $ADODB_COUNTRECS = false. This variable is checked \r
94   every time a query is executed, so you can selectively choose which recordsets \r
95   to count.</p>\r
96 <p>If you prefer to set $ADODB_COUNTRECS = false, ADOdb still has the PO_RecordCount( \r
97   ) function. This will return the number of rows, or if it is not found, it will \r
98   return an estimate using SELECT COUNT(*):</p>\r
99 <pre>$rs = $db-&gt;Execute(&quot;select * from table where state=$state&quot;);\r
100 $numrows = $rs-&gt;PO_RecordCount('table', &quot;state=$state&quot;);</pre>\r
101 <p><b>Selects: Locking</b> </p>\r
102 <p>SELECT statements are commonly used to implement row-level locking of tables. \r
103   Other databases such as Oracle, Interbase, PostgreSQL and MySQL with InnoDB \r
104   do not require row-level locking because they use versioning to display data \r
105   consistent with a specific point in time.</p>\r
106 <p>Currently, I recommend encapsulating the row-level locking in a separate function, \r
107   such as RowLock($table, $where):</p>\r
108 <pre>$connection-&gt;BeginTrans( );\r
109 $connection-&gt;RowLock($table, $where); </pre>\r
110 <pre><font color=green># some operation</font></pre>\r
111 <pre>if ($ok) $connection-&gt;CommitTrans( );\r
112 else $connection-&gt;RollbackTrans( );\r
113 </pre>\r
114 <p><b>Selects: Outer Joins</b></p>\r
115 <p>Not all databases support outer joins. Furthermore the syntax for outer joins \r
116   differs dramatically between database vendors. One portable (and possibly slower) \r
117   method of implementing outer joins is using UNION.</p>\r
118 <p>For example, an ANSI-92 left outer join between two tables t1 and t2 could \r
119   look like:</p>\r
120 <pre>SELECT t1.col1, t1.col2, t2.cola <br>  FROM t1 <i>LEFT JOIN</i> t2 ON t1.col = t2.col</pre>\r
121 <p>This can be emulated using:</p>\r
122 <pre>SELECT t1.col1, t1.col2, t2.cola FROM t1, t2 <br>     WHERE t1.col = t2.col \r
123    UNION ALL\r
124 SELECT col1, col2, null FROM t1 <br>       WHERE t1.col not in (select distinct col from t2)\r
125 </pre>\r
126 <p>Since ADOdb 2.13, we provide some hints in the connection object as to legal \r
127   join variations. This is still incomplete and sometimes depends on the database \r
128   version you are using, but is useful as a general guideline:</p>\r
129 <p><font face="Courier New, Courier, mono">$conn-&gt;leftOuter</font>: holds the \r
130   operator used for left outer joins (eg. '*='), or false if not known or not \r
131   available.<br>\r
132   <font face="Courier New, Courier, mono">$conn-&gt;rightOuter</font>: holds the \r
133   operator used for right outer joins (eg '=*'), or false if not known or not \r
134   available.<br>\r
135   <font face="Courier New, Courier, mono">$conn-&gt;ansiOuter</font>: boolean \r
136   that if true means that ANSI-92 style outer joins are supported, or false if \r
137   not known.</p>\r
138 <h3><b>Inserts</b> </h3>\r
139 <p>When you create records, you need to generate unique id's for each record. \r
140   There are two common techniques: (1) auto-incrementing columns and (2) sequences. \r
141 </p>\r
142 <p>Auto-incrementing columns are supported by MySQL, Sybase and Microsoft Access \r
143   and SQL Server. However most other databases do not support this feature. So \r
144   for portability, you have little choice but to use sequences. Sequences are \r
145   special functions that return a unique incrementing number every time you call \r
146   it, suitable to be used as database keys. In ADOdb, we use the GenID( ) function. \r
147   It has takes a parameter, the sequence name. Different tables can have different \r
148   sequences. </p>\r
149 <pre>$id = $connection-&gt;GenID('sequence_name');<br>$connection-&gt;Execute(&quot;insert into table (id, firstname, lastname) <br>                       values ($id, $firstname, $lastname)&quot;);</pre>\r
150 <p>For databases that do not support sequences natively, ADOdb emulates sequences \r
151   by creating a table for every sequence.</p>\r
152 <h3><b>Binding</b></h3>\r
153 <p>Binding variables in an SQL statement is another tricky feature. Binding is \r
154   useful because it allows pre-compilation of SQL. When inserting multiple records \r
155   into a database in a loop, binding can offer a 50% (or greater) speedup. However \r
156   many databases such as Access and MySQL do not support binding natively and \r
157   there is some overhead in emulating binding. Furthermore, different databases \r
158   (specificly Oracle!) implement binding differently. My recommendation is to \r
159   use binding if your database queries are too slow, but make sure you are using \r
160   a database that supports it like Oracle. </p>\r
161 <p>ADOdb supports portable Prepare/Execute with:</p>\r
162 <pre>$stmt = $db-&gt;Prepare('select * from customers where custid=? and state=?');\r
163 $rs = $db-&gt;Execute($stmt, array($id,'New York'));</pre>\r
164 <p>Oracle uses named bind placeholders, not "?", so to support portable binding, we have Param() that generates \r
165 the correct placeholder (available since ADOdb 3.92):\r
166 <pre><font color="#000000">$sql = <font color="#993300">'insert into table (col1,col2) values ('</font>.$DB-&gt;Param('a').<font color="#993300">','</font>.$DB-&gt;Param('b').<font color="#993300">')'</font>;\r
167 <font color="#006600"># generates 'insert into table (col1,col2) values (?,?)'\r
168 # or        'insert into table (col1,col2) values (:a,:b)</font>'\r
169 $stmt = $DB-&gt;Prepare($sql);\r
170 $stmt = $DB-&gt;Execute($stmt,array('one','two'));\r
171 </font></pre>\r
172 <a name="native"></a>\r
173 <h2>Portable Native SQL</h2>\r
174 <p>ADOdb provides the following functions for portably generating SQL functions \r
175   as strings to be merged into your SQL statements (some are only available since \r
176   ADOdb 3.92): </p>\r
177 <table width="75%" border="1" align=center>\r
178   <tr> \r
179     <td width=30%><b>Function</b></td>\r
180     <td><b>Description</b></td>\r
181   </tr>\r
182   <tr> \r
183     <td>DBDate($date)</td>\r
184     <td>Pass in a UNIX timestamp or ISO date and it will convert it to a date \r
185       string formatted for INSERT/UPDATE</td>\r
186   </tr>\r
187   <tr> \r
188     <td>DBTimeStamp($date)</td>\r
189     <td>Pass in a UNIX timestamp or ISO date and it will convert it to a timestamp \r
190       string formatted for INSERT/UPDATE</td>\r
191   </tr>\r
192   <tr> \r
193     <td>SQLDate($date, $fmt)</td>\r
194     <td>Portably generate a date formatted using $fmt mask, for use in SELECT \r
195       statements.</td>\r
196   </tr>\r
197   <tr> \r
198     <td>OffsetDate($date, $ndays)</td>\r
199     <td>Portably generate a $date offset by $ndays.</td>\r
200   </tr>\r
201   <tr> \r
202     <td>Concat($s1, $s2, ...)</td>\r
203     <td>Portably concatenate strings. Alternatively, for mssql use mssqlpo driver, \r
204       which allows || operator.</td>\r
205   </tr>\r
206   <tr> \r
207     <td>IfNull($fld, $replaceNull)</td>\r
208     <td>Returns a string that is the equivalent of MySQL IFNULL or Oracle NVL.</td>\r
209   </tr>\r
210   <tr>\r
211     <td>Param($name)</td>\r
212     <td>Generates bind placeholders, using ? or named conventions as appropriate.</td>\r
213   </tr>\r
214   <tr><td>$db->sysDate</td><td>Property that holds the SQL function that returns today's date</td>\r
215 </tr>\r
216 <tr><td>$db->sysTimeStamp</td><td>Property that holds the SQL function that returns the current\r
217 timestamp (date+time).\r
218 </td>\r
219 </tr>\r
220 <tr>\r
221 <td>$db->concat_operator</td><td>Property that holds the concatenation operator\r
222 </td>\r
223 </tr>\r
224 <tr><td>$db->length</td><td>Property that holds the name of the SQL strlen function.\r
225 </td></tr>\r
226 \r
227 <tr><td>$db->upperCase</td><td>Property that holds the name of the SQL strtoupper function.\r
228 </td></tr>\r
229 <tr><td>$db->random</td><td>Property that holds the SQL to generate a random number between 0.00 and 1.00.\r
230 </td>\r
231 </tr>\r
232 <tr><td>$db->substr</td><td>Property that holds the name of the SQL substring function.\r
233 </td></tr>\r
234 </table>\r
235 <p>&nbsp; </p>\r
236 <h2>DDL and Tuning</h2>\r
237 There are database design tools such as ERWin or Dezign that allow you to generate data definition language commands such as ALTER TABLE or CREATE INDEX from Entity-Relationship diagrams. \r
238 <p>\r
239 However if you prefer to use a PHP-based table creation scheme, adodb provides you with this feature. Here is the code to generate the SQL to create a table with: \r
240 <ol>\r
241         <li> Auto-increment primary key 'ID', </li>\r
242         <li>The person's 'NAME' VARCHAR(32) NOT NULL and defaults to '', </li>\r
243         <li>The date and time of record creation 'CREATED', </li>\r
244         <li> The person's 'AGE', defaulting to 0, type NUMERIC(16). </li>\r
245 </ol>\r
246 <p>\r
247 Also create a compound index consisting of 'NAME' and 'AGE': \r
248 <pre>\r
249 $datadict = <strong>NewDataDictionary</strong>($connection);\r
250 $flds = " \r
251 <font color="#660000">  ID I AUTOINCREMENT PRIMARY,\r
252   NAME C(32) DEFAULT '' NOTNULL,\r
253   CREATED T DEFTIMESTAMP,\r
254   AGE N(16) DEFAULT 0</font>\r
255 ";\r
256 $sql1 = $datadict-><strong>CreateTableSQL</strong>('tabname', $flds);\r
257 $sql2 = $datadict-><strong>CreateIndexSQL</strong>('idx_name_age', 'tabname', 'NAME,AGE');\r
258 </pre>\r
259 \r
260 <h3>Data Types</h3>\r
261 <p>Stick to a few data types that are available in most databases. Char, varchar \r
262   and numeric/number are supported by most databases. Most other data types (including \r
263   integer, boolean and float) cannot be relied on being available. I recommend \r
264   using char(1) or number(1) to hold booleans. </p>\r
265 <p>Different databases have different ways of representing dates and timestamps/datetime. \r
266   ADOdb attempts to display all dates in ISO (YYYY-MM-DD) format. ADOdb also provides \r
267   DBDate( ) and DBTimeStamp( ) to convert dates to formats that are acceptable \r
268   to that database. Both functions accept Unix integer timestamps and date strings \r
269   in ISO format.</p>\r
270 <pre>$date1 = $connection-&gt;DBDate(time( ));<br>$date2 = $connection-&gt;DBTimeStamp('2002-02-23 13:03:33');</pre>\r
271 <p>We also provide functions to convert database dates to Unix timestamps:</p>\r
272 <pre>$unixts = $recordset-&gt;UnixDate('#2002-02-30#'); <font color="green"># MS Access date =gt; unix timestamp</font></pre>\r
273 <p>For date calculations, we have OffsetDate which allows you to calculate dates such as <i>yesterday</i> and <i>next week</i> in a RDBMS independant fashion. For example, if we want to set a field to 6 hour from now, use:\r
274 <pre>\r
275 $sql = 'update table set dtimefld='.$db-&gt;OffsetDate($db-&gtsysTimeStamp, 6/24).' where ...';\r
276 </pre>\r
277 <p>The maximum length of a char/varchar field is also database specific. You can \r
278   only assume that field lengths of up to 250 characters are supported. This is \r
279   normally impractical for web based forum or content management systems. You \r
280   will need to be familiar with how databases handle large objects (LOBs). ADOdb \r
281   implements two functions, UpdateBlob( ) and UpdateClob( ) that allow you to \r
282   update fields holding Binary Large Objects (eg. pictures) and Character Large \r
283   Objects (eg. HTML articles):</p>\r
284 <pre><font color=green># for oracle </font>\r
285 $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1,empty_blob())'); \r
286 $conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1'); \r
287    \r
288 <font color=green># non-oracle databases</font>\r
289 $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); \r
290 $conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');\r
291 </pre>\r
292 <p>Null handling is another area where differences can occur. This is a mine-field, \r
293   because 3-value logic is tricky.\r
294 <p>In general, I avoid using nulls except for dates and default all my numeric \r
295   and character fields to 0 or the empty string. This maintains consistency with \r
296   PHP, where empty strings and zero are treated as equivalent, and avoids SQL \r
297   ambiguities when you use the ANY and EXISTS operators. However if your database \r
298   has significant amounts of missing or unknown data, using nulls might be a good \r
299   idea. \r
300   <p>\r
301   ADOdb also supports a portable <a href=http://phplens.com/adodb/reference.functions.concat.html#ifnull>IfNull</a> function, so you can define what to display\r
302   if the field contains a null.\r
303 <h3><b>Stored Procedures</b></h3>\r
304 <p>Stored procedures are another problem area. Some databases allow recordsets \r
305   to be returned in a stored procedure (Microsoft SQL Server and Sybase), and \r
306   others only allow output parameters to be returned. Stored procedures sometimes \r
307   need to be wrapped in special syntax. For example, Oracle requires such code \r
308   to be wrapped in an anonymous block with BEGIN and END. Also internal sql operators \r
309   and functions such as +, ||, TRIM( ), SUBSTR( ) or INSTR( ) vary between vendors. \r
310 </p>\r
311 <p>An example of how to call a stored procedure with 2 parameters and 1 return \r
312   value follows:</p>\r
313 <pre>   switch ($db->databaseType) {\r
314         case '<font color="#993300">mssql</font>':\r
315           $sql = <font color="#000000"><font color="#993333">'<font color="#993300">SP_RUNSOMETHING</font>'</font></font>; break;\r
316         case '<font color="#993300">oci8</font>':\r
317           $sql = \r
318 <font color="#993300">    </font><font color="#000000"><font color="#993300">&quot;declare RETVAL integer;begin :RETVAL := </font><font color="#000000"><font color="#993333"><font color="#993300">SP_RUNSOMETHING</font></font></font><font color="#993300">(:myid,:group);end;&quot;;\r
319 </font>   break;</font>\r
320         default:\r
321           die('<font color="#993300">Unsupported feature</font>');\r
322         }\r
323 <font color="#000000"><font color="green">      # @RETVAL = SP_RUNSOMETHING @myid,@group</font>\r
324         $stmt = $db-&gt;PrepareSP($sql);        <br>    $db-&gt;Parameter($stmt,$id,'<font color="#993300">myid</font>'); \r
325         $db-&gt;Parameter($stmt,$group,'<font color="#993300">group</font>');\r
326         <font color="green"># true indicates output parameter<br>       </font>$db-&gt;Parameter($stmt,$ret,'<font color="#993300">RETVAL</font>',true); \r
327         $db-&gt;Execute($stmt); </font></pre>\r
328 <p>As you can see, the ADOdb API is the same for both databases. But the stored \r
329   procedure SQL syntax is quite different between databases and is not portable, \r
330   so be forewarned! However sometimes you have little choice as some systems only \r
331   allow data to be accessed via stored procedures. This is when the ultimate portability \r
332   solution might be the only solution: <i>treating portable SQL as a localization \r
333   exercise...</i></p>\r
334 <h3><b>SQL as a Localization Exercise</b></h3>\r
335 <p> In general to provide real portability, you will have to treat SQL coding \r
336   as a localization exercise. In PHP, it has become common to define separate \r
337   language files for English, Russian, Korean, etc. Similarly, I would suggest \r
338   you have separate Sybase, Intebase, MySQL, etc files, and conditionally include \r
339   the SQL based on the database. For example, each MySQL SQL statement would be \r
340   stored in a separate variable, in a file called 'mysql-lang.inc.php'.</p>\r
341 <pre>$sqlGetPassword = '<font color="#993300">select password from users where userid=%s</font>';\r
342 $sqlSearchKeyword = quot;<font color="#993300">SELECT * FROM articles WHERE match (title,body) against (%s</font>)&quot;;</pre>\r
343 <p>In our main PHP file:</p>\r
344 <pre><font color=green># define which database to load...</font>\r
345 <b>$database = '<font color="#993300">mysql</font>';\r
346 include_once(&quot;<font color="#993300">$database-lang.inc.php</font>&quot;);</b>\r
347 \r
348 $db = NewADOConnection($database);\r
349 $db->PConnect(...) or die('<font color="#993300">Failed to connect to database</font>');\r
350 \r
351 <font color=green># search for a keyword $word</font>\r
352 $rs = $db-&gt;Execute(sprintf($sqlSearchKeyWord,$db-&gt;qstr($word)));</pre>\r
353 <p>Note that we quote the $word variable using the qstr( ) function. This is because \r
354   each database quotes strings using different conventions.</p>\r
355 <p>\r
356 <h3>Final Thoughts</h3>\r
357 <p>The best way to ensure that you have portable SQL is to have your data tables designed using \r
358 sound principles. Learn the theory of normalization and entity-relationship diagrams and model \r
359 your data carefully. Understand how joins and indexes work and how they are used to tune performance.\r
360 <p> Visit the following page for more references on database theory and vendors: \r
361   <a href="http://php.weblogs.com/sql_tutorial">http://php.weblogs.com/sql_tutorial</a>. \r
362   Also read this article on <a href=http://phplens.com/lens/php-book/optimizing-debugging-php.php>Optimizing PHP</a>.\r
363 <p>\r
364 <font size=1>(c) 2002-2003 John Lim.</font>\r
365 \r
366 </body>\r
367 </html>\r