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' => 'add a company name of the company',
36 'add-company-with-type' => array(
37 'desc' => 'the type of company (default OWNER)',
44 'desc' => 'Initialize the database (pg only supported)',
51 'json-person' => array(
52 'desc' => 'Person JSON file',
60 static function cli_opts()
63 $ret = self::$cli_opts;
64 $ff = HTML_FlexyFramework::get();
66 $mods = $a->modulesList();
67 foreach($mods as $m) {
69 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
70 if (!file_exists($fd)) {
76 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
78 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
93 $ff = HTML_FlexyFramework::get();
94 if (!empty($ff->cli)) {
99 parent::getAuth(); // load company!
100 $au = $this->getAuthUser();
101 if (!$au || $au->company()->comptype != 'OWNER') {
102 $this->jerr("Not authenticated", array('authFailure' => true));
104 $this->authUser = $au;
108 function get($args, $opt)
110 $this->fixSequencesPgsql();exit;
113 // ask all the modules to verify the opts
115 $this->checkOpts($opt);
120 if($args == 'Company'){
121 if(empty($opt['name']) || empty($opt['comptype'])){
122 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
125 DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
131 $this->runUpdateModulesData();
138 * imports SQL files from all DataObjects directories....
140 * except any matching /migrate/
145 $ff = HTML_Flexyframework::get();
147 $url = parse_url($ff->DB_DataObject['database']);
149 $this->{'import' . $url['scheme']}($url);
154 * mysql - does not support conversions.
160 function importmysqldir($dburl, $dir)
162 echo "Import MYSQL :: $dir\n";
165 require_once 'System.php';
166 $cat = System::which('cat');
167 $mysql = System::which('mysql');
171 $mysql_cmd = $mysql .
172 ' -h ' . $dburl['host'] .
173 ' -u' . escapeshellarg($dburl['user']) .
174 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
175 ' ' . basename($dburl['path']);
176 //echo $mysql_cmd . "\n" ;
179 foreach(glob($dir.'/*.sql') as $fn) {
182 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
185 // .my.sql but not .pg.sql
186 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
187 && !preg_match('#\.my\.sql#i', basename($fn))
188 ) { // skip migration scripts at present..
191 if (!strlen(trim($fn))) {
195 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
197 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
210 function importmysql($dburl)
213 // hide stuff for web..
214 $ar = $this->modulesList();
218 // old -- DAtaObjects/*.sql
222 $fd = $this->rootDir. "/Pman/$m/DataObjects";
224 $this->importmysqldir($dburl, $fd);
226 // new -- sql directory..
227 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
228 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
230 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
231 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
240 * postgresql import..
242 function importpgsql($dburl)
245 // hide stuff for web..
250 $ar = $this->modulesList();
254 // if init has been called
256 if (!empty($this->opts['init'])) {
257 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
263 $fd = $this->rootDir. "/Pman/$m/DataObjects";
265 $this->importpgsqldir($dburl, $fd);
267 // new -- sql directory..
268 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
269 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
271 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
272 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
276 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
277 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
279 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
280 $this->fixSequencesPgsql();
289 function importpgsqldir($url, $dir, $disable_triggers = false)
291 require_once 'System.php';
292 $cat = System::which('cat');
293 $psql = System::which('psql');
296 if (!empty($url['pass'])) {
297 putenv("PGPASSWORD=". $url['pass']);
301 ' -h ' . $url['host'] .
302 ' -U' . escapeshellarg($url['user']) .
303 ' ' . basename($url['path']);
306 echo $psql_cmd . "\n" ;
307 echo "scan : $dir\n";
308 foreach(glob($dir.'/*.sql') as $bfn) {
311 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
314 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
315 && !preg_match('#\.pg\.sql#i', basename($bfn))
316 ) { // skip migration scripts at present..
321 if (!preg_match('/pgsql/', basename($dir) )) {
322 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
323 $fn = $this->convertToPG($bfn);
327 // files ending in .pg.sql are native postgres files.. ## depricated
330 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
332 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
347 * simple regex based convert mysql to pgsql...
349 function convertToPG($src)
351 //echo "Convert $src\n";
353 $fn = $this->tempName('sql');
355 $ret = array( ); // pad it a bit.
356 $extra = array("", "" );
359 foreach(file($src) as $l) {
362 if (!strlen($l) || $l[0] == '#') {
366 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
369 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
370 $tbl = 'shop_' . strtolower($m[1]);
371 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
373 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
374 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
377 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
378 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
379 $extra[] = "create sequence {$tbl}_seq;";
383 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
384 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
387 // enum value -- use the text instead..
389 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
390 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
392 // ignore the alter enum
393 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
397 // UNIQUE KEY .. ignore
398 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
399 $last = array_pop($ret);
400 $ret[] = trim($last, ",");
404 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
408 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
412 // INDEX lookup ..ignore
413 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
414 $last = array_pop($ret);
415 $ret[] = trim($last, ",");
420 // CREATE INDEX ..ignore
421 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
422 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
427 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
429 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
430 $l = preg_replace('# blob#i', ' TEXT', $l);
431 $l = preg_replace('# longtext#i', ' TEXT', $l);
432 $l = preg_replace('# tinyint#i', ' INT', $l);
438 $ret = array_merge($extra,$ret);
439 // echo implode("\n", $ret); exit;
441 file_put_contents($fn, implode("\n", $ret));
447 function checkOpts($opts)
451 foreach($opts as $o=>$v) {
452 if (!preg_match('/^json-/', $o) || empty($v)) {
455 if (!file_exists($v)) {
456 die("File does not exist : OPTION --{$o} = {$v} \n");
460 $modules = array_reverse($this->modulesList());
462 // move 'project' one to the end...
464 foreach ($modules as $module){
465 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
466 if($module == 'Core' || !file_exists($file)){
470 $class = "Pman_{$module}_UpdateDatabase";
472 if(!method_exists($x, 'checkOpts')){
475 $x->checkOpts($opts);
479 static function jsonImportFromArray($opts)
481 foreach($opts as $o=>$v) {
482 if (!preg_match('/^json-/', $o) || empty($v)) {
485 $type = str_replace('_', '-', substr($o,6));
486 $data= json_decode(file_get_contents($file),true);
487 DB_DataObject::factory($type)->importFromArray($this,$data,$opts);
495 function runUpdateModulesData()
499 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
500 echo "Running jsonImportFromArray\n";
501 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
504 echo "Running updateData on modules\n";
508 $modules = array_reverse($this->modulesList());
510 // move 'project' one to the end...
512 foreach ($modules as $module){
513 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
514 if($module == 'Core' || !file_exists($file)){
519 $class = "Pman_{$module}_UpdateDatabase";
521 if(!method_exists($x, 'updateData')){
531 function updateDataEnums()
533 $enum = DB_DataObject::Factory('core_enum');
538 'name' => 'COMPTYPE',
539 'display_name' => 'Company Types',
540 'is_system_enum' => 1,
544 'display_name' => 'Owner',
545 'seqid' => 999, // last...
546 'is_system_enum' => 1,
553 'name' => 'HtmlEditor.font-family',
554 'display_name' => 'HTML Editor font families',
555 'is_system_enum' => 1,
558 'name' => 'Helvetica,Arial,sans-serif',
559 'display_name' => 'Helvetica',
564 'name' => 'Courier New',
565 'display_name' => 'Courier',
570 'display_name' => 'Tahoma',
574 'name' => 'Times New Roman,serif',
575 'display_name' => 'Times',
580 'display_name' => 'Verdana',
592 function updateDataGroups()
595 $groups = DB_DataObject::factory('groups');
596 $groups->initGroups();
598 $groups->initDatabase($this,array(
600 'name' => 'bcc-email', // group who are bcc'ed on all requests.
601 'type' => 0, // system
608 function updateDataCompanies()
611 // fix comptypes enums..
612 $c = DB_DataObject::Factory('Companies');
614 $c->selectAdd('distinct(comptype) as comptype');
615 $c->whereAdd("comptype != ''");
618 foreach($c->fetchAll('comptype') as $cts) {
622 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
625 $c = DB_DataObject::Factory('core_enum');
628 //DB_DataObject::debugLevel(1);
630 $c = DB_DataObject::Factory('Companies');
634 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
647 function updateData()
651 $this->updateDataEnums();
652 $this->updateDataGroups();
653 $this->updateDataCompanies();
655 $c = DB_DataObject::Factory('I18n');
662 function fixSequencesPgsql()
664 //DB_DataObject::debugLevel(1);
665 $cs = DB_DataObject::factory('core_enum');
667 SELECT 'ALTER SEQUENCE '|| quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
668 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
669 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
673 n.nspname AS schema_name,
674 c.relname AS table_name,
675 a.attname AS column_name,
676 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\"]*', ''),E'[''\"]*::.*\$','') AS seq_name
678 JOIN pg_attribute a ON (c.oid=a.attrelid)
679 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
680 JOIN pg_namespace n ON (c.relnamespace=n.oid)
681 WHERE has_schema_privilege(n.oid,'USAGE')
682 AND n.nspname NOT LIKE 'pg!_%' escape '!'
683 AND has_table_privilege(c.oid,'SELECT')
684 AND (NOT a.attisdropped)
685 AND d.adsrc ~ '^nextval'
688 GROUP BY seq_name HAVING count(*)=1
691 while ($cs->fetch()) {
694 foreach($cmds as $cmd) {
695 $cs = DB_DataObject::factory('core_enum');
698 $cs = DB_DataObject::factory('core_enum');
700 SELECT 'SELECT SETVAL(' ||
701 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
702 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
708 WHERE S.relkind = 'S'
710 AND D.refobjid = T.oid
711 AND D.refobjid = C.attrelid
712 AND D.refobjsubid = C.attnum
713 AND NS.oid = T.relnamespace
717 while ($cs->fetch()) {
720 foreach($cmds as $cmd) {
721 $cs = DB_DataObject::factory('core_enum');