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

Last change on this file since 6666 was 6666, checked in by nikrou, 14 years ago

Bug 1766 fixed : [PostgreSQL] unkown database function UNIX_TIMESTAMP()
Add a new function pwg_db_date_to_ts() to calculate a timestamp from a date

File size: 13.5 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_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/**
331 * inserts multiple lines in a table
332 *
333 * @param string table_name
334 * @param array dbfields
335 * @param array inserts
336 * @return void
337 */
338
339function mass_inserts($table_name, $dbfields, $datas)
340{
341  if (count($datas) != 0)
342  {
343    $first = true;
344
345    $packet_size = 16777216;
346    $packet_size = $packet_size - 2000; // The last list of values MUST not exceed 2000 character*/
347    $query = '';
348
349    foreach ($datas as $insert)
350    {
351      if (strlen($query) >= $packet_size)
352      {
353        pwg_query($query);
354        $first = true;
355      }
356
357      if ($first)
358      {
359        $query = '
360INSERT INTO '.$table_name.'
361  ('.implode(',', $dbfields).')
362  VALUES';
363        $first = false;
364      }
365      else
366      {
367        $query .= '
368  , ';
369      }
370
371      $query .= '(';
372      foreach ($dbfields as $field_id => $dbfield)
373      {
374        if ($field_id > 0)
375        {
376          $query .= ',';
377        }
378
379        if (!isset($insert[$dbfield]) or $insert[$dbfield] === '')
380        {
381          $query .= 'NULL';
382        }
383        else
384        {
385          $query .= "'".$insert[$dbfield]."'";
386        }
387      }
388      $query .= ')';
389    }
390    pwg_query($query);
391  }
392}
393
394/**
395 * Do maintenance on all PWG tables
396 *
397 * @return none
398 */
399function do_maintenance_all_tables()
400{
401  global $prefixeTable, $page;
402
403  $all_tables = array();
404
405  // List all tables
406  $query = 'SELECT name FROM SQLITE_MASTER
407WHERE name LIKE \''.$prefixeTable.'%\'';
408
409  $all_tables = array_from_query($query, 'name');
410  foreach ($all_tables as $table_name)
411  {
412    $query = 'VACUUM '.$table_name.';';
413    $result = pwg_query($query);
414  }
415 
416  array_push($page['infos'],
417             l10n('All optimizations have been successfully completed.')
418             );
419}
420
421function pwg_db_concat($array)
422{
423  return implode($array, ' || ');
424}
425
426function pwg_db_concat_ws($array, $separator)
427{
428  return implode($array, ' || \''.$separator.'\' || ');
429}
430
431function pwg_db_cast_to_text($string)
432{
433  return $string;
434}
435
436/**
437 * returns an array containing the possible values of an enum field
438 *
439 * @param string tablename
440 * @param string fieldname
441 */
442function get_enums($table, $field)
443{
444  $Enums['categories']['status'] = array('public', 'private');
445  $Enums['history']['section'] = array('categories','tags','search','list','favorites','most_visited','best_rated','recent_pics','recent_cats');
446  $Enums['user_infos']['status'] = array('webmaster','admin','normal','generic','guest');
447  $Enums['image']['type'] = array('picture','high','other');
448  $Enums['plugins']['state'] = array('active', 'inactive');
449  $Enums['user_cache_image']['access_type'] = array('NOT IN','IN');
450
451  $table = str_replace($GLOBALS['prefixeTable'], '', $table);
452  if (isset($Enums[$table][$field])) {
453    return $Enums[$table][$field];
454  } else {
455    return array();
456  }
457}
458
459// get_boolean transforms a string to a boolean value. If the string is
460// "false" (case insensitive), then the boolean value false is returned. In
461// any other case, true is returned.
462function get_boolean( $string )
463{
464  $boolean = true;
465  if ('f' === $string || 'false' === $string)
466  {
467    $boolean = false;
468  }
469  return $boolean;
470}
471
472/**
473 * returns boolean string 'true' or 'false' if the given var is boolean
474 *
475 * @param mixed $var
476 * @return mixed
477 */
478function boolean_to_string($var)
479{
480  if (is_bool($var))
481  {
482    return $var ? 'true' : 'false';
483  }
484  else
485  {
486    return $var;
487  }
488}
489
490/**
491 *
492 * interval and date functions
493 *
494 */
495
496function pwg_db_get_recent_period_expression($period, $date='CURRENT_DATE')
497{
498  if ($date!='CURRENT_DATE')
499  {
500    $date = '\''.$date.'\'';
501  }
502
503  return 'date('.$date.',\''.-$period.' DAY\')';
504}
505
506function pwg_db_get_recent_period($period, $date='CURRENT_DATE')
507{
508  $query = 'select '.pwg_db_get_recent_period_expression($period, $date);
509  list($d) = pwg_db_fetch_row(pwg_query($query));
510
511  return $d;
512}
513
514function pwg_db_get_flood_period_expression($seconds)
515{
516  return 'datetime(\'now\', \'localtime\', \''.-$seconds.' seconds\')';
517}
518
519function pwg_db_get_hour($date)
520{
521  return 'strftime(\'%H\', '.$date.')';
522}
523
524function pwg_db_get_date_YYYYMM($date)
525{
526  return 'strftime(\'%Y%m\','.$date.')';
527}
528
529function pwg_db_get_date_MMDD($date)
530{
531  return 'strftime(\'%m%d\','.$date.')';
532}
533
534function pwg_db_get_year($date)
535{
536  return 'strftime(\'%Y\','.$date.')';
537}
538
539function pwg_db_get_month($date)
540{
541  return 'strftime(\'%m\','.$date.')';
542}
543
544function pwg_db_get_week($date, $mode=null)
545{
546  return 'strftime(\'%W\','.$date.')';
547}
548
549function pwg_db_get_dayofmonth($date)
550{
551  return 'strftime(\'%d\','.$date.')';
552}
553
554function pwg_db_get_dayofweek($date)
555{
556  return 'strftime(\'%w\','.$date.')';
557}
558
559function pwg_db_get_weekday($date)
560{
561  return 'strftime(\'%w\',date('.$date.',\'-1 DAY\'))';
562}
563
564function pwg_db_date_to_ts($date) 
565{
566  return 'UNIX_TIMESTAMP('.$date.')';
567}
568
569// my_error returns (or send to standard output) the message concerning the
570// error occured for the last mysql query.
571function my_error($header, $die)
572{
573  global $pwg_db_link;
574
575  $error = '';
576  if (isset($pwg_db_link)) 
577  {
578    $error .= '[sqlite error]'.$pwg_db_link->lastErrorMsg()."\n";
579  }
580
581  $error .= $header;
582
583  if ($die)
584  {
585    fatal_error($error);
586  }
587  echo("<pre>");
588  trigger_error($error, E_USER_WARNING);
589  echo("</pre>");
590}
591
592// sqlite create functions
593function pwg_now()
594{
595  return date('Y-m-d H:i:s');
596}
597
598function pwg_unix_timestamp()
599{
600  return time();
601}
602
603function pwg_if($expression, $value1, $value2) 
604{
605  if ($expression)
606  {
607    return $value1;
608  }
609  else
610  {
611    return $value2;
612  }
613} 
614
615function pwg_regexp($pattern, $string)
616{
617  $pattern = sprintf('`%s`', $pattern);
618  return preg_match($pattern, $string);
619}
620?>
Note: See TracBrowser for help on using the repository browser.