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);
141 if (empty($opts['data-only'])) {
144 if (!empty($opts['only-module-sql'])) {
148 $this->runUpdateModulesData();
151 if (!empty($opts['add-company'])) {
152 // make sure we have a good cache...?
154 DB_DataObject::factory('companies')->initCompanies($this, $opts);
157 $this->runExtensions();
165 * imports SQL files from all DataObjects directories....
167 * except any matching /migrate/
172 // loop through all the modules, and see if they have a importSQL method?
175 $ff = HTML_Flexyframework::get();
177 $dburl = parse_url($ff->DB_DataObject['database']);
179 //$this->{'import' . $url['scheme']}($url);
181 $dbtype = $dburl['scheme'];
182 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
187 $ar = $this->modulesList();
191 echo "Importing SQL from module $m\n";
192 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
197 // check to see if the class has
201 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
202 if($m != 'Core' && file_exists($file)){
205 $class = "Pman_{$m}_UpdateDatabase";
207 if(method_exists($x, 'importModuleSQL')){
208 echo "Importing SQL from module $m using Module::importModuleSQL\n";
209 $x->opts = $this->opts;
210 $x->rootDir = $this->rootDir;
211 $x->importModuleSQL($dburl);
216 echo "Importing SQL from module $m\n";
219 // if init has been called
221 if (!empty($this->opts['init'])) {
222 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
228 $fd = $this->rootDir. "/Pman/$m/DataObjects";
230 $this->{$dirmethod}($dburl, $fd);
232 // new -- sql directory..
233 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
234 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
236 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
237 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
241 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
242 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
244 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
245 $this->{'fixSequences'. $dbtype}();
257 /** -------------- code to handle importing a whole directory of files into the database ------- **/
260 function importpgsqldir($url, $dir, $disable_triggers = false)
262 $ff = HTML_FlexyFramework::get();
264 require_once 'System.php';
265 $cat = System::which('cat');
266 $psql = System::which('psql');
269 if (!empty($url['pass'])) {
270 putenv("PGPASSWORD=". $url['pass']);
274 ' -h ' . $url['host'] .
275 ' -U' . escapeshellarg($url['user']) .
276 ' ' . basename($url['path']);
279 echo $psql_cmd . "\n" ;
280 echo "scan : $dir\n";
283 $files = array($dir);
288 $files = glob($dir.'/*.sql');
289 uksort($files, 'strcasecmp');
291 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
292 //usort($files, $lsort);
295 foreach($files as $bfn) {
298 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
301 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
302 && !preg_match('#\.pg\.sql#i', basename($bfn))
303 ) { // skip migration scripts at present..
308 if (!preg_match('/pgsql/', basename($dir) )) {
309 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
310 $fn = $this->convertToPG($bfn);
314 // files ending in .pg.sql are native postgres files.. ## depricated
317 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
319 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
335 * mysql - does not support conversions.
341 function importmysqldir($dburl, $dir)
344 $this->fixMysqlInnodb(); /// run once
346 echo "Import MYSQL :: $dir\n";
349 require_once 'System.php';
350 $cat = System::which('cat');
351 $mysql = System::which('mysql');
355 $mysql_cmd = $mysql .
356 ' -h ' . $dburl['host'] .
357 ' -u' . escapeshellarg($dburl['user']) .
358 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
359 ' ' . basename($dburl['path']);
360 //echo $mysql_cmd . "\n" ;
362 $files = glob($dir.'/*.sql');
363 uksort($files, 'strcasecmp');
366 foreach($files as $fn) {
369 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
372 // .my.sql but not .pg.sql
373 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
374 && !preg_match('#\.my\.sql#i', basename($fn))
375 ) { // skip migration scripts at present..
378 if (!strlen(trim($fn))) {
382 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
384 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
397 * simple regex based convert mysql to pgsql...
399 function convertToPG($src)
401 //echo "Convert $src\n";
403 $fn = $this->tempName('sql');
405 $ret = array( ); // pad it a bit.
406 $extra = array("", "" );
409 foreach(file($src) as $l) {
412 if (!strlen($l) || $l[0] == '#') {
416 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
419 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
420 $tbl = 'shop_' . strtolower($m[1]);
421 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
423 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
424 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
427 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
428 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
429 $extra[] = "create sequence {$tbl}_seq;";
433 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
434 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
437 // enum value -- use the text instead..
439 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
440 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
442 // ignore the alter enum
443 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
447 // UNIQUE KEY .. ignore
448 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
449 $last = array_pop($ret);
450 $ret[] = trim($last, ",");
454 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
458 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
462 // INDEX lookup ..ignore
463 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
464 $last = array_pop($ret);
465 $ret[] = trim($last, ",");
470 // CREATE INDEX ..ignore
471 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
472 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
477 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
479 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
480 $l = preg_replace('# blob#i', ' TEXT', $l);
481 $l = preg_replace('# longtext#i', ' TEXT', $l);
482 $l = preg_replace('# tinyint#i', ' INT', $l);
488 $ret = array_merge($extra,$ret);
489 // echo implode("\n", $ret); exit;
491 file_put_contents($fn, implode("\n", $ret));
497 function checkOpts($opts)
501 foreach($opts as $o=>$v) {
502 if (!preg_match('/^json-/', $o) || empty($v)) {
505 if (!file_exists($v)) {
506 die("File does not exist : OPTION --{$o} = {$v} \n");
510 $modules = array_reverse($this->modulesList());
512 // move 'project' one to the end...
514 foreach ($modules as $module){
515 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
516 if($module == 'Core' || !file_exists($file)){
520 $class = "Pman_{$module}_UpdateDatabase";
522 if(!method_exists($x, 'checkOpts')){
525 $x->checkOpts($opts);
529 static function jsonImportFromArray($opts)
531 foreach($opts as $o=>$v) {
532 if (!preg_match('/^json-/', $o) || empty($v)) {
535 $type = str_replace('_', '-', substr($o,5));
537 $data= json_decode(file_get_contents($v),true);
538 $pg = HTML_FlexyFramework::get()->page;
539 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
549 function runUpdateModulesData()
553 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
554 echo "Running jsonImportFromArray\n";
555 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
558 echo "Running updateData on modules\n";
562 $modules = array_reverse($this->modulesList());
564 // move 'project' one to the end...
566 foreach ($modules as $module){
567 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
568 if($module == 'Core' || !file_exists($file)){
573 $class = "Pman_{$module}_UpdateDatabase";
575 if(!method_exists($x, 'updateData')){
585 function updateDataEnums()
588 $enum = DB_DataObject::Factory('core_enum');
589 //DB_DAtaObject::debugLevel(1);
594 'name' => 'COMPTYPE',
595 'display_name' => 'Company Types',
596 'is_system_enum' => 1,
600 'display_name' => 'Owner',
601 'seqid' => 999, // last...
602 'is_system_enum' => 1,
609 'name' => 'HtmlEditor.font-family',
610 'display_name' => 'HTML Editor font families',
611 'is_system_enum' => 1,
614 'name' => 'Helvetica,Arial,sans-serif',
615 'display_name' => 'Helvetica',
620 'name' => 'Courier New',
621 'display_name' => 'Courier',
626 'display_name' => 'Tahoma',
630 'name' => 'Times New Roman,serif',
631 'display_name' => 'Times',
636 'display_name' => 'Verdana',
648 function updateDataGroups()
651 $groups = DB_DataObject::factory('groups');
652 $groups->initGroups();
654 $groups->initDatabase($this,array(
656 'name' => 'bcc-email', // group who are bcc'ed on all requests.
657 'type' => 0, // system
660 'name' => 'system-email-from',
661 'type' => 0, // system
664 'name' => 'core-person-signup-bcc',
665 'type' => 0, // system
671 function updateDataCompanies()
674 // fix comptypes enums..
675 $c = DB_DataObject::Factory('Companies');
677 $c->selectAdd('distinct(comptype) as comptype');
678 $c->whereAdd("comptype != ''");
681 foreach($c->fetchAll('comptype') as $cts) {
685 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
688 $c = DB_DataObject::Factory('core_enum');
691 //DB_DataObject::debugLevel(1);
693 $c = DB_DataObject::Factory('Companies');
697 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
710 function updateData()
713 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
714 $this->updateDataEnums();
715 $this->updateDataGroups();
716 $this->updateDataCompanies();
718 $c = DB_DataObject::Factory('I18n');
726 function fixMysqlInnodb()
729 static $done_check = false;
733 // innodb in single files is far more efficient that MYD or one big innodb file.
734 // first check if database is using this format.
735 $db = DB_DataObject::factory('core_enum');
736 $db->query("show variables like 'innodb_file_per_table'");
738 if ($db->Value == 'OFF') {
739 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
753 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
755 function fixSequencesMysql()
760 function fixSequencesPgsql()
764 //DB_DataObject::debugLevel(1);
765 $cs = DB_DataObject::factory('core_enum');
769 CASE WHEN strpos(seq_name, '.') > 0 THEN
772 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
775 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
776 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
780 n.nspname AS schema_name,
781 c.relname AS table_name,
782 a.attname AS column_name,
783 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
785 JOIN pg_attribute a ON (c.oid=a.attrelid)
786 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
787 JOIN pg_namespace n ON (c.relnamespace=n.oid)
788 WHERE has_schema_privilege(n.oid,'USAGE')
789 AND n.nspname NOT LIKE 'pg!_%' escape '!'
790 AND has_table_privilege(c.oid,'SELECT')
791 AND (NOT a.attisdropped)
792 AND d.adsrc ~ '^nextval'
796 CASE WHEN strpos(seq_name, '.') > 0 THEN
797 substring(seq_name, 1,strpos(seq_name,'.')-1)
802 GROUP BY seq_name HAVING count(*)=1
805 while ($cs->fetch()) {
808 foreach($cmds as $cmd) {
809 $cs = DB_DataObject::factory('core_enum');
813 $cs = DB_DataObject::factory('core_enum');
815 SELECT 'SELECT SETVAL(' ||
816 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
817 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
823 WHERE S.relkind = 'S'
825 AND D.refobjid = T.oid
826 AND D.refobjid = C.attrelid
827 AND D.refobjsubid = C.attnum
828 AND NS.oid = T.relnamespace
832 while ($cs->fetch()) {
835 foreach($cmds as $cmd) {
836 $cs = DB_DataObject::factory('core_enum');
843 var $extensions = array(
848 function runExtensions()
851 $ff = HTML_Flexyframework::get();
853 $dburl = parse_url($ff->DB_DataObject['database']);
855 $dbtype = $dburl['scheme'];
857 foreach($this->extensions as $ext) {
859 $scls = ucfirst($dbtype). $ext;
860 $cls = __CLASS__ . '_'. $scls;
861 $fn = implode('/',explode('_', $cls)).'.php';
862 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {