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