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',
64 'procedures-only' => array(
65 'desc' => 'Only import procedures (not supported by most modules yet) - ignores sql directory',
72 'json-person' => array(
73 'desc' => 'Person JSON file',
81 static function cli_opts()
84 $ret = self::$cli_opts;
85 $ff = HTML_FlexyFramework::get();
87 $mods = $a->modulesList();
88 foreach($mods as $m) {
90 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
91 if (!file_exists($fd)) {
97 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
99 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
114 $ff = HTML_FlexyFramework::get();
115 if (!empty($ff->cli)) {
120 parent::getAuth(); // load company!
121 $au = $this->getAuthUser();
122 if (!$au || $au->company()->comptype != 'OWNER') {
123 $this->jerr("Not authenticated", array('authFailure' => true));
125 $this->authUser = $au;
129 function get($args, $opts)
131 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
134 //$this->fixSequencesPgsql();exit;
137 // ask all the modules to verify the opts
139 $this->checkOpts($opts);
143 if (empty($opts['data-only'])) {
146 if (!empty($opts['only-module-sql'])) {
150 $this->runUpdateModulesData();
153 if (!empty($opts['add-company'])) {
154 // make sure we have a good cache...?
156 DB_DataObject::factory('companies')->initCompanies($this, $opts);
164 * imports SQL files from all DataObjects directories....
166 * except any matching /migrate/
171 // loop through all the modules, and see if they have a importSQL method?
174 $ff = HTML_Flexyframework::get();
176 $url = parse_url($ff->DB_DataObject['database']);
178 $this->{'import' . $url['scheme']}($url);
186 * mysql - does not support conversions.
192 function importmysqldir($dburl, $dir)
194 echo "Import MYSQL :: $dir\n";
197 require_once 'System.php';
198 $cat = System::which('cat');
199 $mysql = System::which('mysql');
203 $mysql_cmd = $mysql .
204 ' -h ' . $dburl['host'] .
205 ' -u' . escapeshellarg($dburl['user']) .
206 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
207 ' ' . basename($dburl['path']);
208 //echo $mysql_cmd . "\n" ;
210 $files = glob($dir.'/*.sql');
211 uksort($files, 'strcasecmp');
214 foreach($files as $fn) {
217 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
220 // .my.sql but not .pg.sql
221 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
222 && !preg_match('#\.my\.sql#i', basename($fn))
223 ) { // skip migration scripts at present..
226 if (!strlen(trim($fn))) {
230 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
232 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
245 function importmysql($dburl)
248 // hide stuff for web..
249 $ar = $this->modulesList();
253 // old -- DAtaObjects/*.sql
257 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
261 $fd = $this->rootDir. "/Pman/$m/DataObjects";
263 $this->importmysqldir($dburl, $fd);
265 // new -- sql directory..
266 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
267 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
269 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
270 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
279 * postgresql import..
281 function importpgsql($dburl)
284 // hide stuff for web..
289 $ar = $this->modulesList();
293 echo "Importing SQL from module $m\n";
294 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
297 echo "Importing SQL from module $m\n";
298 // if init has been called
300 if (!empty($this->opts['init'])) {
301 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
307 $fd = $this->rootDir. "/Pman/$m/DataObjects";
309 $this->importpgsqldir($dburl, $fd);
311 // new -- sql directory..
312 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
313 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
315 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
316 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
320 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
321 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
323 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
324 $this->fixSequencesPgsql();
333 function importpgsqldir($url, $dir, $disable_triggers = false)
335 require_once 'System.php';
336 $cat = System::which('cat');
337 $psql = System::which('psql');
340 if (!empty($url['pass'])) {
341 putenv("PGPASSWORD=". $url['pass']);
345 ' -h ' . $url['host'] .
346 ' -U' . escapeshellarg($url['user']) .
347 ' ' . basename($url['path']);
350 echo $psql_cmd . "\n" ;
351 echo "scan : $dir\n";
353 $files = glob($dir.'/*.sql');
354 uksort($files, 'strcasecmp');
355 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
356 //usort($files, $lsort);
360 foreach($files as $bfn) {
363 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
366 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
367 && !preg_match('#\.pg\.sql#i', basename($bfn))
368 ) { // skip migration scripts at present..
373 if (!preg_match('/pgsql/', basename($dir) )) {
374 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
375 $fn = $this->convertToPG($bfn);
379 // files ending in .pg.sql are native postgres files.. ## depricated
382 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
384 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
399 * simple regex based convert mysql to pgsql...
401 function convertToPG($src)
403 //echo "Convert $src\n";
405 $fn = $this->tempName('sql');
407 $ret = array( ); // pad it a bit.
408 $extra = array("", "" );
411 foreach(file($src) as $l) {
414 if (!strlen($l) || $l[0] == '#') {
418 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
421 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
422 $tbl = 'shop_' . strtolower($m[1]);
423 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
425 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
426 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
429 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
430 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
431 $extra[] = "create sequence {$tbl}_seq;";
435 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
436 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
439 // enum value -- use the text instead..
441 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
442 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
444 // ignore the alter enum
445 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
449 // UNIQUE KEY .. ignore
450 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
451 $last = array_pop($ret);
452 $ret[] = trim($last, ",");
456 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
460 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
464 // INDEX lookup ..ignore
465 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
466 $last = array_pop($ret);
467 $ret[] = trim($last, ",");
472 // CREATE INDEX ..ignore
473 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
474 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
479 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
481 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
482 $l = preg_replace('# blob#i', ' TEXT', $l);
483 $l = preg_replace('# longtext#i', ' TEXT', $l);
484 $l = preg_replace('# tinyint#i', ' INT', $l);
490 $ret = array_merge($extra,$ret);
491 // echo implode("\n", $ret); exit;
493 file_put_contents($fn, implode("\n", $ret));
499 function checkOpts($opts)
503 foreach($opts as $o=>$v) {
504 if (!preg_match('/^json-/', $o) || empty($v)) {
507 if (!file_exists($v)) {
508 die("File does not exist : OPTION --{$o} = {$v} \n");
512 $modules = array_reverse($this->modulesList());
514 // move 'project' one to the end...
516 foreach ($modules as $module){
517 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
518 if($module == 'Core' || !file_exists($file)){
522 $class = "Pman_{$module}_UpdateDatabase";
524 if(!method_exists($x, 'checkOpts')){
527 $x->checkOpts($opts);
531 static function jsonImportFromArray($opts)
533 foreach($opts as $o=>$v) {
534 if (!preg_match('/^json-/', $o) || empty($v)) {
537 $type = str_replace('_', '-', substr($o,5));
539 $data= json_decode(file_get_contents($v),true);
540 $pg = HTML_FlexyFramework::get()->page;
541 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
550 * modular import of SQL.
551 * -- if a module implements importSQL
552 * - then we should not run the import SQL on the children of that folder as it is handled by the module.
556 function runModulesImportSQL()
560 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
561 echo "Running runModulesImportSQL\n";
564 echo "Running importSQL on modules\n";
569 $modules = array_reverse($this->modulesList());
571 // move 'project' one to the end...
573 foreach ($modules as $module){
574 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
575 if($module == 'Core' || !file_exists($file)){
580 $class = "Pman_{$module}_UpdateDatabase";
582 if(!method_exists($x, 'updateData')){
594 function runUpdateModulesData()
598 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
599 echo "Running jsonImportFromArray\n";
600 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
603 echo "Running updateData on modules\n";
607 $modules = array_reverse($this->modulesList());
609 // move 'project' one to the end...
611 foreach ($modules as $module){
612 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
613 if($module == 'Core' || !file_exists($file)){
618 $class = "Pman_{$module}_UpdateDatabase";
620 if(!method_exists($x, 'updateData')){
630 function updateDataEnums()
633 $enum = DB_DataObject::Factory('core_enum');
634 //DB_DAtaObject::debugLevel(1);
639 'name' => 'COMPTYPE',
640 'display_name' => 'Company Types',
641 'is_system_enum' => 1,
645 'display_name' => 'Owner',
646 'seqid' => 999, // last...
647 'is_system_enum' => 1,
654 'name' => 'HtmlEditor.font-family',
655 'display_name' => 'HTML Editor font families',
656 'is_system_enum' => 1,
659 'name' => 'Helvetica,Arial,sans-serif',
660 'display_name' => 'Helvetica',
665 'name' => 'Courier New',
666 'display_name' => 'Courier',
671 'display_name' => 'Tahoma',
675 'name' => 'Times New Roman,serif',
676 'display_name' => 'Times',
681 'display_name' => 'Verdana',
693 function updateDataGroups()
696 $groups = DB_DataObject::factory('groups');
697 $groups->initGroups();
699 $groups->initDatabase($this,array(
701 'name' => 'bcc-email', // group who are bcc'ed on all requests.
702 'type' => 0, // system
705 'name' => 'system-email-from',
706 'type' => 0, // system
712 function updateDataCompanies()
715 // fix comptypes enums..
716 $c = DB_DataObject::Factory('Companies');
718 $c->selectAdd('distinct(comptype) as comptype');
719 $c->whereAdd("comptype != ''");
722 foreach($c->fetchAll('comptype') as $cts) {
726 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
729 $c = DB_DataObject::Factory('core_enum');
732 //DB_DataObject::debugLevel(1);
734 $c = DB_DataObject::Factory('Companies');
738 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
751 function updateData()
754 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
755 $this->updateDataEnums();
756 $this->updateDataGroups();
757 $this->updateDataCompanies();
759 $c = DB_DataObject::Factory('I18n');
766 function fixSequencesPgsql()
770 //DB_DataObject::debugLevel(1);
771 $cs = DB_DataObject::factory('core_enum');
775 CASE WHEN strpos(seq_name, '.') > 0 THEN
778 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
781 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
782 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
786 n.nspname AS schema_name,
787 c.relname AS table_name,
788 a.attname AS column_name,
789 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
791 JOIN pg_attribute a ON (c.oid=a.attrelid)
792 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
793 JOIN pg_namespace n ON (c.relnamespace=n.oid)
794 WHERE has_schema_privilege(n.oid,'USAGE')
795 AND n.nspname NOT LIKE 'pg!_%' escape '!'
796 AND has_table_privilege(c.oid,'SELECT')
797 AND (NOT a.attisdropped)
798 AND d.adsrc ~ '^nextval'
802 CASE WHEN strpos(seq_name, '.') > 0 THEN
803 substring(seq_name, 1,strpos(seq_name,'.')-1)
808 GROUP BY seq_name HAVING count(*)=1
811 while ($cs->fetch()) {
814 foreach($cmds as $cmd) {
815 $cs = DB_DataObject::factory('core_enum');
819 $cs = DB_DataObject::factory('core_enum');
821 SELECT 'SELECT SETVAL(' ||
822 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
823 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
829 WHERE S.relkind = 'S'
831 AND D.refobjid = T.oid
832 AND D.refobjid = C.attrelid
833 AND D.refobjsubid = C.attnum
834 AND NS.oid = T.relnamespace
838 while ($cs->fetch()) {
841 foreach($cmds as $cmd) {
842 $cs = DB_DataObject::factory('core_enum');