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'));
108 var $disabled = array();
115 $ff = HTML_FlexyFramework::get();
116 if (!empty($ff->cli)) {
121 parent::getAuth(); // load company!
122 $au = $this->getAuthUser();
123 if (!$au || $au->company()->comptype != 'OWNER') {
124 $this->jerr("Not authenticated", array('authFailure' => true));
126 $this->authUser = $au;
130 function get($args, $opts)
132 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
134 $ff = HTML_FlexyFramework::get();
136 $this->disabled = explode(',', $ff->disable);
138 //$this->fixSequencesPgsql();exit;
141 // ask all the modules to verify the opts
143 $this->checkOpts($opts);
145 if (empty($opts['data-only'])) {
148 if (!empty($opts['only-module-sql'])) {
152 $this->runUpdateModulesData();
155 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
156 // make sure we have a good cache...?
158 DB_DataObject::factory('companies')->initCompanies($this, $opts);
161 $this->runExtensions();
169 * imports SQL files from all DataObjects directories....
171 * except any matching /migrate/
176 // loop through all the modules, and see if they have a importSQL method?
179 $ff = HTML_Flexyframework::get();
181 $dburl = parse_url($ff->DB_DataObject['database']);
183 //$this->{'import' . $url['scheme']}($url);
185 $dbtype = $dburl['scheme'];
186 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
191 $ar = $this->modulesList();
196 if(in_array($m, $this->disabled)){
197 echo "module $m is disabled \n";
201 echo "Importing SQL from module $m\n";
202 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
207 // check to see if the class has
211 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
212 if($m != 'Core' && file_exists($file)){
215 $class = "Pman_{$m}_UpdateDatabase";
217 if(method_exists($x, 'importModuleSQL')){
218 echo "Importing SQL from module $m using Module::importModuleSQL\n";
219 $x->opts = $this->opts;
220 $x->rootDir = $this->rootDir;
221 $x->importModuleSQL($dburl);
226 echo "Importing SQL from module $m\n";
229 // if init has been called
231 if (!empty($this->opts['init'])) {
232 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
238 $fd = $this->rootDir. "/Pman/$m/DataObjects";
240 $this->{$dirmethod}($dburl, $fd);
242 // new -- sql directory..
243 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
244 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
246 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
247 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
251 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
252 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
254 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
255 $this->{'fixSequences'. $dbtype}();
267 /** -------------- code to handle importing a whole directory of files into the database ------- **/
270 function importpgsqldir($url, $dir, $disable_triggers = false)
272 $ff = HTML_FlexyFramework::get();
274 require_once 'System.php';
275 $cat = System::which('cat');
276 $psql = System::which('psql');
279 if (!empty($url['pass'])) {
280 putenv("PGPASSWORD=". $url['pass']);
284 ' -h ' . $url['host'] .
285 ' -U' . escapeshellarg($url['user']) .
286 ' ' . basename($url['path']);
289 echo $psql_cmd . "\n" ;
290 echo "scan : $dir\n";
293 $files = array($dir);
298 $files = glob($dir.'/*.sql');
299 uksort($files, 'strcasecmp');
301 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
302 //usort($files, $lsort);
305 foreach($files as $bfn) {
308 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
311 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
312 && !preg_match('#\.pg\.sql#i', basename($bfn))
313 ) { // skip migration scripts at present..
318 if (!preg_match('/pgsql/', basename($dir) )) {
319 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
320 $fn = $this->convertToPG($bfn);
324 // files ending in .pg.sql are native postgres files.. ## depricated
327 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
329 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
345 * mysql - does not support conversions.
351 function importmysqldir($dburl, $dir)
354 $this->fixMysqlInnodb(); /// run once
356 echo "Import MYSQL :: $dir\n";
359 require_once 'System.php';
360 $cat = System::which('cat');
361 $mysql = System::which('mysql');
365 $mysql_cmd = $mysql .
366 ' -h ' . $dburl['host'] .
367 ' -u' . escapeshellarg($dburl['user']) .
368 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
369 ' ' . basename($dburl['path']);
370 //echo $mysql_cmd . "\n" ;
372 $files = glob($dir.'/*.sql');
373 uksort($files, 'strcasecmp');
376 foreach($files as $fn) {
379 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
382 // .my.sql but not .pg.sql
383 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
384 && !preg_match('#\.my\.sql#i', basename($fn))
385 ) { // skip migration scripts at present..
388 if (!strlen(trim($fn))) {
392 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
394 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
407 * simple regex based convert mysql to pgsql...
409 function convertToPG($src)
411 //echo "Convert $src\n";
413 $fn = $this->tempName('sql');
415 $ret = array( ); // pad it a bit.
416 $extra = array("", "" );
419 foreach(file($src) as $l) {
422 if (!strlen($l) || $l[0] == '#') {
426 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
429 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
430 $tbl = 'shop_' . strtolower($m[1]);
431 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
433 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
434 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
437 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
438 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
439 $extra[] = "create sequence {$tbl}_seq;";
443 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
444 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
447 // enum value -- use the text instead..
449 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
450 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
452 // ignore the alter enum
453 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
457 // UNIQUE KEY .. ignore
458 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
459 $last = array_pop($ret);
460 $ret[] = trim($last, ",");
464 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
468 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
472 // INDEX lookup ..ignore
473 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
474 $last = array_pop($ret);
475 $ret[] = trim($last, ",");
480 // CREATE INDEX ..ignore
481 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
482 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
487 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
489 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
490 $l = preg_replace('# blob#i', ' TEXT', $l);
491 $l = preg_replace('# longtext#i', ' TEXT', $l);
492 $l = preg_replace('# tinyint#i', ' INT', $l);
498 $ret = array_merge($extra,$ret);
499 // echo implode("\n", $ret); exit;
501 file_put_contents($fn, implode("\n", $ret));
507 function checkOpts($opts)
511 foreach($opts as $o=>$v) {
512 if (!preg_match('/^json-/', $o) || empty($v)) {
515 if (!file_exists($v)) {
516 die("File does not exist : OPTION --{$o} = {$v} \n");
520 $modules = array_reverse($this->modulesList());
522 // move 'project' one to the end...
524 foreach ($modules as $module){
525 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
526 if($module == 'Core' || !file_exists($file)){
530 $class = "Pman_{$module}_UpdateDatabase";
532 if(!method_exists($x, 'checkOpts')){
535 $x->checkOpts($opts);
539 static function jsonImportFromArray($opts)
541 foreach($opts as $o=>$v) {
542 if (!preg_match('/^json-/', $o) || empty($v)) {
545 $type = str_replace('_', '-', substr($o,5));
547 $data= json_decode(file_get_contents($v),true);
548 $pg = HTML_FlexyFramework::get()->page;
549 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
559 function runUpdateModulesData()
561 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
563 if(!in_array('Core', $this->disabled)){
564 echo "Running jsonImportFromArray\n";
565 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
568 echo "Running updateData on modules\n";
574 $modules = array_reverse($this->modulesList());
576 // move 'project' one to the end...
578 foreach ($modules as $module){
579 if(in_array($module, $this->disabled)){
582 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
583 if($module == 'Core' || !file_exists($file)){
588 $class = "Pman_{$module}_UpdateDatabase";
590 if(!method_exists($x, 'updateData')){
600 function updateDataEnums()
603 $enum = DB_DataObject::Factory('core_enum');
604 //DB_DAtaObject::debugLevel(1);
609 'name' => 'COMPTYPE',
610 'display_name' => 'Company Types',
611 'is_system_enum' => 1,
615 'display_name' => 'Owner',
616 'seqid' => 999, // last...
617 'is_system_enum' => 1,
624 'name' => 'HtmlEditor.font-family',
625 'display_name' => 'HTML Editor font families',
626 'is_system_enum' => 1,
629 'name' => 'Helvetica,Arial,sans-serif',
630 'display_name' => 'Helvetica',
635 'name' => 'Courier New',
636 'display_name' => 'Courier',
641 'display_name' => 'Tahoma',
645 'name' => 'Times New Roman,serif',
646 'display_name' => 'Times',
651 'display_name' => 'Verdana',
663 function updateDataGroups()
666 $groups = DB_DataObject::factory('groups');
667 $groups->initGroups();
669 $groups->initDatabase($this,array(
671 'name' => 'bcc-email', // group who are bcc'ed on all requests.
672 'type' => 0, // system
675 'name' => 'system-email-from',
676 'type' => 0, // system
679 'name' => 'core-person-signup-bcc',
680 'type' => 0, // system
686 function updateDataCompanies()
689 // fix comptypes enums..
690 $c = DB_DataObject::Factory('Companies');
692 $c->selectAdd('distinct(comptype) as comptype');
693 $c->whereAdd("comptype != ''");
696 foreach($c->fetchAll('comptype') as $cts) {
700 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
703 $c = DB_DataObject::Factory('core_enum');
706 //DB_DataObject::debugLevel(1);
708 $c = DB_DataObject::Factory('Companies');
712 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
725 function updateData()
728 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
729 $this->updateDataEnums();
730 $this->updateDataGroups();
731 $this->updateDataCompanies();
733 $c = DB_DataObject::Factory('I18n');
741 function fixMysqlInnodb()
744 static $done_check = false;
748 // innodb in single files is far more efficient that MYD or one big innodb file.
749 // first check if database is using this format.
750 $db = DB_DataObject::factory('core_enum');
751 $db->query("show variables like 'innodb_file_per_table'");
753 if ($db->Value == 'OFF') {
754 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
768 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
770 function fixSequencesMysql()
775 function fixSequencesPgsql()
779 //DB_DataObject::debugLevel(1);
780 $cs = DB_DataObject::factory('core_enum');
784 CASE WHEN strpos(seq_name, '.') > 0 THEN
787 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
790 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
791 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
795 n.nspname AS schema_name,
796 c.relname AS table_name,
797 a.attname AS column_name,
798 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
800 JOIN pg_attribute a ON (c.oid=a.attrelid)
801 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
802 JOIN pg_namespace n ON (c.relnamespace=n.oid)
803 WHERE has_schema_privilege(n.oid,'USAGE')
804 AND n.nspname NOT LIKE 'pg!_%' escape '!'
805 AND has_table_privilege(c.oid,'SELECT')
806 AND (NOT a.attisdropped)
807 AND d.adsrc ~ '^nextval'
811 CASE WHEN strpos(seq_name, '.') > 0 THEN
812 substring(seq_name, 1,strpos(seq_name,'.')-1)
817 GROUP BY seq_name HAVING count(*)=1
820 while ($cs->fetch()) {
823 foreach($cmds as $cmd) {
824 $cs = DB_DataObject::factory('core_enum');
828 $cs = DB_DataObject::factory('core_enum');
830 SELECT 'SELECT SETVAL(' ||
831 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
832 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
838 WHERE S.relkind = 'S'
840 AND D.refobjid = T.oid
841 AND D.refobjid = C.attrelid
842 AND D.refobjsubid = C.attnum
843 AND NS.oid = T.relnamespace
847 while ($cs->fetch()) {
850 foreach($cmds as $cmd) {
851 $cs = DB_DataObject::factory('core_enum');
858 var $extensions = array(
863 function runExtensions()
866 $ff = HTML_Flexyframework::get();
868 $dburl = parse_url($ff->DB_DataObject['database']);
870 $dbtype = $dburl['scheme'];
872 foreach($this->extensions as $ext) {
874 $scls = ucfirst($dbtype). $ext;
875 $cls = __CLASS__ . '_'. $scls;
876 $fn = implode('/',explode('_', $cls)).'.php';
877 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {