/**
  * Destroy the database table for this lookup table.
  */
 public static function uninstall()
 {
     $db = \cge_utils::get_db();
     $dict = NewDataDictionary($db);
     $sqlarray = $dict->DropTableSQL(static::table_name());
     $dict->ExecuteSQLArray($sqlarray, FALSE);
 }
示例#2
0
/**
 * This function creates the DB on new installs
 */
function make_db($dbhost, $dbuname, $dbpass, $dbname, $prefix_table, $dbtype, $dbmake)
{
    global $db;
    echo '<font class="oos-title">' . INPUT_DATA . '</font>';
    echo '<table align="center"><tr><td align="left">';
    if ($dbmake) {
        $db =& NewADOConnection($dbtype);
        $dbh = $db->Connect($dbhost, $dbuname, $dbpass);
        if (!$dbh) {
            $dbpass = "";
            die("{$dbtype}://{$dbuname}:{$dbpass}@{$dbhost} failed to connect" . $db->ErrorMsg());
        }
        $dict = NewDataDictionary($db);
        if (!$dict) {
            continue;
        }
        $dict->debug = 1;
        // ToDo CREATE DATABASE $dbname DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
        $sqlarray = $dict->CreateDatabase($dbname);
        $dict->ExecuteSQLArray($sqlarray);
    }
    oosDBInit($dbhost, $dbuname, $dbpass, $dbname, $dbtype);
    if (!$prefix_table == '') {
        $prefix_table = $prefix_table . '_';
    }
    include 'newtables.php';
    echo '</td></tr></table>';
}
示例#3
0
 /**
  * Prepare a DatabaseConnection subject.
  * Used by driver specific test cases.
  *
  * @param string $driver Driver to use like "mssql", "oci8" and "postgres7"
  * @param array $configuration Dbal configuration array
  * @return \TYPO3\CMS\Dbal\Database\DatabaseConnection|\PHPUnit_Framework_MockObject_MockObject|\TYPO3\CMS\Core\Tests\AccessibleObjectInterface
  */
 protected function prepareSubject($driver, array $configuration)
 {
     /** @var \TYPO3\CMS\Dbal\Database\DatabaseConnection|\PHPUnit_Framework_MockObject_MockObject|\TYPO3\CMS\Core\Tests\AccessibleObjectInterface $subject */
     $subject = $this->getAccessibleMock(\TYPO3\CMS\Dbal\Database\DatabaseConnection::class, array('getFieldInfoCache'), array(), '', false);
     $subject->conf = $configuration;
     // Disable caching
     $mockCacheFrontend = $this->getMock(\TYPO3\CMS\Core\Cache\Frontend\PhpFrontend::class, array(), array(), '', false);
     $subject->expects($this->any())->method('getFieldInfoCache')->will($this->returnValue($mockCacheFrontend));
     // Inject SqlParser - Its logic is tested with the tests, too.
     $sqlParser = $this->getAccessibleMock(\TYPO3\CMS\Dbal\Database\SqlParser::class, array('dummy'), array(), '', false);
     $sqlParser->_set('databaseConnection', $subject);
     $sqlParser->_set('sqlCompiler', GeneralUtility::makeInstance(\TYPO3\CMS\Dbal\Database\SqlCompilers\Adodb::class, $subject));
     $sqlParser->_set('nativeSqlCompiler', GeneralUtility::makeInstance(\TYPO3\CMS\Dbal\Database\SqlCompilers\Mysql::class, $subject));
     $subject->SQLparser = $sqlParser;
     // Mock away schema migration service from install tool
     $installerSqlMock = $this->getMock(\TYPO3\CMS\Install\Service\SqlSchemaMigrationService::class, array('getFieldDefinitions_fileContent'), array(), '', false);
     $installerSqlMock->expects($this->any())->method('getFieldDefinitions_fileContent')->will($this->returnValue(array()));
     $subject->_set('installerSql', $installerSqlMock);
     $subject->initialize();
     // Fake a working connection
     $handlerKey = '_DEFAULT';
     $subject->lastHandlerKey = $handlerKey;
     $adodbDriverClass = '\\ADODB_' . $driver;
     $subject->handlerInstance[$handlerKey] = new $adodbDriverClass();
     $subject->handlerInstance[$handlerKey]->DataDictionary = NewDataDictionary($subject->handlerInstance[$handlerKey]);
     $subject->handlerInstance[$handlerKey]->_connectionID = rand(1, 1000);
     return $subject;
 }
示例#4
0
function idxsql($idxname, $table, $idxflds)
{
    global $db;
    $dict = NewDataDictionary($db);
    $sqlarray = $dict->CreateIndexSQL($idxname, $table, $idxflds);
    $dict->ExecuteSQLArray($sqlarray);
}
示例#5
0
function upgrade_create_sequence_table($db, $tablename, $idcol)
{
    $num = $db->GetOne("SELECT MAX({$idcol}) FROM {$tablename}");
    $db->DropSequence($tablename . "_seq");
    $db->CreateSequence($tablename . "_seq", $num + 1);
    $dict = NewDataDictionary($db);
    $sqlarray = $dict->AlterColumnSQL($tablename, "{$idcol} I");
    $dict->ExecuteSQLArray($sqlarray);
}
 function idxsql($idxname, $table, $idxflds)
 {
     // Get database information
     $dbconn =& oosDBGetConn();
     $oostable =& oosDBGetTables();
     $dict = NewDataDictionary($dbconn);
     $sqlarray = $dict->CreateIndexSQL($idxname, $table, $idxflds);
     $dict->ExecuteSQLArray($sqlarray);
 }
示例#7
0
 function createTable($ctx)
 {
     $create = 'CREATE TABLE IF NOT EXISTS `' . $ctx . '` (' . '`key` VARCHAR( 60 ) NOT NULL ,' . '`willExpireAt` int NOT NULL DEFAULT 0 ,' . '`lastModified` int NOT NULL DEFAULT 0, ' . '`content` TEXT NULL ,PRIMARY KEY (  `key` ));';
     if (strlen($this->stm['before_create']) > 0) {
         $this->db->Execute($this->stm['before_create'], array()) or die;
     }
     $dict = NewDataDictionary($this->db);
     $x = $dict->ExecuteSQLArray(array($create)) or die;
     return $x;
 }
示例#8
0
 function AkInstaller($db_connection = null)
 {
     if (empty($db_connection)) {
         $this->db =& Ak::db();
     } else {
         $this->db =& $db_connection;
     }
     $this->available_tables = $this->getAvailableTables();
     $this->db->debug =& $this->debug;
     $this->data_dictionary = NewDataDictionary($this->db);
 }
 /**
  * Creates a fake database connection.
  *
  * @param ux_t3lib_db $db
  * @param string $databaseType Type of the database (e.g., 'oracle')
  * @param string $driver Driver to use (e.g., 'oci8')
  * @return ADOConnection
  */
 public static function connect(ux_t3lib_db $db, $driver)
 {
     // Make sure to have a clean configuration
     $db->clearCachedFieldInfo();
     $db->_call('initInternalVariables');
     include_once t3lib_extMgm::extPath('adodb') . 'adodb/drivers/adodb-' . $driver . '.inc.php';
     $handlerKey = '_DEFAULT';
     $db->lastHandlerKey = $handlerKey;
     $db->handlerInstance[$handlerKey] = t3lib_div::makeInstance('ADODB_' . $driver);
     // From method handler_init()
     $db->handlerInstance[$handlerKey]->DataDictionary = NewDataDictionary($db->handlerInstance[$handlerKey]);
     // DataDictionary being set, a connectionID may be arbitrarily chosen
     $db->handlerInstance[$handlerKey]->_connectionID = rand(1, 1000);
 }
示例#10
0
 function createDatabase($mode)
 {
     $success = true;
     $db = $this->databaseConnection('admin');
     if ($db) {
         if ($this->getDatabaseType($mode) != 'sqlite') {
             $DataDict = NewDataDictionary($db);
             if ($this->getDatabaseType($mode) == 'mysql') {
                 $success = $this->_createMysqlDatabase($db, $mode) ? $success : false;
             }
         }
         return $success;
     }
     return false;
 }
 /**
  * @private
  */
 function _checkTables()
 {
     // create the table to keep track of the voters, so that people cannot vote
     // more than once
     $fields = "\r\n\t\t\t      id I(10) NOTNULL PRIMARY AUTOINCREMENT,\r\n\t\t\t      recipients TEXT NOTNULL DEFAULT '',\n\t\t\t      recipients_cc TEXT NOTNULL DEFAULT '',\n\t\t\t      recipients_bcc TEXT NOTNULL DEFAULT '',\r\n\t\t\t      subject C(255) NOTNULL DEFAULT '',\r\n\t\t\t      body XL NOTNULL DEFAULT '',\r\n\t\t\t\t  date T(14) DEFDATE\r\n\t\t\t\t  ";
     $db =& Db::getDb();
     $dbPrefix = Db::getPrefix();
     $tableName = $dbPrefix . "mailcentre_sent";
     // create the data dictionary and create the table if necessary
     $dict = NewDataDictionary($db);
     $sqlArray = $dict->ChangeTableSQL($tableName, $fields);
     $result = $dict->ExecuteSQLArray($sqlArray);
     if (!$result) {
         die("There was an error creating the plugin tables!");
     }
     return true;
 }
示例#12
0
 function createTable($table_name, $table_fields, $table_options, $add_sequence_table = true, $table_index_fields = null)
 {
     if (!isset($this->_db)) {
         $db =& Ak::db();
     } else {
         $db =& $this->_db;
     }
     $dict = NewDataDictionary($db);
     $sqlarray = $dict->CreateTableSQL($table_name, $table_fields, $table_options);
     $dict->ExecuteSQLArray($sqlarray);
     if (isset($table_index_fields)) {
         $sqlarray = $dict->CreateIndexSQL('idx_' . $table_name, $table_name, $table_index_fields);
         $dict->ExecuteSQLArray($sqlarray);
     }
     if ($add_sequence_table) {
         $db->CreateSequence('seq_' . $table_name);
     }
 }
示例#13
0
 /**
  * Connects to the database using options in the given configuration array.
  *
  * @param array $config Configuration array for connecting
  */
 function connect()
 {
     $config = $this->config;
     $persistent = strrpos($config['connect'], '|p');
     if ($persistent === false) {
         $adodb_driver = $config['connect'];
         $connect = 'Connect';
     } else {
         $adodb_driver = substr($config['connect'], 0, $persistent);
         $connect = 'PConnect';
     }
     $this->_adodb = NewADOConnection($adodb_driver);
     $this->_adodbDataDict = NewDataDictionary($this->_adodb, $adodb_driver);
     $this->startQuote = $this->_adodb->nameQuote;
     $this->endQuote = $this->_adodb->nameQuote;
     $this->connected = $this->_adodb->{$connect}($config['host'], $config['login'], $config['password'], $config['database']);
     $this->_adodbMetatyper =& $this->_adodb->execute('Select 1');
     return $this->connected;
 }
 function _verifyTable()
 {
     $fields = "\n      id I(11) NOTNULL PRIMARY AUTOINCREMENT,\n      blogId I(11) NOTNULL KEY,\n      active C(1) NOTNULL KEY,\n      subject TEXT NOTNULL,\n      responses TEXT NOTNULL,\n      responsedata TEXT NOTNULL,\n      dateadded I(11) NOTNULL";
     $fields2 = "\n      id I(11) NOTNULL KEY,\n      ip I8 NOTNULL KEY,\n      date I(11) NOTNULL KEY";
     $db =& Db::getDb();
     $dbPrefix = Db::getPrefix();
     $tableName = $dbPrefix . "plogpoll_polls";
     $tableName2 = $dbPrefix . "plogpoll_voterips";
     $dict = NewDataDictionary($db);
     $sqlAry = $dict->ChangeTableSQL($tableName, $fields);
     $result = $dict->ExecuteSQLArray($sqlAry);
     if (!$result) {
         die("There was an error creating/updating plogpoll plugin tables!");
     }
     $sqlAry = $dict->ChangeTableSQL($tableName2, $fields2);
     $result = $dict->ExecuteSQLArray($sqlAry);
     if (!$result) {
         die("There was an error creating/updating plogpoll plugin tables!");
     }
 }
示例#15
0
 function perform()
 {
     if (empty($this->loop)) {
         $this->loop = 1;
     }
     if ($this->prepareParameters() === FALSE) {
         $this->result = INSTALLER_ACTION_FAIL;
         return $this->result;
     }
     if (!is_readable($this->schema_file)) {
         $this->result = INSTALLER_ACTION_FAIL;
         $this->result_message = "Could not read file sql {$this->schema_file}.";
         $this->loop = 2;
         return $this->result;
     }
     # Connect to the DB
     $db = $this->connect();
     if ($db === FALSE) {
         return $this->result;
     }
     # Create empty ADOdb connection
     $conn = ADONewConnection($this->type);
     # Create new ADO Schema object
     $schema = new adoSchema($conn);
     # Build the SQL query from the Schema file
     $sql = $schema->ParseSchema($this->schema_file);
     # Execute the SQL query
     # "2" is status returned by ExecuteSQLArray()
     $dict = NewDataDictionary($db);
     @($ok = 2 == $dict->ExecuteSQLArray($sql, FALSE));
     if ($ok) {
         $this->result = INSTALLER_ACTION_SUCCESS;
         $this->result_message = "DB schema loaded successfully";
         $this->loop = 3;
     } else {
         $this->result = INSTALLER_ACTION_FAIL;
         $this->result_message = "Errors on execution of the schema SQL: " . $db->ErrorMsg();
         $this->loop = 2;
     }
     return $this->result;
 }
示例#16
0
 function _createNewTestingModelDatabase($test_model_name)
 {
     static $shutdown_called;
     // Create a data dictionary object, using this connection
     $db =& AK::db();
     //$db->debug = true;
     $table_name = AkInflector::tableize($test_model_name);
     if (in_array($table_name, (array) $db->MetaTables())) {
         return false;
     }
     switch ($table_name) {
         case 'ak_test_bank_accounts':
             $table = array('table_name' => 'ak_test_bank_accounts', 'fields' => 'id I AUTO KEY,
         balance I(20),
         lock_version I(20),
         created_at T, 
         updated_at T', 'index_fileds' => 'id', 'table_options' => array('mysql' => 'TYPE=InnoDB', 'REPLACE'));
             break;
         default:
             return false;
             break;
     }
     $dict = NewDataDictionary($db);
     $sqlarray = $dict->CreateTableSQL($table['table_name'], $table['fields'], $table['table_options']);
     $dict->ExecuteSQLArray($sqlarray);
     if (isset($table['index_fileds'])) {
         $sqlarray = $dict->CreateIndexSQL('idx_' . $table['table_name'], $table['table_name'], $table['index_fileds']);
         $dict->ExecuteSQLArray($sqlarray);
     }
     $db->CreateSequence('seq_' . $table['table_name']);
     $this->_testing_model_databases_to_delete[] = $table_name;
     if (!isset($shutdown_called)) {
         $shutdown_called = true;
         register_shutdown_function(array(&$this, '_deleteTestingModelDatabases'));
     }
     //$db->debug = false;
     return true;
 }
示例#17
0
 /**
  * Drop indexes to deal with AUTONUM / PRIMARY KEY wierdness (primarily MySQL / ADODB)
  * @return boolean
  */
 function dropAllIndexes()
 {
     $siteDao = DAORegistry::getDAO('SiteDAO');
     $dict = NewDataDictionary($siteDao->_dataSource);
     $dropIndexSql = array();
     // This is a list of tables that were used in 2.1.1 (i.e.
     // before the way indexes were used was changed). All indexes
     // from these tables will be dropped.
     $tables = array('versions', 'site', 'site_settings', 'scheduled_tasks', 'sessions', 'plugin_settings', 'roles', 'email_templates_default_data', 'email_templates_data', 'oai_resumption_tokens');
     // Assemble a list of indexes to be dropped
     foreach ($tables as $tableName) {
         $indexes = $dict->MetaIndexes($tableName);
         if (is_array($indexes)) {
             foreach ($indexes as $indexName => $indexData) {
                 $dropIndexSql = array_merge($dropIndexSql, $dict->DropIndexSQL($indexName, $tableName));
             }
         }
     }
     // Execute the DROP INDEX statements.
     foreach ($dropIndexSql as $sql) {
         $siteDao->update($sql);
     }
     // Second run: Only return primary indexes. This is necessary
     // so that primary indexes can be dropped by MySQL.
     foreach ($tables as $tableName) {
         $indexes = $dict->MetaIndexes($tableName, true);
         if (!empty($indexes)) {
             switch (Config::getVar('database', 'driver')) {
                 case 'mysql':
                     $siteDao->update("ALTER TABLE {$tableName} DROP PRIMARY KEY");
                     break;
             }
         }
     }
     return true;
 }
示例#18
0
 * let us take over your shared e-mail headache is a worthwhile investment.  
 * It will give you a sense of control over your in-box that you probably 
 * haven't had since spammers found you in a game of "E-mail Address 
 * Battleship".  Miss. Miss. You sunk my in-box!
 * 
 * A legitimate license entitles you to support, access to the developer 
 * mailing list, the ability to participate in betas and the warm fuzzy 
 * feeling of feeding a couple obsessed developers who want to help you get 
 * more done than 'the other guy'.
 *
 * - Jeff Standen, Mike Fogg, Brenan Cavish, Darren Sugita, Dan Hildebrandt
 * 		and Joe Geck.
 *   WEBGROUP MEDIA LLC. - Developers of Cerberus Helpdesk
 */
$db = DevblocksPlatform::getDatabaseService();
$datadict = NewDataDictionary($db, 'mysql');
/* @var $datadict ADODB2_mysql */
// ,'mysql'
$tables = $datadict->MetaTables();
$tables = array_flip($tables);
// `attachment` =============================
$columns = $datadict->MetaColumns('attachment');
$indexes = $datadict->MetaIndexes('attachment', false);
if (!isset($indexes['message_id'])) {
    $sql = $datadict->CreateIndexSQL('message_id', 'attachment', 'message_id');
    $datadict->ExecuteSQLArray($sql);
}
// `kb_category` =============================
if (!isset($tables['kb_category'])) {
    $flds = "\r\n\t\tid I4 DEFAULT 0 NOTNULL PRIMARY,\r\n\t\tparent_id I4 DEFAULT 0 NOTNULL,\r\n\t\tname C(64) DEFAULT '' NOTNULL\r\n\t";
    $sql = $datadict->CreateTableSQL('kb_category', $flds);
示例#19
0
 /**
  * Check to see whether a table exists.
  * Used in installer XML in conditional checks on <data> nodes.
  * @param $tableName string
  * @return boolean
  */
 function tableExists($tableName)
 {
     $siteDao =& DAORegistry::getDAO('SiteDAO');
     $dict = NewDataDictionary($siteDao->getDataSource());
     // Check whether the table exists.
     $tables = $dict->MetaTables('TABLES', false);
     return in_array($tableName, $tables);
 }
示例#20
0
 /**
  * Create a new database if required.
  * @return boolean
  */
 function createDatabase()
 {
     if (!$this->getParam('createDatabase')) {
         return true;
     }
     // Get database creation sql
     $dbdict =& NewDataDictionary($this->dbconn);
     if ($this->getParam('databaseCharset')) {
         $dbdict->SetCharSet($this->getParam('databaseCharset'));
     }
     list($sql) = $dbdict->CreateDatabase($this->getParam('databaseName'));
     unset($dbdict);
     if (!$this->executeSQL($sql)) {
         return false;
     }
     // Re-connect to the created database
     $this->dbconn->disconnect();
     $conn = new DBConnection($this->getParam('databaseDriver'), $this->getParam('databaseHost'), $this->getParam('databaseUsername'), $this->getParam('databasePassword'), $this->getParam('databaseName'), true, $this->getParam('connectionCharset') == '' ? false : $this->getParam('connectionCharset'));
     DBConnection::getInstance($conn);
     $this->dbconn =& $conn->getDBConn();
     if (!$conn->isConnected()) {
         $this->setError(INSTALLER_ERROR_DB, $this->dbconn->errorMsg());
         return false;
     }
     return true;
 }
示例#21
0
 public function DDcreateIndex($name, $table, $cols, $opts)
 {
     $dict = NewDataDictionary($this->_db, w2PgetConfig('dbtype'));
     $query_array = $dict->CreateIndexSQL($name, $table, $cols, $opts);
     //returns 0 - failed, 1 - executed with errors, 2 - success
     return $dict->ExecuteSQLArray($query_array);
 }
echo "\nPost 1.0 schema changes\n";
echo "Connecting to database... ";
$t_result = @$g_db->Connect($f_hostname, $f_db_username, $f_db_password, $f_database_name);
if (false == $t_result) {
    echo "failed\n";
    exit(1);
}
echo "OK\n";
$g_db_connected = true;
# fake out database access routines used by config_get
$t_last_update = config_get('database_version', -1, ALL_USERS, ALL_PROJECTS);
$lastid = count($upgrade) - 1;
$i = $t_last_update + 1;
while ($i <= $lastid && !$g_failed) {
    echo 'Create Schema ( ' . $upgrade[$i][0] . ' on ' . $upgrade[$i][1][0] . ' )';
    $dict = NewDataDictionary($g_db);
    if ($upgrade[$i][0] == 'InsertData') {
        $sqlarray = call_user_func_array($upgrade[$i][0], $upgrade[$i][1]);
    } else {
        $sqlarray = call_user_func_array(array($dict, $upgrade[$i][0]), $upgrade[$i][1]);
    }
    $ret = $dict->ExecuteSQLArray($sqlarray);
    if ($ret == 2) {
        print_test_result(GOOD);
        config_set('database_version', $i);
    } else {
        print_test_result(BAD, true, $sqlarray[0] . '<br />' . $g_db->ErrorMsg());
    }
    $i++;
}
if (false == $g_failed) {
示例#23
0
 public static function &dict()
 {
     static $dict;
     if (!isset($dict)) {
         $dict = NewDataDictionary(self::$ado);
     }
     return $dict;
 }
 /**
  * Creates an adoSchema object
  *
  * Creating an adoSchema object is the first step in processing an XML schema.
  * The only parameter is an ADOdb database connection object, which must already
  * have been created.
  *
  * @param object $db ADOdb database connection object.
  */
 function adoSchema(&$db)
 {
     // Initialize the environment
     $this->mgq = get_magic_quotes_runtime();
     set_magic_quotes_runtime(0);
     $this->db = $db;
     $this->debug = $this->db->debug;
     $this->dict = NewDataDictionary($this->db);
     $this->sqlArray = array();
     $this->schemaVersion = XMLS_SCHEMA_VERSION;
     $this->executeInline(XMLS_EXECUTE_INLINE);
     $this->continueOnError(XMLS_CONTINUE_ON_ERROR);
     $this->setUpgradeMethod();
 }
示例#25
0
 function &getDictionary()
 {
     if (empty($this->dictionary)){
         if (!$this->connected()){
             $this->connect();
         }
         require_once(AK_CONTRIB_DIR.DS.'adodb'.DS.'adodb.inc.php');
         $this->dictionary =& NewDataDictionary($this->connection);
     }
     return $this->dictionary;
 }
示例#26
0
 function alterTable($tablename, $flds, $oper)
 {
     $this->println("ADODB alterTableTable table=" . $tablename . " flds=" . $flds . " oper=" . $oper);
     $this->checkConnection();
     $dict = NewDataDictionary($this->database);
     if ($oper == 'Add_Column') {
         $sqlarray = $dict->AddColumnSQL($tablename, $flds);
     } else {
         if ($oper == 'Delete_Column') {
             $sqlarray = $dict->DropColumnSQL($tablename, $flds);
         }
     }
     $this->println("sqlarray");
     $this->println($sqlarray);
     $result = $dict->ExecuteSQLArray($sqlarray);
     $this->println("ADODB alterTableTable table=" . $tablename . " flds=" . $flds . " oper=" . $oper . " status=" . $result);
     return $result;
 }
 /**
  * Constructor. Initializes the xmlschema object
  *
  * @param object $dbconn		ADOdb connection object
  */
 function adoSchema($dbconn)
 {
     // Initialize the environment
     $this->mgq = get_magic_quotes_runtime();
     set_magic_quotes_runtime(0);
     $this->dbconn =& $dbconn;
     $this->dbType = $dbconn->databaseType;
     $this->sqlArray = array();
     // Create an ADOdb dictionary object
     $this->dict = NewDataDictionary($dbconn);
 }
示例#28
0
if ($subaction == "updatetokenattributes" && bHasSurveyPermission($surveyid, 'tokens', 'update'))
{
    $number2add=sanitize_int($_POST['addnumber'],1,100);
    // find out the existing token attribute fieldnames
    $tokenfieldnames = array_values($connect->MetaColumnNames("{$dbprefix}tokens_$surveyid", true));
    $tokenattributefieldnames=array_filter($tokenfieldnames,'filterforattributes');
    $i=1;
    for ($b=0;$b<$number2add;$b++)
    {
        while (in_array('attribute_'.$i,$tokenattributefieldnames)!==false) {
            $i++;
        }
        $tokenattributefieldnames[]='attribute_'.$i;
        $fields[]=array('attribute_'.$i,'C','255');
    }
    $dict = NewDataDictionary($connect);
    $sqlarray = $dict->ChangeTableSQL("{$dbprefix}tokens_$surveyid", $fields);
    $execresult=$dict->ExecuteSQLArray($sqlarray, false);

    $tokenoutput .= "\t<div class='header ui-widget-header'>".$clang->gT("Update token attributes")."</div>\n"
    ."\t<div class='messagebox ui-corner-all'>";
    if ($execresult==0)
    {
        $tokenoutput.="\t\t<div class='warningheader'>".$clang->gT("Adding attribute fields failed:")."".htmlspecialchars($connect->ErrorMsg())."</div>"
        ."\t\t<br /><input type='button' value='".$clang->gT("Back to attribute field management.")."' onclick=\"window.open('$scriptname?action=tokens&amp;sid=$surveyid&amp;subaction=managetokenattributes', '_top')\" />\n";
    }
    else
    {
        $tokenoutput.="\t\t<div class='successheader'>".sprintf($clang->gT("%s field(s) were successfully added."),$number2add)."</div>"
        ."\t\t<br /><input type='button' value='".$clang->gT("Back to attribute field management.")."' onclick=\"window.open('$scriptname?action=tokens&amp;sid=$surveyid&amp;subaction=managetokenattributes', '_top')\" />\n";
    }
示例#29
0
<?php

echo '<p>Adding stylesheet association ordering capability... ';
$dbdict = NewDataDictionary($db);
$sqlarray = $dbdict->AddColumnSQL(cms_db_prefix() . 'css_assoc', 'assoc_order I');
$dbdict->ExecuteSQLArray($sqlarray);
// Now update the values
$query = 'SELECT assoc_to_id, assoc_css_id FROM ' . cms_db_prefix() . 'css_assoc 
          ORDER BY assoc_to_id, assoc_css_id';
$allrows = $db->GetArray($query);
$assoc_to_id = -1;
foreach ($allrows as $row) {
    if ($assoc_to_id != $row['assoc_to_id']) {
        $ord = 1;
        $assoc_to_id = $row['assoc_to_id'];
    }
    $q2 = 'UPDATE ' . cms_db_prefix() . 'css_assoc SET assoc_order = ?
            WHERE assoc_to_id = ? AND assoc_css_id = ?';
    $db->Execute($q2, array($ord, $row['assoc_to_id'], $row['assoc_css_id']));
    $ord++;
}
echo '[done]</p>';
echo '<p>Updating schema version... ';
$query = "UPDATE " . cms_db_prefix() . "version SET version = 30";
$db->Execute($query);
echo '[done]</p>';
 /**
  * Parse an XML data file into SQL statements.
  * @param $file string path to the XML file to parse
  * @return array the array of SQL statements parsed
  */
 function parseData($file)
 {
     $this->sql = array();
     $parser = new XMLParser();
     $tree = $parser->parse($file);
     if (!$tree) {
         return array();
     }
     $allTables = $this->dbconn->MetaTables();
     foreach ($tree->getChildren() as $type) {
         switch ($type->getName()) {
             case 'table':
                 $fieldDefaultValues = array();
                 // Match table element
                 foreach ($type->getChildren() as $row) {
                     switch ($row->getName()) {
                         case 'field_default':
                             // Match a default field element
                             list($fieldName, $value) = $this->_getFieldData($row);
                             $fieldDefaultValues[$fieldName] = $value;
                             break;
                         case 'row':
                             // Match a row element
                             $fieldValues = array();
                             foreach ($row->getChildren() as $field) {
                                 // Get the field names and values for this INSERT
                                 list($fieldName, $value) = $this->_getFieldData($field);
                                 $fieldValues[$fieldName] = $value;
                             }
                             $fieldValues = array_merge($fieldDefaultValues, $fieldValues);
                             if (count($fieldValues) > 0) {
                                 $this->sql[] = sprintf('INSERT INTO %s (%s) VALUES (%s)', $type->getAttribute('name'), join(', ', array_keys($fieldValues)), join(', ', array_values($fieldValues)));
                             }
                             break;
                         default:
                             assert(false);
                     }
                 }
                 break;
             case 'sql':
                 // Match sql element (set of SQL queries)
                 foreach ($type->getChildren() as $child) {
                     switch ($child->getName()) {
                         case 'drop':
                             if (!isset($dbdict)) {
                                 $dbdict = @NewDataDictionary($this->dbconn);
                             }
                             $table = $child->getAttribute('table');
                             $column = $child->getAttribute('column');
                             if ($column) {
                                 // NOT PORTABLE; do not use this
                                 $this->sql[] = $dbdict->DropColumnSql($table, $column);
                             } else {
                                 $this->sql[] = $dbdict->DropTableSQL($table);
                             }
                             break;
                         case 'rename':
                             if (!isset($dbdict)) {
                                 $dbdict = @NewDataDictionary($this->dbconn);
                             }
                             $table = $child->getAttribute('table');
                             $column = $child->getAttribute('column');
                             $to = $child->getAttribute('to');
                             if ($column) {
                                 // Make sure the target column does not yet exist.
                                 // This is to guarantee idempotence of upgrade scripts.
                                 $run = false;
                                 if (in_array($table, $allTables)) {
                                     $columns =& $this->dbconn->MetaColumns($table, true);
                                     if (!isset($columns[strtoupper($to)])) {
                                         // Only run if the column has not yet been
                                         // renamed.
                                         $run = true;
                                     }
                                 } else {
                                     // If the target table does not exist then
                                     // we assume that another rename entry will still
                                     // rename it and we should run after it.
                                     $run = true;
                                 }
                                 if ($run) {
                                     $colId = strtoupper($column);
                                     $flds = '';
                                     if (isset($columns[$colId])) {
                                         $col = $columns[$colId];
                                         if ($col->max_length == "-1") {
                                             $max_length = '';
                                         } else {
                                             $max_length = $col->max_length;
                                         }
                                         $fld = array('NAME' => $col->name, 'TYPE' => $dbdict->MetaType($col), 'SIZE' => $max_length);
                                         if ($col->primary_key) {
                                             $fld['KEY'] = 'KEY';
                                         }
                                         if ($col->auto_increment) {
                                             $fld['AUTOINCREMENT'] = 'AUTOINCREMENT';
                                         }
                                         if ($col->not_null) {
                                             $fld['NOTNULL'] = 'NOTNULL';
                                         }
                                         if ($col->has_default) {
                                             $fld['DEFAULT'] = $col->default_value;
                                         }
                                         $flds = array($colId => $fld);
                                     } else {
                                         assert(false);
                                     }
                                     $this->sql[] = $dbdict->RenameColumnSQL($table, $column, $to, $flds);
                                 }
                             } else {
                                 // Make sure the target table does not yet exist.
                                 // This is to guarantee idempotence of upgrade scripts.
                                 if (!in_array($to, $allTables)) {
                                     $this->sql[] = $dbdict->RenameTableSQL($table, $to);
                                 }
                             }
                             break;
                         case 'query':
                             $driver = $child->getAttribute('driver');
                             if (empty($driver) || $this->dbconn->databaseType === $driver) {
                                 $this->sql[] = $child->getValue();
                             }
                             break;
                     }
                 }
                 break;
         }
     }
     return $this->sql;
 }