/*!
\protected

\note Calls generateTableInsertSQLList and joins the SQLs to a string
493039
function generateTableInsert( $tableName, $tableDef, $dataEntries, $params )
    {
        return join( "\n", $this->generateTableInsertSQLList( $tableName, $tableDef, $dataEntries, $params, true ) );
    }
672875
private String createInsertQuery() {
        StringBuilder query = new StringBuilder();
        query.append("insert into ").append(m_tableName)
                .append("(").append(m_propertyNames[0]);
        for (int i = 1; i < m_propertyNames.length; i++) {
            query.append(",").append(m_propertyNames[i]);
        }
        query.append(") values (?");
        for (int i = 1; i < m_propertyNames.length; i++) {
            query.append(",?");
        }
        query.append(")");
        return query.toString();
    }
448966
public function buildInsertQuery($table, $data)
    {
        $sql = "INSERT INTO " . $this->quoteSpecialName($table) . " ";

        if (!empty($data['ON DUPLICATE'])) {
            $onDuplicate = $data['ON DUPLICATE'];
            unset($data['ON DUPLICATE']);
        }

        $keys = $values = '';

        foreach ($data as $key => $value) {
            if (!empty($keys)) $keys .= ', ';
            if (!empty($values)) $values .= ', ';

            $keys .= '`' . $key . '`';
            $values .= $this->escapeItem($value);
        }

        $keys = '(' . $keys . ')';
        $values = '(' . $values . ')';

        $sql .= $keys . ' VALUES ' . $values;

        if (!empty($onDuplicate)) {
            $sql .= " ON DUPLICATE KEY UPDATE " . $onDuplicate;
        }

        $sql .= ';';

        return $sql;
    }
883776
public function toSql(): array
    {
        if (!$this->into) {
            throw new SqlException('Undefined INSERT table.');
        }

        if (!$this->columns and !$this->select) {
            throw new SqlException('Undefined INSERT columns.');
        }

        $params = [];

        $sql = ['INSERT INTO', $this->into, '(' . implode(', ', $this->columns) . ')'];

        if ($this->select) {
            $select = $this->prepareSelect($this->select);

            $sql[] = $select['sql'];

            $params = array_merge($params, $select['params']);
        } else {
            $columnsCount = count($this->columns);

            $valuesCount = count($this->values);

            if ($columnsCount !== $valuesCount) {
                throw new SqlException('INSERT values count does not match.'
                    . ' Expected ' . $columnsCount . ', got ' . $valuesCount . '.');
            }

            $sql[] = 'VALUES ' . $this->prepareBindKeys($this->values);

            $params = array_merge($params, $this->values);
        }

        $sql = implode(' ', $sql);

        return [$sql, $params];
    }
558175
static function createSortingSQLStrings( $sortList, $treeTableName = 'ezcontentobject_tree', $allowCustomColumns = false )
    {
        $sortingInfo = array( 'sortCount'           => 0,
                              'sortingFields'       => " path_string ASC",
                              'attributeJoinCount'  => 0,
                              'attributeFromSQL'    => "",
                              'attributeTargetSQL'  => "",
                              'attributeWhereSQL'   => "" );

        if ( $sortList and is_array( $sortList ) and count( $sortList ) > 0 )
        {
            if ( count( $sortList ) > 1 and !is_array( $sortList[0] ) )
            {
                $sortList = array( $sortList );
            }

            $sortingFields      = '';
            $sortCount          = 0;
            $attributeJoinCount = 0;
            $stateJoinCount     = 0;
            $attributeFromSQL   = "";
            $attributeWhereSQL  = "";
            $datatypeSortingTargetSQL = "";

            foreach ( $sortList as $sortBy )
            {
                if ( is_array( $sortBy ) and count( $sortBy ) > 0 )
                {
                    if ( $sortCount > 0 )
                    {
                        $sortingFields .= ', ';
                    }

                    $sortField = $sortBy[0];
                    switch ( $sortField )
                    {
                        case 'path':
                        {
                            $sortingFields .= 'path_string';
                        } break;
                        case 'path_string':
                        {
                            $sortingFields .= 'path_identification_string';
                        } break;
                        case 'published':
                        {
                            $sortingFields .= 'ezcontentobject.published';
                        } break;
                        case 'modified':
                        {
                            $sortingFields .= 'ezcontentobject.modified';
                        } break;
                        case 'modified_subnode':
                        {
                            $sortingFields .= 'modified_subnode';
                        } break;
                        case 'section':
                        {
                            $sortingFields .= 'ezcontentobject.section_id';
                        } break;
                        case 'node_id':
                        {
                            $sortingFields .= $treeTableName . '.node_id';
                        } break;
                        case 'contentobject_id':
                        {
                            $sortingFields .= 'ezcontentobject.id';
                        } break;
                        case 'depth':
                        {
                            $sortingFields .= 'depth';
                        } break;
                        case 'class_identifier':
                        {
                            $sortingFields .= 'ezcontentclass.identifier';
                        } break;
                        case 'class_name':
                        {
                            $classNameFilter = eZContentClassName::sqlFilter();
                            $sortingFields .= 'contentclass_name';
                            $datatypeSortingTargetSQL .= ", $classNameFilter[nameField] AS contentclass_name";
                            $attributeFromSQL .= " INNER JOIN $classNameFilter[from] ON ($classNameFilter[where])";
                        } break;
                        case 'priority':
                        {
                            $sortingFields .= $treeTableName . '.priority';
                        } break;
                        case 'visibility':
                        {
                            $sortingFields .= $treeTableName . '.is_invisible';
                        } break;
                        case 'name':
                        {
                            $sortingFields .= 'ezcontentobject_name.name';
                        } break;
                        case 'attribute':
                        {
                            $classAttributeID = $sortBy[2];
                            if ( !is_numeric( $classAttributeID ) )
                                $classAttributeID = eZContentObjectTreeNode::classAttributeIDByIdentifier( $classAttributeID );


                            $contentAttributeTableAlias = "a$attributeJoinCount";
                            $datatypeFromSQL = "ezcontentobject_attribute $contentAttributeTableAlias";
                            $datatypeWhereSQL = "
                                   $contentAttributeTableAlias.contentobject_id = ezcontentobject.id AND
                                   $contentAttributeTableAlias.contentclassattribute_id = $classAttributeID AND
                                   $contentAttributeTableAlias.version = ezcontentobject.current_version AND";
                            $datatypeWhereSQL .= eZContentLanguage::sqlFilter( $contentAttributeTableAlias, 'ezcontentobject' );

                            $dataType = eZDataType::create( eZContentObjectTreeNode::dataTypeByClassAttributeID( $classAttributeID ) );
                            if( is_object( $dataType ) && $dataType->customSorting() )
                            {
                                $params = array();
                                $params['contentobject_attr_id'] = "$contentAttributeTableAlias.id";
                                $params['contentobject_attr_version'] = "$contentAttributeTableAlias.version";
                                $params['table_alias_suffix'] = "$attributeJoinCount";

                                $sql = $dataType->customSortingSQL( $params );

                                $datatypeFromSQL .= " INNER JOIN $sql[from] ON ($sql[where])";
                                $datatypeSortingFieldSQL = $sql['sorting_field'];
                                $datatypeSortingTargetSQL .= ', ' . $sql['sorting_field'];
                            }
                            else
                            {
                                // Look up datatype for standard sorting
                                $sortKeyType = eZContentObjectTreeNode::sortKeyByClassAttributeID( $classAttributeID );
                                switch ( $sortKeyType )
                                {
                                    case 'string':
                                        {
                                            $sortKey = 'sort_key_string';
                                        } break;

                                    case 'int':
                                    default:
                                        {
                                            $sortKey = 'sort_key_int';
                                        } break;
                                }

                                $datatypeSortingFieldSQL = "a$attributeJoinCount.$sortKey";
                                $datatypeSortingTargetSQL .= ', ' . $datatypeSortingFieldSQL;
                            }

                            $sortingFields .= "$datatypeSortingFieldSQL";
                            $attributeFromSQL .= " INNER JOIN $datatypeFromSQL ON ($datatypeWhereSQL)";

                            $attributeJoinCount++;
                        }break;

                        case 'state':
                        {
                            $stateGroupID = $sortBy[2];
                            if ( !is_numeric( $stateGroupID ) )
                            {
                                $stateGroup = eZContentObjectStateGroup::fetchByIdentifier( $stateGroupID );
                                if ( $stateGroup )
                                {
                                    $stateGroupID = $stateGroup->attribute( 'id' );
                                }
                                else
                                {
                                    eZDebug::writeError( "Unknown content object state group '$stateGroupID'" );
                                    continue 2;
                                }
                            }

                            $stateAlias = "s$stateJoinCount";
                            $stateLinkAlias = "sl$stateJoinCount";
                            $sortingFields .= "$stateAlias.priority";
                            $datatypeSortingTargetSQL .= ", $stateAlias.priority";
                            $attributeFromSQL .=
                                " INNER JOIN ezcobj_state $stateAlias ON ($stateAlias.group_id = $stateGroupID)" .
                                " INNER JOIN ezcobj_state_link $stateLinkAlias" .
                                "     ON ($stateLinkAlias.contentobject_id = ezcontentobject.id AND $stateLinkAlias.contentobject_state_id = $stateAlias.id)";
                        } break;

                        default:
                        {
                            if ( $allowCustomColumns )
                            {
                                $sortingFields .= $sortField;
                            }
                            else
                            {
                                eZDebug::writeWarning( 'Unknown sort field: ' . $sortField, __METHOD__ );
                                continue 2;
                            }
                        }
                    }
                    $sortOrder = true; // true is ascending
                    if ( isset( $sortBy[1] ) )
                        $sortOrder = $sortBy[1];
                    $sortingFields .= $sortOrder ? " ASC" : " DESC";
                    ++$sortCount;
                }
            }

            $sortingInfo['sortCount']           = $sortCount;
            $sortingInfo['sortingFields']       = $sortingFields;
            $sortingInfo['attributeTargetSQL'] = $datatypeSortingTargetSQL;
            $sortingInfo['attributeJoinCount']  = $attributeJoinCount;
            $sortingInfo['attributeFromSQL']    = $attributeFromSQL;
            $sortingInfo['attributeWhereSQL']   = $attributeWhereSQL;
        }
        else if ( $sortList === array() )
        {
            $sortingInfo['sortingFields'] = '';
        }

        return $sortingInfo;
    }
1057667
private static PreparedStatement createStatementForInsert(final Connection connection,
                                                             final Introspected introspected,
                                                             final FieldColumnInfo[] fcInfos) throws SQLException
   {
      final String sql = createStatementCache.computeIfAbsent(introspected, key -> {
         final String tableName = introspected.getTableName();
         final StringBuilder sqlSB = new StringBuilder("INSERT INTO ").append(tableName).append('(');
         final StringBuilder sqlValues = new StringBuilder(") VALUES (");

         for (final FieldColumnInfo fcInfo : fcInfos) {
            sqlSB.append(fcInfo.getDelimitedColumnName()).append(',');
            sqlValues.append("?,");
         }

         sqlValues.deleteCharAt(sqlValues.length() - 1);
         sqlSB.deleteCharAt(sqlSB.length() - 1).append(sqlValues).append(')');

         return sqlSB.toString();
      });

      if (introspected.hasGeneratedId()) {
         return connection.prepareStatement(sql, introspected.getIdColumnNames());
      }
      else {
         return connection.prepareStatement(sql);
      }
   }
1095111
function SQL(strs) {
  for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  var values = [];
  var text = strs.reduce(function (prev, curr, i) {
    var arg = args[i - 1];
    if (arg instanceof InsertValue) {
      return prev + arg.value + curr;
    } else {
      values.push(arg);
      return prev + '$' + values.length + curr;
    }
  });

  return {
    text: text,
    values: values
  };
}
664172
public function upsert($table, $insertFieldValues, $updateFieldValues = [], $primaryKey = null)
    {
        if (!$primaryKey) {
            $primaryKey = (string)key($insertFieldValues);
        }

        if (!$updateFieldValues) {
            $updateFieldValues = $insertFieldValues;
        }

        $fields = array_keys($insertFieldValues);

        $bind = $insertFieldValues;
        $updates = [];
        foreach ($updateFieldValues as $k => $v) {
            $field = is_string($k) ? $k : $v;
            if ($primaryKey === $field) {
                continue;
            }

            if (is_int($k)) {
                $updates[] = "[$field]=:{$field}_dku";
                $bind["{$field}_dku"] = $insertFieldValues[$field];
            } elseif ($v instanceof AssignmentInterface) {
                $v->setFieldName($k);
                $updates[] = $v->getSql();
                /** @noinspection SlowArrayOperationsInLoopInspection */
                $bind = array_merge($bind, $v->getBind());
            } else {
                $updates[] = $v;
            }
        }

        $insertFieldsSql = '[' . implode('],[', $fields) . ']';
        $insertValuesSql = ':' . implode(',:', $fields);

        $updateFieldsSql = implode(',', $updates);

        $sql = 'INSERT' . " INTO {$this->_escapeIdentifier($table)}($insertFieldsSql) VALUES($insertValuesSql) ON DUPLICATE KEY UPDATE $updateFieldsSql";

        return $this->execute('insert', $sql, $bind);
    }
715230
function prepareBatchInsertSql(tableName, toInserts, options, needArgs) {
  options = options || {};
  var returnFields = options.fields || [];

  var insertsCount = toInserts.length;
  var oneElem = toInserts[0];
  var sql = 'insert into "' + tableName + '"(';
  var fieldClause = '';
  var valueClause = ' values';
  var args = null;
  if (needArgs) args = [];
  var fieldList = Object.keys(oneElem);
  var fieldNameCount = fieldList.length;
  var elemKeyIndex = 1;
  fieldList.forEach(function (f) {
    let endSymbol = ',';
    if (fieldNameCount == elemKeyIndex) endSymbol = ')';
    fieldClause += '"' + f + '"' + endSymbol;
    elemKeyIndex++;
  });

  for (var i = 0; i < insertsCount; i++) {
    var toInsert = toInserts[i];
    var keyCount = Object.keys(toInsert).length;
    if (keyCount != fieldNameCount) throw new Error('prepareBatchInsertSql:one element\'s key count:' + keyCount + ' not equal first element:' + fieldNameCount);
    var keyIndex = 1;
    fieldList.forEach(function (f) {
      let endSymbol = ',';
      if (keyIndex == 1) valueClause += '(';
      if (keyIndex == keyCount) endSymbol = ')';
      var val = toInsert[f];
      var valType = typeof val;
      if (valType == 'string' || valType == 'object') {
        if (valType == 'object') val = JSON.stringify(val);
        valueClause += '$' + (args.length + 1) + endSymbol;
        args.push(val);
      } else if (valType == 'number' || valType == 'boolean') {
        valueClause += val + endSymbol;
      } else {
        console.error('tableName:', tableName, " toInserts:", JSON.stringify(toInserts), " f:", f, " valType:", valType);
        throw new Error('prepareBatchInsertSql:filed:' + f + ',invalid value type, must be one of them:string,number');
      }
      keyIndex++;
    });

    if (i < (insertsCount - 1)) {
      valueClause += ',';
    }
  }
  sql = sql + fieldClause + valueClause;
  if (returnFields) sql += fieldsToReturningClause(returnFields);
  return { sql: sql, args: needArgs ? args : [] };
}
1049843
public function compileInsert(string $table, array $columns, array $rowsets): string
    {
        //@todo possibly different statement for versions higher than 3.7.11
        if (count($rowsets) == 1) {
            return parent::compileInsert($table, $columns, $rowsets);
        }

        //SQLite uses alternative syntax
        $statement = [];
        $statement[] = "INSERT INTO {$this->quote($table, true)} ({$this->prepareColumns($columns)})";

        foreach ($rowsets as $rowset) {
            if (count($statement) == 1) {
                $selectColumns = [];
                foreach ($columns as $column) {
                    $selectColumns[] = "? AS {$this->quote($column)}";
                }

                $statement[] = 'SELECT ' . implode(', ', $selectColumns);
            } else {
                //It is crityially important to use UNION ALL, UNION will try to merge values together
                //which will cause non predictable insert order
                $statement[] = 'UNION ALL SELECT ' . trim(str_repeat('?, ', count($columns)), ', ');
            }
        }

        return implode("\n", $statement);
    }
30925
function generateTableSQLList( $tableName, $table, $params, $separateTypes )
    {
        return $this->generateTableSQL( $tableName, $table, $params, true, $separateTypes );
    }
1042262
public function toString()
    {
        if (!$this->_parts['table']) {
            throw new SqlException("Invalid `UPDATE` statement, missing `TABLE` clause.");
        }

        if (!$this->_parts['values']) {
            throw new SqlException("Invalid `UPDATE` statement, missing `VALUES` clause.");
        }

        return 'UPDATE' .
            $this->_buildFlags($this->_parts['flags']) .
            $this->_buildChunk($this->dialect()->names($this->_parts['table'])) .
            $this->_buildSet() .
            $this->_buildClause('WHERE', $this->dialect()->conditions($this->_parts['where'], [
                'schemas' => ['' => $this->_schema]
            ])) .
            $this->_buildOrder() .
            $this->_buildClause('LIMIT', $this->_parts['limit']) .
            $this->_buildClause('RETURNING', $this->dialect()->names($this->_parts['returning']));
    }
326577
function insertSql($table, array $bind)
    {
        // extract and quote col names from the array keys
        $cols = array();
        $vals = array();
        $this->extractAndQuoteCols($bind, $cols, $vals);
        // build the statement
        $sql = "INSERT INTO "
            . $this->wrappedAdapter->quoteIdentifier($table, true)
            . ' (' . implode(', ', $cols) . ') '
            . 'VALUES (' . implode(', ', $vals) . ')';
        return $sql;
    }
76105
public long[] executeInsert(Connection conn, DataObject object, boolean generatedKeys) throws SQLException {
        PreparedStatement statement = conn.prepareStatement(_sql, generatedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
        try {
            load(statement, object);
            long[] keys = new long[statement.executeUpdate()];
            if (generatedKeys) {
                ResultSet rs = statement.getGeneratedKeys();
                for (int i = 0; rs.next(); ++i) {
                    keys[i] = rs.getLong(1);
                }
                rs.close();
            }
            return keys;
        } finally {
            statement.close();
        }
    }
1065533
protected function generateJoinSQL()
        {
            $sql = ' FROM ' . $this->getTable()->getSelectFromSql();
            foreach ($this->query->getJoins() as $join) {
                $sql .= ' ' . $join->getJoinType() . ' ' . $join->getTable()->getSelectFromSql();
                $sql .= ' ON (' . Query::quoteIdentifier($join->getLeftColumn()) . Criterion::EQUALS . Query::quoteIdentifier($join->getRightColumn());

                if ($join->hasAdditionalCriteria()) {
                    $sql_parts = [];

                    foreach ($join->getAdditionalCriteria() as $criteria) {
                        $criteria->setQuery($this->query);
                        $sql_parts[] = $criteria->getSql();
                        foreach ($criteria->getValues() as $value) {
                            $this->query->addValue($value);
                        }
                    }

                    $sql .= ' AND ' . join(' AND ', $sql_parts);
                }

                $sql .= ')';
            }

            return $sql;
        }
502945
function insertUpdate(string $tableName, array $values, array $wheres)
  {
    $wClause = implode(" and ", $this->makeClauses($wheres));

    if ($this->queryValue("select count(*) from $tableName where $wClause") != 0)
    {
      if (count($values))
      {
        $v = [];
        foreach ($values as $key => &$value)
          $v[] = "`$key`=".$this->quote($value);

        $this->q
        (
          "update $tableName set ".
          implode(",",$v).
          " where $wClause"
        );
      }
      return null;
    }
    else
    {
      return $this->insert($tableName, array_merge($values, $wheres));
    }
  }
882733
public String generateSqlInsert(String tableName) {
        try {
            return cacheSQLs.get("INSERT:" + tableName, () -> {
                return MessageFormat.format("INSERT INTO {0} ({1}) VALUES ({2})", tableName,
                        strAllColumns, StringUtils.repeat("?", ",", getAllColumns().length));
            });
        } catch (ExecutionException e) {
            throw new DaoException(e);
        }
    }