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);
166 * imports SQL files from all DataObjects directories....
168 * except any matching /migrate/
173 // loop through all the modules, and see if they have a importSQL method?
176 $ff = HTML_Flexyframework::get();
178 $dburl = parse_url($ff->DB_DataObject['database']);
180 //$this->{'import' . $url['scheme']}($url);
182 $dbtype = $dburl['scheme'];
183 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
188 $ar = $this->modulesList();
192 echo "Importing SQL from module $m\n";
193 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
198 // check to see if the class has
202 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
203 if($m != 'Core' && file_exists($file)){
206 $class = "Pman_{$m}_UpdateDatabase";
208 if(method_exists($x, 'importModuleSQL')){
209 echo "Importing SQL from module $m using Module::importModuleSQL\n";
210 $x->opts = $this->opts;
211 $x->rootDir = $this->rootDir;
212 $x->importModuleSQL($dburl);
217 echo "Importing SQL from module $m\n";
220 // if init has been called
222 if (!empty($this->opts['init'])) {
223 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
229 $fd = $this->rootDir. "/Pman/$m/DataObjects";
231 $this->{$dirmethod}($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->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
238 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
242 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
243 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
245 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
246 $this->{'fixSequences'. $dbtype}();
258 /** -------------- code to handle importing a whole directory of files into the database ------- **/
261 function importpgsqldir($url, $dir, $disable_triggers = false)
263 $ff = HTML_FlexyFramework::get();
265 require_once 'System.php';
266 $cat = System::which('cat');
267 $psql = System::which('psql');
270 if (!empty($url['pass'])) {
271 putenv("PGPASSWORD=". $url['pass']);
275 ' -h ' . $url['host'] .
276 ' -U' . escapeshellarg($url['user']) .
277 ' ' . basename($url['path']);
280 echo $psql_cmd . "\n" ;
281 echo "scan : $dir\n";
284 $files = array($dir);
289 $files = glob($dir.'/*.sql');
290 uksort($files, 'strcasecmp');
292 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
293 //usort($files, $lsort);
296 foreach($files as $bfn) {
299 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
302 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
303 && !preg_match('#\.pg\.sql#i', basename($bfn))
304 ) { // skip migration scripts at present..
309 if (!preg_match('/pgsql/', basename($dir) )) {
310 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
311 $fn = $this->convertToPG($bfn);
315 // files ending in .pg.sql are native postgres files.. ## depricated
318 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
320 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
336 * mysql - does not support conversions.
342 function importmysqldir($dburl, $dir)
344 echo "Import MYSQL :: $dir\n";
347 require_once 'System.php';
348 $cat = System::which('cat');
349 $mysql = System::which('mysql');
353 $mysql_cmd = $mysql .
354 ' -h ' . $dburl['host'] .
355 ' -u' . escapeshellarg($dburl['user']) .
356 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
357 ' ' . basename($dburl['path']);
358 //echo $mysql_cmd . "\n" ;
360 $files = glob($dir.'/*.sql');
361 uksort($files, 'strcasecmp');
364 foreach($files as $fn) {
367 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
370 // .my.sql but not .pg.sql
371 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
372 && !preg_match('#\.my\.sql#i', basename($fn))
373 ) { // skip migration scripts at present..
376 if (!strlen(trim($fn))) {
380 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
382 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
395 * simple regex based convert mysql to pgsql...
397 function convertToPG($src)
399 //echo "Convert $src\n";
401 $fn = $this->tempName('sql');
403 $ret = array( ); // pad it a bit.
404 $extra = array("", "" );
407 foreach(file($src) as $l) {
410 if (!strlen($l) || $l[0] == '#') {
414 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
417 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
418 $tbl = 'shop_' . strtolower($m[1]);
419 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
421 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
422 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
425 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
426 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
427 $extra[] = "create sequence {$tbl}_seq;";
431 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
432 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
435 // enum value -- use the text instead..
437 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
438 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
440 // ignore the alter enum
441 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
445 // UNIQUE KEY .. ignore
446 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
447 $last = array_pop($ret);
448 $ret[] = trim($last, ",");
452 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
456 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
460 // INDEX lookup ..ignore
461 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
462 $last = array_pop($ret);
463 $ret[] = trim($last, ",");
468 // CREATE INDEX ..ignore
469 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
470 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
475 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
477 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
478 $l = preg_replace('# blob#i', ' TEXT', $l);
479 $l = preg_replace('# longtext#i', ' TEXT', $l);
480 $l = preg_replace('# tinyint#i', ' INT', $l);
486 $ret = array_merge($extra,$ret);
487 // echo implode("\n", $ret); exit;
489 file_put_contents($fn, implode("\n", $ret));
495 function checkOpts($opts)
499 foreach($opts as $o=>$v) {
500 if (!preg_match('/^json-/', $o) || empty($v)) {
503 if (!file_exists($v)) {
504 die("File does not exist : OPTION --{$o} = {$v} \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)){
518 $class = "Pman_{$module}_UpdateDatabase";
520 if(!method_exists($x, 'checkOpts')){
523 $x->checkOpts($opts);
527 static function jsonImportFromArray($opts)
529 foreach($opts as $o=>$v) {
530 if (!preg_match('/^json-/', $o) || empty($v)) {
533 $type = str_replace('_', '-', substr($o,5));
535 $data= json_decode(file_get_contents($v),true);
536 $pg = HTML_FlexyFramework::get()->page;
537 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
547 function runUpdateModulesData()
551 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
552 echo "Running jsonImportFromArray\n";
553 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
556 echo "Running updateData on modules\n";
560 $modules = array_reverse($this->modulesList());
562 // move 'project' one to the end...
564 foreach ($modules as $module){
565 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
566 if($module == 'Core' || !file_exists($file)){
571 $class = "Pman_{$module}_UpdateDatabase";
573 if(!method_exists($x, 'updateData')){
583 function updateDataEnums()
586 $enum = DB_DataObject::Factory('core_enum');
587 //DB_DAtaObject::debugLevel(1);
592 'name' => 'COMPTYPE',
593 'display_name' => 'Company Types',
594 'is_system_enum' => 1,
598 'display_name' => 'Owner',
599 'seqid' => 999, // last...
600 'is_system_enum' => 1,
607 'name' => 'HtmlEditor.font-family',
608 'display_name' => 'HTML Editor font families',
609 'is_system_enum' => 1,
612 'name' => 'Helvetica,Arial,sans-serif',
613 'display_name' => 'Helvetica',
618 'name' => 'Courier New',
619 'display_name' => 'Courier',
624 'display_name' => 'Tahoma',
628 'name' => 'Times New Roman,serif',
629 'display_name' => 'Times',
634 'display_name' => 'Verdana',
646 function updateDataGroups()
649 $groups = DB_DataObject::factory('groups');
650 $groups->initGroups();
652 $groups->initDatabase($this,array(
654 'name' => 'bcc-email', // group who are bcc'ed on all requests.
655 'type' => 0, // system
658 'name' => 'system-email-from',
659 'type' => 0, // system
665 function updateDataCompanies()
668 // fix comptypes enums..
669 $c = DB_DataObject::Factory('Companies');
671 $c->selectAdd('distinct(comptype) as comptype');
672 $c->whereAdd("comptype != ''");
675 foreach($c->fetchAll('comptype') as $cts) {
679 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
682 $c = DB_DataObject::Factory('core_enum');
685 //DB_DataObject::debugLevel(1);
687 $c = DB_DataObject::Factory('Companies');
691 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
704 function updateData()
707 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
708 $this->updateDataEnums();
709 $this->updateDataGroups();
710 $this->updateDataCompanies();
712 $c = DB_DataObject::Factory('I18n');
720 function fixMysqlInnodb()
722 // innodb in single files is far more efficient that MYD or one big innodb file.
723 // first check if database is using this format.
724 $db = DB_DataObject::factory('core_enum');
725 $db->query("show variables like 'innodb_file_per_table'");
728 // Value should == ON
730 // I think it needs to look in the mysql directory.... to see if the idb exists..
731 $db = DB_DataObject::factory('core_enum');
732 $db->query("SHOW TABLE STATUS");
733 // Engine should be InnoDB - and file XXX.idb should exist...
746 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
748 function fixSequencesMysql()
753 function fixSequencesPgsql()
757 //DB_DataObject::debugLevel(1);
758 $cs = DB_DataObject::factory('core_enum');
762 CASE WHEN strpos(seq_name, '.') > 0 THEN
765 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
768 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
769 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
773 n.nspname AS schema_name,
774 c.relname AS table_name,
775 a.attname AS column_name,
776 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
778 JOIN pg_attribute a ON (c.oid=a.attrelid)
779 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
780 JOIN pg_namespace n ON (c.relnamespace=n.oid)
781 WHERE has_schema_privilege(n.oid,'USAGE')
782 AND n.nspname NOT LIKE 'pg!_%' escape '!'
783 AND has_table_privilege(c.oid,'SELECT')
784 AND (NOT a.attisdropped)
785 AND d.adsrc ~ '^nextval'
789 CASE WHEN strpos(seq_name, '.') > 0 THEN
790 substring(seq_name, 1,strpos(seq_name,'.')-1)
795 GROUP BY seq_name HAVING count(*)=1
798 while ($cs->fetch()) {
801 foreach($cmds as $cmd) {
802 $cs = DB_DataObject::factory('core_enum');
806 $cs = DB_DataObject::factory('core_enum');
808 SELECT 'SELECT SETVAL(' ||
809 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
810 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
816 WHERE S.relkind = 'S'
818 AND D.refobjid = T.oid
819 AND D.refobjid = C.attrelid
820 AND D.refobjsubid = C.attnum
821 AND NS.oid = T.relnamespace
825 while ($cs->fetch()) {
828 foreach($cmds as $cmd) {
829 $cs = DB_DataObject::factory('core_enum');
839 $ff = HTML_Flexyframework::get();
841 $dburl = parse_url($ff->DB_DataObject['database']);
843 $dbtype = $dburl['scheme'];
845 $scls = ucfirst($dbtype). 'Links';
846 $cls = 'Pman_Core_UpdateDatabase_'. $scls;
847 $fn = implode('/',explode('_', $cls)).'.php';
848 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {