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

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

Feature 1559 : remove custom function (std) for sqlite

File size: 12.0 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_charset() 
59{
60  return true;
61}
62
63function pwg_get_db_version() 
64{
65  global $pwg_db_link;
66
67  return $pwg_db_link->getAttribute(PDO::ATTR_SERVER_VERSION);
68}
69
70function pwg_query($query)
71{
72  global $conf,$page,$debug,$t2,$pwg_db_link;
73
74  $start = get_moment();
75
76  $truncate_pattern = '`truncate(.*)`i';
77  $insert_pattern = '`(INSERT INTO [^)]*\)\s*VALUES)(\([^)]*\))\s*,\s*(.*)`mi'; 
78
79  if (preg_match($truncate_pattern, $query, $matches))
80  {
81    $query = str_replace('TRUNCATE TABLE', 'DELETE FROM', $query);
82    $truncate_query = true;
83    ($result = $pwg_db_link->exec($query)) or die($query."\n<br>".$pwg_db_link->errorInfo());
84  }
85  elseif (preg_match($insert_pattern, $query, $matches))
86  {
87    $base_query = substr($query, 0, strlen($matches[1])+1);
88    $values_pattern = '`\)\s*,\s*\(`';
89    $values = preg_split($values_pattern, substr($query, strlen($matches[1])+1));
90    $values[0] = substr($values[0], 1);
91    $values[count($values)-1] = substr($values[count($values)-1], 
92                                     0, 
93                                     strlen($values[count($values)-1])-1
94                                     );
95    for ($n=0;$n<count($values);$n++)
96    {
97      $query = $base_query . '('. $values[$n] . ")\n;";
98      ($result = $pwg_db_link->query($query)) 
99        or die($query."\n<br>".$pwg_db_link->lastErrorMsg());
100    }
101  }
102  else 
103  {
104    ($result = $pwg_db_link->query($query)) 
105      or die($query."\n<br>".$pwg_db_link->errorInfo());
106  }
107
108  $time = get_moment() - $start;
109
110  if (!isset($page['count_queries']))
111  {
112    $page['count_queries'] = 0;
113    $page['queries_time'] = 0;
114  }
115
116  $page['count_queries']++;
117  $page['queries_time']+= $time;
118
119  if ($conf['show_queries'])
120  {
121    $output = '';
122    $output.= '<pre>['.$page['count_queries'].'] ';
123    $output.= "\n".$query;
124    $output.= "\n".'(this query time : ';
125    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
126    $output.= "\n".'(total SQL time  : ';
127    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
128    $output.= "\n".'(total time      : ';
129    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
130    if ( $result!=null and preg_match('/\s*SELECT\s+/i',$query) )
131    {
132      $output.= "\n".'(num rows        : ';
133      $output.= pwg_db_num_rows($result).' )';
134    }
135    elseif ( $result!=null
136      and preg_match('/\s*INSERT|UPDATE|REPLACE|DELETE\s+/i',$query) 
137      and !isset($truncate_query))
138    {
139      $output.= "\n".'(affected rows   : ';
140      $output.= pwg_db_changes($result).' )';
141    }
142    $output.= "</pre>\n";
143
144    $debug .= $output;
145  }
146
147  return $result;
148}
149
150function pwg_db_nextval($column, $table)
151{
152  $query = '
153SELECT MAX('.$column.')+1
154  FROM '.$table;
155  list($next) = pwg_db_fetch_row(pwg_query($query));
156  if (is_null($next))
157  {
158    $next = 1;
159  }
160  return $next;
161}
162
163/**
164 *
165 * complex functions
166 *
167 */
168
169function pwg_db_changes(PDOStatement $result=null) 
170{
171  return $result->rowCount();
172}
173
174function pwg_db_num_rows(PDOStatement $result) 
175{ 
176  return $result->rowCount();
177}
178
179function pwg_db_fetch_assoc($result)
180{
181  return $result->fetch(PDO::FETCH_ASSOC);
182}
183
184function pwg_db_fetch_row($result)
185{
186  return $result->fetch(PDO::FETCH_NUM);
187}
188
189function pwg_db_fetch_object($result)
190{
191  return $result;
192}
193
194function pwg_db_free_result($result) 
195{
196}
197
198function pwg_db_real_escape_string($s)
199{
200  global $pwg_db_link;
201
202  return trim($pwg_db_link->quote($s), "'");
203}
204
205function pwg_db_insert_id($table=null, $column='id')
206{
207  global $pwg_db_link;
208
209  return $pwg_db_link->lastInsertRowID();
210}
211
212/**
213 *
214 * complex functions
215 *
216 */
217
218/**
219 * creates an array based on a query, this function is a very common pattern
220 * used here
221 *
222 * @param string $query
223 * @param string $fieldname
224 * @return array
225 */
226function array_from_query($query, $fieldname)
227{
228  $array = array();
229
230  $result = pwg_query($query);
231  while ($row = pwg_db_fetch_assoc($result))
232  {
233    array_push($array, $row[$fieldname]);
234  }
235
236  return $array;
237}
238
239define('MASS_UPDATES_SKIP_EMPTY', 1);
240/**
241 * updates multiple lines in a table
242 *
243 * @param string table_name
244 * @param array dbfields
245 * @param array datas
246 * @param int flags - if MASS_UPDATES_SKIP_EMPTY - empty values do not overwrite existing ones
247 * @return void
248 */
249function mass_updates($tablename, $dbfields, $datas, $flags=0)
250{
251  if (count($datas) == 0)
252    return;
253
254  foreach ($datas as $data)
255  {
256    $query = '
257UPDATE '.$tablename.'
258  SET ';
259    $is_first = true;
260    foreach ($dbfields['update'] as $key)
261    {
262      $separator = $is_first ? '' : ",\n    ";
263     
264      if (isset($data[$key]) and $data[$key] != '')
265      {
266        $query.= $separator.$key.' = \''.$data[$key].'\'';
267      }
268      else
269      {
270        if ($flags & MASS_UPDATES_SKIP_EMPTY )
271          continue; // next field
272        $query.= "$separator$key = NULL";
273      }
274      $is_first = false;
275    }
276    if (!$is_first)
277    {// only if one field at least updated
278      $query.= '
279  WHERE ';
280      $is_first = true;
281      foreach ($dbfields['primary'] as $key)
282      {
283        if (!$is_first)
284        {
285          $query.= ' AND ';
286        }
287        if ( isset($data[$key]) )
288        {
289          $query.= $key.' = \''.$data[$key].'\'';
290        }
291        else
292        {
293          $query.= $key.' IS NULL';
294        }
295        $is_first = false;
296      }
297      pwg_query($query);
298    }
299  }
300}
301
302
303/**
304 * inserts multiple lines in a table
305 *
306 * @param string table_name
307 * @param array dbfields
308 * @param array inserts
309 * @return void
310 */
311
312function mass_inserts($table_name, $dbfields, $datas)
313{
314  if (count($datas) != 0)
315  {
316    $first = true;
317
318    $packet_size = 16777216;
319    $packet_size = $packet_size - 2000; // The last list of values MUST not exceed 2000 character*/
320    $query = '';
321
322    foreach ($datas as $insert)
323    {
324      if (strlen($query) >= $packet_size)
325      {
326        pwg_query($query);
327        $first = true;
328      }
329
330      if ($first)
331      {
332        $query = '
333INSERT INTO '.$table_name.'
334  ('.implode(',', $dbfields).')
335  VALUES';
336        $first = false;
337      }
338      else
339      {
340        $query .= '
341  , ';
342      }
343
344      $query .= '(';
345      foreach ($dbfields as $field_id => $dbfield)
346      {
347        if ($field_id > 0)
348        {
349          $query .= ',';
350        }
351
352        if (!isset($insert[$dbfield]) or $insert[$dbfield] === '')
353        {
354          $query .= 'NULL';
355        }
356        else
357        {
358          $query .= "'".$insert[$dbfield]."'";
359        }
360      }
361      $query .= ')';
362    }
363    pwg_query($query);
364  }
365}
366
367/**
368 * Do maintenance on all PWG tables
369 *
370 * @return none
371 */
372function do_maintenance_all_tables()
373{
374  global $prefixeTable, $page;
375
376  $all_tables = array();
377
378  // List all tables
379  $query = 'SELECT name FROM SQLITE_MASTER
380WHERE name LIKE \''.$prefixeTable.'%\'';
381
382  $all_tables = array_from_query($query, 'name');
383  foreach ($all_tables as $table_name)
384  {
385    $query = 'VACUUM '.$table_name.';';
386    $result = pwg_query($query);
387  }
388 
389  array_push($page['infos'],
390             l10n('All optimizations have been successfully completed.')
391             );
392}
393
394function pwg_db_concat($array)
395{
396  return implode($array, ' || ');
397}
398
399function pwg_db_concat_ws($array, $separator)
400{
401  $glue = sprintf(' || \'%s\' || ', $separator);
402
403  return implode($array, $glue);
404}
405
406function pwg_db_cast_to_text($string)
407{
408  return $string;
409}
410
411/**
412 * returns an array containing the possible values of an enum field
413 *
414 * @param string tablename
415 * @param string fieldname
416 */
417function get_enums($table, $field)
418{
419  return array();
420}
421
422// get_boolean transforms a string to a boolean value. If the string is
423// "false" (case insensitive), then the boolean value false is returned. In
424// any other case, true is returned.
425function get_boolean( $string )
426{
427  $boolean = true;
428  if ('f' === $string || 'false' === $string)
429  {
430    $boolean = false;
431  }
432  return $boolean;
433}
434
435/**
436 * returns boolean string 'true' or 'false' if the given var is boolean
437 *
438 * @param mixed $var
439 * @return mixed
440 */
441function boolean_to_string($var)
442{
443  if (!empty($var) && ($var == 'true'))
444  {
445    return 'true';
446  }
447  else
448  {
449    return 'false';
450  }
451}
452
453/**
454 *
455 * interval and date functions
456 *
457 */
458
459function pwg_db_get_recent_period_expression($period, $date='CURRENT_DATE')
460{
461  if ($date!='CURRENT_DATE')
462  {
463    $date = '\''.$date.'\'';
464  }
465
466  return 'date('.$date.',\''.-$period.' DAY\')';
467}
468
469function pwg_db_get_recent_period($period, $date='CURRENT_DATE')
470{
471  $query = 'select '.pwg_db_get_recent_period_expression($period, $date);
472  list($d) = pwg_db_fetch_row(pwg_query($query));
473
474  return $d;
475}
476
477function pwg_db_get_date_YYYYMM($date)
478{
479  return 'strftime(\'%Y%m\','.$date.')';
480}
481
482function pwg_db_get_date_MMDD($date)
483{
484  return 'strftime(\'%m%d\','.$date.')';
485}
486
487function pwg_db_get_year($date)
488{
489  return 'strftime(\'%Y\','.$date.')';
490}
491
492function pwg_db_get_month($date)
493{
494  return 'strftime(\'%m\','.$date.')';
495}
496
497function pwg_db_get_week($date, $mode=null)
498{
499  return 'strftime(\'%W\','.$date.')';
500}
501
502function pwg_db_get_dayofmonth($date)
503{
504  return 'strftime(\'%d\','.$date.')';
505}
506
507function pwg_db_get_dayofweek($date)
508{
509  return 'strftime(\'%w\','.$date.')';
510}
511
512function pwg_db_get_weekday($date)
513{
514  return 'strftime(\'%w\',date('.$date.',\'-1 DAY\'))';
515}
516
517// my_error returns (or send to standard output) the message concerning the
518// error occured for the last mysql query.
519function my_error($header, $die)
520{
521  global $pwg_db_link;
522
523  $error = '';
524  if (isset($pwg_db_link)) 
525  {
526    $error .= '[sqlite error]'.$pwg_db_link->errorInfo()."\n";
527  }
528
529  $error .= $header;
530
531  if ($die)
532  {
533    fatal_error($error);
534  }
535  echo("<pre>");
536  trigger_error($error, E_USER_WARNING);
537  echo("</pre>");
538}
539
540// sqlite create functions
541function pwg_now()
542{
543  return date('Y-m-d H:i:s');
544}
545
546function pwg_unix_timestamp()
547{
548  return time();
549}
550
551function pwg_if($expression, $value1, $value2) 
552{
553  if ($expression)
554  {
555    return $value1;
556  }
557  else
558  {
559    return $value2;
560  }
561} 
562
563function pwg_regexp($pattern, $string)
564{
565  $pattern = sprintf('`%s`', $pattern);
566  return preg_match($pattern, $string);
567}
568?>
Note: See TracBrowser for help on using the repository browser.