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(
23 'desc' => 'prefix for the password (eg. fred > xxx4fred - prefix is xxx4)',
29 'add-company' => array(
30 'desc' => 'name of the company',
36 'add-company-with-type' => array(
37 'desc' => 'the type of company',
44 'desc' => 'Initialize the database (pg only supported)',
51 'json-company' => array(
52 'desc' => 'Company JSON file',
58 'json-person' => array(
59 'desc' => 'Person JSON file',
67 static function cli_opts()
70 $ret = self::$cli_opts;
71 $ff = HTML_FlexyFramework::get();
73 $mods = $a->modulesList();
74 foreach($mods as $m) {
76 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
77 if (!file_exists($fd)) {
83 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
85 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
100 $ff = HTML_FlexyFramework::get();
101 if (!empty($ff->cli)) {
106 parent::getAuth(); // load company!
107 $au = $this->getAuthUser();
108 if (!$au || $au->company()->comptype != 'OWNER') {
109 $this->jerr("Not authenticated", array('authFailure' => true));
111 $this->authUser = $au;
115 function get($args, $opt)
117 $this->fixSequencesPgsql();exit;
120 // ask all the modules to verify the opts
122 $this->checkOpts($opt);
127 if($args == 'Company'){
128 if(empty($opt['name']) || empty($opt['comptype'])){
129 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
132 DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
138 $this->runUpdateModulesData();
145 * imports SQL files from all DataObjects directories....
147 * except any matching /migrate/
152 $ff = HTML_Flexyframework::get();
154 $url = parse_url($ff->DB_DataObject['database']);
156 $this->{'import' . $url['scheme']}($url);
161 * mysql - does not support conversions.
167 function importmysqldir($dburl, $dir)
169 echo "Import MYSQL :: $dir\n";
172 require_once 'System.php';
173 $cat = System::which('cat');
174 $mysql = System::which('mysql');
178 $mysql_cmd = $mysql .
179 ' -h ' . $dburl['host'] .
180 ' -u' . escapeshellarg($dburl['user']) .
181 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
182 ' ' . basename($dburl['path']);
183 //echo $mysql_cmd . "\n" ;
186 foreach(glob($dir.'/*.sql') as $fn) {
189 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
192 // .my.sql but not .pg.sql
193 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
194 && !preg_match('#\.my\.sql#i', basename($fn))
195 ) { // skip migration scripts at present..
198 if (!strlen(trim($fn))) {
202 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
204 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
217 function importmysql($dburl)
220 // hide stuff for web..
221 $ar = $this->modulesList();
225 // old -- DAtaObjects/*.sql
229 $fd = $this->rootDir. "/Pman/$m/DataObjects";
231 $this->importmysqldir($dburl, $fd);
233 // new -- sql directory..
234 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
235 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
237 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
238 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
247 * postgresql import..
249 function importpgsql($dburl)
252 // hide stuff for web..
257 $ar = $this->modulesList();
261 // if init has been called
263 if (!empty($this->opts['init'])) {
264 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
270 $fd = $this->rootDir. "/Pman/$m/DataObjects";
272 $this->importpgsqldir($dburl, $fd);
274 // new -- sql directory..
275 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
276 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
278 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
279 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
283 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
284 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
286 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
287 $this->fixSequencesPgsql();
296 function importpgsqldir($url, $dir, $disable_triggers = false)
298 require_once 'System.php';
299 $cat = System::which('cat');
300 $psql = System::which('psql');
303 if (!empty($url['pass'])) {
304 putenv("PGPASSWORD=". $url['pass']);
308 ' -h ' . $url['host'] .
309 ' -U' . escapeshellarg($url['user']) .
310 ' ' . basename($url['path']);
313 echo $psql_cmd . "\n" ;
314 echo "scan : $dir\n";
315 foreach(glob($dir.'/*.sql') as $bfn) {
318 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
321 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
322 && !preg_match('#\.pg\.sql#i', basename($bfn))
323 ) { // skip migration scripts at present..
328 if (!preg_match('/pgsql/', basename($dir) )) {
329 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
330 $fn = $this->convertToPG($bfn);
334 // files ending in .pg.sql are native postgres files.. ## depricated
337 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
339 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
354 * simple regex based convert mysql to pgsql...
356 function convertToPG($src)
358 //echo "Convert $src\n";
360 $fn = $this->tempName('sql');
362 $ret = array( ); // pad it a bit.
363 $extra = array("", "" );
366 foreach(file($src) as $l) {
369 if (!strlen($l) || $l[0] == '#') {
373 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
376 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
377 $tbl = 'shop_' . strtolower($m[1]);
378 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
380 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
381 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
384 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
385 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
386 $extra[] = "create sequence {$tbl}_seq;";
390 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
391 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
394 // enum value -- use the text instead..
396 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
397 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
399 // ignore the alter enum
400 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
404 // UNIQUE KEY .. ignore
405 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
406 $last = array_pop($ret);
407 $ret[] = trim($last, ",");
411 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
415 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
419 // INDEX lookup ..ignore
420 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
421 $last = array_pop($ret);
422 $ret[] = trim($last, ",");
427 // CREATE INDEX ..ignore
428 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
429 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
434 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
436 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
437 $l = preg_replace('# blob#i', ' TEXT', $l);
438 $l = preg_replace('# longtext#i', ' TEXT', $l);
439 $l = preg_replace('# tinyint#i', ' INT', $l);
445 $ret = array_merge($extra,$ret);
446 // echo implode("\n", $ret); exit;
448 file_put_contents($fn, implode("\n", $ret));
454 function checkOpts($opts)
458 foreach($opts as $o=>$v) {
459 if (!preg_match('/^json-/', $o) || empty($v)) {
462 if (!file_exists($v)) {
463 die("File does not exist : OPTION --{$o} = {$v} \n");
467 $modules = array_reverse($this->modulesList());
469 // move 'project' one to the end...
471 foreach ($modules as $module){
472 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
473 if($module == 'Core' || !file_exists($file)){
477 $class = "Pman_{$module}_UpdateDatabase";
479 if(!method_exists($x, 'checkOpts')){
482 $x->checkOpts($opts);
486 static function jsonImportFromArray($opts)
488 foreach($opts as $o=>$v) {
489 if (!preg_match('/^json-/', $o) || empty($v)) {
492 $type = str_replace('_', '-', substr($o,6));
493 $data= json_decode(file_get_contents($file),true);
494 DB_DataObject::factory($type)->importFromArray($this,$data,$opts);
502 function runUpdateModulesData()
506 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
507 echo "Running jsonImportFromArray\n";
508 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
511 echo "Running updateData on modules\n";
515 $modules = array_reverse($this->modulesList());
517 // move 'project' one to the end...
519 foreach ($modules as $module){
520 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
521 if($module == 'Core' || !file_exists($file)){
526 $class = "Pman_{$module}_UpdateDatabase";
528 if(!method_exists($x, 'updateData')){
538 function updateDataEnums()
540 $enum = DB_DataObject::Factory('core_enum');
545 'name' => 'COMPTYPE',
546 'display_name' => 'Company Types',
547 'is_system_enum' => 1,
551 'display_name' => 'Owner',
552 'seqid' => 999, // last...
553 'is_system_enum' => 1,
560 'name' => 'HtmlEditor.font-family',
561 'display_name' => 'HTML Editor font families',
562 'is_system_enum' => 1,
565 'name' => 'Helvetica,Arial,sans-serif',
566 'display_name' => 'Helvetica',
571 'name' => 'Courier New',
572 'display_name' => 'Courier',
577 'display_name' => 'Tahoma',
581 'name' => 'Times New Roman,serif',
582 'display_name' => 'Times',
587 'display_name' => 'Verdana',
599 function updateDataGroups()
602 $groups = DB_DataObject::factory('groups');
603 $groups->initGroups();
605 $groups->initDatabase($this,array(
607 'name' => 'bcc-email', // group who are bcc'ed on all requests.
608 'type' => 0, // system
615 function updateDataCompanies()
618 // fix comptypes enums..
619 $c = DB_DataObject::Factory('Companies');
621 $c->selectAdd('distinct(comptype) as comptype');
622 $c->whereAdd("comptype != ''");
625 foreach($c->fetchAll('comptype') as $cts) {
629 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
632 $c = DB_DataObject::Factory('core_enum');
635 //DB_DataObject::debugLevel(1);
637 $c = DB_DataObject::Factory('Companies');
641 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
654 function updateData()
658 $this->updateDataEnums();
659 $this->updateDataGroups();
660 $this->updateDataCompanies();
662 $c = DB_DataObject::Factory('I18n');
669 function fixSequencesPgsql()
671 //DB_DataObject::debugLevel(1);
672 $cs = DB_DataObject::factory('core_enum');
674 SELECT 'ALTER SEQUENCE '|| quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
675 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
676 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
680 n.nspname AS schema_name,
681 c.relname AS table_name,
682 a.attname AS column_name,
683 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\"]*', ''),E'[''\"]*::.*\$','') AS seq_name
685 JOIN pg_attribute a ON (c.oid=a.attrelid)
686 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
687 JOIN pg_namespace n ON (c.relnamespace=n.oid)
688 WHERE has_schema_privilege(n.oid,'USAGE')
689 AND n.nspname NOT LIKE 'pg!_%' escape '!'
690 AND has_table_privilege(c.oid,'SELECT')
691 AND (NOT a.attisdropped)
692 AND d.adsrc ~ '^nextval'
695 GROUP BY seq_name HAVING count(*)=1
698 while ($cs->fetch()) {
701 foreach($cmds as $cmd) {
702 $cs = DB_DataObject::factory('core_enum');
705 $cs = DB_DataObject::factory('core_enum');
707 SELECT 'SELECT SETVAL(' ||
708 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
709 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
715 WHERE S.relkind = 'S'
717 AND D.refobjid = T.oid
718 AND D.refobjid = C.attrelid
719 AND D.refobjsubid = C.attnum
720 AND NS.oid = T.relnamespace
724 while ($cs->fetch()) {
727 foreach($cmds as $cmd) {
728 $cs = DB_DataObject::factory('core_enum');