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