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);
180 $dbtype = $url['scheme'];
181 $dirmethod = 'import' . $url['scheme'] . '.dir';
186 $ar = $this->modulesList();
190 echo "Importing SQL from module $m\n";
191 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
194 echo "Importing SQL from module $m\n";
195 // if init has been called
197 if (!empty($this->opts['init'])) {
198 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
204 $fd = $this->rootDir. "/Pman/$m/DataObjects";
206 $this->{$dirmethod}($dburl, $fd);
208 // new -- sql directory..
209 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
210 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
212 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
213 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
217 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
218 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
220 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
221 $this->{'fixSequences'. $dbtype}();
233 function importmysql($dburl)
236 // hide stuff for web..
237 $ar = $this->modulesList();
241 // old -- DAtaObjects/*.sql
245 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
249 $fd = $this->rootDir. "/Pman/$m/DataObjects";
251 $this->importmysqldir($dburl, $fd);
253 // new -- sql directory..
254 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
255 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
257 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
258 $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
267 * postgresql import..
269 function importpgsql($dburl)
272 // hide stuff for web..
277 $ar = $this->modulesList();
281 echo "Importing SQL from module $m\n";
282 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
285 echo "Importing SQL from module $m\n";
286 // if init has been called
288 if (!empty($this->opts['init'])) {
289 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
295 $fd = $this->rootDir. "/Pman/$m/DataObjects";
297 $this->importpgsqldir($dburl, $fd);
299 // new -- sql directory..
300 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
301 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
303 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
304 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
308 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
309 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
311 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
312 $this->fixSequencesPgsql();
321 /** -------------- code to handle importing a whole directory of files into the database ------- **/
324 function importpgsqldir($url, $dir, $disable_triggers = false)
326 require_once 'System.php';
327 $cat = System::which('cat');
328 $psql = System::which('psql');
331 if (!empty($url['pass'])) {
332 putenv("PGPASSWORD=". $url['pass']);
336 ' -h ' . $url['host'] .
337 ' -U' . escapeshellarg($url['user']) .
338 ' ' . basename($url['path']);
341 echo $psql_cmd . "\n" ;
342 echo "scan : $dir\n";
344 $files = glob($dir.'/*.sql');
345 uksort($files, 'strcasecmp');
346 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
347 //usort($files, $lsort);
351 foreach($files as $bfn) {
354 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
357 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
358 && !preg_match('#\.pg\.sql#i', basename($bfn))
359 ) { // skip migration scripts at present..
364 if (!preg_match('/pgsql/', basename($dir) )) {
365 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
366 $fn = $this->convertToPG($bfn);
370 // files ending in .pg.sql are native postgres files.. ## depricated
373 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
375 echo "$bfn: $cmd ". ($this->cli ? "\n" : "<BR>\n");
392 * mysql - does not support conversions.
398 function importmysqldir($dburl, $dir)
400 echo "Import MYSQL :: $dir\n";
403 require_once 'System.php';
404 $cat = System::which('cat');
405 $mysql = System::which('mysql');
409 $mysql_cmd = $mysql .
410 ' -h ' . $dburl['host'] .
411 ' -u' . escapeshellarg($dburl['user']) .
412 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
413 ' ' . basename($dburl['path']);
414 //echo $mysql_cmd . "\n" ;
416 $files = glob($dir.'/*.sql');
417 uksort($files, 'strcasecmp');
420 foreach($files as $fn) {
423 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
426 // .my.sql but not .pg.sql
427 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
428 && !preg_match('#\.my\.sql#i', basename($fn))
429 ) { // skip migration scripts at present..
432 if (!strlen(trim($fn))) {
436 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
438 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
451 * simple regex based convert mysql to pgsql...
453 function convertToPG($src)
455 //echo "Convert $src\n";
457 $fn = $this->tempName('sql');
459 $ret = array( ); // pad it a bit.
460 $extra = array("", "" );
463 foreach(file($src) as $l) {
466 if (!strlen($l) || $l[0] == '#') {
470 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
473 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
474 $tbl = 'shop_' . strtolower($m[1]);
475 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
477 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
478 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
481 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
482 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
483 $extra[] = "create sequence {$tbl}_seq;";
487 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
488 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
491 // enum value -- use the text instead..
493 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
494 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
496 // ignore the alter enum
497 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
501 // UNIQUE KEY .. ignore
502 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
503 $last = array_pop($ret);
504 $ret[] = trim($last, ",");
508 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
512 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
516 // INDEX lookup ..ignore
517 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
518 $last = array_pop($ret);
519 $ret[] = trim($last, ",");
524 // CREATE INDEX ..ignore
525 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
526 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
531 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
533 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
534 $l = preg_replace('# blob#i', ' TEXT', $l);
535 $l = preg_replace('# longtext#i', ' TEXT', $l);
536 $l = preg_replace('# tinyint#i', ' INT', $l);
542 $ret = array_merge($extra,$ret);
543 // echo implode("\n", $ret); exit;
545 file_put_contents($fn, implode("\n", $ret));
551 function checkOpts($opts)
555 foreach($opts as $o=>$v) {
556 if (!preg_match('/^json-/', $o) || empty($v)) {
559 if (!file_exists($v)) {
560 die("File does not exist : OPTION --{$o} = {$v} \n");
564 $modules = array_reverse($this->modulesList());
566 // move 'project' one to the end...
568 foreach ($modules as $module){
569 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
570 if($module == 'Core' || !file_exists($file)){
574 $class = "Pman_{$module}_UpdateDatabase";
576 if(!method_exists($x, 'checkOpts')){
579 $x->checkOpts($opts);
583 static function jsonImportFromArray($opts)
585 foreach($opts as $o=>$v) {
586 if (!preg_match('/^json-/', $o) || empty($v)) {
589 $type = str_replace('_', '-', substr($o,5));
591 $data= json_decode(file_get_contents($v),true);
592 $pg = HTML_FlexyFramework::get()->page;
593 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
603 function runUpdateModulesData()
607 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
608 echo "Running jsonImportFromArray\n";
609 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
612 echo "Running updateData on modules\n";
616 $modules = array_reverse($this->modulesList());
618 // move 'project' one to the end...
620 foreach ($modules as $module){
621 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
622 if($module == 'Core' || !file_exists($file)){
627 $class = "Pman_{$module}_UpdateDatabase";
629 if(!method_exists($x, 'updateData')){
639 function updateDataEnums()
642 $enum = DB_DataObject::Factory('core_enum');
643 //DB_DAtaObject::debugLevel(1);
648 'name' => 'COMPTYPE',
649 'display_name' => 'Company Types',
650 'is_system_enum' => 1,
654 'display_name' => 'Owner',
655 'seqid' => 999, // last...
656 'is_system_enum' => 1,
663 'name' => 'HtmlEditor.font-family',
664 'display_name' => 'HTML Editor font families',
665 'is_system_enum' => 1,
668 'name' => 'Helvetica,Arial,sans-serif',
669 'display_name' => 'Helvetica',
674 'name' => 'Courier New',
675 'display_name' => 'Courier',
680 'display_name' => 'Tahoma',
684 'name' => 'Times New Roman,serif',
685 'display_name' => 'Times',
690 'display_name' => 'Verdana',
702 function updateDataGroups()
705 $groups = DB_DataObject::factory('groups');
706 $groups->initGroups();
708 $groups->initDatabase($this,array(
710 'name' => 'bcc-email', // group who are bcc'ed on all requests.
711 'type' => 0, // system
714 'name' => 'system-email-from',
715 'type' => 0, // system
721 function updateDataCompanies()
724 // fix comptypes enums..
725 $c = DB_DataObject::Factory('Companies');
727 $c->selectAdd('distinct(comptype) as comptype');
728 $c->whereAdd("comptype != ''");
731 foreach($c->fetchAll('comptype') as $cts) {
735 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
738 $c = DB_DataObject::Factory('core_enum');
741 //DB_DataObject::debugLevel(1);
743 $c = DB_DataObject::Factory('Companies');
747 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
760 function updateData()
763 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
764 $this->updateDataEnums();
765 $this->updateDataGroups();
766 $this->updateDataCompanies();
768 $c = DB_DataObject::Factory('I18n');
776 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
778 function fixSequencesMysql()
783 function fixSequencesPgsql()
787 //DB_DataObject::debugLevel(1);
788 $cs = DB_DataObject::factory('core_enum');
792 CASE WHEN strpos(seq_name, '.') > 0 THEN
795 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
798 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
799 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
803 n.nspname AS schema_name,
804 c.relname AS table_name,
805 a.attname AS column_name,
806 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
808 JOIN pg_attribute a ON (c.oid=a.attrelid)
809 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
810 JOIN pg_namespace n ON (c.relnamespace=n.oid)
811 WHERE has_schema_privilege(n.oid,'USAGE')
812 AND n.nspname NOT LIKE 'pg!_%' escape '!'
813 AND has_table_privilege(c.oid,'SELECT')
814 AND (NOT a.attisdropped)
815 AND d.adsrc ~ '^nextval'
819 CASE WHEN strpos(seq_name, '.') > 0 THEN
820 substring(seq_name, 1,strpos(seq_name,'.')-1)
825 GROUP BY seq_name HAVING count(*)=1
828 while ($cs->fetch()) {
831 foreach($cmds as $cmd) {
832 $cs = DB_DataObject::factory('core_enum');
836 $cs = DB_DataObject::factory('core_enum');
838 SELECT 'SELECT SETVAL(' ||
839 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
840 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
846 WHERE S.relkind = 'S'
848 AND D.refobjid = T.oid
849 AND D.refobjid = C.attrelid
850 AND D.refobjsubid = C.attnum
851 AND NS.oid = T.relnamespace
855 while ($cs->fetch()) {
858 foreach($cmds as $cmd) {
859 $cs = DB_DataObject::factory('core_enum');