Generates the SQL that will add/update the data in the database

@param object $xmls adoSchema object
@return array Array containing index creation SQL
495729
function create( &$xmls ) {
		$table = $xmls->dict->TableName($this->parent->name);
		$table_field_count = count($this->parent->fields);
		$tables = $xmls->db->MetaTables();
		$sql = array();

		$ukeys = $xmls->db->MetaPrimaryKeys( $table );
		if( !empty( $this->parent->indexes ) and !empty( $ukeys ) ) {
			foreach( $this->parent->indexes as $indexObj ) {
				if( !in_array( $indexObj->name, $ukeys ) ) $ukeys[] = $indexObj->name;
			}
		}

		// eliminate any columns that aren't in the table
		foreach( $this->data as $row ) {
			$table_fields = $this->parent->fields;
			$fields = array();
			$rawfields = array(); // Need to keep some of the unprocessed data on hand.

			foreach( $row as $field_id => $field_data ) {
				if( !array_key_exists( $field_id, $table_fields ) ) {
					if( is_numeric( $field_id ) ) {
						$field_id = reset( array_keys( $table_fields ) );
					} else {
						continue;
					}
				}

				$name = $table_fields[$field_id]['NAME'];

				switch( $table_fields[$field_id]['TYPE'] ) {
					case 'I':
					case 'I1':
					case 'I2':
					case 'I4':
					case 'I8':
						$fields[$name] = intval($field_data);
						break;
					case 'C':
					case 'C2':
					case 'X':
					case 'X2':
					default:
						$fields[$name] = $xmls->db->qstr( $field_data );
						$rawfields[$name] = $field_data;
				}

				unset($table_fields[$field_id]);

			}

			// check that at least 1 column is specified
			if( empty( $fields ) ) {
				continue;
			}

			// check that no required columns are missing
			if( count( $fields ) < $table_field_count ) {
				foreach( $table_fields as $field ) {
					if( isset( $field['OPTS'] ) and ( in_array( 'NOTNULL', $field['OPTS'] ) || in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
							continue(2);
						}
				}
			}

			// The rest of this method deals with updating existing data records.

			if( !in_array( $table, $tables ) or ( $mode = $xmls->existingData() ) == XMLS_MODE_INSERT ) {
				// Table doesn't yet exist, so it's safe to insert.
				logMsg( "$table doesn't exist, inserting or mode is INSERT" );
			$sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
				continue;
		}

			// Prepare to test for potential violations. Get primary keys and unique indexes
			$mfields = array_merge( $fields, $rawfields );
			$keyFields = array_intersect( $ukeys, array_keys( $mfields ) );

			if( empty( $ukeys ) or count( $keyFields ) == 0 ) {
				// No unique keys in schema, so safe to insert
				logMsg( "Either schema or data has no unique keys, so safe to insert" );
				$sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
				continue;
			}

			// Select record containing matching unique keys.
			$where = '';
			foreach( $ukeys as $key ) {
				if( isset( $mfields[$key] ) and $mfields[$key] ) {
					if( $where ) $where .= ' AND ';
					$where .= $key . ' = ' . $xmls->db->qstr( $mfields[$key] );
				}
			}
			$records = $xmls->db->Execute( 'SELECT * FROM ' . $table . ' WHERE ' . $where );
			switch( $records->RecordCount() ) {
				case 0:
					// No matching record, so safe to insert.
					logMsg( "No matching records. Inserting new row with unique data" );
					$sql[] = $xmls->db->GetInsertSQL( $records, $mfields );
					break;
				case 1:
					// Exactly one matching record, so we can update if the mode permits.
					logMsg( "One matching record..." );
					if( $mode == XMLS_MODE_UPDATE ) {
						logMsg( "...Updating existing row from unique data" );
						$sql[] = $xmls->db->GetUpdateSQL( $records, $mfields );
					}
					break;
				default:
					// More than one matching record; the result is ambiguous, so we must ignore the row.
					logMsg( "More than one matching record. Ignoring row." );
			}
		}
		return $sql;
	}
1187303
public function generateXmlSchemaBuilders()
	{
		$result = [];
		
		foreach($this->helpers->findAll() as $key => $helper)
		{
			list($namespace, $name) = explode('>', $key, 2);
			
			if(empty($result[$namespace]))
			{
				$result[$namespace] = new HelperXmlSchemaBuilder($namespace);
			}
			
			$result[$namespace]->addHelper($name, $helper);
		}
		
		return $result;
	}
569593
protected function prepareInsert($inserts)
    {
        if ($this->isHasOneRelation($inserts)) {
            $inserts = Arr::dot($inserts);
        }

        foreach ($inserts as $column => $value) {
            if (is_null($field = $this->getFieldByColumn($column))) {
                unset($inserts[$column]);
                continue;
            }

            $inserts[$column] = $field->prepare($value);
        }

        $prepared = [];

        foreach ($inserts as $key => $value) {
            Arr::set($prepared, $key, $value);
        }

        return $prepared;
    }
34367
public function getCreateStructureSQL($xmldb_structure) {
        $results = array();

        if ($tables = $xmldb_structure->getTables()) {
            foreach ($tables as $table) {
                $results = array_merge($results, $this->getCreateTableSQL($table));
            }
        }

        return $results;
    }
236466
private function generateManyManyRelations($table, $fks, $relations)
    {
        $db = $this->getDbConnection();

        foreach ($fks as $pair) {
            list($firstKey, $secondKey) = $pair;
            $table0 = $firstKey[0];
            $table1 = $secondKey[0];
            unset($firstKey[0], $secondKey[0]);
            $className0 = $this->generateClassName($table0);
            $className1 = $this->generateClassName($table1);
            $table0Schema = $db->getTableSchema($table0);
            $table1Schema = $db->getTableSchema($table1);

            // @see https://github.com/yiisoft/yii2-gii/issues/166
            if ($table0Schema === null || $table1Schema === null) {
                continue;
            }

            $link = $this->generateRelationLink(array_flip($secondKey));
            $viaLink = $this->generateRelationLink($firstKey);
            $relationName = $this->generateRelationName($relations, $table0Schema, key($secondKey), true);
            $relations[$table0Schema->fullName][$relationName] = [
                "return \$this->hasMany($className1::className(), $link)->viaTable('"
                . $this->generateTableName($table->name) . "', $viaLink);",
                $className1,
                true,
            ];

            $link = $this->generateRelationLink(array_flip($firstKey));
            $viaLink = $this->generateRelationLink($secondKey);
            $relationName = $this->generateRelationName($relations, $table1Schema, key($firstKey), true);
            $relations[$table1Schema->fullName][$relationName] = [
                "return \$this->hasMany($className0::className(), $link)->viaTable('"
                . $this->generateTableName($table->name) . "', $viaLink);",
                $className0,
                true,
            ];
        }

        return $relations;
    }
201229
public function getUpdateGenericSql(array $cols)
    {
        $sql = ['update', "`{$this->getTableNameLazy()}`", 'set'];
        $sqlCols = [];
        foreach ($cols as $col) {
            $sqlCols[] = "`$col` = :$col";
        }
        $sql[] = implode(', ', $sqlCols);
        $sql[] = "where `id` = :id";
        return implode(' ', $sql);
    }
626676
public static function createConditionals(array $tokens) {
        if(!isset($tokens['WHERE'])) return '';

        $tableAlias = Table::alias($tokens);
        $primaryKeyColumn = sprintf('%s.%s', $tableAlias, Identifier::column($tokens, new MetaData));

        // Get WHERE conditions as string including table alias and primary key column if present
        $sqlWhereString = array_reduce($tokens['WHERE'], function($query, $token) use ($tableAlias) {
            return $query . str_replace(['"', '\''], '', str_replace('OR', '|', str_replace('AND', '&', $token['base_expr'])));
        });

        // Remove primary key column before removing table alias and returning
        return str_replace($tableAlias . '.', '', preg_replace('/' . preg_quote($primaryKeyColumn) . '=[\w\d]*&*/', '', $sqlWhereString));
    }
1028557
public function joinSchemas(array $schemas)
    {
        foreach ($schemas as $schema) {
            foreach ($schema->getDatabases(false) as $addDb) {
                $addDbName = $addDb->getName();
                if ($this->hasDatabase($addDbName)) {
                    $db = $this->getDatabase($addDbName, false);
                    // temporarily reset database namespace to avoid double namespace decoration (see ticket #1355)
                    $namespace = $db->getNamespace();
                    $db->setNamespace(null);
                    // join tables
                    foreach ($addDb->getTables() as $addTable) {
                        if ($db->getTable($addTable->getName())) {
                            throw new EngineException(sprintf('Duplicate table found: %s.', $addTable->getName()));
                        }
                        $db->addTable($addTable);
                    }
                    // join database behaviors
                    foreach ($addDb->getBehaviors() as $addBehavior) {
                        if (!$db->hasBehavior($addBehavior->getId())) {
                            $db->addBehavior($addBehavior);
                        }
                    }
                    // restore the database namespace
                    $db->setNamespace($namespace);
                } else {
                    $this->addDatabase($addDb);
                }
            }
        }
    }
857865
public function fromXSD($xsd): array
    {
        if (!$this->isEmptyValue($xsd)) {
            return $this->fromXml($xsd->output);
        }

        return $this->result;

    }
114820
public function toSQL($parseBindings = true) {
        $sql = $this->sql;
        if ($parseBindings && !empty($this->bindings)) {
            $sql = $this->xpdo->parseBindings($sql, $this->bindings);
        }
        return $sql;
    }
6724
public function generateSelectClause($tableAliases = array())
    {
        $sql = "";

        foreach ($this->columnOwnerMap as $columnName => $dqlAlias) {
            $tableAlias = isset($tableAliases[$dqlAlias])
                ? $tableAliases[$dqlAlias] : $dqlAlias;

            if ($sql) {
                $sql .= ", ";
            }

            $sql .= $tableAlias . ".";

            if (isset($this->fieldMappings[$columnName])) {
                $class = $this->em->getClassMetadata($this->declaringClasses[$columnName]);
                $sql  .= $class->fieldMappings[$this->fieldMappings[$columnName]]['columnName'];
            } else if (isset($this->metaMappings[$columnName])) {
                $sql .= $this->metaMappings[$columnName];
            } else if (isset($this->discriminatorColumn[$columnName])) {
                $sql .= $this->discriminatorColumn[$columnName];
            }

            $sql .= " AS " . $columnName;
        }

        return $sql;
    }
824192
public function getXMLValues($fields)
    {
        $result = [];

        foreach ($fields as $field) {
            $result[$field] = $this->XML_val($field);
        }

        return $result;
    }
894302
public function getCreateTempTableSQL($xmldb_table) {
        $this->temptables->add_temptable($xmldb_table->getName());
        $sqlarr = $this->getCreateTableSQL($xmldb_table);
        return $sqlarr;
    }
239357
protected function getTableColumns(array $indexes = [], ?string $schema = null): array
    {
        $columns = [];

        if ($this->tableSchema instanceof TableSchema) {
            $indexData = !empty($indexes) ? $indexes : $this->getTableIndexes();

            foreach ($this->tableSchema->columns as $column) {
                $isUnique = false;

                foreach ($indexData as $index) {
                    if ($index->unique && $index->columns[0] === $column->name && count($index->columns) === 1) {
                        $isUnique = true;

                        break;
                    }
                }

                $columns[$column->name] = TableColumnFactory::build([
                    'schema' => $schema,
                    'name' => $column->name,
                    'type' => $column->type,
                    'size' => $column->size,
                    'precision' => $column->precision,
                    'scale' => $column->scale,
                    'isNotNull' => $column->allowNull ? null : true,
                    'isUnique' => $isUnique,
                    'check' => null,
                    'default' => $column->defaultValue,
                    'isPrimaryKey' => $column->isPrimaryKey,
                    'autoIncrement' => $column->autoIncrement,
                    'isUnsigned' => $column->unsigned,
                    'comment' => $column->comment ?: null,
                ]);
            }
        }

        return $columns;
    }
694745
public function get_install_xml_schema() {
        global $CFG;
        require_once($CFG->libdir.'/adminlib.php');

        $schema = new xmldb_structure('export');
        $schema->setVersion($CFG->version);

        foreach ($this->get_install_xml_files() as $filename) {
            $xmldb_file = new xmldb_file($filename);
            if (!$xmldb_file->loadXMLStructure()) {
                continue;
            }
            $structure = $xmldb_file->getStructure();
            $tables = $structure->getTables();
            foreach ($tables as $table) {
                $table->setPrevious(null);
                $table->setNext(null);
                $schema->addTable($table);
            }
        }
        return $schema;
    }
1018122
protected function buildXmlStructure()
	{
		$buffer = array();

		foreach ($this->from as $table)
		{
			// Replace the magic prefix if found.
			$table = $this->getGenericTableName($table);

			// Get the details columns information.
			$fields    = $this->db->getTableColumns($table, false);
			$keys      = $this->db->getTableKeys($table);
			$sequences = $this->db->getTableSequences($table);

			$buffer[] = '  <table_structure name="' . $table . '">';

			foreach ($sequences as $sequence)
			{
				if (version_compare($this->db->getVersion(), '9.1.0') < 0)
				{
					$sequence->start_value = null;
				}

				$buffer[] = '   <sequence Name="' . $sequence->sequence . '" Schema="' . $sequence->schema . '"' .
					' Table="' . $sequence->table . '" Column="' . $sequence->column . '" Type="' . $sequence->data_type . '"' .
					' Start_Value="' . $sequence->start_value . '" Min_Value="' . $sequence->minimum_value . '"' .
					' Max_Value="' . $sequence->maximum_value . '" Increment="' . $sequence->increment . '"' .
					' Cycle_option="' . $sequence->cycle_option . '"' .
					' />';
			}

			foreach ($fields as $field)
			{
				$buffer[] = '   <field Field="' . $field->column_name . '" Type="' . $field->type . '" Null="' . $field->null . '"' .
							(isset($field->default) ? ' Default="' . $field->default . '"' : '') . ' Comments="' . $field->comments . '"' .
					' />';
			}

			foreach ($keys as $key)
			{
				$buffer[] = '   <key Index="' . $key->idxName . '" is_primary="' . $key->isPrimary . '" is_unique="' . $key->isUnique . '"' .
					' Query="' . $key->Query . '" />';
			}

			$buffer[] = '  </table_structure>';
		}

		return $buffer;
	}
628391
public static function xmlRecompileFromStructValArray(array $vals) {
		$XMLcontent = '';

		foreach ($vals as $val) {
			$type = $val['type'];

				// open tag:
			if ($type == 'open' || $type == 'complete') {
				$XMLcontent .= '<' . $val['tag'];
				if (isset($val['attributes'])) {
					foreach ($val['attributes'] as $k => $v) {
						$XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
					}
				}
				if ($type == 'complete') {
					if (isset($val['value'])) {
						$XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
					} else {
						$XMLcontent .= '/>';
					}
				} else {
					$XMLcontent .= '>';
				}

				if ($type == 'open' && isset($val['value'])) {
					$XMLcontent .= htmlspecialchars($val['value']);
				}
			}
				// finish tag:
			if ($type == 'close') {
				$XMLcontent .= '</' . $val['tag'] . '>';
			}
				// cdata
			if ($type == 'cdata') {
				$XMLcontent .= htmlspecialchars($val['value']);
			}
		}

		return $XMLcontent;
	}