// Remainder SQL and other string expressions may contain more than one
// statement such as:
//
//    use schema_x;  show tables;
//
//    set @my_var = "value"; select a,b from `users` where name = @my_var;
//
163551
func (l *Lexer) Remainder() (string, bool) {
	l.SkipWhiteSpaces()
	if r := l.Peek(); r == ';' {
		l.Next()
	}
	l.SkipWhiteSpaces()
	if l.pos >= len(l.input) {
		return "", false
	}
	input := l.input[l.pos:]
	if len(input) < 5 {
		return "", false
	}
	return input, true
}
26823
func (session *Session) QueryString(sqlorArgs ...interface{}) ([]map[string]string, error) {
	if session.isAutoClose {
		defer session.Close()
	}

	sqlStr, args, err := session.genQuerySQL(sqlorArgs...)
	if err != nil {
		return nil, err
	}

	rows, err := session.queryRows(sqlStr, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	return rows2Strings(rows)
}
1082786
func initSQLStmtsTable(driver string) {
	// The sqlStmts table is initialized with MySQL statements.
	// Update the statements for the selected driver.
	switch driver {
	case driverPostgres:
		// Replace ? with $1, $2, etc...
		for i, stmt := range sqlStmts {
			n := 0
			for strings.IndexByte(stmt, '?') != -1 {
				n++
				param := "$" + strconv.Itoa(n)
				stmt = strings.Replace(stmt, "?", param, 1)
			}
			sqlStmts[i] = stmt
		}
		// Replace `row` with row
		for i, stmt := range sqlStmts {
			stmt := strings.Replace(stmt, "`row`", "row", -1)
			sqlStmts[i] = stmt
		}
		// OVER (PARTITION ...) is not supported in older MySQL servers.
		// So the default SQL statement is specific to MySQL and uses variables.
		// For Postgres, replace with this statement:
		sqlStmts[sqlRecoverGetSeqFloorForMaxBytes] = "SELECT COALESCE(MIN(seq), 0) FROM (SELECT seq, SUM(size) OVER (PARTITION BY id ORDER BY seq DESC) AS total FROM Messages WHERE id=$1)t WHERE t.total<=$2"
	}
}
1219204
func (me *DefaultAdapter) PlaceHolderSql(buf *SqlBuilder, i interface{}) error {
	buf.WriteRune(me.PlaceHolderRune)
	if me.IncludePlaceholderNum {
		buf.WriteString(strconv.FormatInt(int64(buf.CurrentArgPosition), 10))
	}
	buf.WriteArg(i)
	return nil
}
1061696
func truncateSQLAndBindVars(sql string, bindVariables map[string]*querypb.BindVariable) string {
	truncatedQuery := sqlparser.TruncateForLog(sql)
	buf := &bytes.Buffer{}
	fmt.Fprintf(buf, "BindVars: {")
	var keys []string
	for key := range bindVariables {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	var valString string
	for _, key := range keys {
		valString = fmt.Sprintf("%v", bindVariables[key])
		fmt.Fprintf(buf, "%s: %q", key, valString)
	}
	fmt.Fprintf(buf, "}")
	bv := buf.String()
	maxLen := *sqlparser.TruncateErrLen
	if maxLen != 0 && len(bv) > maxLen {
		bv = bv[:maxLen-12] + " [TRUNCATED]"
	}
	return fmt.Sprintf("Sql: %q, %s", truncatedQuery, bv)
}
225353
func (s *Stmt) Query(args []driver.Value) (r driver.Rows, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("fatalf error: %s", r)
			return
		}
	}()
	defer s.conn.mutex.Unlock()

	if s.query == "" {
		return nil, fmt.Errorf("empty statement")
	}

	finalQuery := replaceArguments(s.query, args)
	log.Info("Query < %s >\n", finalQuery)
	err = s.conn.conn.WriteQuery(finalQuery)
	if err != nil {
		return nil, err
	}

	rowsChannel, err := s.conn.conn.ReadRows()
	if err != nil {
		return nil, err
	}

	r = newRows(rowsChannel)
	return r, nil
}
455074
func Regproceduresend(db XODB, v0 pgtypes.Regprocedure) ([]byte, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.regproceduresend($1)`

	// run query
	var ret []byte
	XOLog(sqlstr, v0)
	err = db.QueryRow(sqlstr, v0).Scan(&ret)
	if err != nil {
		return nil, err
	}

	return ret, nil
}
121722
func (m *dbConn) DeleteExpression(p interface{}, where expr.Node) (int, error) {

	var deletedKeys []schema.Key
	txn := m.db.Txn(true)
	iter, err := txn.Get(m.md.tbl.Name, m.md.primaryIndex)
	if err != nil {
		txn.Abort()
		u.Errorf("could not get values %v", err)
		return 0, err
	}
deleteLoop:
	for {
		item := iter.Next()
		if item == nil {
			break
		}

		msg, ok := item.(*datasource.SqlDriverMessage)
		if !ok {
			u.Warnf("wat?  %T   %#v", item, item)
			err = fmt.Errorf("unexpected message type %T", item)
			break
		}
		whereValue, ok := vm.Eval(msg.ToMsgMap(m.md.tbl.FieldPositions), where)
		if !ok {
			u.Debugf("could not evaluate where: %v", msg)
		}
		switch whereVal := whereValue.(type) {
		case value.BoolValue:
			if whereVal.Val() == false {
				//this means do NOT delete
			} else {
				// Delete!
				if err = txn.Delete(m.md.tbl.Name, msg); err != nil {
					u.Errorf("could not delete %v", err)
					break deleteLoop
				}
				indexVal := msg.Vals[0]
				deletedKeys = append(deletedKeys, schema.NewKeyUint(makeId(indexVal)))
			}
		case nil:
			// ??
			u.Warnf("this should be fine, couldn't evaluate so don't delete %v", msg)
		default:
			if whereVal.Nil() {
				// Doesn't match, so don't delete
			} else {
				u.Warnf("unknown where eval result? %T", whereVal)
			}
		}
	}
	if err != nil {
		txn.Abort()
		return 0, err
	}
	txn.Commit()
	return len(deletedKeys), nil
}
1220275
func (e *baseExecutor) Schema() *expression.Schema {
	if e.schema == nil {
		return expression.NewSchema()
	}
	return e.schema
}
568234
func (session *Session) SQL(query interface{}, args ...interface{}) *Session {
	session.Statement.SQL(query, args...)
	return session
}
522639
func (h *HashMap) All() ([]string, error) {
	var (
		values []string
		value  string
	)
	rows, err := h.host.db.Query(fmt.Sprintf("SELECT %s FROM %s", ownerCol, h.table))
	if err != nil {
		return values, err
	}
	if rows == nil {
		return values, ErrNoAvailableValues
	}
	defer rows.Close()
	for rows.Next() {
		err = rows.Scan(&value)
		if !h.host.rawUTF8 {
			Decode(&value)
		}
		values = append(values, value)
		if err != nil {
			return values, err
		}
	}
	err = rows.Err()
	return values, err
}
137662
func (qb *MySQLQueryBuilder) Values(vals ...string) QueryBuilder {
	valsStr := strings.Join(vals, CommaSpace)
	qb.Tokens = append(qb.Tokens, "VALUES", "(", valsStr, ")")
	return qb
}
844208
func (sc *StatementContext) SQLDigest() (normalized, sqlDigest string) {
	sc.digestMemo.Do(func() {
		sc.digestMemo.normalized, sc.digestMemo.digest = parser.NormalizeDigest(sc.OriginalSQL)
	})
	return sc.digestMemo.normalized, sc.digestMemo.digest
}
1127500
func Literal(v interface{}) Expression {
	value, err := sqltypes.BuildValue(v)
	if err != nil {
		panic(errors.Wrap(err, "Invalid literal value"))
	}
	return &literalExpression{value: value}
}
1323354
func (s *ShowMeasurementCardinalityStatement) String() string {
	var buf bytes.Buffer
	_, _ = buf.WriteString("SHOW MEASUREMENT")

	if s.Exact {
		_, _ = buf.WriteString(" EXACT")
	}
	_, _ = buf.WriteString(" CARDINALITY")

	if s.Database != "" {
		_, _ = buf.WriteString(" ON ")
		_, _ = buf.WriteString(QuoteIdent(s.Database))
	}

	if s.Sources != nil {
		_, _ = buf.WriteString(" FROM ")
		_, _ = buf.WriteString(s.Sources.String())
	}
	if s.Condition != nil {
		_, _ = buf.WriteString(" WHERE ")
		_, _ = buf.WriteString(s.Condition.String())
	}
	if len(s.Dimensions) > 0 {
		_, _ = buf.WriteString(" GROUP BY ")
		_, _ = buf.WriteString(s.Dimensions.String())
	}
	if s.Limit > 0 {
		_, _ = fmt.Fprintf(&buf, " LIMIT %d", s.Limit)
	}
	if s.Offset > 0 {
		_, _ = buf.WriteString(" OFFSET ")
		_, _ = buf.WriteString(strconv.Itoa(s.Offset))
	}
	return buf.String()
}
646649
func (session *Session) sum(res interface{}, bean interface{}, columnNames ...string) error {
	if session.isAutoClose {
		defer session.Close()
	}

	v := reflect.ValueOf(res)
	if v.Kind() != reflect.Ptr {
		return errors.New("need a pointer to a variable")
	}

	var isSlice = v.Elem().Kind() == reflect.Slice
	var sqlStr string
	var args []interface{}
	var err error
	if len(session.statement.RawSQL) == 0 {
		sqlStr, args, err = session.statement.genSumSQL(bean, columnNames...)
		if err != nil {
			return err
		}
	} else {
		sqlStr = session.statement.RawSQL
		args = session.statement.RawParams
	}

	if isSlice {
		err = session.queryRow(sqlStr, args...).ScanSlice(res)
	} else {
		err = session.queryRow(sqlStr, args...).Scan(res)
	}
	if err == sql.ErrNoRows || err == nil {
		return nil
	}
	return err
}
221164
func queryAsString(sql string, bindVariables map[string]*querypb.BindVariable) string {
	buf := &bytes.Buffer{}
	fmt.Fprintf(buf, "Sql: %q", sql)
	fmt.Fprintf(buf, ", BindVars: {")
	var keys []string
	for key := range bindVariables {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	var valString string
	for _, key := range keys {
		valString = fmt.Sprintf("%v", bindVariables[key])
		fmt.Fprintf(buf, "%s: %q", key, valString)
	}
	fmt.Fprintf(buf, "}")
	return buf.String()
}