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)',
57 'json-company' => array(
58 'desc' => 'Company JSON file',
64 'json-person' => array(
65 'desc' => 'Person JSON file',
73 static function cli_opts()
76 $ret = self::$cli_opts;
77 $ff = HTML_FlexyFramework::get();
79 $mods = $a->modulesList();
80 foreach($mods as $m) {
82 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
83 if (!file_exists($fd)) {
89 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
91 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
106 $ff = HTML_FlexyFramework::get();
107 if (!empty($ff->cli)) {
112 parent::getAuth(); // load company!
113 $au = $this->getAuthUser();
114 if (!$au || $au->company()->comptype != 'OWNER') {
115 $this->jerr("Not authenticated", array('authFailure' => true));
117 $this->authUser = $au;
121 function get($args, $opt)
126 // ask all the modules to verify the opts
128 $this->checkOpts($opt);
132 if($args == 'Person'){
133 if(empty($opt['source']) || empty($opt['prefix'])){
134 die("Missing Source directory for person json files or prefix for the passwrod! Try -f [JSON file path] -p [prefix] \n");
136 if (!file_exists($opt['source'])) {
137 die("can not found person json file : {$opt['source']} \n");
140 $persons = json_decode(file_get_contents($opt['source']),true);
142 DB_DataObject::factory('person')->importFromArray($this, $persons, $opt['prefix']);
148 if($args == 'Company'){
149 if(empty($opt['name']) || empty($opt['comptype'])){
150 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
153 DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
159 $this->runUpdateModulesData();
166 * imports SQL files from all DataObjects directories....
168 * except any matching /migrate/
173 $ff = HTML_Flexyframework::get();
175 $url = parse_url($ff->DB_DataObject['database']);
177 $this->{'import' . $url['scheme']}($url);
182 * mysql - does not support conversions.
188 function importmysqldir($dburl, $dir)
190 echo "Import MYSQL :: $dir\n";
193 require_once 'System.php';
194 $cat = System::which('cat');
195 $mysql = System::which('mysql');
199 $mysql_cmd = $mysql .
200 ' -h ' . $dburl['host'] .
201 ' -u' . escapeshellarg($dburl['user']) .
202 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
203 ' ' . basename($dburl['path']);
204 //echo $mysql_cmd . "\n" ;
207 foreach(glob($dir.'/*.sql') as $fn) {
210 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
213 // .my.sql but not .pg.sql
214 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
215 && !preg_match('#\.my\.sql#i', basename($fn))
216 ) { // skip migration scripts at present..
219 if (!strlen(trim($fn))) {
223 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
225 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
238 function importmysql($dburl)
241 // hide stuff for web..
242 $ar = $this->modulesList();
246 // old -- DAtaObjects/*.sql
250 $fd = $this->rootDir. "/Pman/$m/DataObjects";
252 $this->importmysqldir($dburl, $fd);
254 // new -- sql directory..
255 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
256 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
258 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
259 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
268 * postgresql import..
270 function importpgsql($dburl)
273 // hide stuff for web..
278 $ar = $this->modulesList();
282 // if init has been called
284 if (!empty($this->opts['init'])) {
285 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
291 $fd = $this->rootDir. "/Pman/$m/DataObjects";
293 $this->importpgsqldir($dburl, $fd);
295 // new -- sql directory..
296 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
297 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
299 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
300 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
304 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
305 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
307 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
308 $this->fixSequencesPgsql();
317 function importpgsqldir($url, $dir, $disable_triggers = false)
319 require_once 'System.php';
320 $cat = System::which('cat');
321 $psql = System::which('psql');
324 if (!empty($url['pass'])) {
325 putenv("PGPASSWORD=". $url['pass']);
329 ' -h ' . $url['host'] .
330 ' -U' . escapeshellarg($url['user']) .
331 ' ' . basename($url['path']);
334 echo $psql_cmd . "\n" ;
335 echo "scan : $dir\n";
336 foreach(glob($dir.'/*.sql') as $bfn) {
339 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
342 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
343 && !preg_match('#\.pg\.sql#i', basename($bfn))
344 ) { // skip migration scripts at present..
349 if (!preg_match('/pgsql/', basename($dir) )) {
350 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
351 $fn = $this->convertToPG($bfn);
355 // files ending in .pg.sql are native postgres files.. ## depricated
358 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
360 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
375 * simple regex based convert mysql to pgsql...
377 function convertToPG($src)
379 //echo "Convert $src\n";
381 $fn = $this->tempName('sql');
383 $ret = array( ); // pad it a bit.
384 $extra = array("", "" );
387 foreach(file($src) as $l) {
390 if (!strlen($l) || $l[0] == '#') {
394 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
397 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
398 $tbl = 'shop_' . strtolower($m[1]);
399 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
401 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
402 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
405 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
406 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
407 $extra[] = "create sequence {$tbl}_seq;";
411 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
412 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
415 // enum value -- use the text instead..
417 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
418 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
420 // ignore the alter enum
421 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
425 // UNIQUE KEY .. ignore
426 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
427 $last = array_pop($ret);
428 $ret[] = trim($last, ",");
432 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
436 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
440 // INDEX lookup ..ignore
441 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
442 $last = array_pop($ret);
443 $ret[] = trim($last, ",");
448 // CREATE INDEX ..ignore
449 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
450 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
455 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
457 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
458 $l = preg_replace('# blob#i', ' TEXT', $l);
459 $l = preg_replace('# longtext#i', ' TEXT', $l);
460 $l = preg_replace('# tinyint#i', ' INT', $l);
466 $ret = array_merge($extra,$ret);
467 // echo implode("\n", $ret); exit;
469 file_put_contents($fn, implode("\n", $ret));
475 function checkOpts($opts)
479 foreach($opts as $o=>$v) {
480 if (!preg_match('/^json-/', $o) || empty($v)) {
483 if (!file_exists($v)) {
484 die("File does not exist : OPTION --{$o} = {$v} \n");
488 $modules = array_reverse($this->modulesList());
490 // move 'project' one to the end...
492 foreach ($modules as $module){
493 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
494 if($module == 'Core' || !file_exists($file)){
498 $class = "Pman_{$module}_UpdateDatabase";
500 if(!method_exists($x, 'checkOpts')){
503 $x->checkOpts($opts);
507 static function jsonImportFromArray($opts)
509 foreach($opts as $o=>$v) {
510 if (!preg_match('/^json-/', $o) || empty($v)) {
513 $type = str_replace('_', '-', substr($o,6));
514 $data= json_decode(file_get_contents($file),true);
515 DB_DataObject::factory($type)->importFromArray($data);
523 function runUpdateModulesData()
527 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
528 echo "Running jsonImportFromArray\n";
529 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
532 echo "Running updateData on modules\n";
536 $modules = array_reverse($this->modulesList());
538 // move 'project' one to the end...
540 foreach ($modules as $module){
541 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
542 if($module == 'Core' || !file_exists($file)){
547 $class = "Pman_{$module}_UpdateDatabase";
549 if(!method_exists($x, 'updateData')){
559 function updateDataEnums()
561 $enum = DB_DataObject::Factory('core_enum');
566 'name' => 'COMPTYPE',
567 'display_name' => 'Company Types',
568 'is_system_enum' => 1,
572 'display_name' => 'Owner',
573 'seqid' => 999, // last...
574 'is_system_enum' => 1,
581 'name' => 'HtmlEditor.font-family',
582 'display_name' => 'HTML Editor font families',
583 'is_system_enum' => 1,
586 'name' => 'Helvetica,Arial,sans-serif',
587 'display_name' => 'Helvetica',
592 'name' => 'Courier New',
593 'display_name' => 'Courier',
598 'display_name' => 'Tahoma',
602 'name' => 'Times New Roman,serif',
603 'display_name' => 'Times',
608 'display_name' => 'Verdana',
620 function updateDataGroups()
623 $groups = DB_DataObject::factory('groups');
624 $groups->initGroups();
626 $groups->initDatabase($this,array(
628 'name' => 'bcc-email', // group who are bcc'ed on all requests.
629 'type' => 0, // system
636 function updateDataCompanies()
639 // fix comptypes enums..
640 $c = DB_DataObject::Factory('Companies');
642 $c->selectAdd('distinct(comptype) as comptype');
643 $c->whereAdd("comptype != ''");
646 foreach($c->fetchAll('comptype') as $cts) {
650 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
653 $c = DB_DataObject::Factory('core_enum');
656 //DB_DataObject::debugLevel(1);
658 $c = DB_DataObject::Factory('Companies');
662 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
675 function updateData()
679 $this->updateDataEnums();
680 $this->updateDataGroups();
681 $this->updateDataCompanies();
683 $c = DB_DataObject::Factory('I18n');
690 function fixSequencesPgsql()
692 DB_DataObject::debugLevel(1);
693 $cs = DB_DataObject::factory('core_enum');
695 SELECT 'SELECT SETVAL(' ||
696 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
697 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
703 WHERE S.relkind = 'S'
705 AND D.refobjid = T.oid
706 AND D.refobjid = C.attrelid
707 AND D.refobjsubid = C.attnum
708 AND NS.oid = T.relnamespace
711 while ($cs->fetch()) {
714 foreach($cmds as $cmd) {
715 $cs = DB_DataObject::factory('core_enum');