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

Last change on this file since 6090 was 6090, checked in by plg, 14 years ago

bug 1648 fixed: add the pwg_db_check_version functions for pdo-sqlite, sqlite
and pgsql, also make the $pwg_db_link global in the install_db_connect function
so that it can be used in SQLite functions.

bug fixed: with pdo-sqlite, pwg_db_num_rows always returns 0, so when
initializing user data, it tries to insert the same row twice.

File size: 12.4 KB
RevLine 
[4967]1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
[5196]5// | Copyright(C) 2008-2010 Piwigo Team                  http://piwigo.org |
[4967]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
[6090]24define('REQUIRED_PDO_SQLITE_VERSION', '3.0.0');
[4967]25define('DB_ENGINE', 'SQLite');
26
27define('DB_REGEX_OPERATOR', 'REGEXP');
28define('DB_RANDOM_FUNCTION', 'RANDOM');
29
30/**
31 *
32 * simple functions
33 *
34 */
35
[5236]36function pwg_db_connect($host, $user, $password, $database)
[4967]37{
38  global $conf;
39
40  $db_file = sprintf('sqlite:%s/%s.db', $conf['local_data_dir'], $database);
41
[5236]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');
[4967]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
[6090]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
[4967]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{ 
[5452]191  return $result->rowCount();
[4967]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'],
[5036]405             l10n('All optimizations have been successfully completed.')
[4967]406             );
407}
408
409function pwg_db_concat($array)
410{
411  return implode($array, ' || ');
412}
413
414function pwg_db_concat_ws($array, $separator)
415{
416  $glue = sprintf(' || \'%s\' || ', $separator);
417
418  return implode($array, $glue);
419}
420
421function pwg_db_cast_to_text($string)
422{
423  return $string;
424}
425
426/**
427 * returns an array containing the possible values of an enum field
428 *
429 * @param string tablename
430 * @param string fieldname
431 */
432function get_enums($table, $field)
433{
434  return array();
435}
436
437// get_boolean transforms a string to a boolean value. If the string is
438// "false" (case insensitive), then the boolean value false is returned. In
439// any other case, true is returned.
440function get_boolean( $string )
441{
442  $boolean = true;
443  if ('f' === $string || 'false' === $string)
444  {
445    $boolean = false;
446  }
447  return $boolean;
448}
449
450/**
451 * returns boolean string 'true' or 'false' if the given var is boolean
452 *
453 * @param mixed $var
454 * @return mixed
455 */
456function boolean_to_string($var)
457{
458  if (!empty($var) && ($var == 'true'))
459  {
460    return 'true';
461  }
462  else
463  {
464    return 'false';
465  }
466}
467
468/**
469 *
470 * interval and date functions
471 *
472 */
473
474function pwg_db_get_recent_period_expression($period, $date='CURRENT_DATE')
475{
476  if ($date!='CURRENT_DATE')
477  {
478    $date = '\''.$date.'\'';
479  }
480
481  return 'date('.$date.',\''.-$period.' DAY\')';
482}
483
484function pwg_db_get_recent_period($period, $date='CURRENT_DATE')
485{
486  $query = 'select '.pwg_db_get_recent_period_expression($period, $date);
487  list($d) = pwg_db_fetch_row(pwg_query($query));
488
489  return $d;
490}
491
492function pwg_db_get_date_YYYYMM($date)
493{
494  return 'strftime(\'%Y%m\','.$date.')';
495}
496
497function pwg_db_get_date_MMDD($date)
498{
499  return 'strftime(\'%m%d\','.$date.')';
500}
501
502function pwg_db_get_year($date)
503{
504  return 'strftime(\'%Y\','.$date.')';
505}
506
507function pwg_db_get_month($date)
508{
509  return 'strftime(\'%m\','.$date.')';
510}
511
512function pwg_db_get_week($date, $mode=null)
513{
514  return 'strftime(\'%W\','.$date.')';
515}
516
517function pwg_db_get_dayofmonth($date)
518{
519  return 'strftime(\'%d\','.$date.')';
520}
521
522function pwg_db_get_dayofweek($date)
523{
524  return 'strftime(\'%w\','.$date.')';
525}
526
527function pwg_db_get_weekday($date)
528{
529  return 'strftime(\'%w\',date('.$date.',\'-1 DAY\'))';
530}
531
532// my_error returns (or send to standard output) the message concerning the
533// error occured for the last mysql query.
534function my_error($header, $die)
535{
536  global $pwg_db_link;
537
538  $error = '';
539  if (isset($pwg_db_link)) 
540  {
541    $error .= '[sqlite error]'.$pwg_db_link->errorInfo()."\n";
542  }
543
544  $error .= $header;
545
546  if ($die)
547  {
548    fatal_error($error);
549  }
550  echo("<pre>");
551  trigger_error($error, E_USER_WARNING);
552  echo("</pre>");
553}
554
555// sqlite create functions
556function pwg_now()
557{
558  return date('Y-m-d H:i:s');
559}
560
561function pwg_unix_timestamp()
562{
563  return time();
564}
565
566function pwg_if($expression, $value1, $value2) 
567{
568  if ($expression)
569  {
570    return $value1;
571  }
572  else
573  {
574    return $value2;
575  }
576} 
577
578function pwg_regexp($pattern, $string)
579{
580  $pattern = sprintf('`%s`', $pattern);
581  return preg_match($pattern, $string);
582}
583?>
Note: See TracBrowser for help on using the repository browser.