UpdateDatabase.php
[Pman.Core] / UpdateDatabase.php
1 <?php
2
3 /**
4  *
5  * This applies database files from
6  * a) OLD - {MODULE}/DataObjects/XXXX.{dbtype}.sql
7  *
8  * b) NEW - {MODULE}/sql/XXX.sql (SHARED or translable)
9  *  and {MODULE}/{dbtype}/XXX.sql (SHARED or translable)
10  *
11  *
12  */
13
14 require_once 'Pman.php';
15 class Pman_Core_UpdateDatabase extends Pman
16 {
17     
18     static $cli_desc = "Update SQL - Beta (it will run updateData of all modules)";
19  
20     static $cli_opts = array(
21         'source' => array(
22             'desc' => 'Source directory for json files.',
23             'short' => 'f',
24             'default' => '',
25             'min' => 1,
26             'max' => 1,
27         ),
28         'prefix' => array(
29             'desc' => 'prefix for the passwrod',
30             'short' => 'p',
31             'default' => '',
32             'min' => 1,
33             'max' => 1,
34         ),
35         
36     );
37     
38     var $cli = false;
39     function getAuth() {
40         
41         
42         $ff = HTML_FlexyFramework::get();
43         if (!empty($ff->cli)) {
44             $this->cli = true;
45             return true;
46         }
47         
48         parent::getAuth(); // load company!
49         $au = $this->getAuthUser();
50         if (!$au || $au->company()->comptype != 'OWNER') {
51             $this->jerr("Not authenticated", array('authFailure' => true));
52         }
53         $this->authUser = $au;
54         return true;
55     }
56      
57     function get($args, $opt)
58     {
59         if($args == 'Person'){
60             if(empty($opt['source']) || empty($opt['prefix'])){
61                 die("Missing Source directory for person json files or prefix for the passwrod! Try -f [JSON file path] -p [prefix] \n");
62             }
63             if (!file_exists($opt['source'])) {
64                 die("can not found person json file : {$opt['source']} \n");
65             }
66             
67             $persons = json_decode(file_get_contents($source),true);
68             
69             DB_DataObject::factory('person')->importFromArray(HTML_Flexyframework::get()->page, $persons, $opt['prefix']);
70             die("DONE! \n");
71         }
72         
73         if($args == 'Account'){
74             if(empty($opt['source'])){
75                 die("Missing Source directory for account json files! Try -f [JSON file path] \n");
76             }
77             
78             DB_DataObject::factory('accnt')->importFromJson($opt['source']);
79             die("DONE! \n");
80         }
81         
82         $this->importSQL();
83         $this->runUpdateModulesData();
84          
85     }
86     function output() {
87         return '';
88     }
89      /**
90      * imports SQL files from all DataObjects directories....
91      * 
92      * except any matching /migrate/
93      */
94     function importSQL()
95     {
96         
97         $ff = HTML_Flexyframework::get();
98         
99         $url = parse_url($ff->DB_DataObject['database']);
100         
101         $this->{'import' . $url['scheme']}($url);
102         
103     }
104     
105     /**
106      * mysql - does not support conversions.
107      * 
108      *
109      */
110     
111     
112     
113     function importmysql($url)
114     {
115         
116         // hide stuff for web..
117         
118         require_once 'System.php';
119         $cat = System::which('cat');
120         $mysql = System::which('mysql');
121         
122         $ar = $this->modulesList();
123         
124            
125         $mysql_cmd = $mysql .
126             ' -h ' . $url['host'] .
127             ' -u' . escapeshellarg($url['user']) .
128             (!empty($url['pass']) ? ' -p' . escapeshellarg($url['pass'])  :  '') .
129             ' ' . basename($url['path']);
130         echo $mysql_cmd . "\n" ;
131         
132         
133         // old -- DAtaObjects/*.sql
134         
135         foreach($ar as $m) {
136             
137             $fd = $this->rootDir. "/Pman/$m/DataObjects";
138             
139             foreach(glob($fd.'/*.sql') as $fn) {
140                 
141                  
142                 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
143                     continue;
144                 }
145                 // .my.sql but not .pg.sql
146                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
147                     && !preg_match('#\.my\.sql#i', basename($fn))
148                 ) { // skip migration scripts at present..
149                     continue;
150                 }
151                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
152                 
153                 echo $cmd. ($this->cli ? "\n" : "<BR>\n");
154                 
155                 passthru($cmd);
156             
157                 
158             }
159             // new -- sql directory..
160             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
161             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
162             $fd = $this->rootDir. "/Pman/$m/sql";
163             
164             foreach(glob($fd.'/*.sql') as $fn) {
165                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
166                 echo $cmd. ($this->cli ? "\n" : "<BR>\n");
167                 passthru($cmd);
168             }
169             $fd = $this->rootDir. "/Pman/$m/mysql";
170             
171             foreach(glob($fd.'/*.sql') as $fn) {
172                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
173                 echo $cmd. ($this->cli ? "\n" : "<BR>\n");
174                 passthru($cmd);
175             }
176               
177             
178             
179             
180             
181             
182         }
183         
184         
185         
186     }
187     /**
188      * postgresql import..
189      */
190     function importpgsql($url)
191     {
192         
193         // hide stuff for web..
194         
195         require_once 'System.php';
196         $cat = System::which('cat');
197         $psql = System::which('psql');
198         
199         $ar = $this->modulesList();
200         
201         if (!empty($url['pass'])) { 
202             putenv("PGPASSWORD=". $url['pass']);
203         }
204            
205         $psql_cmd = $psql .
206             ' -h ' . $url['host'] .
207             ' -U' . escapeshellarg($url['user']) .
208              ' ' . basename($url['path']);
209         echo $psql_cmd . "\n" ;
210         
211         
212         
213         
214         foreach($ar as $m) {
215             
216             $fd = $this->rootDir. "/Pman/$m/DataObjects";
217             
218             foreach(glob($fd.'/*.sql') as $bfn) {
219                 
220                  
221                 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
222                     continue;
223                 }
224                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
225                     && !preg_match('#\.pg\.sql#i', basename($bfn))
226                 ) { // skip migration scripts at present..
227                     continue;
228                 }
229                 // files ending in .pg.sql are native postgres files..
230                 $fn = preg_match('#\.pg\.sql$#', basename($bfn)) ? false : $this->convertToPG($bfn);
231                 
232                 $cmd = "$psql_cmd  < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
233                 
234                 echo "$bfn:   $cmd ". ($this->cli ? "\n" : "<BR>\n");
235                 
236                 
237                 passthru($cmd);
238                 
239                 if ($fn) {
240                     unlink($fn);
241                 }
242             }
243             
244             
245             
246             $fd = $this->rootDir. "/Pman/$m/sql";
247             // sql directory  - we try to convert..
248             foreach(glob($fd.'/*.sql') as $bfn) {
249                 $fn =  $this->convertToPG($bfn);
250                 $cmd = "$psql_cmd  < " . escapeshellarg($fn) ;
251                 echo $cmd. ($this->cli ? "\n" : "<BR>\n");
252                 passthru($cmd);
253             }
254             
255             // postgres specific directory..
256             
257             $fd = $this->rootDir. "/Pman/$m/pgsql";
258             
259             foreach(glob($fd.'/*.sql') as $fn) {
260                 $cmd = "$psql_cmd   < " . escapeshellarg($fn) ;
261                 echo $cmd. ($this->cli ? "\n" : "<BR>\n");
262                 passthru($cmd);
263             }
264             
265             
266             
267         }
268         
269     }
270     /**
271      * simple regex based convert mysql to pgsql...
272      */
273     function convertToPG($src)
274     {
275         $fn = $this->tempName('sql');
276         
277         $ret = array( ); // pad it a bit.
278         $extra = array("", "" );
279         
280         $tbl = false;
281         foreach(file($src) as $l) {
282             $l = trim($l);
283             
284             if (!strlen($l) || $l[0] == '#') {
285                 continue;
286             }
287             $m = array();
288             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
289                 $tbl = $m[1];
290                // $extra[]  =   "drop table {$tbl};";
291              }
292             // autoinc
293             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
294                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
295                 $extra[]  =   "create sequence {$tbl}_seq;";
296               
297             }
298             $m = array();
299             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+([^(]+)(.*)$#i',  $l, $m)) {
300                $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
301              }
302             // ALTER TABLE core_event_audit ADD     INDEX looku
303             // CREATE INDEX 
304             
305             // basic types..
306             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
307             
308             $l = preg_replace('# datetime #i', ' TIMESTAMP WITHOUT TIME ZONE ', $l);
309             $l = preg_replace('# blob #i', ' TEXT ', $l);
310              $l = preg_replace('# longtext #i', ' TEXT ', $l);
311             //$l = preg_match('#int\([0-9]+\)#i', 'INT', $l);
312                             
313             $ret[] = $l;
314             
315             
316             
317             
318             
319             
320             
321         }
322         $ret = array_merge($extra,$ret);
323         
324         //echo implode("\n", $ret); //exit;
325         file_put_contents($fn, implode("\n", $ret));
326         
327         return $fn;
328     }
329     
330     function runUpdateModulesData()
331     {
332         $this->updateData();
333         $modules = $this->modulesList();
334         foreach ($modules as $module){
335             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
336             if($module == 'Core' || !file_exists($file)){
337                 continue;
338             }
339             require_once $file;
340             $class = "Pman_{$module}_UpdateDatabase";
341             $x = new $class;
342             if(!method_exists($x, 'updateData')){
343                 continue;
344             };
345             $x->updateData();
346         }
347                 
348     }
349     
350     function updateData()
351     {
352         // fill i18n data..
353         
354         $enum = DB_DataObject::Factory('core_enum');
355         $enum->initEnums(
356             array(
357                 array(
358                     'etype' => '',
359                     'name' => 'COMPTYPE',
360                     'display_name' =>  'Company Types',
361                     'cn' => array(
362                         array(
363                             'name' => 'OWNER',
364                             'display_name' => 'Owner',
365                             'seqid' => 999, // last...
366                         )
367                         
368                     )
369                 )
370             )
371         ); 
372     }
373     
374     
375 }