source: extensions/GrumPluginClasses/classes/GPCTables.class.inc.php @ 8992

Last change on this file since 8992 was 8992, checked in by grum, 13 years ago

release 3.4.0
review create table statement

  • Property svn:executable set to *
File size: 12.0 KB
Line 
1<?php
2
3/* -----------------------------------------------------------------------------
4  class name: GPCTables
5  class version: 1.5
6  date: 2010-03-28
7  ------------------------------------------------------------------------------
8  author: grum at piwigo.org
9  << May the Little SpaceFrog be with you >>
10  ------------------------------------------------------------------------------
11
12  this class provides base functions to manage tables while plugin installation
13    - constructor GPCTables($tables)
14    - (public) function create($tables_def)
15    - (public) function updateTablesFields($tables_alteration)
16    - (public) function drop()
17    - (public) function rename($list)  -v1.1
18    - (public) function exists()  -v1.1
19    - (public) function export($filename, $options, $tables, $infos)  -v1.3
20    - (public) function multi_queries($queries)  -v1.3
21    - (public) function import($filename)  -v1.3
22
23  ------------------------------------------------------------------------------
24  v1.1              + add rename($list) function
25                    + add exists() function
26  v1.2              + add export($filename, $options, $tables) function
27  v1.3              + modify export($filename, $options, $tables, $infos, $resultboolean) function
28                        + new parameters '$infos' allows to add some information on the
29                          exported file
30                        + add 'delete' and 'colnames' options
31                        + $resultbooelan option for return
32                    + add multi_queries($queries) function
33                    + add import($filename) function
34  v1.4 - 2009-03-01 + PHP5 migration (use of public/protected/private)
35                    + export => DROP TABLE IF EXISTS
36                    + import => if DROP TABLE without IF EXISTS, add IF EXISTS
37  v1.5 - 2010-03-28 + Uses piwigo pwg_db_* functions instead of mysql_* functions
38
39   -------------------------------------------------------------------------- */
40class GPCTables
41{
42  public $tables;    //array of tables names
43  public $version = "1.5";
44
45  public function __construct($tables)
46  {
47    $this->tables = $tables;
48  }
49
50  public function __destruct()
51  {
52    unset($this->tables);
53    unset($this->version);
54  }
55
56
57  /*
58      create tables
59      $tables_def is an array of SQL CREATE queries
60
61      return true if everything is ok, otherwise tablename
62  */
63  public function create($tables_def)
64  {
65    //deleting tables if exists
66
67    $this->drop($tables_def);
68
69    for($i=0;$i<count($tables_def);$i++)
70    {
71      $result=pwg_query($tables_def[$i]);
72      if(!$result)
73      {
74        //if an error occurs, deleting created tables
75        $this->drop();
76        return(false);
77      }
78    }
79    return(true);
80  }
81
82  /* update tables definition
83     $tables_alteration : array of arrays
84      example :
85      $tables_alteration['table1']=array(
86        "attribute1" => " ADD COLUMN `attribute1` text null default ''",
87        "attribute2" => " ADD COLUMN `attribute2` text null default ''"));
88      $tables_alteration['table2']=array(
89        "attribute1" => " ADD COLUMN `attribute1` text null default ''",
90        "attribute2" => " ADD COLUMN `attribute2` text null default ''"));
91
92      return true if no error, otherwise return table.fields of error
93  */
94  public function updateTablesFields($tables_alteration)
95  {
96    if(!is_array($tables_alteration))
97    {
98      return('');
99    }
100
101    reset($tables_alteration);
102    while (list($key, $val) = each($tables_alteration))
103    {
104      $sql="SHOW COLUMNS FROM $key";
105      $result=pwg_query($sql);
106      if($result)
107      {
108        $columns=array();
109        while($row=pwg_db_fetch_assoc($result))
110        {
111          array_push($columns, $row['Field']);
112        }
113
114        reset($val);
115        while (list($attname, $sql) = each($val))
116        {
117          if(!in_array($attname, $columns))
118          {
119            $result=pwg_query("ALTER TABLE `$key` ".$sql);
120            if(!$result)
121            {
122              return($key.".".$attname);
123            }
124          }
125        }
126      }
127    }
128    return(true);
129  }
130
131
132  /*
133      delete tables listed in $this->tables_list
134  */
135  public function drop($list=array())
136  {
137    if(count($list)==0) $list=$this->tables;
138    foreach($list as $key => $table_name)
139    {
140      $sql="DROP TABLE IF EXISTS ".$table_name;
141      $result=pwg_query($sql);
142    }
143  }
144
145  /*
146      rename tables name of list
147        $list is an array('old_name' => 'new_name')
148      return true if ok, else old table name
149  */
150  public function rename($list)
151  {
152    $tmplist=array_flip($this->tables);
153    foreach($list as $key => $val)
154    {
155      if(isset($tmplist[$key]))
156      {
157        $this->tables[$tmplist[$key]] = $val;
158        $sql="ALTER TABLE `$key` RENAME TO `$val`";
159        if(!pwg_query($sql))
160        {
161          return($key);
162        }
163      }
164      else
165      {
166        return($key);
167      }
168    }
169    return(true);
170  }
171
172  /*
173    return true if all listed tables exists
174  */
175  public function exists()
176  {
177    $list=array_flip($this->tables);
178    $sql="SHOW TABLES";
179    $result=pwg_query($sql);
180    if($result)
181    {
182      while($row=pwg_db_fetch_row($result))
183      {
184        if(isset($list[$row[0]]))
185        {
186          array_splice($list, $row[0],1);
187        }
188      }
189    }
190    if(count($list)>0)
191    {
192      return(false);
193    }
194    else
195    {
196      return(true);
197    }
198  }
199
200  /*
201    export all tables as SQL in a text file
202
203    each query end with a " -- EOQ" ; it's just a method to increase parsing for
204    import function
205
206      $filename : name of the file
207      $options : array of options like
208                    array(
209                      'drop' => true/false,  //add DROP TABLE statements
210                      'create' => true/false,  //add CREATE TABLE statements
211                      'insert' => true/false,  //add INSERT statements
212                      'delete' => true/false, //add delete statements
213                      'colnames' => true/false, //add columns names for inserts statements
214                    )
215      $tables : array of tables names to export
216                    array('tablename1', 'tablenamen', 'tablename3', ...)
217                  if empty, assume that all tables have to be exported
218      $infos : additional info written in exported file (as comment)
219      $resultboolean : if true, result is true/false ;
220                       if false, if result, return a string with nfo about export
221  */
222  public function export($filename, $options=array(), $tables=array(), $infos="", $resultboolean=true)
223  {
224    $defaultopt=array(
225      'drop' => true,
226      'create' => true,
227      'insert' => true,
228      'delete' => false,
229      'colnames' => false
230    );
231
232    if(!isset($options['drop']))
233    {
234      $options['drop']=$defaultopt['drop'];
235    }
236    if(!isset($options['create']))
237    {
238      $options['create']=$defaultopt['create'];
239    }
240    if(!isset($options['insert']))
241    {
242      $options['insert']=$defaultopt['insert'];
243    }
244    if(!isset($options['delete']))
245    {
246      $options['delete']=$defaultopt['delete'];
247    }
248    if(!isset($options['colnames']))
249    {
250      $options['colnames']=$defaultopt['colnames'];
251    }
252    if(count($tables)==0)
253    {
254      $tables=$this->tables;
255    }
256
257    $resultnfo='';
258
259    $returned=true;
260    $text='
261-- ***************************************************************              -- EOQ
262-- * SQL export made with Grum Plugins Classes (Export tool r'.$this->version.')         -- EOQ
263-- * Export date    :'.date('Y-m-d H:i:s').'                                    -- EOQ
264-- * Export options :';
265if($options['drop']){$text.=' [drop]';}
266if($options['delete']){$text.=' [delete]';}
267if($options['create']){$text.=' [create]';}
268if($options['insert']){$text.=' [insert]';}
269if($options['colnames']){$text.=' [colnames]';}
270$text.="                            -- EOQ";
271if($infos!="")
272{
273  $text.='
274-- * '.$infos." -- EOQ";
275}
276$text.='
277-- ***************************************************************              -- EOQ
278
279';
280    foreach($tables as $key => $val)
281    {
282      $countelems=0;
283
284      $text.="
285
286-- ***************************************************************              -- EOQ
287-- * Statements for ".$this->tables[$key]." table                               -- EOQ
288-- ***************************************************************              -- EOQ
289";
290
291      if($options['drop'])
292      {
293        $text.=sprintf("DROP TABLE IF EXISTS `%s`; -- EOQ\n", $this->tables[$key]);
294      }
295
296      if($options['delete'])
297      {
298        $text.=sprintf("DELETE FROM `%s`; -- EOQ\n", $this->tables[$key]);
299      }
300
301      if($options['create'])
302      {
303        $sql='SHOW CREATE TABLE '.$this->tables[$key];
304        $result=pwg_query($sql);
305        if($result)
306        {
307          while($row=pwg_db_fetch_row($result))
308          {
309            $text.=sprintf("%s; -- EOQ\n", $row[1]);
310          }
311        }
312        else
313        {
314          $returned=false;
315        }
316      }
317
318      if($options['insert'])
319      {
320        $colnames="";
321        if($options['colnames'])
322        {
323          $sql='SHOW COLUMNS FROM `'.$this->tables[$key].'`';
324          $result=pwg_query($sql);
325          if($result)
326          {
327            $tmp=array();
328            while($row=pwg_db_fetch_row($result))
329            {
330              $tmp[]=$row[0];
331            }
332          }
333          $colnames='('.implode(',', $tmp).')';
334        }
335
336        $sql='SELECT * FROM '.$this->tables[$key];
337        $result=pwg_query($sql);
338        if($result)
339        {
340          while($row=pwg_db_fetch_row($result))
341          {
342            foreach($row as $key2 => $val2)
343            {
344              $row[$key2]="'".addslashes($val2)."'";
345            }
346            $text.=sprintf("INSERT INTO `%s` %s VALUES(%s); -- EOQ\n", $this->tables[$key], $colnames, implode(', ', $row));
347            $countelems++;
348          }
349        }
350        else
351        {
352          $returned=false;
353        }
354        $resultnfo.=$key.':'.$countelems.'@';
355      }
356    }
357    $fhandle=fopen($filename, 'wb');
358    if($fhandle)
359    {
360      fwrite($fhandle, $text);
361      fclose($fhandle);
362    }
363    else
364    {
365      $returned=false;
366    }
367    if(($resultboolean==false)&&($returned))
368    {
369      $returned=$resultnfo;
370    }
371    return($returned);
372  }
373
374  /*
375    import an .sql file
376      $filename : name of the file
377      'errors' : -1 file don't exists
378                 -2 can't open file
379  */
380  public function import($filename)
381  {
382    $return = array(
383      'numinsert'=>0,
384      'numdelete'=>0,
385      'numdrop'=>0,
386      'numcreate'=>0,
387      'errors'=>array(),
388      'total_ok'=>0
389    );
390
391    if(file_exists($filename))
392    {
393      $fhandle=fopen($filename, 'r');
394      if($fhandle)
395      {
396        $queries=fread($fhandle, filesize($filename));
397        fclose($fhandle);
398        $return=$this->multi_queries($queries);
399      }
400      else
401      {
402        $return['errors']=-2;
403      }
404    }
405    else
406    {
407      $return['errors']=-1;
408    }
409    return($return);
410  }
411
412  /*
413    execute multiple query
414      each query have to be separated by a "-- EOQ\n"
415
416      $queries : sql queries
417  */
418  public function multi_queries($queries)
419  {
420    $queries_list=preg_split(
421      '/\s*;?\s*--\s+EOQ[\r\n]{1}/i', $queries, -1, PREG_SPLIT_NO_EMPTY);
422
423    $return = array(
424      'numinsert'=>0,
425      'numdelete'=>0,
426      'numdrop'=>0,
427      'numcreate'=>0,
428      'errors'=>array(),
429      'total_ok'=>0
430    );
431
432    $i=0;
433    foreach($queries_list as $key => $sql)
434    {
435      $i++;
436
437      // replace " DROP TABLE `xxxx`; " by " DROP TABLE IF EXISTS `xxxx`; "
438      $sql=preg_replace("/(.*DROP TABLE)\s*(`.*)/i", "$1 IF EXISTS $2", $sql);
439
440      @$result=pwg_query($sql);
441      if($result)
442      {
443        $return['total_ok']++;
444        if(preg_match('/\b[\s]*insert[\s]+/i', $sql)>0)
445        {$return['numinsert']++;}
446        elseif(preg_match('/\b[\s]*drop[\s]+/i', $sql)>0)
447        {$return['numdrop']++;}
448        elseif(preg_match('/\b[\s]*delete[\s]+/i', $sql)>0)
449        {$return['numdelete']++;}
450        elseif(preg_match('/\b[\s]*create[\s]+/i',$sql)>0)
451        {$return['numcreate']++;}
452      }
453      else
454      {
455        array_push($return['errors'], '['.$i.'] '.$sql);
456      }
457    }
458    return($return);
459  }
460
461} //class
462
463
464?>
Note: See TracBrowser for help on using the repository browser.