starts the cloning process

@param $main_db    string
@param $clone_db   string
@param $table_list array|string

@throws \chilimatic\exception\DatabaseException
@throws \Exception
@return boolean
335150
public function init($main_db, $clone_db, $table_list = null)
    {

        try {
            if (empty($main_db) && empty($clone_db)) return false;

            if (!$this->select_db((string)$main_db)) {
                throw new DatabaseException('Could not select Main Database ' . $main_db);
            }

            $this->clone_dbname = $clone_db;
            $this->main_dbname  = $main_db;

            $sql = "SHOW DATABASES";

            if (($this->database_list = $this->fetch_simple_list($this->query((string)$sql))) == false) {
                throw new DatabaseException('No Databases on the Main Server');
            }

            $this->clone_exists = (!in_array($clone_db, $this->database_list)) ? false : true;

            if (empty($table_list)) {
                $sql              = "SHOW TABLES";
                $this->table_list = $this->fetch_simple_list($this->query($sql));
            } elseif (!is_array($table_list)) {
                $this->table_list = array(
                    $table_list
                );
            } else {
                $this->table_list = $table_list;
            }

            if ($this->clone_exists === false && !$this->clone_database($main_db, $clone_db)) {
                throw new DatabaseException('Couldnt replicate database');
            }

            foreach ($this->table_list as $table_name) {
                if ($this->clone_exists) {
                    $sql = ($this->force_rebuild) ? "DROP TABLE `{$clone_db}`.`{$table_name}`" : "TRUNCATE `{$clone_db}`.`{$table_name}`";
                    $this->query($sql);
                }
                $sql = "CREATE TABLE `{$clone_db}`.`{$table_name}` LIKE `{$main_db}`.`{$table_name}`";
                if (!$this->query($sql)) continue;
                $sql = "INSERT INTO `{$clone_db}`.`{$table_name}` SELECT * FROM `{$main_db}`.`{$table_name}`";
                if (!$this->query($sql)) continue;
            }

        } catch (DatabaseException $e) {
            throw $e;
        }

        return true;
    }
214522
public function main()
    {
        $clone = $this->getFactoryInstance('log');

        if ($this->repository === '') {
            $project = $this->getProject();
            $dir = $project->getProperty('application.startdir');
        } else {
            $dir = $this->repository;
        }
        $clone->setCwd($dir);

        if ($this->maxCount !== null) {
            $max = filter_var($this->maxCount, FILTER_VALIDATE_INT);
            if ($max) {
                $max = (int) $this->maxCount;
            }
            if (!$max || (int) $this->maxCount <= 0) {
                throw new BuildException("maxcount should be a positive integer.");
            }
            $clone->setLimit('' . $this->maxCount);
        }

        if ($this->format !== null) {
            $clone->setTemplate($this->format);
        }

        if ($this->revision !== '') {
            $clone->setRev($this->revision);
        }

        try {
            $this->log("Executing: " . $clone->asString(), Project::MSG_INFO);
            $output = $clone->execute();
            if ($this->outputProperty !== null) {
                $this->project->setProperty($this->outputProperty, $output);
            } else {
                if ($output !== '') {
                    $this->log(PHP_EOL . $output);
                }
            }
        } catch (Exception $ex) {
            $msg = $ex->getMessage();
            $p = strpos($msg, 'hg returned:');
            if ($p !== false) {
                $msg = substr($msg, $p + 13);
            }
            throw new BuildException($msg);
        }
    }
312519
public void add(Rec fieldList) throws DBException
    {
        Record record = (Record)fieldList;
        boolean bRefreshed = true;
        if ((this.getRecord().getOpenMode() & DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY) == DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY)
            bRefreshed = record.isRefreshedRecord();    // Only do this on the second write
        super.add(record);
        if (bRefreshed)
        {   // On second only
            Iterator<BaseTable> iterator = this.getTables();
            while (iterator.hasNext())
            {
                BaseTable table = iterator.next();
                if ((table != null) && (table != this.getNextTable()))
                {
                    if (table.getRecord().getEditMode() == Constants.EDIT_ADD)
                    {   // Should have been in sync, but it is now!
                        Record record2 = table.getRecord();
                        boolean bIsAutoSequence = record2.setAutoSequence(false);
                        this.copyRecord(record2, record);
                        try {
                            table.add(record2);
                        } catch (DBException ex) {
                            throw ex;
                        } finally {
                            record2.setAutoSequence(bIsAutoSequence);
                        }
                    }
                }
            }
        }
    }
325763
public function backupDb()
    {
        $database = new Database($this->connection);

        if (! $this->checkBackupIsPossible()) {
            $message = 'Your database is too big for an automatic backup';

            $this->log('error', $message);

            throw new UpdateException($message);
        }

        $this->backupFile = THELIA_ROOT . $this->backupDir . 'update.sql';
        $backupDir = THELIA_ROOT . $this->backupDir;

        $fs = new Filesystem();

        try {
            $this->log('debug', sprintf('Backup database to file : %s', $this->backupFile));

            // test if backup dir exists
            if (!$fs->exists($backupDir)) {
                $fs->mkdir($backupDir);
            }

            if (!is_writable($backupDir)) {
                throw new \RuntimeException(sprintf('impossible to write in directory : %s', $backupDir));
            }

            // test if backup file already exists
            if ($fs->exists($this->backupFile)) {
                // remove file
                $fs->remove($this->backupFile);
            }

            $database->backupDb($this->backupFile);
        } catch (\Exception $ex) {
            $this->log('error', sprintf('error during backup process with message : %s', $ex->getMessage()));
            throw $ex;
        }
    }
1212359
static public function setup($db=null, $table=null, $fields=null) {
		/** @var Cortex $self */
		$self = get_called_class();
		$self::$schema_cache=[];
		if (is_null($db) || is_null($table) || is_null($fields))
			$df = $self::resolveConfiguration();
		if (!is_object($db=(is_string($db=($db?:$df['db']))?\Base::instance()->get($db):$db)))
			trigger_error(self::E_CONNECTION,E_USER_ERROR);
		if (strlen($table=$table?:$df['table'])==0)
			trigger_error(self::E_NO_TABLE,E_USER_ERROR);
		if (is_null($fields))
			if (!empty($df['fieldConf']))
				$fields = $df['fieldConf'];
			elseif(!$df['fluid']) {
				trigger_error(self::E_FIELD_SETUP,E_USER_ERROR);
				return false;
			} else
				$fields = array();
		if ($db instanceof SQL) {
			$schema = new Schema($db);
			// prepare field configuration
			foreach($fields as $key => &$field) {
				// fetch relation field types
				$field = static::resolveRelationConf($field);
				// check m:m relation
				if (array_key_exists('has-many', $field)) {
					// m:m relation conf [class,to-key,from-key]
					if (is_array($relConf = $field['has-many'])) {
						$rel = $relConf[0]::resolveConfiguration();
						// check if foreign conf matches m:m
						if (array_key_exists($relConf[1],$rel['fieldConf'])
							&& !is_null($rel['fieldConf'][$relConf[1]])
							&& $relConf['hasRel'] == 'has-many') {
							// compute mm table name
							$mmTable = isset($relConf[2]) ? $relConf[2] :
								static::getMMTableName($rel['table'], $relConf['relField'],
									$table, $key, $rel['fieldConf'][$relConf[1]]['has-many']);
							if (!in_array($mmTable,$schema->getTables())) {
								$mmt = $schema->createTable($mmTable);
								$relField = $relConf['relField'].($relConf['isSelf']?'_ref':'');
								$mmt->addColumn($relField)->type($relConf['relFieldType']);
								$mmt->addColumn($key)->type($field['type']);
								$index = array($relField,$key);
								sort($index);
								$mmt->addIndex($index);
								$mmt->build();
							}
						}
					}
					unset($fields[$key]);
					continue;
				}
				// skip virtual fields with no type
				if (!array_key_exists('type', $field)) {
					unset($fields[$key]);
					continue;
				}
				// transform array fields
				if (in_array($field['type'], array(self::DT_JSON, self::DT_SERIALIZED)))
					$field['type']=$schema::DT_TEXT;
				// defaults values
				if (!array_key_exists('nullable', $field))
					$field['nullable'] = true;
				unset($field);
			}
			if (!in_array($table, $schema->getTables())) {
				// create table
				$table = $schema->createTable($table);
				if (isset($df) && $df['charset'])
					$table->setCharset($df['charset']);
				foreach ($fields as $field_key => $field_conf)
					$table->addColumn($field_key, $field_conf);
				if(isset($df) && $df['primary'] != 'id') {
					$table->addColumn($df['primary'])->type_int();
					$table->primary($df['primary']);
				}
				$table->build();
			} else {
				// add missing fields
				$table = $schema->alterTable($table);
				$existingCols = $table->getCols();
				foreach ($fields as $field_key => $field_conf)
					if (!in_array($field_key, $existingCols))
						$table->addColumn($field_key, $field_conf);
				// remove unused fields
				// foreach ($existingCols as $col)
				//     if (!in_array($col, array_keys($fields)) && $col!='id')
				//     $table->dropColumn($col);
				$table->build();
			}
		}
		return true;
	}
972031
public synchronized void start() throws ManagedProcessException {
        logger.info("Starting up the database...");
        boolean ready = false;
        try {
            mysqldProcess = startPreparation();
            ready = mysqldProcess.startAndWaitForConsoleMessageMaxMs(getReadyForConnectionsTag(), dbStartMaxWaitInMS);
        } catch (Exception e) {
            logger.error("failed to start mysqld", e);
            throw new ManagedProcessException("An error occurred while starting the database", e);
        }
        if (!ready) {
            if (mysqldProcess.isAlive())
                mysqldProcess.destroy();
            throw new ManagedProcessException("Database does not seem to have started up correctly? Magic string not seen in "
                    + dbStartMaxWaitInMS + "ms: " + getReadyForConnectionsTag() + mysqldProcess.getLastConsoleLines());
        }
        logger.info("Database startup complete.");
    }
315388
public function beginDatabaseTransaction()
    {
        $database = $this->app->make('db');

        foreach ($this->connectionsToTransact() as $name) {
            $connection = $database->connection($name);
            $dispatcher = $connection->getEventDispatcher();

            $connection->unsetEventDispatcher();
            $connection->beginTransaction();
            $connection->setEventDispatcher($dispatcher);
        }

        $this->beforeApplicationDestroyed(function () use ($database) {
            foreach ($this->connectionsToTransact() as $name) {
                $connection = $database->connection($name);
                $dispatcher = $connection->getEventDispatcher();

                $connection->unsetEventDispatcher();
                $connection->rollback();
                $connection->setEventDispatcher($dispatcher);
                $connection->disconnect();
            }
        });
    }
484546
public function main()
    {
        $manager = new PropelMigrationManager();
        $manager->setConnections($this->getGeneratorConfig()->getBuildConnections());
        $manager->setMigrationTable($this->getMigrationTable());
        $manager->setMigrationDir($this->getOutputDirectory());

        $previousTimestamps = $manager->getAlreadyExecutedMigrationTimestamps();
        if (!$nextMigrationTimestamp = array_pop($previousTimestamps)) {
            $this->log('No migration were ever executed on this database - nothing to reverse.');

            return false;
        }
        $this->log(sprintf('Executing migration %s down', $manager->getMigrationClassName($nextMigrationTimestamp)));

        if ($nbPreviousTimestamps = count($previousTimestamps)) {
            $previousTimestamp = array_pop($previousTimestamps);
        } else {
            $previousTimestamp = 0;
        }

        $migration = $manager->getMigrationObject($nextMigrationTimestamp);
        if (false === $migration->preDown($manager)) {
            $this->log('preDown() returned false. Aborting migration.', Project::MSG_ERR);

            return false;
        }

        foreach ($migration->getDownSQL() as $datasource => $sql) {
            $connection = $manager->getConnection($datasource);
            $this->log(sprintf(
                'Connecting to database "%s" using DSN "%s"',
                $datasource,
                $connection['dsn']
            ), Project::MSG_VERBOSE);
            $pdo = $manager->getPdoConnection($datasource);
            $res = 0;
            $statements = PropelSQLParser::parseString($sql);
            foreach ($statements as $statement) {
                try {
                    $this->log(sprintf('Executing statement "%s"', $statement), Project::MSG_VERBOSE);
                    $stmt = $pdo->prepare($statement);
                    $stmt->execute();
                    $res++;
                } catch (PDOException $e) {
                    $this->log(sprintf('Failed to execute SQL "%s"', $statement), Project::MSG_ERR);
                    // continue
                }
            }
            if (!$res) {
                $this->log('No statement was executed. The version was not updated.');
                $this->log(sprintf(
                    'Please review the code in "%s"',
                    $manager->getMigrationDir() . DIRECTORY_SEPARATOR . $manager->getMigrationClassName($nextMigrationTimestamp)
                ));
                $this->log('Migration aborted', Project::MSG_ERR);

                return false;
            }
            $this->log(sprintf(
                '%d of %d SQL statements executed successfully on datasource "%s"',
                $res,
                count($statements),
                $datasource
            ));

            $manager->updateLatestMigrationTimestamp($datasource, $previousTimestamp);
            $this->log(sprintf(
                'Downgraded migration date to %d for datasource "%s"',
                $previousTimestamp,
                $datasource
            ), Project::MSG_VERBOSE);
        }

        $migration->postDown($manager);

        if ($nbPreviousTimestamps) {
            $this->log(sprintf('Reverse migration complete. %d more migrations available for reverse.', $nbPreviousTimestamps));
        } else {
            $this->log('Reverse migration complete. No more migration available for reverse');
        }
    }
1123257
public static function create_index($table, $index_columns, $index_name = '', $index = '', $db = null)
	{
		static $accepted_index = array('UNIQUE', 'FULLTEXT', 'SPATIAL', 'NONCLUSTERED', 'PRIMARY');

		// make sure the index type is uppercase
		$index !== '' and $index = strtoupper($index);

		if (empty($index_name))
		{
			if (is_array($index_columns))
			{
				foreach ($index_columns as $key => $value)
				{
					if (is_numeric($key))
					{
						$index_name .= ($index_name == '' ? '' : '_').$value;
					}
					else
					{
						$index_name .= ($index_name == '' ? '' : '_').str_replace(array('(', ')', ' '), '', $key);
					}
				}
			}
			else
			{
				$index_name = $index_columns;
			}
		}

		if ($index == 'PRIMARY')
		{
			$sql = 'ALTER TABLE ';
			$sql .= \DB::quote_identifier(\DB::table_prefix($table, $db ? $db : static::$connection), $db ? $db : static::$connection);
			$sql .= ' ADD PRIMARY KEY ';
			if (is_array($index_columns))
			{
				$columns = '';
				foreach ($index_columns as $key => $value)
				{
					if (is_numeric($key))
					{
						$columns .= ($columns=='' ? '' : ', ').\DB::quote_identifier($value, $db ? $db : static::$connection);
					}
					else
					{
						$columns .= ($columns=='' ? '' : ', ').\DB::quote_identifier($key, $db ? $db : static::$connection).' '.strtoupper($value);
					}
				}
				$sql .= ' ('.$columns.')';
			}
		}
		else
		{
			$sql = 'CREATE ';

			$index !== '' and $sql .= (in_array($index, $accepted_index)) ? $index.' ' : '';

			$sql .= 'INDEX ';
			$sql .= \DB::quote_identifier($index_name, $db ? $db : static::$connection);
			$sql .= ' ON ';
			$sql .= \DB::quote_identifier(\DB::table_prefix($table, $db ? $db : static::$connection), $db ? $db : static::$connection);
			if (is_array($index_columns))
			{
				$columns = '';
				foreach ($index_columns as $key => $value)
				{
					if (is_numeric($key))
					{
						$columns .= ($columns=='' ? '' : ', ').\DB::quote_identifier($value, $db ? $db : static::$connection);
					}
					else
					{
						$columns .= ($columns=='' ? '' : ', ').\DB::quote_identifier($key, $db ? $db : static::$connection).' '.strtoupper($value);
					}
				}
				$sql .= ' ('.$columns.')';
			}
			else
			{
				$sql .= ' ('.\DB::quote_identifier($index_columns, $db ? $db : static::$connection).')';
			}
		}


		return \DB::query($sql, \DB::UPDATE)->execute($db ? $db : static::$connection);
	}
1070366
public function use_database($db_name)
    {
        if (!$this->connection) {
            $this->last_error_id = "db_server_conn_error";
            return false;
        }
        
        $this->db_name = $db_name;
        
        $db_name = $this->escape($db_name);
        
        if (!$this->execute_query("USE " . $db_name)) {
            $this->last_error = $this->sys_get_errors();
            $this->last_error_id = "db_not_exists_error";
            return false;
        }
        
        return true;
    }
1269617
public boolean create() throws DBException
    {
        boolean bSuccess = true;
        this.setResultSet(null, DBConstants.SQL_CREATE_TYPE);
        ResultSet resultSet = (ResultSet)this.getResultSet();
        if (resultSet == null)
        {
            Map<String,Object> properties = this.getDatabase().getProperties();
            String strAltSecondaryIndex = (String)this.getDatabase().getProperties().get(SQLParams.ALT_SECONDARY_INDEX);
            try   {
                int iFirstIndex = 0;
                Record record = this.getRecord();
                StringBuilder sql = new StringBuilder();
                sql.append("CREATE TABLE ");
                sql.append(record.makeTableNames(true));
                sql.append(" (");
                for (int iIndex = 0; iIndex < record.getFieldCount(); iIndex++)
                {
                    BaseField field = record.getField(iIndex);
                    if (field.isVirtual())
                        continue;
                    String strType = field.getSQLType(true, properties);
                    if (field instanceof CounterField)
                        if (this.getDatabase().isAutosequenceSupport())
                        {
                            String strCounterType = (String)this.getDatabase().getProperties().get(SQLParams.AUTO_SEQUENCE_TYPE);
                            if (strCounterType != null)
                                strType = strCounterType;
                            String strAutoseqExtra = (String)this.getDatabase().getProperties().get(SQLParams.AUTO_SEQUENCE_EXTRA);
                            if (strAutoseqExtra != null)
                                strType += strAutoseqExtra;
                            String strCounterExtra = (String)this.getDatabase().getProperties().get(SQLParams.COUNTER_EXTRA);
                            if (strCounterExtra != null)
                            {
                                strType += strCounterExtra;
                                iFirstIndex = 1;    // No need to build primary index
                            }
                        }
                    if (iIndex > 0)
                        sql.append(", ");
                    if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_KEY_SUPPORT)))
                        this.checkNullableKey(field, strAltSecondaryIndex != null); // Set the key to not nullable for create.
                    if (!field.isNullable())
                    	if (!DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_FIELD_SUPPORT)))	// Rare (or for locale dbs)
                    		strType += " NOT NULL";
                    if (strAltSecondaryIndex != null)
                        if (this.checkIndexField(field))
                            strType += ' ' + strAltSecondaryIndex;
                    sql.append(field.getFieldName(true, false)).append(' ').append(strType);
                }
                String strPrimaryKey = (String)this.getDatabase().getProperties().get(SQLParams.AUTO_SEQUENCE_PRIMARY_KEY);
                if (strPrimaryKey != null)
                    if (record.getCounterField() != null)
                        if (this.getDatabase().isAutosequenceSupport())
                {
                    sql.append(", ").append(strPrimaryKey).append(" (").append(record.getCounterField().getFieldName(true, false)).append(")");
                    iFirstIndex = 1;    // No need to build primary index
                }
                sql.append(")");
                Utility.getLogger().info(sql.toString());
                if (DBConstants.TRUE.equals((String)this.getDatabase().getProperties().get(SQLParams.NO_PREPARED_STATEMENTS_ON_CREATE)))
                    this.setStatement(null, DBConstants.SQL_CREATE_TYPE);
                if (this.getStatement(DBConstants.SQL_CREATE_TYPE) == null)
                    this.setStatement(((JdbcDatabase)this.getDatabase()).getJDBCConnection().createStatement(), DBConstants.SQL_CREATE_TYPE);
                this.getStatement(DBConstants.SQL_CREATE_TYPE).execute(sql.toString());
                // Now set up the index(es)
                sql = new StringBuilder();
                String strPrimaryKeySQL = (String)this.getDatabase().getProperties().get(SQLParams.CREATE_PRIMARY_INDEX);
                if (strPrimaryKeySQL == null)   // null=use default, If empty string, not supported.
                    strPrimaryKeySQL = "CREATE ${unique} INDEX ${keyname} ON ${table} (${fieldsandorder})";    // Default
                String strCreateIndexSQL = (String)this.getDatabase().getProperties().get(SQLParams.CREATE_INDEX);
                if (strCreateIndexSQL == null)   // null=use default, If empty string, not supported.
                    strCreateIndexSQL = strPrimaryKeySQL;    // Default
                for (int iIndex = iFirstIndex; iIndex < record.getKeyAreaCount(); iIndex++)
                {
                    KeyArea keyArea = record.getKeyArea(iIndex);
                    if ((keyArea.getUniqueKeyCode() == DBConstants.UNIQUE)
                        && (iIndex == iFirstIndex)
                            && (keyArea.getKeyFields() == 1))
                        sql = new StringBuilder(strPrimaryKeySQL);
                    else
                        sql = new StringBuilder(strCreateIndexSQL);
                    if (sql.length() == 0)
                        continue;   // Not supported.
                    boolean indexCanBeUnique = true;
                	if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_UNIQUE_KEYS)))
                        if (iIndex > 0)
                    {	// This db considers null a valid index value and will throw a unique key error on write
                        for (int iFieldIndex = 0; iFieldIndex < keyArea.getKeyFields(); iFieldIndex++)
                        {
                            KeyField keyField = keyArea.getKeyField(iFieldIndex);
                            BaseField field = keyField.getField(DBConstants.FILE_KEY_AREA);
                            if (field.isNullable())
                            	indexCanBeUnique = false;
                        }
                    }
                    if (iIndex > 0)
                    	if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_NULL_FIELD_SUPPORT)))	// Rare (or for locale dbs)
                    		indexCanBeUnique = false;
                    
                    if ((keyArea.getUniqueKeyCode() == DBConstants.UNIQUE) && (indexCanBeUnique))
                        sql = Utility.replace(sql, "${unique}", "UNIQUE");
                    else
                        sql = Utility.replace(sql, "${unique}", DBConstants.BLANK);
                    String strKeyName = keyArea.getKeyName();
                    String strTableNames = record.makeTableNames(true);
                    if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_DUPLICATE_KEY_NAMES)))
                    {
                    	if (strTableNames.endsWith("_temp"))
                    		strKeyName = strTableNames.substring(0, strTableNames.length() - 5) + "_" + strKeyName;
                    	else
                    		strKeyName = strTableNames + "_" + strKeyName;
                    }
                    String strMaxKeyNameLength = (String)this.getDatabase().getProperties().get(SQLParams.MAX_KEY_NAME_LENGTH);
                    if (strMaxKeyNameLength != null)
                    {
                        int iMaxKeyNameLength = Integer.parseInt(strMaxKeyNameLength);
                        if (strKeyName.length() > iMaxKeyNameLength)
                        {
                        	strKeyName = strKeyName + (int)(Math.random() * 100000);
                            strKeyName = strKeyName.substring(strKeyName.length() - iMaxKeyNameLength);
                            while (!Character.isLetter(strKeyName.charAt(0))) {
                            	strKeyName = strKeyName.substring(1);
                            }
                        }
                    }
                    sql = Utility.replace(sql, "${keyname}", strKeyName);
                    sql = Utility.replace(sql, "${table}", strTableNames);
                    String strFields = DBConstants.BLANK;
                    String strFieldAndOrder = DBConstants.BLANK;
                    for (int iFieldIndex = 0; iFieldIndex < keyArea.getKeyFields(); iFieldIndex++)
                    {
                        KeyField keyField = keyArea.getKeyField(iFieldIndex);
                        BaseField field = keyField.getField(DBConstants.FILE_KEY_AREA);
                        if (iFieldIndex > 0)
                        {
                            strFields += ", ";
                            strFieldAndOrder += ", ";
                        }
                        strFields += field.getFieldName(true, false) + " ";
                        strFieldAndOrder += field.getFieldName(true, false) + " ";
                        if (keyField.getKeyOrder() == DBConstants.DESCENDING)
                            strFieldAndOrder += "DESC ";
                    }
                    sql = Utility.replace(sql, "${fields}", strFields);
                    sql = Utility.replace(sql, "${fieldsandorder}", strFieldAndOrder);
                    Utility.getLogger().info(sql.toString());
                    this.getStatement(DBConstants.SQL_CREATE_TYPE).execute(sql.toString());
                }
            } catch (SQLException e)    {
                throw this.getDatabase().convertError(e);
            } finally {
                if (DBConstants.TRUE.equals(this.getDatabase().getProperties().get(SQLParams.NO_PREPARED_STATEMENTS_ON_CREATE)))
                    this.setStatement(null, DBConstants.SQL_CREATE_TYPE);
            }
        }
        this.setResultSet(null, DBConstants.SQL_CREATE_TYPE);
        return bSuccess;    // Success!!!
    }
118557
def cloneTable(self, login, tableName, newTableName, flush, propertiesToSet, propertiesToExclude):
    
    self.send_cloneTable(login, tableName, newTableName, flush, propertiesToSet, propertiesToExclude)
    self.recv_cloneTable()
449422
public function copyTable(string $tableNameSource, string $tableNameDestination): bool
    {
        $tableNameSource = $this->quoter->quoteName($tableNameSource);
        $tableNameDestination = $this->quoter->quoteName($tableNameDestination);
        $this->db->exec(sprintf('CREATE TABLE %s LIKE %s;', $tableNameDestination, $tableNameSource));

        return true;
    }
727450
public function showSchemaInList()
    {
        //change connection if provide
        if ($this->option('c')) {
            $this->schema->setConnection($this->option('c'));
            $this->schema->switchWrapper();
        }

        $tables = $this->schema->databaseWrapper->getTables();
        if (!count($tables)) {
            $this->warn('Database does not contain any table');
        }

        $tableName = $this->option('t');
        if (!empty($tableName)) {
            if ($this->isNamespaceModel($tableName)) {
                $tableName = $this->tableNameFromModel($tableName);
            }
            if (!in_array($tableName, $tables)) {
                $this->warn('Table name is not correct!');
                return false;
            }

            $attributes = $this->schema->databaseWrapper->getColumns($tableName);
            $rowsCount = $this->schema->getTableRowCount($tableName);
            $this->info($tableName . ' (rows: ' . $rowsCount . ')');
            foreach ($attributes as $attribute) {
                $this->line('  ' . $attribute['Field'] . '  ' . $attribute['Type']);
            }
            return true;
        }

        foreach ($this->schema->databaseWrapper->getSchema() as $key => $value) {
            $this->info($key . ' (rows: ' . $value['rowsCount'] . ')');
            foreach ($value['attributes'] as $attribute) {
                $this->line('  ' . $attribute['Field'] . '  ' . $attribute['Type']);
            }
            $this->line('');
        }
    }
299016
protected function startRevertDatabase() {
		// Mark self as creating a snapshot
		$this->Status = 'Started';
		$this->Doing = 'Snapshot';
		$this->log("{$this->Title} reverting database from snapshot");

		// Skip deployment for dry run
		if($this->Pipeline()->DryRun) {
			$this->write();
			$this->log("[Skipped] Create DNDataTransfer restore");
			return true;
		}

		// Get snapshot
		$pipeline = $this->Pipeline();
		$backup = $pipeline->PreviousSnapshot();
		if(empty($backup) || !$backup->exists()) {
			$this->log("No database to revert for {$this->Title}");
			$this->markFailed();
			return false;
		}

		// Create restore job
		$job = DNDataTransfer::create();
		$job->EnvironmentID = $pipeline->EnvironmentID;
		$job->Direction = 'push';
		$job->Mode = 'db';
		$job->DataArchiveID = $backup->DataArchiveID;
		$job->AuthorID = $pipeline->AuthorID;
		$job->EnvironmentID = $pipeline->EnvironmentID;
		$job->write();
		$job->start();

		// Save rollback
		$this->RollbackDatabaseID = $job->ID;
		$this->write();
		return true;
	}
1202448
private void setMainTable(final SQLTable _mainTable)
    {
        SQLTable table = _mainTable;
        while (table.getMainTable() != null) {
            table = table.getMainTable();
        }
        this.mainTable = table;
    }
656953
public function run()
    {
        $this->_scanner->stdout('Detect DatabaseTable - BEGIN', Console::FG_GREY);
        if (is_array($this->_tables)) {
            foreach ($this->_tables as $tables) {
                $this->_scanningTable($tables);
            }
        }

        $this->_scanner->stdout('Detect DatabaseTable - END', Console::FG_GREY);
    }