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