sabshere 2/10/11 dkastner pointed out that this doesn't include metadata like later versions of mysql do
 this matches the xml generated by "mysql --xml"
 i tried to use builder, but the String#to_xs nonsense got in the way
344791
def to_file(f)
      result = client.query(last_statement, :stream => true, :cache_rows => false, :as => :array)
      escaped_fields = result.fields.map { |k| k.to_xs }

      f.write %{<?xml version="1.0" encoding="utf-8" ?>}
      f.write %{<resultset statement="#{config.execute.to_xs}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">}
      result.each do |ary|
        next if ary.nil?
        f.write %{<row>}
        ary.each_with_index do |v, i|
          f.write %{<field name="#{escaped_fields[i]}"#{' xsi:nil="true"' if v.nil?}>#{v.to_s.to_xs}</field>}
        end
        f.write %{</row>}
      end
      f.write %{</resultset>}
      nil
    end
646977
public function xml2query()
    {
        if (array_key_exists("CogModule", $this->data)) {
            $q = &$this->data["CogModule"];
        } else {
            $q = &$this->data["Report"];
        }

        $criteria_links = array();

        // Generate Output Information...
        $ds = false;
        if (!$q) {
            return;
        }

        foreach ($q as $cogquery) {
            // Set Query Attributes
            foreach ($cogquery["Format"] as $att => $val) {
                $this->query->setAttribute($att, $val);
            }

            // Set DataSource
            if (isset($cogquery["Datasource"])) {
                foreach ($cogquery["Datasource"] as $att => $val) {
                    //if ( $att == "SourceType" )
                    //$this->query->source_type = $val;

                    if ($att == "SourceConnection") {
                        // No longer relevant - connections are not supplied in xml files
                    }
                }
            }

            // Set Query Columns
            if (!($ef = &$this->getArrayElement($cogquery, "EntryForm"))) {
                $this->ErrorMsg = "No EntryForm tag within Format";
                return false;
            }

            if (!($qu = &$this->getArrayElement($ef, "Query"))) {
                $this->ErrorMsg = "No Query tag within EntryForm";
                return false;
            }

            $this->query->table_text = $this->getArrayElement($qu, "TableSql");
            $this->query->where_text = $this->getArrayElement($qu, "WhereSql");
            $this->query->group_text = $this->getArrayElement($qu, "GroupSql");
            $this->query->rowselection = $this->getArrayElement($qu, "RowSelection");
            $has_cols = true;

            if (($qc = &$this->getArrayElement($qu, "SQL"))) {
                $this->query->sql_raw = $this->getArrayElement($qc, "SQLRaw");
            }

            if (!($qc = &$this->getArrayElement($qu, "QueryColumns"))) {
                $this->ErrorMsg = "No QueryColumns tag within Query";
                $has_cols = false;
            }

            // Generate QueryColumn for each column found
            if ($has_cols) {
                foreach ($qc as $col) {
                    $in_query = true;
                    if (!$col["ColumnName"]) {
                        $in_query = false;
                    }

                    $this->query->createCriteriaColumn
                    (
                        $col["Name"],
                        $col["TableName"],
                        $col["ColumnName"],
                        $col["ColumnType"],
                        $col["ColumnLength"],
                        "###.##",
                        $in_query
                    );

                    // Set any Attributes
                    if (($fm = &$this->getArrayElement($col, "Format"))) {
                        foreach ($fm as $att => $val) {
                            $this->query->setColumnAttribute($col["Name"], $att, $val);
                        }
                    }
                }

                // Generate Order By List
                if (($oc = &$this->getArrayElement($qu, "OrderColumns"))) {
                    // Generate QueryColumn for each column found
                    foreach ($oc as $col) {
                        if (!$col["Name"]) {
                            return;
                        }

                        $this->query->createQueryColumn
                        (
                            $col["Name"],
                            $col["OrderType"]
                        );
                    }
                }

                // Generate Query Assignments
                if (($as = &$this->getArrayElement($ef, "Assignments"))) {
                    foreach ($as as $col) {
                        if (array_key_exists("AssignName", $col)) {
                            $this->query->addAssignment($col["AssignName"], $col["Expression"], $col["Condition"]);
                        } else {
                            $this->query->addAssignment($col["Name"], $col["Expression"], $col["Condition"]);
                        }

                    }
                }
            }

            // Generate Query Assignments
            if (($pq = &$this->getArrayElement($qu, "PreSQLS"))) {
                foreach ($pq as $col) {
                    $this->query->addPreSql($col["SQLText"]);
                }
            }

            // Generate Output Information...
            if (($op = &$this->getArrayElement($ef, "Output"))) {
                // Generate Page Headers
                if (($ph = $this->getArrayElement($op, "PageHeaders"))) {
                    foreach ($ph as $k => $phi) {
                        $this->query->createPageHeader($k, $phi["LineNumber"], $phi["HeaderText"]);
                        if (($fm = &$this->getArrayElement($phi, "Format"))) {
                            foreach ($fm as $att => $val) {
                                $this->query->setPageHeaderAttribute($k, $att, $val);
                            }
                        }

                    }
                }

                // Generate Page Footers
                if (($ph = $this->getArrayElement($op, "PageFooters"))) {
                    foreach ($ph as $k => $phi) {
                        $this->query->createPageFooter($k, $phi["LineNumber"], $phi["FooterText"]);
                        if (($fm = &$this->getArrayElement($phi, "Format"))) {
                            foreach ($fm as $att => $val) {
                                $this->query->setPageFooterAttribute($k, $att, $val);
                            }
                        }

                    }
                }

                // Generate Display Orders
                if ($has_cols && ($ph = $this->getArrayElement($op, "DisplayOrders"))) {
                    foreach ($ph as $k => $phi) {
                        $this->query->setColumnOrder($phi["ColumnName"], $phi["OrderNumber"]);
                    }
                }

                if ($has_cols && ($ph = $this->getArrayElement($op, "Groups"))) {
                    foreach ($ph as $k => $phi) {
                        if (array_key_exists("GroupName", $phi)) {
                            $gpname = $phi["GroupName"];
                        } else {
                            $gpname = $phi["Name"];
                        }

                        $grn = $this->query->createGroup($gpname);

                        if (array_key_exists("BeforeGroupHeader", $phi)) {
                            $grn->setAttribute("before_header", $phi["BeforeGroupHeader"]);
                            $grn->setAttribute("after_header", $phi["AfterGroupHeader"]);
                            $grn->setAttribute("before_trailer", $phi["BeforeGroupTrailer"]);
                            $grn->setAttribute("after_trailer", $phi["AfterGroupTrailer"]);
                            $grn->setFormat("before_header", $phi["BeforeGroupHeader"]);
                            $grn->setFormat("after_header", $phi["AfterGroupHeader"]);
                            $grn->setFormat("before_trailer", $phi["BeforeGroupTrailer"]);
                            $grn->setFormat("after_trailer", $phi["AfterGroupTrailer"]);
                        }

                        if (($gp = &$this->getArrayElement($phi, "GroupHeaders"))) {
                            foreach ($gp as $att => $val) {
                                if (!isset($val["GroupHeaderCustom"])) {
                                    $val["GroupHeaderCustom"] = false;
                                }

                                if (!isset($val["ShowInHTML"])) {
                                    $val["ShowInHTML"] = "yes";
                                }

                                if (!isset($val["ShowInPDF"])) {
                                    $val["ShowInPDF"] = "yes";
                                }

                                $this->query->createGroupHeader($gpname, $val["GroupHeaderColumn"], $val["GroupHeaderCustom"], $val["ShowInHTML"], $val["ShowInPDF"]);
                            }
                        }

                        if (($gp = &$this->getArrayElement($phi, "GroupTrailers"))) {
                            foreach ($gp as $att => $val) {
                                if (!isset($val["GroupTrailerCustom"])) {
                                    $val["GroupTrailerCustom"] = false;
                                }

                                if (!isset($val["ShowInHTML"])) {
                                    $val["ShowInHTML"] = "yes";
                                }

                                if (!isset($val["ShowInPDF"])) {
                                    $val["ShowInPDF"] = "yes";
                                }

                                $this->query->createGroupTrailer($gpname, $val["GroupTrailerDisplayColumn"],
                                    $val["GroupTrailerValueColumn"],
                                    $val["GroupTrailerCustom"], $val["ShowInHTML"], $val["ShowInPDF"]);
                            }
                        }

                    }
                }

                // Generate Graphs
                if ($has_cols && ($gph = $this->getArrayElement($op, "Graphs"))) {
                    foreach ($gph as $k => $gphi) {
                        $ka = array_keys($gphi);
                        $gph = &$this->query->createGraph();

                        $gph->setGraphColumn($gphi["GraphColumn"]);

                        $gph->setTitle($gphi["Title"]);
                        $gph->setXtitle($gphi["XTitle"]);
                        $gph->setXlabelColumn($gphi["XLabelColumn"]);
                        $gph->setYtitle($gphi["YTitle"]);
                        //$gph->setYlabelColumn($gphi["YLabelColumn"]);
                        //////HERE!!!
                        if (array_key_exists("GraphWidth", $gphi)) {
                            $gph->setWidth($gphi["GraphWidth"]);
                            $gph->setHeight($gphi["GraphHeight"]);
                            $gph->setWidthPdf($gphi["GraphWidthPDF"]);
                            $gph->setHeightPdf($gphi["GraphHeightPDF"]);
                        } else {
                            $gph->setWidth($gphi["Width"]);
                            $gph->setHeight($gphi["Height"]);
                        }

                        if (array_key_exists("GraphColor", $gphi)) {
                            $gph->setGraphColor($gphi["GraphColor"]);
                            $gph->setGrid($gphi["GridPosition"],
                                $gphi["XGridDisplay"], $gphi["XGridColor"],
                                $gphi["YGridDisplay"], $gphi["YGridColor"]
                            );
                            $gph->setTitleFont($gphi["TitleFont"], $gphi["TitleFontStyle"],
                                $gphi["TitleFontSize"], $gphi["TitleColor"]);
                            $gph->setXtitleFont($gphi["XTitleFont"], $gphi["XTitleFontStyle"],
                                $gphi["XTitleFontSize"], $gphi["XTitleColor"]);
                            $gph->setYtitleFont($gphi["YTitleFont"], $gphi["YTitleFontStyle"],
                                $gphi["YTitleFontSize"], $gphi["YTitleColor"]);
                            $gph->setXaxis($gphi["XTickInterval"], $gphi["XTickLabelInterval"], $gphi["XAxisColor"]);
                            $gph->setYaxis($gphi["YTickInterval"], $gphi["YTickLabelInterval"], $gphi["YAxisColor"]);
                            $gph->setXaxisFont($gphi["XAxisFont"], $gphi["XAxisFontStyle"],
                                $gphi["XAxisFontSize"], $gphi["XAxisFontColor"]);
                            $gph->setYaxisFont($gphi["YAxisFont"], $gphi["YAxisFontStyle"],
                                $gphi["YAxisFontSize"], $gphi["YAxisFontColor"]);
                            $gph->setMarginColor($gphi["MarginColor"]);
                            $gph->setMargins($gphi["MarginLeft"], $gphi["MarginRight"],
                                $gphi["MarginTop"], $gphi["MarginBottom"]);
                        }
                        foreach ($gphi["Plots"] as $pltk => $pltv) {
                            $pl = &$gph->createPlot($pltv["PlotColumn"]);
                            $pl["type"] = $pltv["PlotType"];
                            $pl["fillcolor"] = $pltv["FillColor"];
                            $pl["linecolor"] = $pltv["LineColor"];
                            $pl["legend"] = $pltv["Legend"];
                        }
                    }
                }

            } // Output

            // Check for Criteria Items ...

            if (($crt = &$this->getArrayElement($ef, "Criteria"))) {
                foreach ($crt as $ci) {
                    $critnm = $this->getArrayElement($ci, "Name");

                    $crittb = $this->getArrayElement($ci, "QueryTableName");
                    $critcl = $this->getArrayElement($ci, "QueryColumnName");
                    $linked_report = $this->getArrayElement($ci, "LinkToReport");
                    $linked_report_item = $this->getArrayElement($ci, "LinkToReportItem");

                    // If we are not designing a report then
                    // replace a linked criteria with the criteria
                    // item it links to from another report
                    if ($linked_report && $this->query->execute_mode != "MAINTAIN") {
                        $q = new Reportico();
                        $q->reports_path = $q->projects_folder . "/" . ReporticoApp::getConfig("project");
                        $reader = new XmlReader($q, $linked_report, false);
                        $reader->xml2query();

                        foreach ($q->lookup_queries as $k => $v) {

                            $found = false;
                            foreach ($this->query->columns as $querycol) {
                                if ($querycol->query_name == $v->query_name) {
                                    $found = true;
                                }
                            }

                            $qu = new Reportico();
                            if ($linked_report_item == $v->query_name) {
                                $this->query->lookup_queries[$v->query_name] = $v;
                            }

                        }
                        continue;
                    }

                    if ($crittb) {
                        $critcl = $crittb . "." . $critcl;
                        $crittb = "";
                    }
                    $crittp = $this->getArrayElement($ci, "CriteriaType");
                    $critlt = $this->getArrayElement($ci, "CriteriaList");
                    $crituse = $this->getArrayElement($ci, "Use");
                    $critds = $this->getArrayElement($ci, "CriteriaDisplay");
                    $critexp = $this->getArrayElement($ci, "ExpandDisplay");
                    $critmatch = $this->getArrayElement($ci, "MatchColumn");
                    $critdefault = $this->getArrayElement($ci, "CriteriaDefaults");
                    $crithelp = $this->getArrayElement($ci, "CriteriaHelp");
                    $crittitle = $this->getArrayElement($ci, "Title");
                    $crit_required = $this->getArrayElement($ci, "CriteriaRequired");
                    $crit_hidden = $this->getArrayElement($ci, "CriteriaHidden");
                    $crit_display_group = $this->getArrayElement($ci, "CriteriaDisplayGroup");
                    $crit_lookup_return = $this->getArrayElement($ci, "ReturnColumn");
                    $crit_lookup_display = $this->getArrayElement($ci, "DisplayColumn");
                    $crit_criteria_display = $this->getArrayElement($ci, "OverviewColumn");

                    if ($crittp == "ANYCHAR") {
                        $crittp = "TEXTFIELD";
                    }

                    if ($critds == "ANYCHAR") {
                        $critds = "TEXTFIELD";
                    }

                    if ($critexp == "ANYCHAR") {
                        $critexp = "TEXTFIELD";
                    }

                    // Generate criteria lookup info unless its a link to a criteria in a nother report
                    if (!$linked_report && !($ciq = &$this->getArrayElement($ci, "Query"))) {
                        continue;
                    }

                    $critquery = new Reportico();

                    // Generate Criteria Query Columns
                    if (!$linked_report && ($ciqc = &$this->getArrayElement($ciq, "QueryColumns"))) {
                        foreach ($ciqc as $ccol) {
                            $in_query = true;
                            if (!$ccol["ColumnName"]) {
                                $in_query = false;
                            }

                            $critquery->createCriteriaColumn
                            (
                                $ccol["Name"],
                                $ccol["TableName"],
                                $ccol["ColumnName"],
                                $ccol["ColumnType"],
                                $ccol["ColumnLength"],
                                "###.##",
                                $in_query
                            );
                        }
                    }
                    // Generate Order By List
                    if (!$linked_report && ($coc = &$this->getArrayElement($ciq, "OrderColumns"))) {
                        // Generate QueryColumn for each column found
                        foreach ($coc as $col) {
                            $critquery->createOrderColumn
                            (
                                $col["Name"],
                                $col["OrderType"]
                            );
                        }
                    }

                    if (!$linked_report && ($as = &$this->getArrayElement($ciq, "Assignments"))) {
                        foreach ($as as $ast) {
                            if (array_key_exists("AssignName", $ast)) {
                                $critquery->addAssignment($ast["AssignName"], $ast["Expression"], $ast["Condition"]);
                            } else {
                                $critquery->addAssignment($ast["Name"], $ast["Expression"], $ast["Condition"]);
                            }

                        }
                    }

                    // Generate Criteria Links  In Array for later use
                    if (!$linked_report && ($cl = &$this->getArrayElement($ci, "CriteriaLinks"))) {
                        foreach ($cl as $clitem) {
                            $criteria_links[] = array(
                                "LinkFrom" => $clitem["LinkFrom"],
                                "LinkTo" => $clitem["LinkTo"],
                                "LinkClause" => $clitem["LinkClause"],
                            );
                        }
                    }

                    // Set Query SQL Text
                    if (!$linked_report) {
                        $critquery->table_text = $this->getArrayElement($ciq, "TableSql");
                        $critquery->where_text = $this->getArrayElement($ciq, "WhereSql");
                        $critquery->group_text = $this->getArrayElement($ciq, "GroupSql");
                        $critquery->sql_raw = $this->getArrayElement($ciq, "SQLRaw");
                        $critquery->rowselection = $this->getArrayElement($ciq, "RowSelection");
                    }
                    $critquery->setLookupReturn($crit_lookup_return);
                    $critquery->setLookupDisplay($crit_lookup_display, $crit_criteria_display);
                    $critquery->setLookupExpandMatch($critmatch);
                    $this->query->setCriteriaLookup($critnm, $critquery, $crittb, $critcl);
                    $this->query->setCriteriaInput($critnm, $crittp, $critds, $critexp, $crituse);
                    $this->query->setCriteriaLinkReport($critnm, $linked_report, $linked_report_item);
//echo "SET $critnm $crit_required<BR>";
                    $this->query->setCriteriaDefaults($critnm, $critdefault);
                    $this->query->setCriteriaList($critnm, $critlt);
                    //var_dump($crit_required);
                    $this->query->setCriteriaRequired($critnm, $crit_required);
                    $this->query->setCriteriaHidden($critnm, $crit_hidden);
                    $this->query->setCriteriaDisplayGroup($critnm, $crit_display_group);
                    //$this->query->setCriteriaHelp($critnm, $crithelp);
                    $this->query->setCriteriaAttribute($critnm, "column_title", $crittitle);

                    $this->query->setCriteriaHelp($critnm, $crithelp);

                } // End Criteria Item

                // Set up any Criteria Links
                foreach ($criteria_links as $cl) {
                    $this->query->set_criteria_link($cl["LinkFrom"], $cl["LinkTo"], $cl["LinkClause"]);
                }
            }
        }

    }
914320
protected function getAlterTableSql(\SimpleXMLElement $structure)
	{
		// Initialise variables.
		$table     = $this->getRealTableName($structure['name']);
		$oldFields = $this->db->getTableColumns($table);
		$oldKeys   = $this->db->getTableKeys($table);
		$alters    = array();

		// Get the fields and keys from the XML that we are aiming for.
		$newFields = $structure->xpath('field');
		$newKeys   = $structure->xpath('key');

		// Loop through each field in the new structure.
		foreach ($newFields as $field)
		{
			$fName = (string) $field['Field'];

			if (isset($oldFields[$fName]))
			{
				// The field exists, check it's the same.
				$column = $oldFields[$fName];

				// Test whether there is a change.
				$change = ((string) $field['Type'] !== $column->Type) || ((string) $field['Null'] !== $column->Null)
					|| ((string) $field['Default'] !== $column->Default) || ((string) $field['Extra'] !== $column->Extra);

				if ($change)
				{
					$alters[] = $this->getChangeColumnSql($table, $field);
				}

				// Unset this field so that what we have left are fields that need to be removed.
				unset($oldFields[$fName]);
			}
			else
			{
				// The field is new.
				$alters[] = $this->getAddColumnSql($table, $field);
			}
		}

		// Any columns left are orphans
		foreach ($oldFields as $name => $column)
		{
			// Delete the column.
			$alters[] = $this->getDropColumnSql($table, $name);
		}

		// Get the lookups for the old and new keys.
		$oldLookup = $this->getKeyLookup($oldKeys);
		$newLookup = $this->getKeyLookup($newKeys);

		// Loop through each key in the new structure.
		foreach ($newLookup as $name => $keys)
		{
			// Check if there are keys on this field in the existing table.
			if (isset($oldLookup[$name]))
			{
				$same     = true;
				$newCount = \count($newLookup[$name]);
				$oldCount = \count($oldLookup[$name]);

				// There is a key on this field in the old and new tables. Are they the same?
				if ($newCount === $oldCount)
				{
					// Need to loop through each key and do a fine grained check.
					for ($i = 0; $i < $newCount; $i++)
					{
						$same = (((string) $newLookup[$name][$i]['Non_unique'] === $oldLookup[$name][$i]->Non_unique)
							&& ((string) $newLookup[$name][$i]['Column_name'] === $oldLookup[$name][$i]->Column_name)
							&& ((string) $newLookup[$name][$i]['Seq_in_index'] === $oldLookup[$name][$i]->Seq_in_index)
							&& ((string) $newLookup[$name][$i]['Collation'] === $oldLookup[$name][$i]->Collation)
							&& ((string) $newLookup[$name][$i]['Index_type'] === $oldLookup[$name][$i]->Index_type));

						/*
						Debug.
						echo '<pre>';
						echo '<br>Non_unique:   '.
							((string) $newLookup[$name][$i]['Non_unique'] == $oldLookup[$name][$i]->Non_unique ? 'Pass' : 'Fail').' '.
							(string) $newLookup[$name][$i]['Non_unique'].' vs '.$oldLookup[$name][$i]->Non_unique;
						echo '<br>Column_name:  '.
							((string) $newLookup[$name][$i]['Column_name'] == $oldLookup[$name][$i]->Column_name ? 'Pass' : 'Fail').' '.
							(string) $newLookup[$name][$i]['Column_name'].' vs '.$oldLookup[$name][$i]->Column_name;
						echo '<br>Seq_in_index: '.
							((string) $newLookup[$name][$i]['Seq_in_index'] == $oldLookup[$name][$i]->Seq_in_index ? 'Pass' : 'Fail').' '.
							(string) $newLookup[$name][$i]['Seq_in_index'].' vs '.$oldLookup[$name][$i]->Seq_in_index;
						echo '<br>Collation:    '.
							((string) $newLookup[$name][$i]['Collation'] == $oldLookup[$name][$i]->Collation ? 'Pass' : 'Fail').' '.
							(string) $newLookup[$name][$i]['Collation'].' vs '.$oldLookup[$name][$i]->Collation;
						echo '<br>Index_type:   '.
							((string) $newLookup[$name][$i]['Index_type'] == $oldLookup[$name][$i]->Index_type ? 'Pass' : 'Fail').' '.
							(string) $newLookup[$name][$i]['Index_type'].' vs '.$oldLookup[$name][$i]->Index_type;
						echo '<br>Same = '.($same ? 'true' : 'false');
						echo '</pre>';
						 */

						if (!$same)
						{
							// Break out of the loop. No need to check further.
							break;
						}
					}
				}
				else
				{
					// Count is different, just drop and add.
					$same = false;
				}

				if (!$same)
				{
					$alters[] = $this->getDropKeySql($table, $name);
					$alters[] = $this->getAddKeySql($table, $keys);
				}

				// Unset this field so that what we have left are fields that need to be removed.
				unset($oldLookup[$name]);
			}
			else
			{
				// This is a new key.
				$alters[] = $this->getAddKeySql($table, $keys);
			}
		}

		// Any keys left are orphans.
		foreach ($oldLookup as $name => $keys)
		{
			if (strtoupper($name) === 'PRIMARY')
			{
				$alters[] = $this->getDropPrimaryKeySql($table);
			}
			else
			{
				$alters[] = $this->getDropKeySql($table, $name);
			}
		}

		return $alters;
	}
4624
def to_xml(options = {})
      xml = options[:builder] ||= Builder::XmlMarkup.new
      xml.instruct! unless options[:skip_instruct]
      each do |key, value|
        # Remove leading and trailing whitespace from tag values
        xml.tag(:k => key, :v => coder.decode(value.strip)) unless value.blank?
      end unless empty?
    end
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;
	}
167224
def render
      xml = Builder::XmlMarkup.new(:indent => 2)
      xml.instruct!(:xml, :version => '1.0', :encoding => 'UTF-8')
      xml.sitemapindex(XmlSitemap::INDEX_SCHEMA_OPTIONS) { |s|
        @maps.each do |item|
          s.sitemap do |m|
            m.loc        item[:loc]
            m.lastmod    item[:lastmod]
          end
        end
      }.to_s
    end
1098423
protected function _mysql()
	{
		$this->_msg(sprintf('Adding label and status columns'), 0);
		$this->_status( '' );

		foreach ($this->_mysql as $table => $columns) {

			if ($this->_schema->tableExists($table)) {

				foreach ($columns as $column => $stmt) {

					$this->_msg(sprintf('Checking column "%1$s.%2$s": ', $table, $column), 1);

					if (!$this->_schema->columnExists($table, $column)) {
						$this->_execute($stmt);
						$this->_status('added');
					} else {
						$this->_status('OK');
					}
				}
			}
		}
	}
1311096
private void parseTableSchemaFromXML(String tableName,
                                         StmtCommonTableScanShared tableScan,
                                         VoltXMLElement voltXMLElement) {
        assert("table".equals(voltXMLElement.name));
        List<VoltXMLElement> columnSet = voltXMLElement.findChildren("columns");
        assert(columnSet.size() == 1);
        columnSet = columnSet.get(0).children;
        for (int idx = 0; idx < columnSet.size(); idx += 1) {
            VoltXMLElement columnXML = columnSet.get(idx);
            assert("column".equals(columnXML.name));
            String columnName = columnXML.attributes.get("name");
            // If valuetype is not defined, then we will get type
            // "none", about which typeFromString will complain.
            // Note that the types may be widened from the type
            // of the base query of a recursive common table.  This
            // happens if the corresponding type in the recursive
            // query is wider than that of the base case.  But
            // HSQL will have taken care of this for us, so we
            // will not see the widening here.
            VoltType valueType = VoltType.typeFromString(columnXML.getStringAttribute("valuetype", "none"));
            Integer columnIndex = columnXML.getIntAttribute("index", null);
            assert(columnIndex != null);
            // These appear to be optional.  Certainly "bytes"
            // only appears if the type is variably sized.
            Integer size = columnXML.getIntAttribute("size", 0);
            Boolean inBytes = columnXML.getBoolAttribute("bytes", null);
            // This TVE holds the metadata.
            TupleValueExpression tve = new TupleValueExpression(tableName, tableName, columnName, columnName, columnIndex);
            tve.setValueType(valueType);
            tve.setDifferentiator(idx);
            if (size == 0) {
                if (valueType.isVariableLength()) {
                    size = valueType.defaultLengthForVariableLengthType();
                }
                else {
                    size = valueType.getLengthInBytesForFixedTypes();
                }
            }
            tve.setValueSize(size);
            if (inBytes != null) {
                tve.setInBytes(inBytes);
            }
            // There really is no aliasing going on here, so the table
            // name and column name are the same as the table alias and
            // column alias.
            SchemaColumn schemaColumn = new SchemaColumn(tableName, tableName, columnName, columnName, tve, idx);
            tableScan.addOutputColumn(schemaColumn);
        }
    }
848612
function MetaDatabases()
	{
		if(@mssql_select_db("master")) {
				 $qry=$this->metaDatabasesSQL;
				 if($rs=@mssql_query($qry,$this->_connectionID)){
						 $tmpAr=$ar=array();
						 while($tmpAr=@mssql_fetch_row($rs))
								 $ar[]=$tmpAr[0];
						@mssql_select_db($this->database);
						 if(sizeof($ar))
								 return($ar);
						 else
								 return(false);
				 } else {
						 @mssql_select_db($this->database);
						 return(false);
				 }
		 }
		 return(false);
	}
1346287
public String toXML()
    {
        RepositoryTags tags = RepositoryTags.getInstance();
        String eol = SystemUtils.LINE_SEPARATOR;

        //opening tag + attributes
        StringBuffer result = new StringBuffer( 1024 );
        result.append( "      " );
        result.append( tags.getOpeningTagNonClosingById( FIELD_DESCRIPTOR ) );
        result.append( " " );
        result.append( eol );

        //        // id
        //        String id = new Integer(getColNo()).toString();
        //        result += /*"        " +*/ tags.getAttribute(ID, id) + eol;

        // name
        result.append( "        " );
        result.append( tags.getAttribute( FIELD_NAME, this.getAttributeName() ) );
        result.append( eol );

        // table not yet implemented

        // column
        result.append( "        " );
        result.append( tags.getAttribute( COLUMN_NAME, this.getColumnName() ) );
        result.append( eol );

        // jdbc-type
        result.append( "        " );
        result.append( tags.getAttribute( JDBC_TYPE, this.getColumnType() ) );
        result.append( eol );

        // primarykey
        if( this.isPrimaryKey() )
        {
            result.append( "        " );
            result.append( tags.getAttribute( PRIMARY_KEY, "true" ) );
            result.append( eol );
        }

        // nullable
        if( this.isRequired() )
        {
            result.append( "        " );
            result.append( tags.getAttribute( NULLABLE, "false" ) );
            result.append( eol );
        }

        // indexed not yet implemented

        // autoincrement
        if( this.isAutoIncrement() )
        {
            result.append( "        " );
            result.append( tags.getAttribute( AUTO_INCREMENT, "true" ) );
            result.append( eol );
        }

        // locking
        if( this.isLocking() )
        {
            result.append( "        " );
            result.append( tags.getAttribute( LOCKING, "true" ) );
            result.append( eol );
        }

        // updateLock
        // default is true so only write if false
        if( !this.isUpdateLock() )
        {
            result.append( "        " );
            result.append( tags.getAttribute( UPDATE_LOCK, "false" ) );
            result.append( eol );
        }

        // default-fetch not yet implemented

        // conversion
        if( this.getFieldConversion().getClass() != FieldConversionDefaultImpl.class )
        {
            result.append( "        " );
            result.append( tags.getAttribute( FIELD_CONVERSION, getFieldConversion().getClass().getName() ) );
            result.append( eol );
        }

        // length
        if( this.isLengthSpecified() )
        {
            result.append( "        " );
            result.append( tags.getAttribute( LENGTH, "" + getLength() ) );
            result.append( eol );
        }

        // precision
        if( this.isPrecisionSpecified() )
        {
            result.append( "        " );
            result.append( tags.getAttribute( PRECISION, "" + getPrecision() ) );
            result.append( eol );
        }

        // scale
        if( this.isScaleSpecified() )
        {
            result.append( "        " );
            result.append( tags.getAttribute( SCALE, "" + getScale() ) );
            result.append( eol );
        }

        // access
        result.append( "        " );
        result.append( tags.getAttribute( ACCESS, this.getAccess() ) );
        result.append( eol );

        result.append( "      />" );
        result.append( eol );
        return result.toString();
    }
145269
private String exportToSql() throws SQLException {

        StringBuilder sql = new StringBuilder();
        sql.append("--");
        sql.append("\n-- Generated by mysql-backup4j");
        sql.append("\n-- https://github.com/SeunMatt/mysql-backup4j");
        sql.append("\n-- Date: ").append(new SimpleDateFormat("d-M-Y H:m:s").format(new Date()));
        sql.append("\n--");

        //these declarations are extracted from HeidiSQL
        sql.append("\n\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;")
                .append("\n/*!40101 SET NAMES utf8 */;")
                .append("\n/*!50503 SET NAMES utf8mb4 */;")
                .append("\n/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;")
                .append("\n/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;");


        //get the tables that are in the database
        List<String> tables = MysqlBaseService.getAllTables(database, stmt);

        //for every table, get the table creation and data
        // insert statement
        for (String s: tables) {
            try {
                sql.append(getTableInsertStatement(s.trim()));
                sql.append(getDataInsertStatement(s.trim()));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        sql.append("\n/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;")
                .append("\n/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;")
                .append("\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;");

        this.generatedSql = sql.toString();
        return sql.toString();
    }
1268707
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);

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

			foreach ($fields as $field)
			{
				$buffer[] = '   <field Field="' . $field->Field . '" Type="' . $field->Type . '" Null="' . $field->Null . '" Key="' .
					$field->Key . '"' . (isset($field->Default) ? ' Default="' . $field->Default . '"' : '') . ' Extra="' . $field->Extra . '"' .
					' />';
			}

			foreach ($keys as $key)
			{
				$buffer[] = '   <key Table="' . $table . '" Non_unique="' . $key->Non_unique . '" Key_name="' . $key->Key_name . '"' .
					' Seq_in_index="' . $key->Seq_in_index . '" Column_name="' . $key->Column_name . '" Collation="' . $key->Collation . '"' .
					' Null="' . $key->Null . '" Index_type="' . $key->Index_type . '"' .
					' Comment="' . htmlspecialchars($key->Comment, ENT_COMPAT, 'UTF-8') . '"' .
					' />';
			}

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

		return $buffer;
	}
927496
static QueryMeta buildUpdateSql(ActiveRecord activeRecord) {
        QueryMeta     queryMeta = new QueryMeta();
        String        sql;
        String        tableName = activeRecord.getTableName();
        StringBuilder sb        = new StringBuilder("UPDATE ");
        sb.append(tableName);
        sb.append(" SET ");

        final int[]  pos  = {1};
        List<Object> list = parseSet(activeRecord, pos, sb);

        sb.append(Const.SQL_WHERE).append(Const.SPACE);
        activeRecord.whereValues.forEach(where -> {
            if ("IS".equals(where.getOpt())) {
                sb.append(where.getKey()).append(Const.SPACE)
                        .append(where.getValue()).append(Const.SPACE).append(Const.SQL_AND).append(Const.SPACE);
                list.add(where.getValue());
            } else {
                sb.append(where.getKey()).append(Const.SPACE)
                        .append(where.getOpt()).append(Const.SPACE)
                        .append(":p").append(pos[0]++).append(Const.SPACE).append(Const.SQL_AND).append(Const.SPACE);
                list.add(where.getValue());
            }
        });

        sql = sb.toString().replace(", " + Const.SQL_WHERE + Const.SPACE, Const.SPACE + Const.SQL_WHERE + Const.SPACE)
                .replace(Const.SQL_AND + Const.SPACE + Const.SQL_OR, Const.SQL_OR);
        if (sql.endsWith(Const.SQL_AND + Const.SPACE)) {
            sql = sql.substring(0, sql.length() - 5);
        }

        Object[] args = list.toArray();
        queryMeta.setParams(args);
        queryMeta.setSql(sql);
        return queryMeta;
    }
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;
    }
788077
protected function buildXml()
    {
        if (empty($_POST['CKFinderCommand']) || $_POST['CKFinderCommand'] != 'true') {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
        }

        $clientPath = $this->_currentFolder->getClientPath();
        $sServerDir = $this->_currentFolder->getServerPath();
        $currentResourceTypeConfig = $this->_currentFolder->getResourceTypeConfig();
        $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config");
        $_aclConfig = $_config->getAccessControlConfig();
        $_thumbnailsConfig = $_config->getThumbnailsConfig();
        $aclMasks = array();
        $_resourceTypeConfig = array();

        if (!$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_RENAME | CKFINDER_CONNECTOR_ACL_FILE_UPLOAD | CKFINDER_CONNECTOR_ACL_FILE_DELETE)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }

        // Create the "Errors" node.
        $oErrorsNode = new CKFinder_Connector_Utils_XmlNode("Errors");
        $errorCode = CKFINDER_CONNECTOR_ERROR_NONE;
        $moved = 0;
        $movedAll = 0;
        if (!empty($_POST['moved'])) {
            $movedAll = intval($_POST['moved']);
        }
        $checkedPaths = array();

        $oMoveFilesNode = new Ckfinder_Connector_Utils_XmlNode("MoveFiles");

        if (!empty($_POST['files']) && is_array($_POST['files'])) {
            foreach ($_POST['files'] as $index => $arr) {
                if (empty($arr['name'])) {
                    continue;
                }
                if (!isset($arr['name'], $arr['type'], $arr['folder'])) {
                    $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
                }

                // file name
                $name = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($arr['name']);
                // resource type
                $type = $arr['type'];
                // client path
                $path = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($arr['folder']);
                // options
                $options = (!empty($arr['options'])) ? $arr['options'] : '';

                $destinationFilePath = $sServerDir.$name;

                // check #1 (path)
                if (!CKFinder_Connector_Utils_FileSystem::checkFileName($name) || preg_match(CKFINDER_REGEX_INVALID_PATH, $path)) {
                    $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
                }

                // get resource type config for current file
                if (!isset($_resourceTypeConfig[$type])) {
                    $_resourceTypeConfig[$type] = $_config->getResourceTypeConfig($type);
                }

                // check #2 (resource type)
                if (is_null($_resourceTypeConfig[$type])) {
                    $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
                }

                // check #3 (extension)
                if (!$_resourceTypeConfig[$type]->checkExtension($name, false)) {
                    $errorCode = CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION;
                    $this->appendErrorNode($oErrorsNode, $errorCode, $name, $type, $path);
                    continue;
                }

                // check #4 (extension) - when moving to another resource type, double check extension
                if ($currentResourceTypeConfig->getName() != $type) {
                    if (!$currentResourceTypeConfig->checkExtension($name, false)) {
                        $errorCode = CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION;
                        $this->appendErrorNode($oErrorsNode, $errorCode, $name, $type, $path);
                        continue;
                    }
                }

                // check #5 (hidden folders)
                // cache results
                if (empty($checkedPaths[$path])) {
                    $checkedPaths[$path] = true;

                    if ($_resourceTypeConfig[$type]->checkIsHiddenPath($path)) {
                        $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
                    }
                }

                $sourceFilePath = $_resourceTypeConfig[$type]->getDirectory().$path.$name;

                // check #6 (hidden file name)
                if ($currentResourceTypeConfig->checkIsHiddenFile($name)) {
                    $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
                }

                // check #7 (Access Control, need file view permission to source files)
                if (!isset($aclMasks[$type."@".$path])) {
                    $aclMasks[$type."@".$path] = $_aclConfig->getComputedMask($type, $path);
                }

                $isAuthorized = (($aclMasks[$type."@".$path] & CKFINDER_CONNECTOR_ACL_FILE_VIEW) == CKFINDER_CONNECTOR_ACL_FILE_VIEW);
                if (!$isAuthorized) {
                    $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
                }

                // check #8 (invalid file name)
                if (!file_exists($sourceFilePath) || !is_file($sourceFilePath)) {
                    $errorCode = CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND;
                    $this->appendErrorNode($oErrorsNode, $errorCode, $name, $type, $path);
                    continue;
                }

                // check #9 (max size)
                if ($currentResourceTypeConfig->getName() != $type) {
                    $maxSize = $currentResourceTypeConfig->getMaxSize();
                    $fileSize = filesize($sourceFilePath);
                    if ($maxSize && $fileSize>$maxSize) {
                        $errorCode = CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
                        $this->appendErrorNode($oErrorsNode, $errorCode, $name, $type, $path);
                        continue;
                    }
                }

                $_thumbsServerPath = CKFinder_Connector_Utils_FileSystem::combinePaths($_thumbnailsConfig->getDirectory(), $_config->getResourceTypeConfig($type)->getName());
                $thumbPath = CKFinder_Connector_Utils_FileSystem::combinePaths($_thumbsServerPath, $path.$name);

                //$overwrite
                // finally, no errors so far, we may attempt to copy a file
                // protection against copying files to itself
                if ($sourceFilePath == $destinationFilePath) {
                    $errorCode = CKFINDER_CONNECTOR_ERROR_SOURCE_AND_TARGET_PATH_EQUAL;
                    $this->appendErrorNode($oErrorsNode, $errorCode, $name, $type, $path);
                    continue;
                }
                // check if file exists if we don't force overwriting
                else if (file_exists($destinationFilePath)) {
                    if (strpos($options, "overwrite") !== false) {
                        if (!@unlink($destinationFilePath)) {
                            $errorCode = CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
                            $this->appendErrorNode($oErrorsNode, $errorCode, $name, $type, $path);
                            continue;
                        }
                        else {
                            if (!@rename($sourceFilePath, $destinationFilePath)) {
                                $errorCode = CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
                                $this->appendErrorNode($oErrorsNode, $errorCode, $name, $type, $path);
                                continue;
                            }
                            else {
                                CKFinder_Connector_Utils_FileSystem::unlink($thumbPath);
                                $moved++;
                            }
                        }
                    }
                    else if (strpos($options, "autorename") !== false) {
                        $fileName = CKFinder_Connector_Utils_FileSystem::autoRename($sServerDir, $name);
                        $destinationFilePath = $sServerDir.$fileName;
                        if (!@rename($sourceFilePath, $destinationFilePath)) {
                            $errorCode = CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
                            $this->appendErrorNode($oErrorsNode, $errorCode, $name, $type, $path);
                            continue;
                        }
                        else {
                            CKFinder_Connector_Utils_FileSystem::unlink($thumbPath);
                            $moved++;
                        }
                    }
                    else {
                        $errorCode = CKFINDER_CONNECTOR_ERROR_ALREADY_EXIST;
                        $this->appendErrorNode($oErrorsNode, $errorCode, $name, $type, $path);
                        continue;
                    }
                }
                else {
                    if (!@rename($sourceFilePath, $destinationFilePath)) {
                        $errorCode = CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
                        $this->appendErrorNode($oErrorsNode, $errorCode, $name, $type, $path);
                        continue;
                    }
                    else {
                        CKFinder_Connector_Utils_FileSystem::unlink($thumbPath);
                        $moved++;
                    }
                }
            }
        }

        $this->_connectorNode->addChild($oMoveFilesNode);
        if ($errorCode != CKFINDER_CONNECTOR_ERROR_NONE) {
            $this->_connectorNode->addChild($oErrorsNode);
        }
        $oMoveFilesNode->addAttribute("moved", $moved);
        $oMoveFilesNode->addAttribute("movedTotal", $movedAll + $moved);

        /**
         * Note: actually we could have more than one error.
         * This is just a flag for CKFinder interface telling it to check all errors.
         */
        if ($errorCode != CKFINDER_CONNECTOR_ERROR_NONE) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_MOVE_FAILED);
        }
    }
954354
public void parseFromXml(VoltXMLElement xmlSQL) {
        m_recentErrorMsg = null;
        m_xmlSQL = xmlSQL;
        if (m_xmlSQL.attributes.containsKey(UPSERT_TAG)) {
            m_isUpsert = true;
        }

        m_planSelector.outputCompiledStatement(m_xmlSQL);
    }
720249
function create( &$xmls ) {
		if( $this->drop ) {
			return NULL;
		}

		// eliminate any columns that aren't in the table
		foreach( $this->columns as $id => $col ) {
			if( !isset( $this->parent->fields[$id] ) ) {
				unset( $this->columns[$id] );
			}
		}

		return $xmls->dict->CreateIndexSQL( $this->name, $this->parent->name, $this->columns, $this->opts );
	}