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

Last change on this file since 11737 was 11485, checked in by mistic100, 13 years ago

feature:2359 add single_update and single_insert functions

File size: 15.2 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2011 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)
37{
38  global $conf;
39
40  $db_file = sprintf('sqlite:%s/%s.db', $conf['local_data_dir'], $database);
41
42  $link = new PDO($db_file);
43  if (!$link)
44  {
45    throw new  Exception('Connection to server succeed, but it was impossible to connect to database');
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->sqliteCreateFunction('regexp', 'pwg_regexp', 2);
54
55  return $link;
56}
57
58function pwg_db_check_version()
59{
60  $current_version = pwg_get_db_version();
61  if (version_compare($current_version, REQUIRED_PDO_SQLITE_VERSION, '<'))
62  {
63    fatal_error(
64      sprintf(
65        'your database version is too old, you have "%s" and you need at least "%s"',
66        $current_version,
67        REQUIRED_PDO_SQLITE_VERSION
68        )
69      );
70  }
71}
72
73function pwg_db_check_charset() 
74{
75  return true;
76}
77
78function pwg_get_db_version() 
79{
80  global $pwg_db_link;
81
82  return $pwg_db_link->getAttribute(PDO::ATTR_SERVER_VERSION);
83}
84
85function pwg_query($query)
86{
87  global $conf,$page,$debug,$t2,$pwg_db_link;
88
89  $start = get_moment();
90
91  $truncate_pattern = '`truncate(.*)`i';
92  $insert_pattern = '`(INSERT INTO [^)]*\)\s*VALUES)(\([^)]*\))\s*,\s*(.*)`mi'; 
93
94  if (preg_match($truncate_pattern, $query, $matches))
95  {
96    $query = str_replace('TRUNCATE TABLE', 'DELETE FROM', $query);
97    $truncate_query = true;
98    ($result = $pwg_db_link->exec($query)) or die($query."\n<br>".$pwg_db_link->errorInfo());
99  }
100  elseif (preg_match($insert_pattern, $query, $matches))
101  {
102    $base_query = substr($query, 0, strlen($matches[1])+1);
103    $values_pattern = '`\)\s*,\s*\(`';
104    $values = preg_split($values_pattern, substr($query, strlen($matches[1])+1));
105    $values[0] = substr($values[0], 1);
106    $values[count($values)-1] = substr($values[count($values)-1], 
107                                     0, 
108                                     strlen($values[count($values)-1])-1
109                                     );
110    for ($n=0;$n<count($values);$n++)
111    {
112      $query = $base_query . '('. $values[$n] . ")\n;";
113      ($result = $pwg_db_link->query($query)) 
114        or die($query."\n<br>".$pwg_db_link->lastErrorMsg());
115    }
116  }
117  else 
118  {
119    ($result = $pwg_db_link->query($query)) 
120      or die($query."\n<br>".$pwg_db_link->errorInfo());
121  }
122
123  $time = get_moment() - $start;
124
125  if (!isset($page['count_queries']))
126  {
127    $page['count_queries'] = 0;
128    $page['queries_time'] = 0;
129  }
130
131  $page['count_queries']++;
132  $page['queries_time']+= $time;
133
134  if ($conf['show_queries'])
135  {
136    $output = '';
137    $output.= '<pre>['.$page['count_queries'].'] ';
138    $output.= "\n".$query;
139    $output.= "\n".'(this query time : ';
140    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
141    $output.= "\n".'(total SQL time  : ';
142    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
143    $output.= "\n".'(total time      : ';
144    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
145    if ( $result!=null and preg_match('/\s*SELECT\s+/i',$query) )
146    {
147      $output.= "\n".'(num rows        : ';
148      $output.= pwg_db_num_rows($result).' )';
149    }
150    elseif ( $result!=null
151      and preg_match('/\s*INSERT|UPDATE|REPLACE|DELETE\s+/i',$query) 
152      and !isset($truncate_query))
153    {
154      $output.= "\n".'(affected rows   : ';
155      $output.= pwg_db_changes($result).' )';
156    }
157    $output.= "</pre>\n";
158
159    $debug .= $output;
160  }
161
162  return $result;
163}
164
165function pwg_db_nextval($column, $table)
166{
167  $query = '
168SELECT MAX('.$column.')+1
169  FROM '.$table;
170  list($next) = pwg_db_fetch_row(pwg_query($query));
171  if (is_null($next))
172  {
173    $next = 1;
174  }
175  return $next;
176}
177
178/**
179 *
180 * complex functions
181 *
182 */
183
184function pwg_db_changes(PDOStatement $result=null) 
185{
186  return $result->rowCount();
187}
188
189function pwg_db_num_rows(PDOStatement $result) 
190{ 
191  return $result->rowCount();
192}
193
194function pwg_db_fetch_assoc($result)
195{
196  return $result->fetch(PDO::FETCH_ASSOC);
197}
198
199function pwg_db_fetch_row($result)
200{
201  return $result->fetch(PDO::FETCH_NUM);
202}
203
204function pwg_db_fetch_object($result)
205{
206  return $result;
207}
208
209function pwg_db_free_result($result) 
210{
211}
212
213function pwg_db_real_escape_string($s)
214{
215  global $pwg_db_link;
216
217  return trim($pwg_db_link->quote($s), "'");
218}
219
220function pwg_db_insert_id($table=null, $column='id')
221{
222  global $pwg_db_link;
223
224  return $pwg_db_link->lastInsertRowID();
225}
226
227/**
228 *
229 * complex functions
230 *
231 */
232
233/**
234 * creates an array based on a query, this function is a very common pattern
235 * used here
236 *
237 * @param string $query
238 * @param string $fieldname
239 * @return array
240 */
241function array_from_query($query, $fieldname)
242{
243  $array = array();
244
245  $result = pwg_query($query);
246  while ($row = pwg_db_fetch_assoc($result))
247  {
248    array_push($array, $row[$fieldname]);
249  }
250
251  return $array;
252}
253
254define('MASS_UPDATES_SKIP_EMPTY', 1);
255/**
256 * updates multiple lines in a table
257 *
258 * @param string table_name
259 * @param array dbfields
260 * @param array datas
261 * @param int flags - if MASS_UPDATES_SKIP_EMPTY - empty values do not overwrite existing ones
262 * @return void
263 */
264function mass_updates($tablename, $dbfields, $datas, $flags=0)
265{
266  if (count($datas) == 0)
267    return;
268
269  foreach ($datas as $data)
270  {
271    $query = '
272UPDATE '.$tablename.'
273  SET ';
274    $is_first = true;
275    foreach ($dbfields['update'] as $key)
276    {
277      $separator = $is_first ? '' : ",\n    ";
278     
279      if (isset($data[$key]) and $data[$key] != '')
280      {
281        $query.= $separator.$key.' = \''.$data[$key].'\'';
282      }
283      else
284      {
285        if ( $flags & MASS_UPDATES_SKIP_EMPTY )
286          continue; // next field
287        $query.= "$separator$key = NULL";
288      }
289      $is_first = false;
290    }
291    if (!$is_first)
292    {// only if one field at least updated
293      $query.= '
294  WHERE ';
295      $is_first = true;
296      foreach ($dbfields['primary'] as $key)
297      {
298        if (!$is_first)
299        {
300          $query.= ' AND ';
301        }
302        if ( isset($data[$key]) )
303        {
304          $query.= $key.' = \''.$data[$key].'\'';
305        }
306        else
307        {
308          $query.= $key.' IS NULL';
309        }
310        $is_first = false;
311      }
312      pwg_query($query);
313    }
314  }
315}
316
317/**
318 * updates on line in a table
319 *
320 * @param string table_name
321 * @param array dbfields
322 * @param array data
323 * @param int flags - if MASS_UPDATES_SKIP_EMPTY - empty values do not overwrite existing ones
324 * @return void
325 */
326function single_update($tablename, $dbfields, $data, $flags=0)
327{
328  if (count($data) == 0)
329    return;
330
331  $query = '
332UPDATE '.$tablename.'
333  SET ';
334  $is_first = true;
335  foreach ($dbfields['update'] as $key)
336  {
337    $separator = $is_first ? '' : ",\n    ";
338   
339    if (isset($data[$key]) and $data[$key] != '')
340    {
341      $query.= $separator.$key.' = \''.$data[$key].'\'';
342    }
343    else
344    {
345      if ( $flags & MASS_UPDATES_SKIP_EMPTY )
346        continue; // next field
347      $query.= "$separator$key = NULL";
348    }
349    $is_first = false;
350  }
351  if (!$is_first)
352  {// only if one field at least updated
353    $query.= '
354  WHERE ';
355    $is_first = true;
356    foreach ($dbfields['primary'] as $key)
357    {
358      if (!$is_first)
359      {
360        $query.= ' AND ';
361      }
362      if ( isset($data[$key]) )
363      {
364        $query.= $key.' = \''.$data[$key].'\'';
365      }
366      else
367      {
368        $query.= $key.' IS NULL';
369      }
370      $is_first = false;
371    }
372    pwg_query($query);
373  }
374}
375
376
377/**
378 * inserts multiple lines in a table
379 *
380 * @param string table_name
381 * @param array dbfields
382 * @param array inserts
383 * @return void
384 */
385function mass_inserts($table_name, $dbfields, $datas)
386{
387  if (count($datas) != 0)
388  {
389    $first = true;
390
391    $packet_size = 16777216;
392    $packet_size = $packet_size - 2000; // The last list of values MUST not exceed 2000 character*/
393    $query = '';
394
395    foreach ($datas as $insert)
396    {
397      if (strlen($query) >= $packet_size)
398      {
399        pwg_query($query);
400        $first = true;
401      }
402
403      if ($first)
404      {
405        $query = '
406INSERT INTO '.$table_name.'
407  ('.implode(',', $dbfields).')
408  VALUES';
409        $first = false;
410      }
411      else
412      {
413        $query .= '
414  , ';
415      }
416
417      $query .= '(';
418      foreach ($dbfields as $field_id => $dbfield)
419      {
420        if ($field_id > 0)
421        {
422          $query .= ',';
423        }
424
425        if (!isset($insert[$dbfield]) or $insert[$dbfield] === '')
426        {
427          $query .= 'NULL';
428        }
429        else
430        {
431          $query .= "'".$insert[$dbfield]."'";
432        }
433      }
434      $query .= ')';
435    }
436    pwg_query($query);
437  }
438}
439
440/**
441 * inserts one line in a table
442 *
443 * @param string table_name
444 * @param array dbfields
445 * @param array insert
446 * @return void
447 */
448function single_insert($table_name, $dbfields, $insert)
449{
450  if (count($insert) != 0)
451  {
452    $query = '
453INSERT INTO '.$table_name.'
454  ('.implode(',', $dbfields).')
455  VALUES';
456
457    $query .= '(';
458    foreach ($dbfields as $field_id => $dbfield)
459    {
460      if ($field_id > 0)
461      {
462        $query .= ',';
463      }
464      if (!isset($insert[$dbfield]) or $insert[$dbfield] === '')
465      {
466        $query .= 'NULL';
467      }
468      else
469      {
470        $query .= "'".$insert[$dbfield]."'";
471      }
472    }
473    $query .= ')';
474   
475    pwg_query($query);
476  }
477}
478
479/**
480 * Do maintenance on all PWG tables
481 *
482 * @return none
483 */
484function do_maintenance_all_tables()
485{
486  global $prefixeTable, $page;
487
488  $all_tables = array();
489
490  // List all tables
491  $query = 'SELECT name FROM SQLITE_MASTER
492WHERE name LIKE \''.$prefixeTable.'%\'';
493
494  $all_tables = array_from_query($query, 'name');
495  foreach ($all_tables as $table_name)
496  {
497    $query = 'VACUUM '.$table_name.';';
498    $result = pwg_query($query);
499  }
500 
501  array_push($page['infos'],
502             l10n('All optimizations have been successfully completed.')
503             );
504}
505
506function pwg_db_concat($array)
507{
508  return implode($array, ' || ');
509}
510
511function pwg_db_concat_ws($array, $separator)
512{
513  return implode($array, ' || \''.$separator.'\' || ');
514}
515
516function pwg_db_cast_to_text($string)
517{
518  return $string;
519}
520
521/**
522 * returns an array containing the possible values of an enum field
523 *
524 * @param string tablename
525 * @param string fieldname
526 */
527function get_enums($table, $field)
528{
529  $Enums['categories']['status'] = array('public', 'private');
530  $Enums['history']['section'] = array('categories','tags','search','list','favorites','most_visited','best_rated','recent_pics','recent_cats');
531  $Enums['user_infos']['status'] = array('webmaster','admin','normal','generic','guest');
532  $Enums['image']['type'] = array('picture','high','other');
533  $Enums['plugins']['state'] = array('active', 'inactive');
534  $Enums['user_cache_image']['access_type'] = array('NOT IN','IN');
535
536  $table = str_replace($GLOBALS['prefixeTable'], '', $table);
537  if (isset($Enums[$table][$field])) {
538    return $Enums[$table][$field];
539  } else {
540    return array();
541  }
542}
543
544// get_boolean transforms a string to a boolean value. If the string is
545// "false" (case insensitive), then the boolean value false is returned. In
546// any other case, true is returned.
547function get_boolean( $string )
548{
549  $boolean = true;
550  if ('f' === $string || 'false' === $string)
551  {
552    $boolean = false;
553  }
554  return $boolean;
555}
556
557/**
558 * returns boolean string 'true' or 'false' if the given var is boolean
559 *
560 * @param mixed $var
561 * @return mixed
562 */
563function boolean_to_string($var)
564{
565  if (is_bool($var))
566  {
567    return $var ? 'true' : 'false';
568  }
569  else
570  {
571    return $var;
572  }
573}
574
575/**
576 *
577 * interval and date functions
578 *
579 */
580
581function pwg_db_get_recent_period_expression($period, $date='CURRENT_DATE')
582{
583  if ($date!='CURRENT_DATE')
584  {
585    $date = '\''.$date.'\'';
586  }
587
588  return 'date('.$date.',\''.-$period.' DAY\')';
589}
590
591function pwg_db_get_recent_period($period, $date='CURRENT_DATE')
592{
593  $query = 'select '.pwg_db_get_recent_period_expression($period, $date);
594  list($d) = pwg_db_fetch_row(pwg_query($query));
595
596  return $d;
597}
598
599function pwg_db_get_flood_period_expression($seconds)
600{
601  return 'datetime(\'now\', \'localtime\', \''.-$seconds.' seconds\')';
602}
603
604function pwg_db_get_hour($date)
605{
606  return 'strftime(\'%H\', '.$date.')';
607}
608
609
610function pwg_db_get_date_YYYYMM($date)
611{
612  return 'strftime(\'%Y%m\','.$date.')';
613}
614
615function pwg_db_get_date_MMDD($date)
616{
617  return 'strftime(\'%m%d\','.$date.')';
618}
619
620function pwg_db_get_year($date)
621{
622  return 'strftime(\'%Y\','.$date.')';
623}
624
625function pwg_db_get_month($date)
626{
627  return 'strftime(\'%m\','.$date.')';
628}
629
630function pwg_db_get_week($date, $mode=null)
631{
632  return 'strftime(\'%W\','.$date.')';
633}
634
635function pwg_db_get_dayofmonth($date)
636{
637  return 'strftime(\'%d\','.$date.')';
638}
639
640function pwg_db_get_dayofweek($date)
641{
642  return 'strftime(\'%w\','.$date.')';
643}
644
645function pwg_db_get_weekday($date)
646{
647  return 'strftime(\'%w\',date('.$date.',\'-1 DAY\'))';
648}
649
650function pwg_db_date_to_ts($date) 
651{
652  return 'UNIX_TIMESTAMP('.$date.')';
653}
654
655// my_error returns (or send to standard output) the message concerning the
656// error occured for the last mysql query.
657function my_error($header, $die)
658{
659  global $pwg_db_link;
660
661  $error = '';
662  if (isset($pwg_db_link)) 
663  {
664    $error .= '[sqlite error]'.$pwg_db_link->errorInfo()."\n";
665  }
666
667  $error .= $header;
668
669  if ($die)
670  {
671    fatal_error($error);
672  }
673  echo("<pre>");
674  trigger_error($error, E_USER_WARNING);
675  echo("</pre>");
676}
677
678// sqlite create functions
679function pwg_now()
680{
681  return date('Y-m-d H:i:s');
682}
683
684function pwg_unix_timestamp()
685{
686  return time();
687}
688
689function pwg_if($expression, $value1, $value2) 
690{
691  if ($expression)
692  {
693    return $value1;
694  }
695  else
696  {
697    return $value2;
698  }
699} 
700
701function pwg_regexp($pattern, $string)
702{
703  $pattern = sprintf('`%s`', $pattern);
704  return preg_match($pattern, $string);
705}
706?>
Note: See TracBrowser for help on using the repository browser.