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'])) {
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();
195 echo "Importing SQL from module $m\n";
196 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
201 // check to see if the class has
205 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
206 if($m != 'Core' && file_exists($file)){
209 $class = "Pman_{$m}_UpdateDatabase";
211 if(method_exists($x, 'importModuleSQL')){
212 echo "Importing SQL from module $m using Module::importModuleSQL\n";
213 $x->opts = $this->opts;
214 $x->rootDir = $this->rootDir;
215 $x->importModuleSQL($dburl);
220 echo "Importing SQL from module $m\n";
223 // if init has been called
225 if (!empty($this->opts['init'])) {
226 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
232 $fd = $this->rootDir. "/Pman/$m/DataObjects";
234 $this->{$dirmethod}($dburl, $fd);
236 // new -- sql directory..
237 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
238 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
240 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
241 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
245 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
246 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
248 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
249 $this->{'fixSequences'. $dbtype}();
261 /** -------------- code to handle importing a whole directory of files into the database ------- **/
264 function importpgsqldir($url, $dir, $disable_triggers = false)
266 $ff = HTML_FlexyFramework::get();
268 require_once 'System.php';
269 $cat = System::which('cat');
270 $psql = System::which('psql');
273 if (!empty($url['pass'])) {
274 putenv("PGPASSWORD=". $url['pass']);
278 ' -h ' . $url['host'] .
279 ' -U' . escapeshellarg($url['user']) .
280 ' ' . basename($url['path']);
283 echo $psql_cmd . "\n" ;
284 echo "scan : $dir\n";
287 $files = array($dir);
292 $files = glob($dir.'/*.sql');
293 uksort($files, 'strcasecmp');
295 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
296 //usort($files, $lsort);
299 foreach($files as $bfn) {
302 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
305 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
306 && !preg_match('#\.pg\.sql#i', basename($bfn))
307 ) { // skip migration scripts at present..
312 if (!preg_match('/pgsql/', basename($dir) )) {
313 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
314 $fn = $this->convertToPG($bfn);
318 // files ending in .pg.sql are native postgres files.. ## depricated
321 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
323 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
339 * mysql - does not support conversions.
345 function importmysqldir($dburl, $dir)
348 $this->fixMysqlInnodb(); /// run once
350 echo "Import MYSQL :: $dir\n";
353 require_once 'System.php';
354 $cat = System::which('cat');
355 $mysql = System::which('mysql');
359 $mysql_cmd = $mysql .
360 ' -h ' . $dburl['host'] .
361 ' -u' . escapeshellarg($dburl['user']) .
362 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
363 ' ' . basename($dburl['path']);
364 //echo $mysql_cmd . "\n" ;
366 $files = glob($dir.'/*.sql');
367 uksort($files, 'strcasecmp');
370 foreach($files as $fn) {
373 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
376 // .my.sql but not .pg.sql
377 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
378 && !preg_match('#\.my\.sql#i', basename($fn))
379 ) { // skip migration scripts at present..
382 if (!strlen(trim($fn))) {
386 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
388 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
401 * simple regex based convert mysql to pgsql...
403 function convertToPG($src)
405 //echo "Convert $src\n";
407 $fn = $this->tempName('sql');
409 $ret = array( ); // pad it a bit.
410 $extra = array("", "" );
413 foreach(file($src) as $l) {
416 if (!strlen($l) || $l[0] == '#') {
420 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
423 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
424 $tbl = 'shop_' . strtolower($m[1]);
425 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
427 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
428 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
431 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
432 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
433 $extra[] = "create sequence {$tbl}_seq;";
437 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
438 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
441 // enum value -- use the text instead..
443 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
444 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
446 // ignore the alter enum
447 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
451 // UNIQUE KEY .. ignore
452 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
453 $last = array_pop($ret);
454 $ret[] = trim($last, ",");
458 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
462 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
466 // INDEX lookup ..ignore
467 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
468 $last = array_pop($ret);
469 $ret[] = trim($last, ",");
474 // CREATE INDEX ..ignore
475 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
476 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
481 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
483 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
484 $l = preg_replace('# blob#i', ' TEXT', $l);
485 $l = preg_replace('# longtext#i', ' TEXT', $l);
486 $l = preg_replace('# tinyint#i', ' INT', $l);
492 $ret = array_merge($extra,$ret);
493 // echo implode("\n", $ret); exit;
495 file_put_contents($fn, implode("\n", $ret));
501 function checkOpts($opts)
505 foreach($opts as $o=>$v) {
506 if (!preg_match('/^json-/', $o) || empty($v)) {
509 if (!file_exists($v)) {
510 die("File does not exist : OPTION --{$o} = {$v} \n");
514 $modules = array_reverse($this->modulesList());
516 // move 'project' one to the end...
518 foreach ($modules as $module){
519 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
520 if($module == 'Core' || !file_exists($file)){
524 $class = "Pman_{$module}_UpdateDatabase";
526 if(!method_exists($x, 'checkOpts')){
529 $x->checkOpts($opts);
533 static function jsonImportFromArray($opts)
535 foreach($opts as $o=>$v) {
536 if (!preg_match('/^json-/', $o) || empty($v)) {
539 $type = str_replace('_', '-', substr($o,5));
541 $data= json_decode(file_get_contents($v),true);
542 $pg = HTML_FlexyFramework::get()->page;
543 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
553 function runUpdateModulesData()
557 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
558 echo "Running jsonImportFromArray\n";
559 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
562 echo "Running updateData on modules\n";
566 $modules = array_reverse($this->modulesList());
568 // move 'project' one to the end...
570 foreach ($modules as $module){
571 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
572 if($module == 'Core' || !file_exists($file)){
577 $class = "Pman_{$module}_UpdateDatabase";
579 if(!method_exists($x, 'updateData')){
589 function updateDataEnums()
592 $enum = DB_DataObject::Factory('core_enum');
593 //DB_DAtaObject::debugLevel(1);
598 'name' => 'COMPTYPE',
599 'display_name' => 'Company Types',
600 'is_system_enum' => 1,
604 'display_name' => 'Owner',
605 'seqid' => 999, // last...
606 'is_system_enum' => 1,
613 'name' => 'HtmlEditor.font-family',
614 'display_name' => 'HTML Editor font families',
615 'is_system_enum' => 1,
618 'name' => 'Helvetica,Arial,sans-serif',
619 'display_name' => 'Helvetica',
624 'name' => 'Courier New',
625 'display_name' => 'Courier',
630 'display_name' => 'Tahoma',
634 'name' => 'Times New Roman,serif',
635 'display_name' => 'Times',
640 'display_name' => 'Verdana',
652 function updateDataGroups()
655 $groups = DB_DataObject::factory('groups');
656 $groups->initGroups();
658 $groups->initDatabase($this,array(
660 'name' => 'bcc-email', // group who are bcc'ed on all requests.
661 'type' => 0, // system
664 'name' => 'system-email-from',
665 'type' => 0, // system
668 'name' => 'core-person-signup-bcc',
669 'type' => 0, // system
675 function updateDataCompanies()
678 // fix comptypes enums..
679 $c = DB_DataObject::Factory('Companies');
681 $c->selectAdd('distinct(comptype) as comptype');
682 $c->whereAdd("comptype != ''");
685 foreach($c->fetchAll('comptype') as $cts) {
689 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
692 $c = DB_DataObject::Factory('core_enum');
695 //DB_DataObject::debugLevel(1);
697 $c = DB_DataObject::Factory('Companies');
701 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
714 function updateData()
717 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
718 $this->updateDataEnums();
719 $this->updateDataGroups();
720 $this->updateDataCompanies();
722 $c = DB_DataObject::Factory('I18n');
730 function fixMysqlInnodb()
733 static $done_check = false;
737 // innodb in single files is far more efficient that MYD or one big innodb file.
738 // first check if database is using this format.
739 $db = DB_DataObject::factory('core_enum');
740 $db->query("show variables like 'innodb_file_per_table'");
742 if ($db->Value == 'OFF') {
743 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
757 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
759 function fixSequencesMysql()
764 function fixSequencesPgsql()
768 //DB_DataObject::debugLevel(1);
769 $cs = DB_DataObject::factory('core_enum');
773 CASE WHEN strpos(seq_name, '.') > 0 THEN
776 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
779 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
780 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
784 n.nspname AS schema_name,
785 c.relname AS table_name,
786 a.attname AS column_name,
787 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
789 JOIN pg_attribute a ON (c.oid=a.attrelid)
790 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
791 JOIN pg_namespace n ON (c.relnamespace=n.oid)
792 WHERE has_schema_privilege(n.oid,'USAGE')
793 AND n.nspname NOT LIKE 'pg!_%' escape '!'
794 AND has_table_privilege(c.oid,'SELECT')
795 AND (NOT a.attisdropped)
796 AND d.adsrc ~ '^nextval'
800 CASE WHEN strpos(seq_name, '.') > 0 THEN
801 substring(seq_name, 1,strpos(seq_name,'.')-1)
806 GROUP BY seq_name HAVING count(*)=1
809 while ($cs->fetch()) {
812 foreach($cmds as $cmd) {
813 $cs = DB_DataObject::factory('core_enum');
817 $cs = DB_DataObject::factory('core_enum');
819 SELECT 'SELECT SETVAL(' ||
820 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
821 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
827 WHERE S.relkind = 'S'
829 AND D.refobjid = T.oid
830 AND D.refobjid = C.attrelid
831 AND D.refobjsubid = C.attnum
832 AND NS.oid = T.relnamespace
836 while ($cs->fetch()) {
839 foreach($cmds as $cmd) {
840 $cs = DB_DataObject::factory('core_enum');
847 var $extensions = array(
852 function runExtensions()
855 $ff = HTML_Flexyframework::get();
857 $dburl = parse_url($ff->DB_DataObject['database']);
859 $dbtype = $dburl['scheme'];
861 foreach($this->extensions as $ext) {
863 $scls = ucfirst($dbtype). $ext;
864 $cls = __CLASS__ . '_'. $scls;
865 $fn = implode('/',explode('_', $cls)).'.php';
866 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {