/*!
Forwards request to generateAddIndexSql() on the otherSchema() object.
547946
function generateAddIndexSql( $table, $index_name, $added_index, $params )
    {
        return $this->OtherSchema->generateAddIndexSql( $table, $index_name, $added_index, $params );
    }
677165
protected function generateChangeFieldSql( $tableName, $fieldName, ezcDbSchemaField $fieldDefinition )
    {
        if ( !$fieldDefinition->autoIncrement )
        {
            $this->queries[] = "ALTER TABLE \"$tableName\" MODIFY " .
                               $this->generateFieldSql( $fieldName, $fieldDefinition );
        }
        else
        {    // mark query to make autoincrement emulation when executing
            $this->queries[] = "ALTER TABLE \"$tableName\" MODIFY " .
                               $this->generateFieldSql( $fieldName, $fieldDefinition ) .
                               " AUTO_INCREMENT";
        }
    }
269389
protected function generateCreateTableSql( $tableName, ezcDbSchemaTable $tableDefinition )
    {
        $sql = $this->generateCreateTableSqlStatement( $tableName );

        $sql .= " (\n";

        // dump fields
        $fieldsSQL = array();

        foreach ( $tableDefinition->fields as $fieldName => $fieldDefinition )
        {
            $fieldsSQL[] = "\t" . $this->generateFieldSql( $fieldName, $fieldDefinition );
        }

        $sql .= join( ",\n", $fieldsSQL );

        $sql .= "\n)";

        $this->queries[] = $sql;

        // dump indexes
        foreach ( $tableDefinition->indexes as $indexName => $indexDefinition)
        {
            $fieldsSQL[] = $this->generateAddIndexSql( $tableName, $indexName, $indexDefinition );
        }
    }
1184913
public function addExtraIndices()
	{
		/**
		 * A collection of indexed columns. The keys is the column name
		 * (concatenated with a comma in the case of multi-col index), the value is
		 * an array with the names of the indexes that index these columns. We use
		 * it to determine which additional indexes must be created for foreign
		 * keys. It could also be used to detect duplicate indexes, but this is not
		 * implemented yet.
		 * @var array
		 */
		$_indices = array();

		$this->collectIndexedColumns('PRIMARY', $this->getPrimaryKey(), $_indices);

		$_tableIndices = array_merge($this->getIndices(), $this->getUnices());
		foreach ($_tableIndices as $_index) {
		  $this->collectIndexedColumns($_index->getName(), $_index->getColumns(), $_indices);
		}

		// we're determining which tables have foreign keys that point to this table,
		// since MySQL needs an index on any column that is referenced by another table
		// (yep, MySQL _is_ a PITA)
		$counter = 0;
		foreach ($this->getReferrers() as $foreignKey) {
			$referencedColumns = $foreignKey->getForeignColumnObjects();
			$referencedColumnsHash = $this->getColumnList($referencedColumns);
		  if (!array_key_exists($referencedColumnsHash, $_indices)) {
				// no matching index defined in the schema, so we have to create one
				$index = new Index();
				$index->setName(sprintf('I_referenced_%s_%s', $foreignKey->getName(), ++$counter));
				$index->setColumns($referencedColumns);
				$index->resetColumnSize();
				$this->addIndex($index);
				// Add this new index to our collection, otherwise we might add it again (bug #725)
				$this->collectIndexedColumns($index->getName(), $referencedColumns, $_indices);
			}
		}

		// we're adding indices for this table foreign keys
		foreach ($this->getForeignKeys() as $foreignKey) {
			$localColumns = $foreignKey->getLocalColumnObjects();
			$localColumnsHash = $this->getColumnList($localColumns);
			if (!array_key_exists($localColumnsHash, $_indices)) {
				// no matching index defined in the schema, so we have to create one. MySQL needs indices on any columns that serve as foreign keys. these are not auto-created prior to 4.1.2
				$index = new Index();
				$index->setName(substr_replace($foreignKey->getName(), 'FI_',  strrpos($foreignKey->getName(), 'FK_'), 3));
				$index->setColumns($localColumns);
				$index->resetColumnSize();
				$this->addIndex($index);
				$this->collectIndexedColumns($index->getName(), $localColumns, $_indices);
			}
		}
	}
313816
def database_forwards(self, app_label, schema_editor, from_state, to_state):
        """"""
        Process = from_state.apps.get_model('flow', 'Process')  # pylint: disable=invalid-name
        Data = from_state.apps.get_model('flow', 'Data')  # pylint: disable=invalid-name
        try:
            # pylint: disable=invalid-name
            ProcessMigrationHistory = from_state.apps.get_model('flow', 'ProcessMigrationHistory')
            DataMigrationHistory = from_state.apps.get_model('flow', 'DataMigrationHistory')
        except LookupError:
            raise LookupError(
                "Unable to retrieve migration history models. Perhaps you need "
                "to add a migration dependency to a recent enough Resolwe flow "
                "app in your migration?"
            )

        # Migrate processes.
        processes = Process.objects.filter(slug=self.process)
        if not processes.exists():
            return

        migrated_processes = set()
        schema_field = '{}_schema'.format(self.schema_type)
        for process in processes:
            current_schema = getattr(process, schema_field)
            if not self.migrate_process_schema(process, current_schema, from_state):
                continue

            setattr(process, schema_field, current_schema)
            process.save()
            migrated_processes.add(process)

            # Update process migration log.
            ProcessMigrationHistory.objects.create(
                migration=self.migration_id,
                process=process,
                metadata=self.describe_process_migration(process),
            )

        if not migrated_processes:
            return

        # Migrate all data objects.
        data = Data.objects.filter(process__in=migrated_processes)
        self.migrate_data(data, from_state)

        # Update data migration log.
        for datum in data:
            DataMigrationHistory.objects.create(
                migration=self.migration_id,
                data=datum,
                metadata=self.describe_data_migration(datum)
            )
767860
function generateDropFieldSql( $table, $field_name, $params )
    {
        return $this->OtherSchema->generateDropFieldSql( $table, $field_name, $params );
    }
1371669
function generateTableSQL( $tableName, $tableDef, $params, $asArray, $separateTypes = false )
    {
        $diffFriendly = isset( $params['diff_friendly'] ) ? $params['diff_friendly'] : false;
        $mysqlCompatible = isset( $params['compatible_sql'] ) ? $params['compatible_sql'] : false;

        if ( $asArray )
        {
            if ( $separateTypes )
            {
                $sqlList = array( 'tables' => array() );
            }
            else
            {
                $sqlList = array();
            }
        }

        $sql = '';
        $skip_pk = false;
        $sql_fields = array();
        $sql .= "CREATE TABLE $tableName (\n";

        $fields = $tableDef['fields'];

        foreach ( $fields as $field_name => $field_def )
        {
            $sql_fields[] = '  ' . eZMysqlSchema::generateFieldDef( $field_name, $field_def, $skip_pk_flag, $params );
            if ( $skip_pk_flag )
            {
                $skip_pk = true;
            }
        }

        // Make sure the order is as defined by 'offset'
        $indexes = $tableDef['indexes'];

        // We need to add all keys in table definition
        foreach ( $indexes as $index_name => $index_def )
        {
            $sql_fields[] = ( $diffFriendly ? '' : '  ' ) . eZMysqlSchema::generateAddIndexSql( $tableName, $index_name, $index_def, $params, true );
        }
        $sql .= join( ",\n", $sql_fields );
        $sql .= "\n)";

        // Add some extra table options if they are required
        $extraOptions = array();
        if ( isset( $params['table_type'] ) and $params['table_type'] )
        {
            $typeName = $this->tableStorageTypeName( $params['table_type'] );
            if ( $typeName )
            {
                $extraOptions[] = "ENGINE=" . $typeName;
            }
        }
        if ( isset( $params['table_charset'] ) and $params['table_charset'] )
        {
            $charsetName = $this->tableCharsetName( $params['table_charset'] );
            if ( $charsetName )
            {
                $extraOptions[] = "DEFAULT CHARACTER SET " . $charsetName;
            }
        }
        if ( isset( $tableDef['options'] ) )
        {
            foreach( $tableDef['options'] as $optionType => $optionValue )
            {
                $optionText = $this->generateTableOption( $tableName, $tableDef, $optionType, $optionValue, $params );
                if ( $optionText )
                    $extraOptions[] = $optionText;
            }
        }

        if ( count( $extraOptions ) > 0 )
        {
            $sql .= " " . implode( $diffFriendly ? "\n" : " ", $extraOptions );
        }

        if ( $asArray )
        {
            if ( $separateTypes )
            {
                $sqlList['tables'][] = $sql;
            }
            else
            {
                $sqlList[] = $sql;
            }
        }
        else
        {
            $sql .= ";\n";

            if ( $mysqlCompatible )
            {
                $sql .= "\n\n\n";
            }
        }

        return $asArray ? $sqlList : $sql;
    }
1272565
public function getAddIndexDDL(Index $index)
    {
        // don't create index form primary key
        if ($this->getPrimaryKeyName($index->getTable()) == $this->quoteIdentifier($index->getName())) {
            return '';
        }

        $pattern = "
CREATE %sINDEX %s ON %s (%s)%s;
";

        return sprintf($pattern,
            $index->isUnique() ? 'UNIQUE ' : '',
            $this->quoteIdentifier($index->getName()),
            $this->quoteIdentifier($index->getTable()->getName()),
            $this->getColumnListDDL($index->getColumnObjects()),
            $this->generateBlockStorage($index)
        );
    }
1063260
protected void configureGeneratedIdSequence(StringBuilder sb, FieldType fieldType, List<String> statementsBefore,
			List<String> additionalArgs, List<String> queriesAfter) throws SQLException {
		throw new SQLException(
				"GeneratedIdSequence is not supported by database " + getDatabaseName() + " for field " + fieldType);
	}
938814
private void appendDirectives(StringBuffer query) {
		StringBuffer sb = new StringBuffer();
		for (String prefix : prefixes.keySet()) {
			sb.append("@PREFIX");
			sb.append(" ");
			sb.append(prefix);
			sb.append(" ");
			sb.append("<");
			sb.append(prefixes.get(prefix));
			sb.append(">");
			sb.append(" .\n");
		}
		sb.append("@PREFIX " + OntopInternal.PREFIX_XSD + " <" + XSD.PREFIX + "> .\n");
		sb.append("@PREFIX " + OntopInternal.PREFIX_OBDA + " <" + Ontop.PREFIX + "> .\n");
		sb.append("@PREFIX " + OntopInternal.PREFIX_RDF + " <" + RDF.PREFIX + "> .\n");
		sb.append("@PREFIX " + OntopInternal.PREFIX_RDFS + " <" + RDFS.PREFIX + "> .\n");
		sb.append("@PREFIX " + OntopInternal.PREFIX_OWL + " <" + OWL.PREFIX + "> .\n");
		query.insert(0, sb);
	}
27670
def gen_query(self):
        
        return (
            SQL.forwards_relation(self.src, self.rel) if self.dst is None else
            SQL.inverse_relation(self.dst, self.rel)
            )
232261
function knexMysqlExpress(options) {
  return function knexMysqlExpress(req, res, next) {
    req.knex = knex(options);
    res.once("finish", done.bind(this, req.knex));
    next();
  };
}
1335431
function(tx) {
      // sniff current table info in the database.
      me.getSchema(function(existing_schema) {
        executed = true;
        for (var i = 0; i < schema.count(); i++) {
          var counter = function(ok) {
            if (ok) {
              updated_count++;
            }
          };
          var table_info = existing_schema.getStore(schema.store(i).getName());
          // hint to sniffed schema, so that some lost info are recovered.
          var hinted_store_schema = table_info ?
              table_info.hintForWebSql(schema.store(i)) : null;

          me.update_store_with_info_(tx, schema.store(i), counter,
              hinted_store_schema);
        }

        for (var j = 0; j < existing_schema.count(); j++) {
          var info_store = existing_schema.store(j);
          if (!schema.hasStore(info_store.getName())) {
            if (schema instanceof ydn.db.schema.EditableDatabase) {
              var edited_schema = schema;
              edited_schema.addStore(info_store);
            } else {
              var sqls = me.prepareDropTable_(info_store);
              for (var i = 0; i < sqls.length; i++) {
                var sql = sqls[i];
                goog.log.finer(me.logger, sql);
                tx.executeSql(sql, [],
                    function(tr) {
                      // ok
                    }, function(tx, e) {
                      throw e;
                    });
              }
            }
          }
        }

      }, tx, db);
    }
1219477
function data( $schema = false, $tableNameList = false, $params = array() )
    {
        return $this->OtherSchema->data( $schema, $tableNameList, $params );
    }
969018
protected function addDoInsertBodyRaw()
    {
        $this->declareClasses('Propel', 'PDO');
        $table = $this->getTable();
        $peerClassname = $this->getPeerClassname();
        $platform = $this->getPlatform();
        $primaryKeyMethodInfo = '';
        if ($table->getIdMethodParameters()) {
            $params = $table->getIdMethodParameters();
            $imp = $params[0];
            $primaryKeyMethodInfo = $imp->getValue();
        } elseif ($table->getIdMethod() == IDMethod::NATIVE && ($platform->getNativeIdMethod() == PropelPlatformInterface::SEQUENCE || $platform->getNativeIdMethod() == PropelPlatformInterface::SERIAL)) {
            $primaryKeyMethodInfo = $platform->getSequenceName($table);
        }
        $query = 'INSERT INTO ' . $platform->quoteIdentifier($table->getName()) . ' (%s) VALUES (%s)';
        $script = "
        \$modifiedColumns = array();
        \$index = 0;
";

        foreach ($table->getPrimaryKey() as $column) {
            if (!$column->isAutoIncrement()) {
                continue;
            }
            $constantName = $this->getColumnConstant($column);
            if ($platform->supportsInsertNullPk()) {
                $script .= "
        \$this->modifiedColumns[] = $constantName;";
            }
            $columnProperty = strtolower($column->getName());
            if (!$table->isAllowPkInsert()) {
                $script .= "
        if (null !== \$this->{$columnProperty}) {
            throw new PropelException('Cannot insert a value for auto-increment primary key (' . $constantName . ')');
        }";
            } elseif (!$platform->supportsInsertNullPk()) {
                $script .= "
        // add primary key column only if it is not null since this database does not accept that
        if (null !== \$this->{$columnProperty}) {
            \$this->modifiedColumns[] = $constantName;
        }";
            }
        }

        // if non auto-increment but using sequence, get the id first
        if (!$platform->isNativeIdMethodAutoIncrement() && $table->getIdMethod() == "native") {
            $column = $table->getFirstPrimaryKeyColumn();
            $columnProperty = strtolower($column->getName());
            $script .= "
        if (null === \$this->{$columnProperty}) {
            try {";
            $script .= $platform->getIdentifierPhp('$this->' . $columnProperty, '$con', $primaryKeyMethodInfo, '				');
            $script .= "
            } catch (Exception \$e) {
                throw new PropelException('Unable to get sequence id.', \$e);
            }
        }
";
        }

        $script .= "

         // check the columns in natural order for more readable SQL queries";
        foreach ($table->getColumns() as $column) {
            $constantName = $this->getColumnConstant($column);
            $identifier = var_export($platform->quoteIdentifier($column->getName()), true);
            $script .= "
        if (\$this->isColumnModified($constantName)) {
            \$modifiedColumns[':p' . \$index++]  = $identifier;
        }";
        }

        $script .= "

        \$sql = sprintf(
            '$query',
            implode(', ', \$modifiedColumns),
            implode(', ', array_keys(\$modifiedColumns))
        );

        try {
            \$stmt = \$con->prepare(\$sql);
            foreach (\$modifiedColumns as \$identifier => \$columnName) {
                switch (\$columnName) {";
        foreach ($table->getColumns() as $column) {
            $columnNameCase = var_export($platform->quoteIdentifier($column->getName()), true);
            $script .= "
                    case $columnNameCase:";
            $script .= $platform->getColumnBindingPHP($column, "\$identifier", '$this->' . strtolower($column->getName()), '						');
            $script .= "
                        break;";
        }
        $script .= "
                }
            }
            \$stmt->execute();
        } catch (Exception \$e) {
            Propel::log(\$e->getMessage(), Propel::LOG_ERR);
            throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', \$sql), \$e);
        }
";

        // if auto-increment, get the id after
        if ($platform->isNativeIdMethodAutoIncrement() && $table->getIdMethod() == "native") {
            $column = $table->getFirstPrimaryKeyColumn();
            $columnProperty = strtolower($column->getName());
            $script .= "
        try {";
            $script .= $platform->getIdentifierPhp('$pk', '$con', $primaryKeyMethodInfo);
            $script .= "
        } catch (Exception \$e) {
            throw new PropelException('Unable to get autoincrement id.', \$e);
        }";
            if ($table->isAllowPkInsert()) {
                $script .= "
        if (\$pk !== null) {
            \$this->set" . $column->getPhpName() . "(\$pk);
        }";
            } else {
                $script .= "
        \$this->set" . $column->getPhpName() . "(\$pk);";
            }
            $script .= "
";
        }

        return $script;
    }
1017062
function create( &$xmls ) {
		foreach( $this->queries as $id => $query ) {
			switch( $this->prefixMethod ) {
				case 'AUTO':
					// Enable auto prefix replacement

					// Process object prefix.
					// Evaluate SQL statements to prepend prefix to objects
					$query = $this->prefixQuery( '/^\s*((?is)INSERT\s+(INTO\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
					$query = $this->prefixQuery( '/^\s*((?is)UPDATE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
					$query = $this->prefixQuery( '/^\s*((?is)DELETE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );

					// SELECT statements aren't working yet
					#$data = preg_replace( '/(?ias)(^\s*SELECT\s+.*\s+FROM)\s+(\W\s*,?\s*)+((?i)\s+WHERE.*$)/', "\1 $prefix\2 \3", $data );

				case 'MANUAL':
					// If prefixKey is set and has a value then we use it to override the default constant XMLS_PREFIX.
					// If prefixKey is not set, we use the default constant XMLS_PREFIX
					if( isset( $this->prefixKey ) AND( $this->prefixKey !== '' ) ) {
						// Enable prefix override
						$query = str_replace( $this->prefixKey, $xmls->objectPrefix, $query );
					} else {
						// Use default replacement
						$query = str_replace( XMLS_PREFIX , $xmls->objectPrefix, $query );
					}
			}

			$this->queries[$id] = trim( $query );
		}

		// Return the query set array
		return $this->queries;
	}
1281332
def _generate_reversed_sql(self, keys, changed_keys):
        
        for key in keys:
            if key not in changed_keys:
                continue
            app_label, sql_name = key
            old_item = self.from_sql_graph.nodes[key]
            new_item = self.to_sql_graph.nodes[key]
            if not old_item.reverse_sql or old_item.reverse_sql == RunSQL.noop or new_item.replace:
                continue

            # migrate backwards
            operation = ReverseAlterSQL(sql_name, old_item.reverse_sql, reverse_sql=old_item.sql)
            sql_deps = [n.key for n in self.from_sql_graph.node_map[key].children]
            sql_deps.append(key)
            self.add_sql_operation(app_label, sql_name, operation, sql_deps)