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