source: trunk/include/dblayer/functions_sqlite.inc.php @ 11485

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

feature:2359 add single_update and single_insert functions

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