]> git.mjollnir.org Git - moodle.git/commitdiff
MDL-14854
authorthepurpleblob <thepurpleblob>
Thu, 15 May 2008 14:47:08 +0000 (14:47 +0000)
committerthepurpleblob <thepurpleblob>
Thu, 15 May 2008 14:47:08 +0000 (14:47 +0000)
Add facility to XMLDB editor to check for inconsistent field defaults.

admin/xmldb/actions/check_defaults/check_defaults.class.php [new file with mode: 0644]
admin/xmldb/actions/main_view/main_view.class.php
lang/en_utf8/xmldb.php

diff --git a/admin/xmldb/actions/check_defaults/check_defaults.class.php b/admin/xmldb/actions/check_defaults/check_defaults.class.php
new file mode 100644 (file)
index 0000000..2c7a902
--- /dev/null
@@ -0,0 +1,278 @@
+<?php // $Id$
+
+///////////////////////////////////////////////////////////////////////////
+//                                                                       //
+// NOTICE OF COPYRIGHT                                                   //
+//                                                                       //
+// Moodle - Modular Object-Oriented Dynamic Learning Environment         //
+//          http://moodle.com                                            //
+//                                                                       //
+// Copyright (C) 1999 onwards Martin Dougiamas        http://dougiamas.com  //
+//           (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com  //
+//                                                                       //
+// This program is free software; you can redistribute it and/or modify  //
+// it under the terms of the GNU General Public License as published by  //
+// the Free Software Foundation; either version 2 of the License, or     //
+// (at your option) any later version.                                   //
+//                                                                       //
+// This program is distributed in the hope that it will be useful,       //
+// but WITHOUT ANY WARRANTY; without even the implied warranty of        //
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         //
+// GNU General Public License for more details:                          //
+//                                                                       //
+//          http://www.gnu.org/copyleft/gpl.html                         //
+//                                                                       //
+///////////////////////////////////////////////////////////////////////////
+
+/// This class will check all the default values existing in the DB
+/// match those specified in the xml specs
+/// and providing one SQL script to fix all them. 
+
+class check_defaults extends XMLDBAction {
+
+    /**
+     * Init method, every subclass will have its own
+     */
+    function init() {
+        parent::init();
+
+    /// Set own core attributes
+
+    /// Set own custom attributes
+
+    /// Get needed strings
+        $this->loadStrings(array(
+            'confirmcheckdefaults' => 'xmldb',
+            'ok' => '',
+            'wrong' => 'xmldb',
+            'table' => 'xmldb',
+            'field' => 'xmldb',
+            'searchresults' => 'xmldb',
+            'wrongdefaults' => 'xmldb',
+            'completelogbelow' => 'xmldb',
+            'nowrongdefaultsfound' => 'xmldb',
+            'yeswrongdefaultsfound' => 'xmldb',
+            'yes' => '',
+            'no' => '',
+            'error' => '',
+            'shouldbe' => 'xmldb',
+            'butis' => 'xmldb',
+            'back' => 'xmldb'
+
+        ));
+    }
+
+    /**
+     * Invoke method, every class will have its own
+     * returns true/false on completion, setting both
+     * errormsg and output as necessary
+     */
+    function invoke() {
+        parent::invoke();
+
+        $result = true;
+
+    /// Set own core attributes
+        $this->does_generate = ACTION_GENERATE_HTML;
+
+    /// These are always here
+        global $CFG, $XMLDB, $db;
+
+    /// And we nedd some ddl suff
+        require_once ($CFG->libdir . '/ddllib.php');
+
+    /// Here we'll acummulate all the wrong fields found
+        $wrong_fields = array();
+
+    /// Do the job, setting $result as needed
+
+    /// Get the confirmed to decide what to do
+        $confirmed = optional_param('confirmed', false, PARAM_BOOL);
+
+    /// If  not confirmed, show confirmation box
+        if (!$confirmed) {
+            $o = '<table class="generalbox" border="0" cellpadding="5" cellspacing="0" id="notice">';
+            $o.= '  <tr><td class="generalboxcontent">';
+            $o.= '    <p class="centerpara">' . $this->str['confirmcheckdefaults'] . '</p>';
+            $o.= '    <table class="boxaligncenter" cellpadding="20"><tr><td>';
+            $o.= '      <div class="singlebutton">';
+            $o.= '        <form action="index.php?action=check_defaults&amp;confirmed=yes" method="post"><fieldset class="invisiblefieldset">';
+            $o.= '          <input type="submit" value="'. $this->str['yes'] .'" /></fieldset></form></div>';
+            $o.= '      </td><td>';
+            $o.= '      <div class="singlebutton">';
+            $o.= '        <form action="index.php?action=main_view" method="post"><fieldset class="invisiblefieldset">';
+            $o.= '          <input type="submit" value="'. $this->str['no'] .'" /></fieldset></form></div>';
+            $o.= '      </td></tr>';
+            $o.= '    </table>';
+            $o.= '  </td></tr>';
+            $o.= '</table>';
+
+            $this->output = $o;
+        } else {
+        /// The back to edit table button
+            $b = ' <p class="centerpara buttons">';
+            $b .= '<a href="index.php">[' . $this->str['back'] . ']</a>';
+            $b .= '</p>';
+
+        /// Iterate over $XMLDB->dbdirs, loading their XML data to memory
+            if ($XMLDB->dbdirs) {
+                $dbdirs =& $XMLDB->dbdirs;
+                $o='<ul>';
+                foreach ($dbdirs as $dbdir) {
+                /// Only if the directory exists
+                    if (!$dbdir->path_exists) {
+                        continue;
+                    }
+                /// Load the XML file
+                    $xmldb_file = new XMLDBFile($dbdir->path . '/install.xml');
+                /// Load the needed XMLDB generator
+                    $classname = 'XMLDB' . $CFG->dbtype;
+                    $generator = new $classname();
+                    $generator->setPrefix($CFG->prefix);
+
+                /// Only if the file exists
+                    if (!$xmldb_file->fileExists()) {
+                        continue;
+                    }
+                /// Load the XML contents to structure
+                    $loaded = $xmldb_file->loadXMLStructure();
+                    if (!$loaded || !$xmldb_file->isLoaded()) {
+                        notify('Errors found in XMLDB file: '. $dbdir->path . '/install.xml');
+                        continue;
+                    }
+                /// Arriving here, everything is ok, get the XMLDB structure
+                    $structure = $xmldb_file->getStructure();
+//echo "<pre>"; print_r( $structure ); die;
+                    $o.='    <li>' . str_replace($CFG->dirroot . '/', '', $dbdir->path . '/install.xml');
+                /// Getting tables
+                    if ($xmldb_tables = $structure->getTables()) {
+                        $o.='        <ul>';
+                    /// Foreach table, process its fields
+                        foreach ($xmldb_tables as $xmldb_table) {
+                        /// Skip table if not exists
+                            if (!table_exists($xmldb_table)) {
+                                continue;
+                            }
+                        /// Fetch metadata from phisical DB. All the columns info.
+                            if ($metacolumns = $db->MetaColumns($CFG->prefix . $xmldb_table->getName())) {
+                                $metacolumns = array_change_key_case($metacolumns, CASE_LOWER);
+// echo "<pre>".$xmldb_table->getName(); print_r( $metacolumns ); die;
+                            } else {
+                            //// Skip table if no metacolumns is available for it
+                                continue;
+                            }
+                        /// Table processing starts here
+                            $o.='            <li>' . $xmldb_table->getName();
+                        /// Get and process XMLDB fields
+                            if ($xmldb_fields = $xmldb_table->getFields()) {
+                                $o.='        <ul>';
+                                foreach ($xmldb_fields as $xmldb_field) {
+//echo "<pre>"; print_r( $xmldb_field ); die; 
+
+                                // Get the default value for the field 
+                                $xmldbdefault = $xmldb_field->getDefault();
+                                
+                                /// If the metadata for that column doesn't exist, skip
+                                if (!isset($metacolumns[$xmldb_field->getName()])) {
+                                    continue;
+                                }
+
+                                /// To variable for better handling
+                                $metacolumn = $metacolumns[$xmldb_field->getName()];
+
+                                /// Going to check this field in DB
+                                $o.='            <li>' . $this->str['field'] . ': ' . $xmldb_field->getName() . ' ';
+
+                                // get the value of the physical default (or blank if there isn't one)
+                                if ($metacolumn->has_default==1) {
+                                    $physicaldefault = $metacolumn->default_value;
+                                }
+                                else {
+                                    $physicaldefault = '';
+                                }
+
+                                // there *is* a default and it's wrong
+                                if ($physicaldefault != $xmldbdefault) {
+                                    $info = '['.$this->str['shouldbe']." '$xmldbdefault' ".$this->str['butis'].
+                                        " '$physicaldefault']";
+                                        $o.='<font color="red">' . $this->str['wrong'] . " $info</font>";
+                                    /// Add the wrong field to the list
+                                        $obj = new object;
+                                        $obj->table = $xmldb_table;
+                                        $obj->field = $xmldb_field;
+                                        $obj->physicaldefault = $physicaldefault;
+                                        $obj->xmldbdefault = $xmldbdefault;
+                                        $wrong_fields[] = $obj;
+                                    } else {
+                                        $o.='<font color="green">' . $this->str['ok'] . '</font>';
+                                    }
+                                    $o.='</li>';
+                                }
+                                $o.='        </ul>';
+                            }
+                            $o.='    </li>';
+                        }
+                        $o.='        </ul>';
+                    }
+                    $o.='    </li>';
+                }
+                $o.='</ul>';
+            }
+
+        /// We have finished, let's show the results of the search
+            $s = '';
+            $r = '<table class="generalbox boxaligncenter boxwidthwide" border="0" cellpadding="5" cellspacing="0" id="results">';
+            $r.= '  <tr><td class="generalboxcontent">';
+            $r.= '    <h2 class="main">' . $this->str['searchresults'] . '</h2>';
+            $r.= '    <p class="centerpara">' . $this->str['wrongdefaults'] . ': ' . count($wrong_fields) . '</p>';
+            $r.= '  </td></tr>';
+            $r.= '  <tr><td class="generalboxcontent">';
+
+        /// If we have found wrong defaults inform about them
+            if (count($wrong_fields)) {
+                $r.= '    <p class="centerpara">' . $this->str['yeswrongdefaultsfound'] . '</p>';
+                $r.= '        <ul>';
+                foreach ($wrong_fields as $obj) {
+                    $xmldb_table = $obj->table;
+                    $xmldb_field = $obj->field;
+                    $physicaldefault = $obj->physicaldefault;
+                    $xmldbdefault = $obj->xmldbdefault;
+                     
+                    // get the alter table command
+                    $sqlarr = $xmldb_table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $xmldb_field, true);
+
+                    $r.= '            <li>' . $this->str['table'] . ': ' . $xmldb_table->getName() . '. ' .
+                                              $this->str['field'] . ': ' . $xmldb_field->getName() . ', ' .
+                                              $this->str['shouldbe'] . ' ' . "'$xmldbdefault'" . ' ' .
+                                              $this->str['butis'] . ' ' . "'$physicaldefault'" . '</li>';
+                    /// Add to output if we have sentences
+                    if ($sqlarr) {
+                        $s.= '<code>' . str_replace("\n", '<br />', implode('<br />', $sqlarr)) . '</code><br />';
+                    }
+                }
+                $r.= '        </ul>';
+            /// Add the SQL statements (all together)
+                $r.= '<hr />' . $s;
+            } else {
+                $r.= '    <p class="centerpara">' . $this->str['nowrongintsfound'] . '</p>';
+            }
+            $r.= '  </td></tr>';
+            $r.= '  <tr><td class="generalboxcontent">';
+        /// Add the complete log message
+            $r.= '    <p class="centerpara">' . $this->str['completelogbelow'] . '</p>';
+            $r.= '  </td></tr>';
+            $r.= '</table>';
+
+            $this->output = $b . $r . $o;
+        }
+
+    /// Launch postaction if exists (leave this here!)
+        if ($this->getPostAction() && $result) {
+            return $this->launch($this->getPostAction());
+        }
+
+    /// Return ok if arrived here
+        return $result;
+    }
+}
+?>
index a9cc67e097c86c8c98580106b715636ce7a2e01a..8428343e085ee5bc35acaec34ebfa586c40d4aa1 100644 (file)
@@ -49,6 +49,7 @@ class main_view extends XMLDBAction {
             'test' => 'xmldb',
             'gotolastused' => 'xmldb',
             'checkindexes' => 'xmldb',
+            'checkdefaults' => 'xmldb',
             'checkbigints' => 'xmldb'
         ));
     }
@@ -88,6 +89,8 @@ class main_view extends XMLDBAction {
         $b .= '&nbsp;<a href="index.php?action=test">[' . $this->str['test'] . ']</a>';
     /// The check indexes button
         $b .= '&nbsp;<a href="index.php?action=check_indexes">[' . $this->str['checkindexes'] . ']</a>';
+    /// The check defaults button
+        $b .= '&nbsp;<a href="index.php?action=check_defaults">[' . $this->str['checkdefaults'] . ']</a>';
     /// The check bigints button (only for MySQL and PostgreSQL) MDL-11038a
         if ($CFG->dbfamily == 'mysql' || $CFG->dbfamily == 'postgres') {
             $b .= '&nbsp;<a href="index.php?action=check_bigints">[' . $this->str['checkbigints'] . ']</a>';
index b9afe43662925d839298a3f7bea23a57ef87d98d..f42df8078dbc260746fa0d28b4447af1b4ae6b45 100644 (file)
@@ -6,11 +6,14 @@ $string['aftertable'] = 'After Table:';
 $string['back'] = 'Back';
 $string['backtomainview'] = 'Back To Main';
 $string['binaryincorrectlength'] = 'Incorrect length for binary field';
+$string['butis'] = 'but is';
 $string['cannotuseidfield'] = 'Cannot insert the \"id\" field. It is an autonumeric column';
 $string['change'] = 'Change';
 $string['charincorrectlength'] = 'Incorrect length for char field';
 $string['checkbigints'] = 'Check Bigints';
+$string['checkdefaults'] = 'Check Defaults';
 $string['checkindexes'] = 'Check Indexes';
+$string['check_defaults'] = 'Look for inconsistent default values';
 $string['check_bigints'] = 'Look for incorrect DB integers';
 $string['check_indexes'] = 'Look for missing DB indexes';
 $string['completelogbelow'] = '(see the complete log of the search below)';
@@ -18,6 +21,10 @@ $string['confirmcheckbigints'] = 'This functionality will search for <a href=\"h
 Once generated you can copy such statements and execute them safely with your favourite SQL interface (don\'t forget to backup your data before doing that).<br /><br />
 It\'s highly recommended to be running the latest (+ version) available of your Moodle release (1.8, 1.9, 2.x ...) before executing the search of wrong integers.<br /><br />
 This functionality doesn\'t perform any action against the DB (just reads from it), so can be safely executed at any moment.';
+$string['confirmcheckdefaults'] = 'This functionality will search for inconsistent default values in your Moodle server, generating (but not executing!) the needed SQL statements to have all the default values properly defined.<br /><br />
+Once generated you can copy such statements and execute them safely with your favourite SQL interface (don\'t forget to backup your data before doing that).<br /><br />
+It\'s highly recommended to be running the latest (+ version) available of your Moodle release (1.8, 1.9, 2.x ...) before executing the search of wrong integers.<br /><br />
+This functionality doesn\'t perform any action against the DB (just reads from it), so can be safely executed at any moment.';
 $string['confirmcheckindexes'] = 'This functionality will search for potential missing indexes in your Moodle server, generating (but not executing!) automatically the needed SQL statements to keep everything updated.<br /><br />
 Once generated you can copy such statements and execute them safely with your favourite SQL interface (don\'t forget to backup your data before doing that).<br /><br />
 It\'s highly recommended to be running the latest (+ version) available of your Moodle release (1.8, 1.9, 2.x ...) before executing the search of missing indexes.<br /><br />
@@ -105,6 +112,7 @@ $string['selectonecommand'] = 'Please, select one Action from the list to view P
 $string['selectonefieldkeyindex'] = 'Please, select one Field/Key/Index from the list to view the PHP code';
 $string['selecttable'] = 'Select Table:';
 $string['sentences'] = 'Sentences';
+$string['shouldbe'] = 'should be';
 $string['statements'] = 'Statements';
 $string['statementtable'] = 'Statement Table:';
 $string['statementtype'] = 'Statement Type:';
@@ -125,10 +133,12 @@ $string['vieworiginal'] = 'View Original';
 $string['viewphpcode'] = 'View PHP Code';
 $string['viewsqlcode'] = 'View SQL Code';
 $string['wrong'] = 'Wrong';
+$string['wrongdefaults'] = 'Wrong Defaults Found';
 $string['wrongints'] = 'Wrong Integers Found';
 $string['wronglengthforenum'] = 'Incorrect length for enum field';
 $string['wrongnumberoffieldsorvalues'] = 'Incorrect number of fields or values in sentence';
 $string['wrongreservedwords'] = 'Currently Used Reserved Words<br />(note that table names aren\'t important if using $CFG->prefix)';
+$string['yeswrongdefaultsfound'] = 'Some inconsistent defaults have been found in your DB. Here there are their details and the needed SQL statements to be executed with your favourite SQL interface to fix them all (don\'t forget to backup your data before doing that).<br /><br />After doing that, it\'s highly recommended to execute this utility again to check that no more iconsistent defaults are found.';
 $string['yesmissingindexesfound'] = 'Some missing indexes have been found in your DB. Here there are their details and the needed SQL statements to be executed with your favourite SQL interface to create all them (don\'t forget to backup your data before doing that).<br /><br />After doing that, it\'s highly recommended to execute this utility again to check that no more missing indexes are found.';
 $string['yeswrongintsfound'] = 'Some wrong integers have been found in your DB. Here there are their details and the needed SQL statements to be executed with your favourite SQL interface to create all them (don\'t forget to backup your data before doing that).<br /><br />After doing that, it\'s highly recommended to execute this utility again to check that no more wrong integers are found.';
 ?>