5 * This applies database files from
6 * a) OLD - {MODULE}/DataObjects/XXXX.{dbtype}.sql
8 * b) NEW - {MODULE}/sql/XXX.sql (SHARED or translable)
9 * and {MODULE}/{dbtype}/XXX.sql (SHARED or translable)
14 require_once 'Pman.php';
15 class Pman_Core_UpdateDatabase extends Pman
18 static $cli_desc = "Update SQL - Beta (it will run updateData of all modules)";
20 static $cli_opts = array(
22 'desc' => 'Source directory for json files.',
29 'desc' => 'prefix for the passwrod',
36 'desc' => 'name of the company',
43 'desc' => 'the type of company',
50 'desc' => 'Initialize the database (pg only supported)',
59 static function cli_opts()
62 $ret = self::$cli_opts;
63 $ff = HTML_FlexyFramework::get();
65 $mods = $a->modulesList();
66 foreach($mods as $m) {
68 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
69 if (!file_exists($fd)) {
75 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
77 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
92 $ff = HTML_FlexyFramework::get();
93 if (!empty($ff->cli)) {
98 parent::getAuth(); // load company!
99 $au = $this->getAuthUser();
100 if (!$au || $au->company()->comptype != 'OWNER') {
101 $this->jerr("Not authenticated", array('authFailure' => true));
103 $this->authUser = $au;
107 function get($args, $opt)
112 // ask all the modules to verify the opts
118 if($args == 'Person'){
119 if(empty($opt['source']) || empty($opt['prefix'])){
120 die("Missing Source directory for person json files or prefix for the passwrod! Try -f [JSON file path] -p [prefix] \n");
122 if (!file_exists($opt['source'])) {
123 die("can not found person json file : {$opt['source']} \n");
126 $persons = json_decode(file_get_contents($opt['source']),true);
128 DB_DataObject::factory('person')->importFromArray($this, $persons, $opt['prefix']);
134 if($args == 'Company'){
135 if(empty($opt['name']) || empty($opt['comptype'])){
136 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
139 DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
145 $this->runUpdateModulesData();
152 * imports SQL files from all DataObjects directories....
154 * except any matching /migrate/
159 $ff = HTML_Flexyframework::get();
161 $url = parse_url($ff->DB_DataObject['database']);
163 $this->{'import' . $url['scheme']}($url);
168 * mysql - does not support conversions.
174 function importmysqldir($dburl, $dir)
176 echo "Import MYSQL :: $dir\n";
179 require_once 'System.php';
180 $cat = System::which('cat');
181 $mysql = System::which('mysql');
185 $mysql_cmd = $mysql .
186 ' -h ' . $dburl['host'] .
187 ' -u' . escapeshellarg($dburl['user']) .
188 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
189 ' ' . basename($dburl['path']);
190 //echo $mysql_cmd . "\n" ;
193 foreach(glob($dir.'/*.sql') as $fn) {
196 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
199 // .my.sql but not .pg.sql
200 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
201 && !preg_match('#\.my\.sql#i', basename($fn))
202 ) { // skip migration scripts at present..
205 if (!strlen(trim($fn))) {
209 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
211 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
224 function importmysql($dburl)
227 // hide stuff for web..
228 $ar = $this->modulesList();
232 // old -- DAtaObjects/*.sql
236 $fd = $this->rootDir. "/Pman/$m/DataObjects";
238 $this->importmysqldir($dburl, $fd);
240 // new -- sql directory..
241 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
242 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
244 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
245 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
254 * postgresql import..
256 function importpgsql($dburl)
259 // hide stuff for web..
264 $ar = $this->modulesList();
268 // if init has been called
270 if (!empty($this->opts['init'])) {
271 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
277 $fd = $this->rootDir. "/Pman/$m/DataObjects";
279 $this->importpgsqldir($dburl, $fd);
281 // new -- sql directory..
282 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
283 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
285 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
286 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
290 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
291 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
293 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
294 $this->fixSequencesPgsql();
303 function importpgsqldir($url, $dir, $disable_triggers = false)
305 require_once 'System.php';
306 $cat = System::which('cat');
307 $psql = System::which('psql');
310 if (!empty($url['pass'])) {
311 putenv("PGPASSWORD=". $url['pass']);
315 ' -h ' . $url['host'] .
316 ' -U' . escapeshellarg($url['user']) .
317 ' ' . basename($url['path']);
320 echo $psql_cmd . "\n" ;
321 echo "scan : $dir\n";
322 foreach(glob($dir.'/*.sql') as $bfn) {
325 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
328 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
329 && !preg_match('#\.pg\.sql#i', basename($bfn))
330 ) { // skip migration scripts at present..
335 if (!preg_match('/pgsql/', basename($dir) )) {
336 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
337 $fn = $this->convertToPG($bfn);
341 // files ending in .pg.sql are native postgres files.. ## depricated
344 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
346 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
361 * simple regex based convert mysql to pgsql...
363 function convertToPG($src)
365 //echo "Convert $src\n";
367 $fn = $this->tempName('sql');
369 $ret = array( ); // pad it a bit.
370 $extra = array("", "" );
373 foreach(file($src) as $l) {
376 if (!strlen($l) || $l[0] == '#') {
380 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
383 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
384 $tbl = 'shop_' . strtolower($m[1]);
385 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
387 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
388 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
391 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
392 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
393 $extra[] = "create sequence {$tbl}_seq;";
397 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
398 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
401 // enum value -- use the text instead..
403 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
404 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
406 // ignore the alter enum
407 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
411 // UNIQUE KEY .. ignore
412 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
413 $last = array_pop($ret);
414 $ret[] = trim($last, ",");
418 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
422 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
426 // INDEX lookup ..ignore
427 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
428 $last = array_pop($ret);
429 $ret[] = trim($last, ",");
434 // CREATE INDEX ..ignore
435 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
436 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
441 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
443 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
444 $l = preg_replace('# blob#i', ' TEXT', $l);
445 $l = preg_replace('# longtext#i', ' TEXT', $l);
446 $l = preg_replace('# tinyint#i', ' INT', $l);
452 $ret = array_merge($extra,$ret);
453 // echo implode("\n", $ret); exit;
455 file_put_contents($fn, implode("\n", $ret));
461 function checkOpts($opts)
463 $modules = array_reverse($this->modulesList());
465 // move 'project' one to the end...
467 foreach ($modules as $module){
468 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
469 if($module == 'Core' || !file_exists($file)){
473 $class = "Pman_{$module}_UpdateDatabase";
475 if(!method_exists($x, 'checkOpts')){
478 $x->checkOpts($opts);
484 function runUpdateModulesData()
486 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
491 $modules = array_reverse($this->modulesList());
493 // move 'project' one to the end...
495 foreach ($modules as $module){
496 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
497 if($module == 'Core' || !file_exists($file)){
501 $class = "Pman_{$module}_UpdateDatabase";
503 if(!method_exists($x, 'updateData')){
512 function updateDataEnums()
514 $enum = DB_DataObject::Factory('core_enum');
519 'name' => 'COMPTYPE',
520 'display_name' => 'Company Types',
521 'is_system_enum' => 1,
525 'display_name' => 'Owner',
526 'seqid' => 999, // last...
527 'is_system_enum' => 1,
534 'name' => 'HtmlEditor.font-family',
535 'display_name' => 'HTML Editor font families',
536 'is_system_enum' => 1,
539 'name' => 'Helvetica,Arial,sans-serif',
540 'display_name' => 'Helvetica',
545 'name' => 'Courier New',
546 'display_name' => 'Courier',
551 'display_name' => 'Tahoma',
555 'name' => 'Times New Roman,serif',
556 'display_name' => 'Times',
561 'display_name' => 'Verdana',
573 function updateDataGroups()
576 $groups = DB_DataObject::factory('groups');
577 $groups->initGroups();
579 $groups->initDatabase($this,array(
581 'name' => 'bcc-email', // group who are bcc'ed on all requests.
582 'type' => 0, // system
589 function updateDataCompanies()
592 // fix comptypes enums..
593 $c = DB_DataObject::Factory('Companies');
595 $c->selectAdd('distinct(comptype) as comptype');
596 $c->whereAdd("comptype != ''");
599 foreach($c->fetchAll('comptype') as $cts) {
603 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
606 $c = DB_DataObject::Factory('core_enum');
609 //DB_DataObject::debugLevel(1);
611 $c = DB_DataObject::Factory('Companies');
615 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
628 function updateData()
632 $this->updateDataEnums();
633 $this->updateDataGroups();
634 $this->updateDataCompanies();
636 $c = DB_DataObject::Factory('I18n');
643 function fixSequencesPgsql()
645 DB_DataObject::debugLevel(1);
646 $cs = DB_DataObject::factory('core_enum');
648 SELECT 'SELECT SETVAL(' ||
649 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
650 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
656 WHERE S.relkind = 'S'
658 AND D.refobjid = T.oid
659 AND D.refobjid = C.attrelid
660 AND D.refobjsubid = C.attnum
661 AND NS.oid = T.relnamespace
664 while ($cs->fetch()) {
667 foreach($cmds as $cmd) {
668 $cs = DB_DataObject::factory('core_enum');