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