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)
345 $this->fixMysqlInnodb(); /// run once
347 echo "Import MYSQL :: $dir\n";
350 require_once 'System.php';
351 $cat = System::which('cat');
352 $mysql = System::which('mysql');
356 $mysql_cmd = $mysql .
357 ' -h ' . $dburl['host'] .
358 ' -u' . escapeshellarg($dburl['user']) .
359 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
360 ' ' . basename($dburl['path']);
361 //echo $mysql_cmd . "\n" ;
363 $files = glob($dir.'/*.sql');
364 uksort($files, 'strcasecmp');
367 foreach($files as $fn) {
370 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
373 // .my.sql but not .pg.sql
374 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
375 && !preg_match('#\.my\.sql#i', basename($fn))
376 ) { // skip migration scripts at present..
379 if (!strlen(trim($fn))) {
383 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
385 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
398 * simple regex based convert mysql to pgsql...
400 function convertToPG($src)
402 //echo "Convert $src\n";
404 $fn = $this->tempName('sql');
406 $ret = array( ); // pad it a bit.
407 $extra = array("", "" );
410 foreach(file($src) as $l) {
413 if (!strlen($l) || $l[0] == '#') {
417 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
420 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
421 $tbl = 'shop_' . strtolower($m[1]);
422 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
424 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
425 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
428 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
429 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
430 $extra[] = "create sequence {$tbl}_seq;";
434 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
435 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
438 // enum value -- use the text instead..
440 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
441 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
443 // ignore the alter enum
444 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
448 // UNIQUE KEY .. ignore
449 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
450 $last = array_pop($ret);
451 $ret[] = trim($last, ",");
455 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
459 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
463 // INDEX lookup ..ignore
464 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
465 $last = array_pop($ret);
466 $ret[] = trim($last, ",");
471 // CREATE INDEX ..ignore
472 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
473 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
478 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
480 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
481 $l = preg_replace('# blob#i', ' TEXT', $l);
482 $l = preg_replace('# longtext#i', ' TEXT', $l);
483 $l = preg_replace('# tinyint#i', ' INT', $l);
489 $ret = array_merge($extra,$ret);
490 // echo implode("\n", $ret); exit;
492 file_put_contents($fn, implode("\n", $ret));
498 function checkOpts($opts)
502 foreach($opts as $o=>$v) {
503 if (!preg_match('/^json-/', $o) || empty($v)) {
506 if (!file_exists($v)) {
507 die("File does not exist : OPTION --{$o} = {$v} \n");
511 $modules = array_reverse($this->modulesList());
513 // move 'project' one to the end...
515 foreach ($modules as $module){
516 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
517 if($module == 'Core' || !file_exists($file)){
521 $class = "Pman_{$module}_UpdateDatabase";
523 if(!method_exists($x, 'checkOpts')){
526 $x->checkOpts($opts);
530 static function jsonImportFromArray($opts)
532 foreach($opts as $o=>$v) {
533 if (!preg_match('/^json-/', $o) || empty($v)) {
536 $type = str_replace('_', '-', substr($o,5));
538 $data= json_decode(file_get_contents($v),true);
539 $pg = HTML_FlexyFramework::get()->page;
540 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
550 function runUpdateModulesData()
554 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
555 echo "Running jsonImportFromArray\n";
556 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
559 echo "Running updateData on modules\n";
563 $modules = array_reverse($this->modulesList());
565 // move 'project' one to the end...
567 foreach ($modules as $module){
568 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
569 if($module == 'Core' || !file_exists($file)){
574 $class = "Pman_{$module}_UpdateDatabase";
576 if(!method_exists($x, 'updateData')){
586 function updateDataEnums()
589 $enum = DB_DataObject::Factory('core_enum');
590 //DB_DAtaObject::debugLevel(1);
595 'name' => 'COMPTYPE',
596 'display_name' => 'Company Types',
597 'is_system_enum' => 1,
601 'display_name' => 'Owner',
602 'seqid' => 999, // last...
603 'is_system_enum' => 1,
610 'name' => 'HtmlEditor.font-family',
611 'display_name' => 'HTML Editor font families',
612 'is_system_enum' => 1,
615 'name' => 'Helvetica,Arial,sans-serif',
616 'display_name' => 'Helvetica',
621 'name' => 'Courier New',
622 'display_name' => 'Courier',
627 'display_name' => 'Tahoma',
631 'name' => 'Times New Roman,serif',
632 'display_name' => 'Times',
637 'display_name' => 'Verdana',
649 function updateDataGroups()
652 $groups = DB_DataObject::factory('groups');
653 $groups->initGroups();
655 $groups->initDatabase($this,array(
657 'name' => 'bcc-email', // group who are bcc'ed on all requests.
658 'type' => 0, // system
661 'name' => 'system-email-from',
662 'type' => 0, // system
665 'name' => 'core-person-signup-bcc',
666 'type' => 0, // system
672 function updateDataCompanies()
675 // fix comptypes enums..
676 $c = DB_DataObject::Factory('Companies');
678 $c->selectAdd('distinct(comptype) as comptype');
679 $c->whereAdd("comptype != ''");
682 foreach($c->fetchAll('comptype') as $cts) {
686 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
689 $c = DB_DataObject::Factory('core_enum');
692 //DB_DataObject::debugLevel(1);
694 $c = DB_DataObject::Factory('Companies');
698 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
711 function updateData()
714 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
715 $this->updateDataEnums();
716 $this->updateDataGroups();
717 $this->updateDataCompanies();
719 $c = DB_DataObject::Factory('I18n');
727 function fixMysqlInnodb()
730 static $done_check = false;
734 // innodb in single files is far more efficient that MYD or one big innodb file.
735 // first check if database is using this format.
736 $db = DB_DataObject::factory('core_enum');
737 $db->query("show variables like 'innodb_file_per_table'");
739 if ($db->Value == 'OFF') {
740 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
754 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
756 function fixSequencesMysql()
761 function fixSequencesPgsql()
765 //DB_DataObject::debugLevel(1);
766 $cs = DB_DataObject::factory('core_enum');
770 CASE WHEN strpos(seq_name, '.') > 0 THEN
773 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
776 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
777 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
781 n.nspname AS schema_name,
782 c.relname AS table_name,
783 a.attname AS column_name,
784 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
786 JOIN pg_attribute a ON (c.oid=a.attrelid)
787 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
788 JOIN pg_namespace n ON (c.relnamespace=n.oid)
789 WHERE has_schema_privilege(n.oid,'USAGE')
790 AND n.nspname NOT LIKE 'pg!_%' escape '!'
791 AND has_table_privilege(c.oid,'SELECT')
792 AND (NOT a.attisdropped)
793 AND d.adsrc ~ '^nextval'
797 CASE WHEN strpos(seq_name, '.') > 0 THEN
798 substring(seq_name, 1,strpos(seq_name,'.')-1)
803 GROUP BY seq_name HAVING count(*)=1
806 while ($cs->fetch()) {
809 foreach($cmds as $cmd) {
810 $cs = DB_DataObject::factory('core_enum');
814 $cs = DB_DataObject::factory('core_enum');
816 SELECT 'SELECT SETVAL(' ||
817 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
818 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
824 WHERE S.relkind = 'S'
826 AND D.refobjid = T.oid
827 AND D.refobjid = C.attrelid
828 AND D.refobjsubid = C.attnum
829 AND NS.oid = T.relnamespace
833 while ($cs->fetch()) {
836 foreach($cmds as $cmd) {
837 $cs = DB_DataObject::factory('core_enum');
847 $ff = HTML_Flexyframework::get();
849 $dburl = parse_url($ff->DB_DataObject['database']);
851 $dbtype = $dburl['scheme'];
853 $scls = ucfirst($dbtype). 'Links';
854 $cls = 'Pman_Core_UpdateDatabase_'. $scls;
855 $fn = implode('/',explode('_', $cls)).'.php';
856 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {