MySQL hack to avoid the "VARCHAR requires a length" error.
9224
def _compile_varchar_mysql(element, compiler, **kw):
    """"""
    if not element.length or element.length == 'max':
        return "TEXT"
    else:
        return compiler.visit_VARCHAR(element, **kw)
691582
def mysql(host, user, passwd, db, charset):
    """"""
    connection_string = database.set_mysql_connection(host=host, user=user, passwd=passwd, db=db, charset=charset)
    test_connection(connection_string)
731091
def _sql_expand_insert(self, spec, key_prefix = '', col_prefix = ''):
        
        col = list(spec)
        sql = '('
        sql += ', '.join(col_prefix + key for key in col)
        sql += ') VALUES ('
        sql += ', '.join('%(' + key_prefix + key + ')s' for key in col)
        sql += ')'
        params = {}
        for key in spec:
            params[key_prefix + key] = spec[key]

        return sql, params
1167628
private boolean isVarcharColumn(String columnName, List<String> tableNames, boolean debugPrint) {
        List<String> varcharColumnTypes = Arrays.asList("VARCHAR");
        return isColumnType(varcharColumnTypes, columnName, tableNames, debugPrint);
    }
333828
static function sanitize($data)
	{
		// remove whitespaces (not a must though)
		//$data = filter_var(trim($data), FILTER_SANITIZE_STRING, !FILTER_FLAG_STRIP_LOW);
		$data = trim(strip_tags($data));
		
		// apply stripslashes if magic_quotes_gpc is enabled
		if(get_magic_quotes_gpc())
			$data = stripslashes($data);
			
		// SQL commands are forbidden
		$banlist = array
			(
			"/alter /i", "/insert /i", "/select /i", "/update /i", "/delete /i", "/distinct /i", "/having /i", "/truncate /i", "/replace /i",
			"/handler /i", "/like /i", "/procedure /i", "/limit /i", "/order by /i", "/group by /i" , "/drop /i", "/database /i"
			);
			
		$data = preg_replace($banlist, '', $data);
		
		return $data;
	}
1351068
def _long_string_handler(c, ctx, is_field_name=False):
    """"""
    assert c == _SINGLE_QUOTE
    is_clob = ctx.ion_type is IonType.CLOB
    max_char = _MAX_CLOB_CHAR if is_clob else _MAX_TEXT_CHAR
    assert not (is_clob and is_field_name)
    if not is_clob and not is_field_name:
        ctx.set_ion_type(IonType.STRING)
    assert not ctx.value
    ctx.set_unicode(quoted_text=True)
    val = ctx.value
    if is_field_name:
        assert not val
        ctx.set_pending_symbol()
        val = ctx.pending_symbol
    quotes = 0
    in_data = True
    c, self = yield
    here = ctx.immediate_transition(self)
    trans = here
    while True:
        if c == _SINGLE_QUOTE and not _is_escaped(c):
            quotes += 1
            if quotes == 3:
                in_data = not in_data
                ctx.set_quoted_text(in_data)
                quotes = 0
        else:
            if in_data:
                _validate_long_string_text(c, ctx, max_char)
                # Any quotes found in the meantime are part of the data
                val.extend(_SINGLE_QUOTES[quotes])
                if not _is_escaped_newline(c):
                    val.append(c)
                quotes = 0
            else:
                if quotes > 0:
                    assert quotes < 3
                    if is_field_name or is_clob:
                        # There are at least two values here, which is illegal for field names or within clobs.
                        _illegal_character(c, ctx, 'Malformed triple-quoted text: %s' % (val,))
                    else:
                        # This string value is followed by a quoted symbol.
                        if ctx.container.is_delimited:
                            _illegal_character(c, ctx, 'Delimiter %s not found after value.'
                                               % (_chr(ctx.container.delimiter[0]),))
                        trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, ctx.ion_type, ctx.value.as_text())
                        if quotes == 1:
                            if BufferQueue.is_eof(c):
                                _illegal_character(c, ctx, "Unexpected EOF.")
                            # c was read as a single byte. Re-read it as a code point.
                            ctx.queue.unread(c)
                            ctx.set_quoted_text(True)
                            c, _ = yield ctx.immediate_transition(self)
                            trans = _CompositeTransition(
                                trans,
                                ctx,
                                partial(_quoted_symbol_handler, c, is_field_name=False),
                            )
                        else:  # quotes == 2
                            trans = _CompositeTransition(trans, ctx, None, ctx.set_empty_symbol())
                elif c not in _WHITESPACE:
                    if is_clob:
                        trans = ctx.immediate_transition(_clob_end_handler(c, ctx))
                    elif c == _SLASH:
                        if ctx.container.ion_type is IonType.SEXP:
                            pending = ctx.event_transition(IonEvent, IonEventType.SCALAR,
                                                           ctx.ion_type, ctx.value.as_text())
                            trans = ctx.immediate_transition(_sexp_slash_handler(c, ctx, self, pending))
                        else:
                            trans = ctx.immediate_transition(_comment_handler(c, ctx, self))
                    elif is_field_name:
                        if c != _COLON:
                            _illegal_character(c, ctx, 'Illegal character after field name %s.' % (val,))
                        trans = ctx.immediate_transition(ctx.whence)
                    else:
                        trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, ctx.ion_type, ctx.value.as_text())
        c, _ = yield trans
        ctx.set_self_delimiting(False)  # If comments separated long string components, this would have been set.
        trans = here
908208
private function mysqltype2moodletype($mysql_type) {
        $type = null;

        switch(strtoupper($mysql_type)) {
            case 'BIT':
                $type = 'L';
                break;

            case 'TINYINT':
            case 'SMALLINT':
            case 'MEDIUMINT':
            case 'INT':
            case 'INTEGER':
            case 'BIGINT':
                $type = 'I';
                break;

            case 'FLOAT':
            case 'DOUBLE':
            case 'DECIMAL':
                $type = 'N';
                break;

            case 'CHAR':
            case 'ENUM':
            case 'SET':
            case 'VARCHAR':
                $type = 'C';
                break;

            case 'TINYTEXT':
            case 'TEXT':
            case 'MEDIUMTEXT':
            case 'LONGTEXT':
                $type = 'X';
                break;

            case 'BINARY':
            case 'VARBINARY':
            case 'BLOB':
            case 'TINYBLOB':
            case 'MEDIUMBLOB':
            case 'LONGBLOB':
                $type = 'B';
                break;

            case 'DATE':
            case 'TIME':
            case 'DATETIME':
            case 'TIMESTAMP':
            case 'YEAR':
                $type = 'D';
                break;
        }

        if (!$type) {
            throw new dml_exception('invalidmysqlnativetype', $mysql_type);
        }
        return $type;
    }
20402
def long_encode(input, errors='strict'):
    
    if not isinstance(input, text_type):
        input = text_type(input, sys.getdefaultencoding(), errors)
    length = len(input)
    input = unicodedata.normalize('NFKC', input)
    return input.translate(long_table), length
120883
def get_sql_insert(table: str,
                   fieldlist: Sequence[str],
                   delims: Tuple[str, str] = ("", "")) -> str:
    """"""
    return (
        "INSERT INTO " + delimit(table, delims) +
        " (" +
        ",".join([delimit(x, delims) for x in fieldlist]) +
        ") VALUES (" +
        ",".join(["?"] * len(fieldlist)) +
        ")"
    )
594935
function (column) {
            if (column.fixed) {
                return ["char(", column.size || 255, ")"].join("");
            } else if (column.text === false || column.size) {
                return ["varchar(", column.size || 255, ")"].join("");
            } else {
                return 'text';
            }

        }
617709
def value_to_sql_str(v):
    
    if v is None:
        return 'null'

    if type(v) in (types.IntType, types.FloatType, types.LongType):
        return str(v)

    if type(v) in (types.StringType, types.UnicodeType):
        return "'%s'" %(v.replace(u"'", u"\\'"))

    if isinstance(v, datetime):
        return "'%s'" %(v.strftime("%Y-%m-%d %H:%M:%S"))

    if isinstance(v, date):
        return "'%s'" %(v.strftime("%Y-%m-%d"))

    return str(v)
143252
function _query($sql,$inputarr=false)
	{
		$this->_errorMsg = false;
		if (is_array($inputarr)) {

			# bind input params with sp_executesql:
			# see http://www.quest-pipelines.com/newsletter-v3/0402_F.htm
			# works only with sql server 7 and newer
            $getIdentity = false;
            if (!is_array($sql) && preg_match('/^\\s*insert/i', $sql)) {
                $getIdentity = true;
                $sql .= (preg_match('/;\\s*$/i', $sql) ? ' ' : '; ') . $this->identitySQL;
            }
			if (!is_array($sql)) $sql = $this->Prepare($sql);
			$params = '';
			$decl = '';
			$i = 0;
			foreach($inputarr as $v) {
				if ($decl) {
					$decl .= ', ';
					$params .= ', ';
				}
				if (is_string($v)) {
					$len = strlen($v);
					if ($len == 0) $len = 1;

					if ($len > 4000 ) {
						// NVARCHAR is max 4000 chars. Let's use NTEXT
						$decl .= "@P$i NTEXT";
					} else {
						$decl .= "@P$i NVARCHAR($len)";
					}

					$params .= "@P$i=N". (strncmp($v,"'",1)==0? $v : $this->qstr($v));
				} else if (is_integer($v)) {
					$decl .= "@P$i INT";
					$params .= "@P$i=".$v;
				} else if (is_float($v)) {
					$decl .= "@P$i FLOAT";
					$params .= "@P$i=".$v;
				} else if (is_bool($v)) {
					$decl .= "@P$i INT"; # Used INT just in case BIT in not supported on the user's MSSQL version. It will cast appropriately.
					$params .= "@P$i=".(($v)?'1':'0'); # True == 1 in MSSQL BIT fields and acceptable for storing logical true in an int field
				} else {
					$decl .= "@P$i CHAR"; # Used char because a type is required even when the value is to be NULL.
					$params .= "@P$i=NULL";
					}
				$i += 1;
			}
			$decl = $this->qstr($decl);
			if ($this->debug) ADOConnection::outp("<font size=-1>sp_executesql N{$sql[1]},N$decl,$params</font>");
			$rez = mssql_query("sp_executesql N{$sql[1]},N$decl,$params", $this->_connectionID);
            if ($getIdentity) {
                $arr = @mssql_fetch_row($rez);
                $this->lastInsID = isset($arr[0]) ? $arr[0] : false;
                @mssql_data_seek($rez, 0);
            }

		} else if (is_array($sql)) {
			# PrepareSP()
			$rez = mssql_execute($sql[1]);
            $this->lastInsID = false;

		} else {
			$rez = mssql_query($sql,$this->_connectionID);
            $this->lastInsID = false;
		}
		return $rez;
	}
1082144
private void setNumeric(PreparedStatement stmt,
                            int varIndex,
                            String columnName,
                            String value) throws SQLException {
        try {
            stmt.setInt(varIndex, Integer.parseInt(value));
        } catch (NumberFormatException e) {
            try {
                stmt.setLong(varIndex, Long.parseLong(value));
            } catch (NumberFormatException e2) {
                throw new SQLException("Value specified for " + columnName
                        + ", '" + value + "' was"
                        + " specified as numeric, but is not");
            }
        }
    }
23877
def _CheckConnectionEncoding(cursor):
  """"""
  cur_character_set = _ReadVariable("character_set_connection", cursor)
  if cur_character_set != CHARACTER_SET:
    raise EncodingEnforcementError(
        "Require MySQL character_set_connection of {}, got {}.".format(
            CHARACTER_SET, cur_character_set))
1113654
public String getSQLType(boolean bIncludeLength, Map<String, Object> properties) 
    {
        String strType = (String)properties.get(DBSQLTypes.STRING);
        if (strType == null)
            strType = "VARCHAR";        // The default SQL Type
        if (this.getMaxLength() < 127)
        {
            String strStart = (String)properties.get("LONGSTRINGSTART");
            if (strStart != null)
            {
                int iStart = Integer.parseInt(strStart);
                if (iStart < this.getMaxLength())
                    strType = (String)properties.get("LONGSTRING");
            }
        }
        if (bIncludeLength)
            strType += "(" + Integer.toString(this.getMaxLength()) + ")";
        return strType;
    }
549936
public void skipLengthEncodedBytes() {
    int type = this.buf[this.position++] & 0xff;
    switch (type) {
      case 251:
        break;

      case 252:
        position += 2 + (0xffff & (((buf[position] & 0xff) + ((buf[position + 1] & 0xff) << 8))));
        break;

      case 253:
        position += 3 + (0xffffff & ((buf[position] & 0xff)
            + ((buf[position + 1] & 0xff) << 8)
            + ((buf[position + 2] & 0xff) << 16)));
        break;

      case 254:
        position += 8 + ((buf[position] & 0xff)
            + ((long) (buf[position + 1] & 0xff) << 8)
            + ((long) (buf[position + 2] & 0xff) << 16)
            + ((long) (buf[position + 3] & 0xff) << 24)
            + ((long) (buf[position + 4] & 0xff) << 32)
            + ((long) (buf[position + 5] & 0xff) << 40)
            + ((long) (buf[position + 6] & 0xff) << 48)
            + ((long) (buf[position + 7] & 0xff) << 56));
        break;

      default:
        position += type;
        break;
    }
  }
876286
function STRING(length) {
    length = length || 255;
    if (!(this instanceof STRING)) {
        return new STRING(length);
    }
    this.length = length;
    this.sql = 'VARCHAR(' + length + ')';
}