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)',
30 'desc' => 'only run the updateData - do not run import the tables and procedures.',
37 'add-company' => array(
38 'desc' => 'add a company name of the company',
44 'add-company-with-type' => array(
45 'desc' => 'the type of company (default OWNER)',
52 'desc' => 'Initialize the database (pg only supported)',
58 'only-module-sql' => array(
59 'desc' => 'Only run sql import on this modules - eg. Core',
65 'json-person' => array(
66 'desc' => 'Person JSON file',
74 static function cli_opts()
77 $ret = self::$cli_opts;
78 $ff = HTML_FlexyFramework::get();
80 $mods = $a->modulesList();
81 foreach($mods as $m) {
83 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
84 if (!file_exists($fd)) {
90 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
92 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
107 $ff = HTML_FlexyFramework::get();
108 if (!empty($ff->cli)) {
113 parent::getAuth(); // load company!
114 $au = $this->getAuthUser();
115 if (!$au || $au->company()->comptype != 'OWNER') {
116 $this->jerr("Not authenticated", array('authFailure' => true));
118 $this->authUser = $au;
122 function get($args, $opts)
125 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
128 $this->fixSequencesPgsql();exit;
131 // ask all the modules to verify the opts
133 $this->checkOpts($opts);
137 if (empty($opts['data-only'])) {
140 if (!empty($opts['only-module-sql'])) {
144 $this->runUpdateModulesData();
147 if (!empty($opts['add-company'])) {
148 DB_DataObject::factory('companies')->initCompanies($this, $opts);
156 * imports SQL files from all DataObjects directories....
158 * except any matching /migrate/
163 $ff = HTML_Flexyframework::get();
165 $url = parse_url($ff->DB_DataObject['database']);
167 $this->{'import' . $url['scheme']}($url);
172 * mysql - does not support conversions.
178 function importmysqldir($dburl, $dir)
180 echo "Import MYSQL :: $dir\n";
183 require_once 'System.php';
184 $cat = System::which('cat');
185 $mysql = System::which('mysql');
189 $mysql_cmd = $mysql .
190 ' -h ' . $dburl['host'] .
191 ' -u' . escapeshellarg($dburl['user']) .
192 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
193 ' ' . basename($dburl['path']);
194 //echo $mysql_cmd . "\n" ;
197 foreach(glob($dir.'/*.sql') as $fn) {
200 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
203 // .my.sql but not .pg.sql
204 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
205 && !preg_match('#\.my\.sql#i', basename($fn))
206 ) { // skip migration scripts at present..
209 if (!strlen(trim($fn))) {
213 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
215 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
228 function importmysql($dburl)
231 // hide stuff for web..
232 $ar = $this->modulesList();
236 // old -- DAtaObjects/*.sql
240 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
244 $fd = $this->rootDir. "/Pman/$m/DataObjects";
246 $this->importmysqldir($dburl, $fd);
248 // new -- sql directory..
249 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
250 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
252 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
253 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
262 * postgresql import..
264 function importpgsql($dburl)
267 // hide stuff for web..
272 $ar = $this->modulesList();
276 echo "Importing SQL from module $m\n";
277 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
280 echo "Importing SQL from module $m\n";
281 // if init has been called
283 if (!empty($this->opts['init'])) {
284 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
290 $fd = $this->rootDir. "/Pman/$m/DataObjects";
292 $this->importpgsqldir($dburl, $fd);
294 // new -- sql directory..
295 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
296 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
298 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
299 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
303 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
304 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
306 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
307 $this->fixSequencesPgsql();
316 function importpgsqldir($url, $dir, $disable_triggers = false)
318 require_once 'System.php';
319 $cat = System::which('cat');
320 $psql = System::which('psql');
323 if (!empty($url['pass'])) {
324 putenv("PGPASSWORD=". $url['pass']);
328 ' -h ' . $url['host'] .
329 ' -U' . escapeshellarg($url['user']) .
330 ' ' . basename($url['path']);
333 echo $psql_cmd . "\n" ;
334 echo "scan : $dir\n";
335 foreach(glob($dir.'/*.sql') as $bfn) {
338 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
341 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
342 && !preg_match('#\.pg\.sql#i', basename($bfn))
343 ) { // skip migration scripts at present..
348 if (!preg_match('/pgsql/', basename($dir) )) {
349 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
350 $fn = $this->convertToPG($bfn);
354 // files ending in .pg.sql are native postgres files.. ## depricated
357 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
359 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
374 * simple regex based convert mysql to pgsql...
376 function convertToPG($src)
378 //echo "Convert $src\n";
380 $fn = $this->tempName('sql');
382 $ret = array( ); // pad it a bit.
383 $extra = array("", "" );
386 foreach(file($src) as $l) {
389 if (!strlen($l) || $l[0] == '#') {
393 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
396 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
397 $tbl = 'shop_' . strtolower($m[1]);
398 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
400 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
401 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
404 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
405 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
406 $extra[] = "create sequence {$tbl}_seq;";
410 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
411 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
414 // enum value -- use the text instead..
416 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
417 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
419 // ignore the alter enum
420 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
424 // UNIQUE KEY .. ignore
425 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
426 $last = array_pop($ret);
427 $ret[] = trim($last, ",");
431 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
435 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
439 // INDEX lookup ..ignore
440 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
441 $last = array_pop($ret);
442 $ret[] = trim($last, ",");
447 // CREATE INDEX ..ignore
448 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
449 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
454 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
456 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
457 $l = preg_replace('# blob#i', ' TEXT', $l);
458 $l = preg_replace('# longtext#i', ' TEXT', $l);
459 $l = preg_replace('# tinyint#i', ' INT', $l);
465 $ret = array_merge($extra,$ret);
466 // echo implode("\n", $ret); exit;
468 file_put_contents($fn, implode("\n", $ret));
474 function checkOpts($opts)
478 foreach($opts as $o=>$v) {
479 if (!preg_match('/^json-/', $o) || empty($v)) {
482 if (!file_exists($v)) {
483 die("File does not exist : OPTION --{$o} = {$v} \n");
487 $modules = array_reverse($this->modulesList());
489 // move 'project' one to the end...
491 foreach ($modules as $module){
492 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
493 if($module == 'Core' || !file_exists($file)){
497 $class = "Pman_{$module}_UpdateDatabase";
499 if(!method_exists($x, 'checkOpts')){
502 $x->checkOpts($opts);
506 static function jsonImportFromArray($opts)
508 foreach($opts as $o=>$v) {
509 if (!preg_match('/^json-/', $o) || empty($v)) {
512 $type = str_replace('_', '-', substr($o,6));
513 $data= json_decode(file_get_contents($file),true);
514 DB_DataObject::factory($type)->importFromArray($this,$data,$opts);
522 function runUpdateModulesData()
526 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
527 echo "Running jsonImportFromArray\n";
528 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
531 echo "Running updateData on modules\n";
535 $modules = array_reverse($this->modulesList());
537 // move 'project' one to the end...
539 foreach ($modules as $module){
540 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
541 if($module == 'Core' || !file_exists($file)){
546 $class = "Pman_{$module}_UpdateDatabase";
548 if(!method_exists($x, 'updateData')){
558 function updateDataEnums()
560 $enum = DB_DataObject::Factory('core_enum');
565 'name' => 'COMPTYPE',
566 'display_name' => 'Company Types',
567 'is_system_enum' => 1,
571 'display_name' => 'Owner',
572 'seqid' => 999, // last...
573 'is_system_enum' => 1,
580 'name' => 'HtmlEditor.font-family',
581 'display_name' => 'HTML Editor font families',
582 'is_system_enum' => 1,
585 'name' => 'Helvetica,Arial,sans-serif',
586 'display_name' => 'Helvetica',
591 'name' => 'Courier New',
592 'display_name' => 'Courier',
597 'display_name' => 'Tahoma',
601 'name' => 'Times New Roman,serif',
602 'display_name' => 'Times',
607 'display_name' => 'Verdana',
619 function updateDataGroups()
622 $groups = DB_DataObject::factory('groups');
623 $groups->initGroups();
625 $groups->initDatabase($this,array(
627 'name' => 'bcc-email', // group who are bcc'ed on all requests.
628 'type' => 0, // system
635 function updateDataCompanies()
638 // fix comptypes enums..
639 $c = DB_DataObject::Factory('Companies');
641 $c->selectAdd('distinct(comptype) as comptype');
642 $c->whereAdd("comptype != ''");
645 foreach($c->fetchAll('comptype') as $cts) {
649 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
652 $c = DB_DataObject::Factory('core_enum');
655 //DB_DataObject::debugLevel(1);
657 $c = DB_DataObject::Factory('Companies');
661 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
674 function updateData()
678 $this->updateDataEnums();
679 $this->updateDataGroups();
680 $this->updateDataCompanies();
682 $c = DB_DataObject::Factory('I18n');
689 function fixSequencesPgsql()
693 //DB_DataObject::debugLevel(1);
694 $cs = DB_DataObject::factory('core_enum');
698 WHEN strpos(seq_name, '.') > 0 THEN
699 quote_ident(min(seq_name))
701 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
704 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
705 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
709 n.nspname AS schema_name,
710 c.relname AS table_name,
711 a.attname AS column_name,
712 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
714 JOIN pg_attribute a ON (c.oid=a.attrelid)
715 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
716 JOIN pg_namespace n ON (c.relnamespace=n.oid)
717 WHERE has_schema_privilege(n.oid,'USAGE')
718 AND n.nspname NOT LIKE 'pg!_%' escape '!'
719 AND has_table_privilege(c.oid,'SELECT')
720 AND (NOT a.attisdropped)
721 AND d.adsrc ~ '^nextval'
724 GROUP BY seq_name HAVING count(*)=1
727 while ($cs->fetch()) {
730 foreach($cmds as $cmd) {
731 $cs = DB_DataObject::factory('core_enum');
735 $cs = DB_DataObject::factory('core_enum');
737 SELECT 'SELECT SETVAL(' ||
738 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
739 ', MAX(' || quote_ident(C.attname)|| ') ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
745 WHERE S.relkind = 'S'
747 AND D.refobjid = T.oid
748 AND D.refobjid = C.attrelid
749 AND D.refobjsubid = C.attnum
750 AND NS.oid = T.relnamespace
754 while ($cs->fetch()) {
757 foreach($cmds as $cmd) {
758 $cs = DB_DataObject::factory('core_enum');