source: trunk/include/dblayer/functions_mysql.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: 16.6 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('DB_ENGINE', 'MySQL');
25define('REQUIRED_MYSQL_VERSION', '5.0.0');
26
27define('DB_REGEX_OPERATOR', 'REGEXP');
28define('DB_RANDOM_FUNCTION', 'RAND');
29
30/**
31 *
32 * simple functions
33 *
34 */
35
36function pwg_db_connect($host, $user, $password, $database)
37{ 
38  $link = @mysql_connect($host, $user, $password);
39  if (!$link)
40  {
41    throw new Exception("Can't connect to server");
42  }
43  if (mysql_select_db($database, $link))
44  {
45    return $link;
46  }
47  else
48  {
49    throw new Exception('Connection to server succeed, but it was impossible to connect to database');
50  }
51}
52
53function pwg_db_check_charset() 
54{
55  $db_charset = 'utf8';
56  if (defined('DB_CHARSET') and DB_CHARSET != '')
57  {
58    $db_charset = DB_CHARSET;
59  }
60  pwg_query('SET NAMES "'.$db_charset.'"');
61}
62
63function pwg_db_check_version()
64{
65  $current_mysql = pwg_get_db_version();
66  if (version_compare($current_mysql, REQUIRED_MYSQL_VERSION, '<'))
67  {
68    fatal_error(
69      sprintf(
70        'your MySQL version is too old, you have "%s" and you need at least "%s"',
71        $current_mysql,
72        REQUIRED_MYSQL_VERSION
73        )
74      );
75  }
76}
77
78function pwg_get_db_version() 
79{
80  return mysql_get_server_info();
81}
82
83function pwg_query($query)
84{
85  global $conf,$page,$debug,$t2;
86
87  $start = get_moment();
88  ($result = mysql_query($query)) or my_error($query, $conf['die_on_sql_error']);
89
90  $time = get_moment() - $start;
91
92  if (!isset($page['count_queries']))
93  {
94    $page['count_queries'] = 0;
95    $page['queries_time'] = 0;
96  }
97
98  $page['count_queries']++;
99  $page['queries_time']+= $time;
100
101  if ($conf['show_queries'])
102  {
103    $output = '';
104    $output.= '<pre>['.$page['count_queries'].'] ';
105    $output.= "\n".$query;
106    $output.= "\n".'(this query time : ';
107    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
108    $output.= "\n".'(total SQL time  : ';
109    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
110    $output.= "\n".'(total time      : ';
111    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
112    if ( $result!=null and preg_match('/\s*SELECT\s+/i',$query) )
113    {
114      $output.= "\n".'(num rows        : ';
115      $output.= mysql_num_rows($result).' )';
116    }
117    elseif ( $result!=null
118      and preg_match('/\s*INSERT|UPDATE|REPLACE|DELETE\s+/i',$query) )
119    {
120      $output.= "\n".'(affected rows   : ';
121      $output.= mysql_affected_rows().' )';
122    }
123    $output.= "</pre>\n";
124
125    $debug .= $output;
126  }
127
128  return $result;
129}
130
131function pwg_db_nextval($column, $table)
132{
133  $query = '
134SELECT IF(MAX('.$column.')+1 IS NULL, 1, MAX('.$column.')+1)
135  FROM '.$table;
136  list($next) = pwg_db_fetch_row(pwg_query($query));
137
138  return $next;
139}
140
141function pwg_db_changes($result) 
142{
143  return mysql_affected_rows();
144}
145
146function pwg_db_num_rows($result) 
147{
148  return mysql_num_rows($result);
149}
150
151function pwg_db_fetch_assoc($result)
152{
153  return mysql_fetch_assoc($result);
154}
155
156function pwg_db_fetch_row($result)
157{
158  return mysql_fetch_row($result);
159}
160
161function pwg_db_fetch_object($result)
162{
163  return mysql_fetch_object($result);
164}
165
166function pwg_db_free_result($result) 
167{
168  return mysql_free_result($result);
169}
170
171function pwg_db_real_escape_string($s)
172{
173  return mysql_real_escape_string($s);
174}
175
176function pwg_db_insert_id($table=null, $column='id')
177{
178  return mysql_insert_id();
179}
180
181/**
182 *
183 * complex functions
184 *
185 */
186
187/**
188 * creates an array based on a query, this function is a very common pattern
189 * used here
190 *
191 * @param string $query
192 * @param string $fieldname
193 * @return array
194 */
195function array_from_query($query, $fieldname)
196{
197  $array = array();
198
199  $result = pwg_query($query);
200  while ($row = mysql_fetch_assoc($result))
201  {
202    array_push($array, $row[$fieldname]);
203  }
204
205  return $array;
206}
207
208define('MASS_UPDATES_SKIP_EMPTY', 1);
209/**
210 * updates multiple lines in a table
211 *
212 * @param string table_name
213 * @param array dbfields
214 * @param array datas
215 * @param int flags - if MASS_UPDATES_SKIP_EMPTY - empty values do not overwrite existing ones
216 * @return void
217 */
218function mass_updates($tablename, $dbfields, $datas, $flags=0)
219{
220  if (count($datas) == 0)
221    return;
222 
223  // depending on the MySQL version, we use the multi table update or N update queries
224  if (count($datas) < 10)
225  {
226    foreach ($datas as $data)
227    {
228      $query = '
229UPDATE '.$tablename.'
230  SET ';
231      $is_first = true;
232      foreach ($dbfields['update'] as $key)
233      {
234        $separator = $is_first ? '' : ",\n    ";
235
236        if (isset($data[$key]) and $data[$key] != '')
237        {
238          $query.= $separator.$key.' = \''.$data[$key].'\'';
239        }
240        else
241        {
242          if ( $flags & MASS_UPDATES_SKIP_EMPTY )
243            continue; // next field
244          $query.= "$separator$key = NULL";
245        }
246        $is_first = false;
247      }
248      if (!$is_first)
249      {// only if one field at least updated
250        $query.= '
251  WHERE ';
252        $is_first = true;
253        foreach ($dbfields['primary'] as $key)
254        {
255          if (!$is_first)
256          {
257            $query.= ' AND ';
258          }
259          if ( isset($data[$key]) )
260          {
261            $query.= $key.' = \''.$data[$key].'\'';
262          }
263          else
264          {
265            $query.= $key.' IS NULL';
266          }
267          $is_first = false;
268        }
269        pwg_query($query);
270      }
271    } // foreach update
272  } // if mysql_ver or count<X
273  else
274  {
275    // creation of the temporary table
276    $query = '
277SHOW FULL COLUMNS FROM '.$tablename;
278    $result = pwg_query($query);
279    $columns = array();
280    $all_fields = array_merge($dbfields['primary'], $dbfields['update']);
281    while ($row = pwg_db_fetch_assoc($result))
282    {
283      if (in_array($row['Field'], $all_fields))
284      {
285        $column = $row['Field'];
286        $column.= ' '.$row['Type'];
287
288        $nullable = true;
289        if (!isset($row['Null']) or $row['Null'] == '' or $row['Null']=='NO')
290        {
291          $column.= ' NOT NULL';
292          $nullable = false;
293        }
294        if (isset($row['Default']))
295        {
296          $column.= " default '".$row['Default']."'";
297        }
298        elseif ($nullable)
299        {
300          $column.= " default NULL";
301        }
302        if (isset($row['Collation']) and $row['Collation'] != 'NULL')
303        {
304          $column.= " collate '".$row['Collation']."'";
305        }
306        array_push($columns, $column);
307      }
308    }
309
310    $temporary_tablename = $tablename.'_'.micro_seconds();
311
312    $query = '
313CREATE TABLE '.$temporary_tablename.'
314(
315  '.implode(",\n  ", $columns).',
316  UNIQUE KEY the_key ('.implode(',', $dbfields['primary']).')
317)';
318
319    pwg_query($query);
320    mass_inserts($temporary_tablename, $all_fields, $datas);
321    if ( $flags & MASS_UPDATES_SKIP_EMPTY )
322      $func_set = create_function('$s', 'return "t1.$s = IFNULL(t2.$s, t1.$s)";');
323    else
324      $func_set = create_function('$s', 'return "t1.$s = t2.$s";');
325
326    // update of images table by joining with temporary table
327    $query = '
328UPDATE '.$tablename.' AS t1, '.$temporary_tablename.' AS t2
329  SET '.
330      implode(
331        "\n    , ",
332        array_map($func_set,$dbfields['update'])
333        ).'
334  WHERE '.
335      implode(
336        "\n    AND ",
337        array_map(
338          create_function('$s', 'return "t1.$s = t2.$s";'),
339          $dbfields['primary']
340          )
341        );
342    pwg_query($query);
343    $query = '
344DROP TABLE '.$temporary_tablename;
345    pwg_query($query);
346  }
347}
348
349/**
350 * updates one line in a table
351 *
352 * @param string table_name
353 * @param array dbfields
354 * @param array data
355 * @param int flags - if MASS_UPDATES_SKIP_EMPTY - empty values do not overwrite existing ones
356 * @return void
357 */
358function single_update($tablename, $dbfields, $data, $flags=0)
359{
360  if (count($data) == 0)
361    return;
362
363  $query = '
364UPDATE '.$tablename.'
365  SET ';
366  $is_first = true;
367  foreach ($dbfields['update'] as $key)
368  {
369    $separator = $is_first ? '' : ",\n    ";
370
371    if (isset($data[$key]) and $data[$key] != '')
372    {
373      $query.= $separator.$key.' = \''.$data[$key].'\'';
374    }
375    else
376    {
377      if ( $flags & MASS_UPDATES_SKIP_EMPTY )
378        continue; // next field
379      $query.= "$separator$key = NULL";
380    }
381    $is_first = false;
382  }
383  if (!$is_first)
384  {// only if one field at least updated
385    $query.= '
386  WHERE ';
387    $is_first = true;
388    foreach ($dbfields['primary'] as $key)
389    {
390      if (!$is_first)
391      {
392        $query.= ' AND ';
393      }
394      if ( isset($data[$key]) )
395      {
396        $query.= $key.' = \''.$data[$key].'\'';
397      }
398      else
399      {
400        $query.= $key.' IS NULL';
401      }
402      $is_first = false;
403    }
404    pwg_query($query);
405  }
406}
407
408
409/**
410 * inserts multiple lines in a table
411 *
412 * @param string table_name
413 * @param array dbfields
414 * @param array inserts
415 * @return void
416 */
417function mass_inserts($table_name, $dbfields, $datas)
418{
419  if (count($datas) != 0)
420  {
421    $first = true;
422
423    $query = 'SHOW VARIABLES LIKE \'max_allowed_packet\'';
424    list(, $packet_size) = pwg_db_fetch_row(pwg_query($query));
425    $packet_size = $packet_size - 2000; // The last list of values MUST not exceed 2000 character*/
426    $query = '';
427
428    foreach ($datas as $insert)
429    {
430      if (strlen($query) >= $packet_size)
431      {
432        pwg_query($query);
433        $first = true;
434      }
435
436      if ($first)
437      {
438        $query = '
439INSERT INTO '.$table_name.'
440  ('.implode(',', $dbfields).')
441  VALUES';
442        $first = false;
443      }
444      else
445      {
446        $query .= '
447  , ';
448      }
449
450      $query .= '(';
451      foreach ($dbfields as $field_id => $dbfield)
452      {
453        if ($field_id > 0)
454        {
455          $query .= ',';
456        }
457
458        if (!isset($insert[$dbfield]) or $insert[$dbfield] === '')
459        {
460          $query .= 'NULL';
461        }
462        else
463        {
464          $query .= "'".$insert[$dbfield]."'";
465        }
466      }
467      $query .= ')';
468    }
469    pwg_query($query);
470  }
471}
472
473/**
474 * inserts on line in a table
475 *
476 * @param string table_name
477 * @param array dbfields
478 * @param array insert
479 * @return void
480 */
481function single_insert($table_name, $dbfields, $insert)
482{
483  if (count($insert) != 0)
484  {
485    $query = '
486INSERT INTO '.$table_name.'
487  ('.implode(',', $dbfields).')
488  VALUES';
489
490    $query .= '(';
491    foreach ($dbfields as $field_id => $dbfield)
492    {
493      if ($field_id > 0)
494      {
495        $query .= ',';
496      }
497      if (!isset($insert[$dbfield]) or $insert[$dbfield] === '')
498      {
499        $query .= 'NULL';
500      }
501      else
502      {
503        $query .= "'".$insert[$dbfield]."'";
504      }
505    }
506    $query .= ')';
507   
508    pwg_query($query);
509  }
510}
511
512/**
513 * Do maintenance on all PWG tables
514 *
515 * @return none
516 */
517function do_maintenance_all_tables()
518{
519  global $prefixeTable, $page;
520
521  $all_tables = array();
522
523  // List all tables
524  $query = 'SHOW TABLES LIKE \''.$prefixeTable.'%\'';
525  $result = pwg_query($query);
526  while ($row = pwg_db_fetch_row($result))
527  {
528    array_push($all_tables, $row[0]);
529  }
530
531  // Repair all tables
532  $query = 'REPAIR TABLE '.implode(', ', $all_tables);
533  $mysql_rc = pwg_query($query);
534
535  // Re-Order all tables
536  foreach ($all_tables as $table_name)
537  {
538    $all_primary_key = array();
539
540    $query = 'DESC '.$table_name.';';
541    $result = pwg_query($query);
542    while ($row = pwg_db_fetch_assoc($result))
543    {
544      if ($row['Key'] == 'PRI')
545      {
546        array_push($all_primary_key, $row['Field']);
547      }
548    }
549
550    if (count($all_primary_key) != 0)
551    {
552      $query = 'ALTER TABLE '.$table_name.' ORDER BY '.implode(', ', $all_primary_key).';';
553      $mysql_rc = $mysql_rc && pwg_query($query);
554    }
555  }
556
557  // Optimize all tables
558  $query = 'OPTIMIZE TABLE '.implode(', ', $all_tables);
559  $mysql_rc = $mysql_rc && pwg_query($query);
560  if ($mysql_rc)
561  {
562    array_push(
563          $page['infos'],
564          l10n('All optimizations have been successfully completed.')
565          );
566  }
567  else
568  {
569    array_push(
570          $page['errors'],
571          l10n('Optimizations have been completed with some errors.')
572          );
573  }
574}
575
576function pwg_db_concat($array)
577{
578  $string = implode($array, ',');
579  return 'CONCAT('. $string.')';
580}
581
582function pwg_db_concat_ws($array, $separator)
583{
584  $string = implode($array, ',');
585  return 'CONCAT_WS(\''.$separator.'\','. $string.')';
586}
587
588function pwg_db_cast_to_text($string)
589{
590  return 'CAST('.$string.' AS CHAR)';
591}
592
593/**
594 * returns an array containing the possible values of an enum field
595 *
596 * @param string tablename
597 * @param string fieldname
598 */
599function get_enums($table, $field)
600{
601  // retrieving the properties of the table. Each line represents a field :
602  // columns are 'Field', 'Type'
603  $result = pwg_query('desc '.$table);
604  while ($row = pwg_db_fetch_assoc($result))
605  {
606    // we are only interested in the the field given in parameter for the
607    // function
608    if ($row['Field'] == $field)
609    {
610      // retrieving possible values of the enum field
611      // enum('blue','green','black')
612      $options = explode(',', substr($row['Type'], 5, -1));
613      foreach ($options as $i => $option)
614      {
615        $options[$i] = str_replace("'", '',$option);
616      }
617    }
618  }
619  pwg_db_free_result($result);
620  return $options;
621}
622
623// get_boolean transforms a string to a boolean value. If the string is
624// "false" (case insensitive), then the boolean value false is returned. In
625// any other case, true is returned.
626function get_boolean( $string )
627{
628  $boolean = true;
629  if ( 'false' == strtolower($string) )
630  {
631    $boolean = false;
632  }
633  return $boolean;
634}
635
636/**
637 * returns boolean string 'true' or 'false' if the given var is boolean
638 *
639 * @param mixed $var
640 * @return mixed
641 */
642function boolean_to_string($var)
643{
644  if (is_bool($var))
645  {
646    return $var ? 'true' : 'false';
647  }
648  else
649  {
650    return $var;
651  }
652}
653
654/**
655 *
656 * interval and date functions
657 *
658 */
659
660function pwg_db_get_recent_period_expression($period, $date='CURRENT_DATE')
661{
662  if ($date!='CURRENT_DATE')
663  {
664    $date = '\''.$date.'\'';
665  }
666
667  return 'SUBDATE('.$date.',INTERVAL '.$period.' DAY)';
668}
669
670function pwg_db_get_recent_period($period, $date='CURRENT_DATE')
671{
672  $query = '
673SELECT '.pwg_db_get_recent_period_expression($period);
674  list($d) = pwg_db_fetch_row(pwg_query($query));
675
676  return $d;
677}
678
679function pwg_db_get_flood_period_expression($seconds)
680{
681  return 'SUBDATE(now(), INTERVAL '.$seconds.' SECOND)';
682}
683
684function pwg_db_get_hour($date) 
685{
686  return 'hour('.$date.')';
687}
688
689function pwg_db_get_date_YYYYMM($date)
690{
691  return 'DATE_FORMAT('.$date.', \'%Y%m\')';
692}
693
694function pwg_db_get_date_MMDD($date)
695{
696  return 'DATE_FORMAT('.$date.', \'%m%d\')';
697}
698
699function pwg_db_get_year($date)
700{
701  return 'YEAR('.$date.')';
702}
703
704function pwg_db_get_month($date)
705{
706  return 'MONTH('.$date.')';
707}
708
709function pwg_db_get_week($date, $mode=null)
710{
711  if ($mode)
712  {
713    return 'WEEK('.$date.', '.$mode.')';
714  }
715  else
716  {
717    return 'WEEK('.$date.')';
718  }
719}
720
721function pwg_db_get_dayofmonth($date)
722{
723  return 'DAYOFMONTH('.$date.')';
724}
725
726function pwg_db_get_dayofweek($date)
727{
728  return 'DAYOFWEEK('.$date.')';
729}
730
731function pwg_db_get_weekday($date)
732{
733  return 'WEEKDAY('.$date.')';
734}
735
736function pwg_db_date_to_ts($date) 
737{
738  return 'UNIX_TIMESTAMP('.$date.')';
739}
740
741// my_error returns (or send to standard output) the message concerning the
742// error occured for the last mysql query.
743function my_error($header, $die)
744{
745  $error = "[mysql error ".mysql_errno().'] '.mysql_error()."\n";
746  $error .= $header;
747
748  if ($die)
749  {
750    fatal_error($error);
751  }
752  echo("<pre>");
753  trigger_error($error, E_USER_WARNING);
754  echo("</pre>");
755}
756
757?>
Note: See TracBrowser for help on using the repository browser.