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