source: trunk/include/dblayer/functions_pdo-sqlite.inc.php @ 5230

Last change on this file since 5230 was 5230, checked in by patdenice, 14 years ago

feature 1255: add pwg_select_db function.

File size: 12.6 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2010 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24define('REQUIRED_PDO-SQLITE_VERSION', '3.0.0');
25define('DB_ENGINE', 'SQLite');
26
27define('DB_REGEX_OPERATOR', 'REGEXP');
28define('DB_RANDOM_FUNCTION', 'RANDOM');
29
30/**
31 *
32 * simple functions
33 *
34 */
35
36function pwg_db_connect($host, $user, $password, $database, $die=true)
37{
38  global $conf;
39
40  $db_file = sprintf('sqlite:%s/%s.db', $conf['local_data_dir'], $database);
41
42  try {
43    $link = new PDO($db_file);
44  } catch (Exception $e) {
45    my_error('sqlite::open', $die);
46  }
47
48  $link->sqliteCreateFunction('now', 'pwg_now', 0);
49  $link->sqliteCreateFunction('unix_timestamp', 'pwg_unix_timestamp', 0);
50  $link->sqliteCreateFunction('md5', 'md5', 1);
51  $link->sqliteCreateFunction('if', 'pwg_if', 3);
52
53  $link->sqliteCreateAggregate('std', 'pwg_std_step', 'pwg_std_finalize');
54  $link->sqliteCreateFunction('regexp', 'pwg_regexp', 2);
55
56  return $link;
57}
58
59function pwg_select_db($database=null, $link=null, $die=null)
60{
61  return true;
62}
63
64function pwg_db_check_charset() 
65{
66  return true;
67}
68
69function pwg_get_db_version() 
70{
71  global $pwg_db_link;
72
73  return $pwg_db_link->getAttribute(PDO::ATTR_SERVER_VERSION);
74}
75
76function pwg_query($query)
77{
78  global $conf,$page,$debug,$t2,$pwg_db_link;
79
80  $start = get_moment();
81
82  $truncate_pattern = '`truncate(.*)`i';
83  $insert_pattern = '`(INSERT INTO [^)]*\)\s*VALUES)(\([^)]*\))\s*,\s*(.*)`mi'; 
84
85  if (preg_match($truncate_pattern, $query, $matches))
86  {
87    $query = str_replace('TRUNCATE TABLE', 'DELETE FROM', $query);
88    $truncate_query = true;
89    ($result = $pwg_db_link->exec($query)) or die($query."\n<br>".$pwg_db_link->errorInfo());
90  }
91  elseif (preg_match($insert_pattern, $query, $matches))
92  {
93    $base_query = substr($query, 0, strlen($matches[1])+1);
94    $values_pattern = '`\)\s*,\s*\(`';
95    $values = preg_split($values_pattern, substr($query, strlen($matches[1])+1));
96    $values[0] = substr($values[0], 1);
97    $values[count($values)-1] = substr($values[count($values)-1], 
98                                     0, 
99                                     strlen($values[count($values)-1])-1
100                                     );
101    for ($n=0;$n<count($values);$n++)
102    {
103      $query = $base_query . '('. $values[$n] . ")\n;";
104      ($result = $pwg_db_link->query($query)) 
105        or die($query."\n<br>".$pwg_db_link->lastErrorMsg());
106    }
107  }
108  else 
109  {
110    ($result = $pwg_db_link->query($query)) 
111      or die($query."\n<br>".$pwg_db_link->errorInfo());
112  }
113
114  $time = get_moment() - $start;
115
116  if (!isset($page['count_queries']))
117  {
118    $page['count_queries'] = 0;
119    $page['queries_time'] = 0;
120  }
121
122  $page['count_queries']++;
123  $page['queries_time']+= $time;
124
125  if ($conf['show_queries'])
126  {
127    $output = '';
128    $output.= '<pre>['.$page['count_queries'].'] ';
129    $output.= "\n".$query;
130    $output.= "\n".'(this query time : ';
131    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
132    $output.= "\n".'(total SQL time  : ';
133    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
134    $output.= "\n".'(total time      : ';
135    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
136    if ( $result!=null and preg_match('/\s*SELECT\s+/i',$query) )
137    {
138      $output.= "\n".'(num rows        : ';
139      $output.= pwg_db_num_rows($result).' )';
140    }
141    elseif ( $result!=null
142      and preg_match('/\s*INSERT|UPDATE|REPLACE|DELETE\s+/i',$query) 
143      and !isset($truncate_query))
144    {
145      $output.= "\n".'(affected rows   : ';
146      $output.= pwg_db_changes($result).' )';
147    }
148    $output.= "</pre>\n";
149
150    $debug .= $output;
151  }
152
153  return $result;
154}
155
156function pwg_db_nextval($column, $table)
157{
158  $query = '
159SELECT MAX('.$column.')+1
160  FROM '.$table;
161  list($next) = pwg_db_fetch_row(pwg_query($query));
162  if (is_null($next))
163  {
164    $next = 1;
165  }
166  return $next;
167}
168
169/**
170 *
171 * complex functions
172 *
173 */
174
175function pwg_db_changes(PDOStatement $result=null) 
176{
177  return $result->rowCount();
178}
179
180function pwg_db_num_rows(PDOStatement $result) 
181{ 
182  return $result->columnCount();
183}
184
185function pwg_db_fetch_assoc($result)
186{
187  return $result->fetch(PDO::FETCH_ASSOC);
188}
189
190function pwg_db_fetch_row($result)
191{
192  return $result->fetch(PDO::FETCH_NUM);
193}
194
195function pwg_db_fetch_object($result)
196{
197  return $result;
198}
199
200function pwg_db_free_result($result) 
201{
202}
203
204function pwg_db_real_escape_string($s)
205{
206  global $pwg_db_link;
207
208  return trim($pwg_db_link->quote($s), "'");
209}
210
211function pwg_db_insert_id($table=null, $column='id')
212{
213  global $pwg_db_link;
214
215  return $pwg_db_link->lastInsertRowID();
216}
217
218/**
219 *
220 * complex functions
221 *
222 */
223
224/**
225 * creates an array based on a query, this function is a very common pattern
226 * used here
227 *
228 * @param string $query
229 * @param string $fieldname
230 * @return array
231 */
232function array_from_query($query, $fieldname)
233{
234  $array = array();
235
236  $result = pwg_query($query);
237  while ($row = pwg_db_fetch_assoc($result))
238  {
239    array_push($array, $row[$fieldname]);
240  }
241
242  return $array;
243}
244
245define('MASS_UPDATES_SKIP_EMPTY', 1);
246/**
247 * updates multiple lines in a table
248 *
249 * @param string table_name
250 * @param array dbfields
251 * @param array datas
252 * @param int flags - if MASS_UPDATES_SKIP_EMPTY - empty values do not overwrite existing ones
253 * @return void
254 */
255function mass_updates($tablename, $dbfields, $datas, $flags=0)
256{
257  if (count($datas) == 0)
258    return;
259
260  foreach ($datas as $data)
261  {
262    $query = '
263UPDATE '.$tablename.'
264  SET ';
265    $is_first = true;
266    foreach ($dbfields['update'] as $key)
267    {
268      $separator = $is_first ? '' : ",\n    ";
269     
270      if (isset($data[$key]) and $data[$key] != '')
271      {
272        $query.= $separator.$key.' = \''.$data[$key].'\'';
273      }
274      else
275      {
276        if ($flags & MASS_UPDATES_SKIP_EMPTY )
277          continue; // next field
278        $query.= "$separator$key = NULL";
279      }
280      $is_first = false;
281    }
282    if (!$is_first)
283    {// only if one field at least updated
284      $query.= '
285  WHERE ';
286      $is_first = true;
287      foreach ($dbfields['primary'] as $key)
288      {
289        if (!$is_first)
290        {
291          $query.= ' AND ';
292        }
293        if ( isset($data[$key]) )
294        {
295          $query.= $key.' = \''.$data[$key].'\'';
296        }
297        else
298        {
299          $query.= $key.' IS NULL';
300        }
301        $is_first = false;
302      }
303      pwg_query($query);
304    }
305  }
306}
307
308
309/**
310 * inserts multiple lines in a table
311 *
312 * @param string table_name
313 * @param array dbfields
314 * @param array inserts
315 * @return void
316 */
317
318function mass_inserts($table_name, $dbfields, $datas)
319{
320  if (count($datas) != 0)
321  {
322    $first = true;
323
324    $packet_size = 16777216;
325    $packet_size = $packet_size - 2000; // The last list of values MUST not exceed 2000 character*/
326    $query = '';
327
328    foreach ($datas as $insert)
329    {
330      if (strlen($query) >= $packet_size)
331      {
332        pwg_query($query);
333        $first = true;
334      }
335
336      if ($first)
337      {
338        $query = '
339INSERT INTO '.$table_name.'
340  ('.implode(',', $dbfields).')
341  VALUES';
342        $first = false;
343      }
344      else
345      {
346        $query .= '
347  , ';
348      }
349
350      $query .= '(';
351      foreach ($dbfields as $field_id => $dbfield)
352      {
353        if ($field_id > 0)
354        {
355          $query .= ',';
356        }
357
358        if (!isset($insert[$dbfield]) or $insert[$dbfield] === '')
359        {
360          $query .= 'NULL';
361        }
362        else
363        {
364          $query .= "'".$insert[$dbfield]."'";
365        }
366      }
367      $query .= ')';
368    }
369    pwg_query($query);
370  }
371}
372
373/**
374 * Do maintenance on all PWG tables
375 *
376 * @return none
377 */
378function do_maintenance_all_tables()
379{
380  global $prefixeTable, $page;
381
382  $all_tables = array();
383
384  // List all tables
385  $query = 'SELECT name FROM SQLITE_MASTER
386WHERE name LIKE \''.$prefixeTable.'%\'';
387
388  $all_tables = array_from_query($query, 'name');
389  foreach ($all_tables as $table_name)
390  {
391    $query = 'VACUUM '.$table_name.';';
392    $result = pwg_query($query);
393  }
394 
395  array_push($page['infos'],
396             l10n('All optimizations have been successfully completed.')
397             );
398}
399
400function pwg_db_concat($array)
401{
402  return implode($array, ' || ');
403}
404
405function pwg_db_concat_ws($array, $separator)
406{
407  $glue = sprintf(' || \'%s\' || ', $separator);
408
409  return implode($array, $glue);
410}
411
412function pwg_db_cast_to_text($string)
413{
414  return $string;
415}
416
417/**
418 * returns an array containing the possible values of an enum field
419 *
420 * @param string tablename
421 * @param string fieldname
422 */
423function get_enums($table, $field)
424{
425  return array();
426}
427
428// get_boolean transforms a string to a boolean value. If the string is
429// "false" (case insensitive), then the boolean value false is returned. In
430// any other case, true is returned.
431function get_boolean( $string )
432{
433  $boolean = true;
434  if ('f' === $string || 'false' === $string)
435  {
436    $boolean = false;
437  }
438  return $boolean;
439}
440
441/**
442 * returns boolean string 'true' or 'false' if the given var is boolean
443 *
444 * @param mixed $var
445 * @return mixed
446 */
447function boolean_to_string($var)
448{
449  if (!empty($var) && ($var == 'true'))
450  {
451    return 'true';
452  }
453  else
454  {
455    return 'false';
456  }
457}
458
459/**
460 *
461 * interval and date functions
462 *
463 */
464
465function pwg_db_get_recent_period_expression($period, $date='CURRENT_DATE')
466{
467  if ($date!='CURRENT_DATE')
468  {
469    $date = '\''.$date.'\'';
470  }
471
472  return 'date('.$date.',\''.-$period.' DAY\')';
473}
474
475function pwg_db_get_recent_period($period, $date='CURRENT_DATE')
476{
477  $query = 'select '.pwg_db_get_recent_period_expression($period, $date);
478  list($d) = pwg_db_fetch_row(pwg_query($query));
479
480  return $d;
481}
482
483function pwg_db_get_date_YYYYMM($date)
484{
485  return 'strftime(\'%Y%m\','.$date.')';
486}
487
488function pwg_db_get_date_MMDD($date)
489{
490  return 'strftime(\'%m%d\','.$date.')';
491}
492
493function pwg_db_get_year($date)
494{
495  return 'strftime(\'%Y\','.$date.')';
496}
497
498function pwg_db_get_month($date)
499{
500  return 'strftime(\'%m\','.$date.')';
501}
502
503function pwg_db_get_week($date, $mode=null)
504{
505  return 'strftime(\'%W\','.$date.')';
506}
507
508function pwg_db_get_dayofmonth($date)
509{
510  return 'strftime(\'%d\','.$date.')';
511}
512
513function pwg_db_get_dayofweek($date)
514{
515  return 'strftime(\'%w\','.$date.')';
516}
517
518function pwg_db_get_weekday($date)
519{
520  return 'strftime(\'%w\',date('.$date.',\'-1 DAY\'))';
521}
522
523// my_error returns (or send to standard output) the message concerning the
524// error occured for the last mysql query.
525function my_error($header, $die)
526{
527  global $pwg_db_link;
528
529  $error = '';
530  if (isset($pwg_db_link)) 
531  {
532    $error .= '[sqlite error]'.$pwg_db_link->errorInfo()."\n";
533  }
534
535  $error .= $header;
536
537  if ($die)
538  {
539    fatal_error($error);
540  }
541  echo("<pre>");
542  trigger_error($error, E_USER_WARNING);
543  echo("</pre>");
544}
545
546// sqlite create functions
547function pwg_now()
548{
549  return date('Y-m-d H:i:s');
550}
551
552function pwg_unix_timestamp()
553{
554  return time();
555}
556
557function pwg_if($expression, $value1, $value2) 
558{
559  if ($expression)
560  {
561    return $value1;
562  }
563  else
564  {
565    return $value2;
566  }
567} 
568
569function pwg_regexp($pattern, $string)
570{
571  $pattern = sprintf('`%s`', $pattern);
572  return preg_match($pattern, $string);
573}
574
575function pwg_std_step(&$values, $rownumber, $value) 
576{
577  $values[] = $value;
578
579  return $values;
580}
581
582function pwg_std_finalize(&$values, $rownumber) 
583{
584  if (count($values)<=1)
585  {
586    return 0;
587  }
588
589  $total = 0;
590  $total_square = 0;
591  foreach ($values as $value)
592  {
593    $total += $value;
594    $total_square += pow($value, 2);
595  }
596
597  $mean = $total/count($values);
598  $var = $total_square/count($values) - pow($mean, 2);
599 
600  return sqrt($var);
601}
602?>
Note: See TracBrowser for help on using the repository browser.