// ToSql builds the sql and returns it as a string, together with the params.
355779
func (sb *SearchBuilder) ToSql() (string, []interface{}) {
	sb.params = make([]interface{}, 0)

	sb.buildSelect()

	if len(sb.tags) > 0 {
		sb.buildTagQuery()
	} else {
		sb.buildMainQuery()
	}

	sb.sql.WriteString(`
		ORDER BY dashboard.id ` + dialect.LimitOffset(sb.limit, (sb.page-1)*sb.limit) + `) as ids
		INNER JOIN dashboard on ids.id = dashboard.id
	`)

	sb.sql.WriteString(`
		LEFT OUTER JOIN dashboard folder on folder.id = dashboard.folder_id
		LEFT OUTER JOIN dashboard_tag on dashboard.id = dashboard_tag.dashboard_id`)

	sb.sql.WriteString(" ORDER BY dashboard.title ASC")
	return sb.sql.String(), sb.params
}
847278
func HandleWithSQL() (*SQLMapper, error) {
	sqlConf, sqlConfErr := GetSQLConf()
	if sqlConfErr == nil {
		s := &SQLMapper{conf: sqlConf}

		db, err := sql.Open(s.conf.driver, s.conf.openStr)
		if err != nil {
			panic(err)
		}

		s.sqlConn = db
		return s, err
	}

	return nil, sqlConfErr
}
36757
func (me *DefaultAdapter) FromSql(buf *SqlBuilder, from ColumnList) error {
	if from != nil && len(from.Columns()) > 0 {
		buf.Write(me.FromFragment)
		return me.SourcesSql(buf, from)
	}
	return nil
}
753136
func (e HashExp) Build(db *DB, params Params) string {
	if len(e) == 0 {
		return ""
	}

	// ensure the hash exp generates the same SQL for different runs
	names := []string{}
	for name := range e {
		names = append(names, name)
	}
	sort.Strings(names)

	var parts []string
	for _, name := range names {
		value := e[name]
		switch value.(type) {
		case nil:
			name = db.QuoteColumnName(name)
			parts = append(parts, name+" IS NULL")
		case Expression:
			if sql := value.(Expression).Build(db, params); sql != "" {
				parts = append(parts, "("+sql+")")
			}
		case []interface{}:
			in := In(name, value.([]interface{})...)
			if sql := in.Build(db, params); sql != "" {
				parts = append(parts, sql)
			}
		default:
			pn := fmt.Sprintf("p%v", len(params))
			name = db.QuoteColumnName(name)
			parts = append(parts, name+"={:"+pn+"}")
			params[pn] = value
		}
	}
	if len(parts) == 1 {
		return parts[0]
	}
	return strings.Join(parts, " AND ")
}
4507
func NewSQL(cfg *SQLConfig) (*SQL, error) {
	if err := validateSQLConfig(cfg); err != nil {
		return nil, err
	}

	return &SQL{
		Config: cfg,
	}, nil
}
139191
func ConvertToBoundSQL(sql string, args []interface{}) (string, error) {
	buf := StringBuilder{}
	var i, j, start int
	for ; i < len(sql); i++ {
		if sql[i] == '?' {
			_, err := buf.WriteString(sql[start:i])
			if err != nil {
				return "", err
			}
			start = i + 1

			if len(args) == j {
				return "", ErrNeedMoreArguments
			}

			arg := args[j]
			if namedArg, ok := arg.(sql2.NamedArg); ok {
				arg = namedArg.Value
			}

			if noSQLQuoteNeeded(arg) {
				_, err = fmt.Fprint(&buf, arg)
			} else {
				_, err = fmt.Fprintf(&buf, "'%v'", arg)
			}
			if err != nil {
				return "", err
			}
			j = j + 1
		}
	}
	_, err := buf.WriteString(sql[start:])
	if err != nil {
		return "", err
	}
	return buf.String(), nil
}
1034916
func (statement *Statement) SQL(query interface{}, args ...interface{}) *Statement {
	switch query.(type) {
	case (*builder.Builder):
		var err error
		statement.RawSQL, statement.RawParams, err = query.(*builder.Builder).ToSQL()
		if err != nil {
			statement.Engine.logger.Error(err)
		}
	case string:
		statement.RawSQL = query.(string)
		statement.RawParams = args
	default:
		statement.Engine.logger.Error("unsupported sql type")
	}

	return statement
}
1299876
func (c *Database) ExecuteSQLWithParams(v *DatabaseExecuteSQLParams) ([]string, []interface{}, *DatabaseError, error) {
	resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Database.executeSQL", Params: v})
	if err != nil {
		return nil, nil, nil, err
	}

	var chromeData struct {
		Result struct {
			ColumnNames []string
			Values      []interface{}
			SqlError    *DatabaseError
		}
	}

	if resp == nil {
		return nil, nil, nil, &gcdmessage.ChromeEmptyResponseErr{}
	}

	// test if error first
	cerr := &gcdmessage.ChromeErrorResponse{}
	json.Unmarshal(resp.Data, cerr)
	if cerr != nil && cerr.Error != nil {
		return nil, nil, nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
	}

	if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
		return nil, nil, nil, err
	}

	return chromeData.Result.ColumnNames, chromeData.Result.Values, chromeData.Result.SqlError, nil
}
369443
func (b *BatchBuilder) ToCql() (stmt string, names []string) {
	cql := bytes.Buffer{}

	cql.WriteString("BEGIN ")
	if b.unlogged {
		cql.WriteString("UNLOGGED ")
	}
	if b.counter {
		cql.WriteString("COUNTER ")
	}
	cql.WriteString("BATCH ")

	names = append(names, b.using.writeCql(&cql)...)

	for _, stmt := range b.stmts {
		cql.WriteString(stmt)
		cql.WriteByte(';')
		cql.WriteByte(' ')
	}
	names = append(names, b.names...)

	cql.WriteString("APPLY BATCH ")

	stmt = cql.String()
	return
}
760413
func (t *Table) Select(columns ...string) (stmt string, names []string) {
	if len(columns) == 0 {
		return t.sel.stmt, t.sel.names
	}

	return qb.Select(t.metadata.Name).
		Columns(columns...).
		Where(t.primaryKeyCmp[0:len(t.metadata.PartKey)]...).
		ToCql()
}
374750
func (session *Session) saveLastSQL(sql string, args ...interface{}) {
	session.lastSQL = sql
	session.lastSQLArgs = args
	session.Engine.logSQL(sql, args...)
}
1253164
func (cb *CreateDatabaseBuilder) Build() string {
	q := fmt.Sprintf("CREATE DATABASE %s;", cb.name)
	if cb.useIt {
		q = fmt.Sprintf("%s\nUSE %s;\n", q, cb.name)
	}
	return q
}
633524
func (db *Database) buildSelect() string {
	if len(db.tables) == 0 {
		db.panicLog("Please set a table with Model [ + Joins ]")
	}

	var query bytes.Buffer
	query.WriteString(db.buildCTE())

	// Select
	var fields string
	query.WriteString("SELECT ")
	if len(db.selectFields) > 0 {
		fields = db.selectFields
	}

	query.WriteString(fields)
	query.WriteString(" FROM ")
	// Model && Join

	query.WriteString(strings.Join(db.tables, ","))
	query.WriteString(" ")

	// Join (optional)
	if len(db.joinTables) > 0 {
		query.WriteString(strings.Join(db.joinTables, " "))
		query.WriteString(" ")
	}

	// Where (optional)
	if len(db.whereFields) > 0 {
		query.WriteString(db.buildWhere())
	}

	// Order (optional)
	if db.order != "" {
		query.WriteString(" ORDER BY ")
		query.WriteString(db.order)
	}

	// Limit (optional)
	if db.limit != 0 {
		query.WriteString(" LIMIT ")
		query.WriteString(strconv.Itoa(db.limit))
	}

	// Offset (optional)
	if db.offset != 0 {
		query.WriteString(" OFFSET ")
		query.WriteString(strconv.Itoa(db.offset))
	}

	query.WriteString(";")
	qs := query.String()
	db.printLog(qs)
	return qs
}
249964
func (b *InsertBuilder) Build() string {
	b.lock.Lock()
	defer b.lock.Unlock()
	return fmt.Sprintf("%s\n    VALUES %s;", b.query, strings.Join(b.sqlValues, ", \n        "))
}
980143
func (session *Session) Q(sqlStr string, params ...interface{}) (resultsSlice []*ResultSet, err error) {

	defer session.resetStatement()
	if session.IsAutoClose {
		defer session.Close()
	}

	resultsSlice = make([]*ResultSet, 0)
	rows, err := session.queryRows(sqlStr, params...)
	if rows != nil {
		if err == nil {
			resultsSlice, err = rows2ResultSetSlice(rows)
		}
		rows.Close()
	}
	return
}
61731
func (d *dbBase) GenerateOperatorSQL(mi *modelInfo, fi *fieldInfo, operator string, args []interface{}, tz *time.Location) (string, []interface{}) {
	sql := ""
	params := getFlatParams(fi, args, tz)

	if len(params) == 0 {
		panic(fmt.Errorf("operator `%s` need at least one args", operator))
	}
	arg := params[0]

	switch operator {
	case "in":
		marks := make([]string, len(params))
		for i := range marks {
			marks[i] = "?"
		}
		sql = fmt.Sprintf("IN (%s)", strings.Join(marks, ", "))
	case "between":
		if len(params) != 2 {
			panic(fmt.Errorf("operator `%s` need 2 args not %d", operator, len(params)))
		}
		sql = "BETWEEN ? AND ?"
	default:
		if len(params) > 1 {
			panic(fmt.Errorf("operator `%s` need 1 args not %d", operator, len(params)))
		}
		sql = d.ins.OperatorSQL(operator)
		switch operator {
		case "exact":
			if arg == nil {
				params[0] = "IS NULL"
			}
		case "iexact", "contains", "icontains", "startswith", "endswith", "istartswith", "iendswith":
			param := strings.Replace(ToStr(arg), `%`, `\%`, -1)
			switch operator {
			case "iexact":
			case "contains", "icontains":
				param = fmt.Sprintf("%%%s%%", param)
			case "startswith", "istartswith":
				param = fmt.Sprintf("%s%%", param)
			case "endswith", "iendswith":
				param = fmt.Sprintf("%%%s", param)
			}
			params[0] = param
		case "isnull":
			if b, ok := arg.(bool); ok {
				if b {
					sql = "IS NULL"
				} else {
					sql = "IS NOT NULL"
				}
				params = nil
			} else {
				panic(fmt.Errorf("operator `%s` need a bool value not `%T`", operator, arg))
			}
		}
	}
	return sql, params
}
339473
func (me *DefaultAdapter) OrderSql(buf *SqlBuilder, order ColumnList) error {
	if order != nil && len(order.Columns()) > 0 {
		buf.Write(me.OrderByFragment)
		return me.Literal(buf, order)
	}
	return nil
}