]> projects.mako.cc - scuttle/blob - includes/db/mssql.php
remove duplicate shared-tag in xml - the android apps dont like this
[scuttle] / includes / db / mssql.php
1 <?php
2 /** 
3 *
4 * @package dbal_mssql
5 * @version $Id: mssql.php,v 1.2 2005/06/10 08:52:03 devalley Exp $
6 * @copyright (c) 2005 phpBB Group 
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License 
8 *
9 */
10
11 /**
12 * @ignore
13 */
14 if (!defined('SQL_LAYER'))
15 {
16
17 define('SQL_LAYER', 'mssql');
18
19 /**
20 * @package dbal_mssql
21 * MSSQL Database Abstraction Layer
22 * Minimum Requirement is MSSQL 2000+
23 */
24 class sql_db
25 {
26         var $db_connect_id;
27         var $query_result;
28         var $return_on_error = false;
29         var $transaction = false;
30         var $sql_time = 0;
31         var $num_queries = 0;
32         var $open_queries = array();
33
34         function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false)
35         {
36                 $this->persistency = $persistency;
37                 $this->user = $sqluser;
38                 $this->server = $sqlserver . (($port) ? ':' . $port : '');
39                 $this->dbname = $database;
40
41                 $this->db_connect_id = ($this->persistency) ? @mssql_pconnect($this->server, $this->user, $sqlpassword) : @mssql_connect($this->server, $this->user, $sqlpassword);
42
43                 if ($this->db_connect_id && $this->dbname != '')
44                 {
45                         if (!@mssql_select_db($this->dbname, $this->db_connect_id))
46                         {
47                                 @mssql_close($this->db_connect_id);
48                                 return false;
49                         }
50                 }
51
52                 return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error('');
53         }
54
55         function sql_close()
56         {
57                 if (!$this->db_connect_id)
58                 {
59                         return false;
60                 }
61
62                 if ($this->transaction)
63                 {
64                         @mssql_query('COMMIT', $this->db_connect_id);
65                 }
66
67                 if (sizeof($this->open_queries))
68                 {
69                         foreach ($this->open_queries as $i_query_id => $query_id)
70                         {
71                                 @mssql_free_result($query_id);
72                         }
73                 }
74
75                 return @mssql_close($this->db_connect_id);
76         }
77
78         function sql_return_on_error($fail = false)
79         {
80                 $this->return_on_error = $fail;
81         }
82
83         function sql_num_queries()
84         {
85                 return $this->num_queries;
86         }
87
88         function sql_transaction($status = 'begin')
89         {
90                 switch ($status)
91                 {
92                         case 'begin':
93                                 $result = @mssql_query('BEGIN TRANSACTION', $this->db_connect_id);
94                                 $this->transaction = true;
95                                 break;
96
97                         case 'commit':
98                                 $result = @mssql_query('commit', $this->db_connect_id);
99                                 $this->transaction = false;
100
101                                 if (!$result)
102                                 {
103                                         @mssql_query('ROLLBACK', $this->db_connect_id);
104                                 }
105                                 break;
106
107                         case 'rollback':
108                                 $result = @mssql_query('ROLLBACK', $this->db_connect_id);
109                                 $this->transaction = false;
110                                 break;
111
112                         default:
113                                 $result = true;
114                 }
115
116                 return $result;
117         }
118
119         // Base query method
120         function sql_query($query = '', $cache_ttl = 0)
121         {
122                 if ($query != '')
123                 {
124                         global $cache;
125
126                         // EXPLAIN only in extra debug mode
127                         if (defined('DEBUG_EXTRA'))
128                         {
129                                 $this->sql_report('start', $query);
130                         }
131
132                         $this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
133
134                         if (!$this->query_result)
135                         {
136                                 $this->num_queries++;
137                                 
138                                 if (($this->query_result = @mssql_query($query, $this->db_connect_id)) === false)
139                                 {
140                                         $this->sql_error($query);
141                                 }
142
143                                 if (defined('DEBUG_EXTRA'))
144                                 {
145                                         $this->sql_report('stop', $query);
146                                 }
147
148                                 if ($cache_ttl && method_exists($cache, 'sql_save'))
149                                 {
150                                         $this->open_queries[(int) $this->query_result] = $this->query_result;
151                                         $cache->sql_save($query, $this->query_result, $cache_ttl);
152                                         // sql_freeresult called within sql_save()
153                                 }
154                                 else if (strpos($query, 'SELECT') !== false && $this->query_result)
155                                 {
156                                         $this->open_queries[(int) $this->query_result] = $this->query_result;
157                                 }
158                         }
159                         else if (defined('DEBUG_EXTRA'))
160                         {
161                                 $this->sql_report('fromcache', $query);
162                         }
163                 }
164                 else
165                 {
166                         return false;
167                 }
168
169                 return ($this->query_result) ? $this->query_result : false;
170         }
171
172         function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) 
173         { 
174                 if ($query != '') 
175                 {
176                         $this->query_result = false; 
177
178                         // if $total is set to 0 we do not want to limit the number of rows
179                         if ($total == 0)
180                         {
181                                 $total = -1;
182                         }
183
184                         $row_offset = ($total) ? $offset : '';
185                         $num_rows = ($total) ? $total : $offset;
186
187                         $query = 'SELECT TOP ' . ($row_offset + $num_rows) . ' ' . substr($query, 6);
188
189                         return $this->sql_query($query, $cache_ttl); 
190                 } 
191                 else 
192                 { 
193                         return false; 
194                 } 
195         }
196
197         // Idea for this from Ikonboard
198         function sql_build_array($query, $assoc_ary = false)
199         {
200                 if (!is_array($assoc_ary))
201                 {
202                         return false;
203                 }
204
205                 $fields = array();
206                 $values = array();
207                 if ($query == 'INSERT')
208                 {
209                         foreach ($assoc_ary as $key => $var)
210                         {
211                                 $fields[] = $key;
212
213                                 if (is_null($var))
214                                 {
215                                         $values[] = 'NULL';
216                                 }
217                                 elseif (is_string($var))
218                                 {
219                                         $values[] = "'" . $this->sql_escape($var) . "'";
220                                 }
221                                 else
222                                 {
223                                         $values[] = (is_bool($var)) ? intval($var) : $var;
224                                 }
225                         }
226
227                         $query = ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
228                 }
229                 else if ($query == 'UPDATE' || $query == 'SELECT')
230                 {
231                         $values = array();
232                         foreach ($assoc_ary as $key => $var)
233                         {
234                                 if (is_null($var))
235                                 {
236                                         $values[] = "$key = NULL";
237                                 }
238                                 elseif (is_string($var))
239                                 {
240                                         $values[] = "$key = '" . $this->sql_escape($var) . "'";
241                                 }
242                                 else
243                                 {
244                                         $values[] = (is_bool($var)) ? "$key = " . intval($var) : "$key = $var";
245                                 }
246                         }
247                         $query = implode(($query == 'UPDATE') ? ', ' : ' AND ', $values);
248                 }
249
250                 return $query;
251         }
252
253         // Other query methods
254         //
255         // NOTE :: Want to remove _ALL_ reliance on sql_numrows from core code ...
256         //         don't want this here by a middle Milestone
257         function sql_numrows($query_id = false)
258         {
259                 if (!$query_id)
260                 {
261                         $query_id = $this->query_result;
262                 }
263
264 //              return (isset($this->limit_offset[$query_id])) ? @mssql_num_rows($query_id) - $this->limit_offset[$query_id] : @mssql_num_rows($query_id);
265                 return ($query_id) ? @mssql_num_rows($query_id) : false;
266         }
267
268         function sql_affectedrows()
269         {
270                 return ($this->db_connect_id) ? @mssql_rows_affected($this->db_connect_id) : false;
271         }
272
273         function sql_fetchrow($query_id = false)
274         {
275                 global $cache;
276
277                 if (!$query_id)
278                 {
279                         $query_id = $this->query_result;
280                 }
281
282                 if (isset($cache->sql_rowset[$query_id]))
283                 {
284                         return $cache->sql_fetchrow($query_id);
285                 }
286
287                 $row = @mssql_fetch_array($query_id, MSSQL_ASSOC);
288                 
289                 if ($row)
290                 {
291                         foreach ($row as $key => $value)
292                         {
293                                 $row[$key] = ($value === ' ') ? trim($value) : $value;
294                         }
295                 }
296
297                 return $row;
298         }
299
300         function sql_fetchrowset($query_id = false)
301         {
302                 if (!$query_id)
303                 {
304                         $query_id = $this->query_result;
305                 }
306
307                 if ($query_id)
308                 {
309                         unset($this->rowset[$query_id]);
310                         unset($this->row[$query_id]);
311
312                         $result = array();
313                         while ($this->rowset[$query_id] = $this->sql_fetchrow($query_id))
314                         {
315                                 $result[] = $this->rowset[$query_id];
316                         }
317                         return $result;
318                 }
319
320                 return false;
321         }
322
323         function sql_fetchfield($field, $rownum = -1, $query_id = false)
324         {
325                 if (!$query_id)
326                 {
327                         $query_id = $this->query_result;
328                 }
329
330                 if ($query_id)
331                 {
332                         if ($rownum > -1)
333                         {
334 //                              (!empty($this->limit_offset[$query_id])) ? @mssql_data_seek($query_id, ($this->limit_offset[$query_id] + $rownum)) : @mssql_data_seek($query_id, $rownum);
335                                 @mssql_data_seek($query_id, $rownum);
336                                 $row = @mssql_fetch_array($query_id, MSSQL_ASSOC);
337                                 $result = isset($row[$field]) ? $row[$field] : false;
338                         }
339                         else
340                         {
341                                 if (empty($this->row[$query_id]) && empty($this->rowset[$query_id]))
342                                 {
343                                         if ($this->sql_fetchrow($query_id))
344                                         {
345                                                 $result = $this->row[$query_id][$field];
346                                         }
347                                 }
348                                 else
349                                 {
350                                         if ($this->rowset[$query_id])
351                                         {
352                                                 $result = $this->rowset[$query_id][$field];
353                                         }
354                                         elseif ($this->row[$query_id])
355                                         {
356                                                 $result = $this->row[$query_id][$field];
357                                         }
358                                 }
359                         }
360
361                         return $result;
362                 }
363
364                 return false;
365         }
366
367         function sql_rowseek($rownum, $query_id = false)
368         {
369                 if (!$query_id)
370                 {
371                         $query_id = $this->query_result;
372                 }
373
374                 if (isset($this->current_row[$query_id]))
375                 {
376 //                      (!empty($this->limit_offset[$query_id])) ? @mssql_data_seek($query_id, ($this->limit_offset[$query_id] + $rownum)) : @mssql_data_seek($query_id, $rownum);
377                         @mssql_data_seek($query_id, $rownum);
378                         return true;
379                 }
380
381                 return false;
382         }
383
384         function sql_nextid()
385         {
386                 $result_id = @mssql_query('SELECT @@IDENTITY', $this->db_connect_id);
387                 if ($result_id)
388                 {
389                         if (@mssql_fetch_array($result_id, MSSQL_ASSOC))
390                         {
391                                 return @mssql_result($result_id, 1);    
392                         }
393                 }
394
395                 return false;
396         }
397
398         function sql_freeresult($query_id = false)
399         {
400                 if (!$query_id)
401                 {
402                         $query_id = $this->query_result;
403                 }
404
405                 if (isset($this->open_queries[$query_id]))
406                 {
407                         unset($this->open_queries[$query_id]);
408                         unset($this->result_rowset[$query_id]);
409
410                         return @mssql_free_result($query_id);
411                 }
412
413                 return false;
414         }
415
416         function sql_escape($msg)
417         {
418                 return str_replace("'", "''", str_replace('\\', '\\\\', $msg));
419         }
420
421         function sql_error($sql = '')
422         {
423                 if (!$this->return_on_error)
424                 {
425                         $this_page = (isset($_SERVER['PHP_SELF']) && !empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : $_ENV['PHP_SELF'];
426                         $this_page .= '&' . ((isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : (isset($_ENV['QUERY_STRING']) ? $_ENV['QUERY_STRING'] : ''));
427
428                         $message = '<u>SQL ERROR</u> [ ' . SQL_LAYER . ' ]<br /><br />' . @mssql_get_last_message() . '<br /><br /><u>CALLING PAGE</u><br /><br />'  . htmlspecialchars($this_page) . (($sql != '') ? '<br /><br /><u>SQL</u><br /><br />' . $sql : '') . '<br />';
429
430                         if ($this->transaction)
431                         {
432                                 $this->sql_transaction('rollback');
433                         }
434                         
435                         trigger_error($message, E_USER_ERROR);
436                 }
437
438                 $result = array(
439                         'message'       => @mssql_get_last_message($this->db_connect_id),
440                         'code'          => ''
441                 );
442
443                 return $result;
444         }
445
446         function sql_report($mode, $query = '')
447         {
448                 if (empty($_GET['explain']))
449                 {
450                         return;
451                 }
452
453                 global $cache, $starttime, $phpbb_root_path;
454                 static $curtime, $query_hold, $html_hold;
455                 static $sql_report = '';
456                 static $cache_num_queries = 0;
457
458                 if (!$query && !empty($query_hold))
459                 {
460                         $query = $query_hold;
461                 }
462
463                 switch ($mode)
464                 {
465                         case 'display':
466                                 if (!empty($cache))
467                                 {
468                                         $cache->unload();
469                                 }
470                                 $this->sql_close();
471
472                                 $mtime = explode(' ', microtime());
473                                 $totaltime = $mtime[0] + $mtime[1] - $starttime;
474
475                                 echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8869-1"><meta http-equiv="Content-Style-Type" content="text/css"><link rel="stylesheet" href="' . $phpbb_root_path . 'adm/subSilver.css" type="text/css"><style type="text/css">' . "\n";
476                                 echo 'th { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic3.gif\') }' . "\n";
477                                 echo 'td.cat    { background-image: url(\'' . $phpbb_root_path . 'adm/images/cellpic1.gif\') }' . "\n";
478                                 echo '</style><title>' . $msg_title . '</title></head><body>';
479                                 echo '<table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td><a href="' . htmlspecialchars(preg_replace('/&explain=([^&]*)/', '', $_SERVER['REQUEST_URI'])) . '"><img src="' . $phpbb_root_path . 'adm/images/header_left.jpg" width="200" height="60" alt="phpBB Logo" title="phpBB Logo" border="0"/></a></td><td width="100%" background="' . $phpbb_root_path . 'adm/images/header_bg.jpg" height="60" align="right" nowrap="nowrap"><span class="maintitle">SQL Report</span> &nbsp; &nbsp; &nbsp;</td></tr></table><br clear="all"/><table width="95%" cellspacing="1" cellpadding="4" border="0" align="center"><tr><td height="40" align="center" valign="middle"><b>Page generated in ' . round($totaltime, 4) . " seconds with {$this->num_queries} queries" . (($cache_num_queries) ? " + $cache_num_queries " . (($cache_num_queries == 1) ? 'query' : 'queries') . ' returning data from cache' : '') . '</b></td></tr><tr><td align="center" nowrap="nowrap">Time spent on MySQL queries: <b>' . round($this->sql_time, 5) . 's</b> | Time spent on PHP: <b>' . round($totaltime - $this->sql_time, 5) . 's</b></td></tr></table><table width="95%" cellspacing="1" cellpadding="4" border="0" align="center"><tr><td>';
480                                 echo $sql_report;
481                                 echo '</td></tr></table><br /></body></html>';
482                                 exit;
483                                 break;
484
485                         case 'start':
486                                 $query_hold = $query;
487                                 $html_hold = '';
488
489                                 $curtime = explode(' ', microtime());
490                                 $curtime = $curtime[0] + $curtime[1];
491                                 break;
492
493                         case 'fromcache':
494                                 $endtime = explode(' ', microtime());
495                                 $endtime = $endtime[0] + $endtime[1];
496
497                                 $result = @mssql_query($query, $this->db_connect_id);
498                                 while ($void = @mssql_fetch_array($result, MSSQL_ASSOC))
499                                 {
500                                         // Take the time spent on parsing rows into account
501                                 }
502                                 $splittime = explode(' ', microtime());
503                                 $splittime = $splittime[0] + $splittime[1];
504
505                                 $time_cache = $endtime - $curtime;
506                                 $time_db = $splittime - $endtime;
507                                 $color = ($time_db > $time_cache) ? 'green' : 'red';
508
509                                 $sql_report .= '<hr width="100%"/><br /><table class="bg" width="100%" cellspacing="1" cellpadding="4" border="0"><tr><th>Query results obtained from the cache</th></tr><tr><td class="row1"><textarea style="font-family:\'Courier New\',monospace;width:100%" rows="5">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></table><p align="center">';
510
511                                 $sql_report .= 'Before: ' . sprintf('%.5f', $curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed [cache]: <b style="color: ' . $color . '">' . sprintf('%.5f', ($time_cache)) . 's</b> | Elapsed [db]: <b>' . sprintf('%.5f', $time_db) . 's</b></p>';
512
513                                 // Pad the start time to not interfere with page timing
514                                 $starttime += $time_db;
515
516                                 @mssql_free_result($result);
517                                 $cache_num_queries++;
518                                 break;
519
520                         case 'stop':
521                                 $endtime = explode(' ', microtime());
522                                 $endtime = $endtime[0] + $endtime[1];
523
524                                 $sql_report .= '<hr width="100%"/><br /><table class="bg" width="100%" cellspacing="1" cellpadding="4" border="0"><tr><th>Query #' . $this->num_queries . '</th></tr><tr><td class="row1"><textarea style="font-family:\'Courier New\',monospace;width:100%" rows="5">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></table> ' . $html_hold . '<p align="center">';
525
526                                 if ($this->query_result)
527                                 {
528                                         if (preg_match('/^(UPDATE|DELETE|REPLACE)/', $query))
529                                         {
530                                                 $sql_report .= "Affected rows: <b>" . $this->sql_affectedrows($this->query_result) . '</b> | ';
531                                         }
532                                         $sql_report .= 'Before: ' . sprintf('%.5f', $curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed: <b>' . sprintf('%.5f', $endtime - $curtime) . 's</b>';
533                                 }
534                                 else
535                                 {
536                                         $error = $this->sql_error();
537                                         $sql_report .= '<b style="color: red">FAILED</b> - ' . SQL_LAYER . ' Error ' . $error['code'] . ': ' . htmlspecialchars($error['message']);
538                                 }
539
540                                 $sql_report .= '</p>';
541
542                                 $this->sql_time += $endtime - $curtime;
543                                 break;
544                 }
545         }
546
547 } // class sql_db
548
549 } // if ... define
550
551 ?>

Benjamin Mako Hill || Want to submit a patch?