// Return the properly escaped SQL statement, against the specified database
430850
func (q *selectStatementImpl) String(database string) (sql string, err error) {
	if !validIdentifierName(database) {
		return "", errors.New("Invalid database name specified")
	}

	buf := new(bytes.Buffer)
	_, _ = buf.WriteString("SELECT ")

	if err = writeComment(q.comment, buf); err != nil {
		return
	}

	if q.distinct {
		_, _ = buf.WriteString("DISTINCT ")
	}

	if q.projections == nil || len(q.projections) == 0 {
		return "", errors.Newf(
			"No column selected.  Generated sql: %s",
			buf.String())
	}

	for i, col := range q.projections {
		if i > 0 {
			_ = buf.WriteByte(',')
		}
		if col == nil {
			return "", errors.Newf(
				"nil column selected.  Generated sql: %s",
				buf.String())
		}
		if err = col.SerializeSqlForColumnList(buf); err != nil {
			return
		}
	}

	_, _ = buf.WriteString(" FROM ")
	if q.table == nil {
		return "", errors.Newf("nil table.  Generated sql: %s", buf.String())
	}
	if err = q.table.SerializeSql(database, buf); err != nil {
		return
	}

	if q.where != nil {
		_, _ = buf.WriteString(" WHERE ")
		if err = q.where.SerializeSql(buf); err != nil {
			return
		}
	}

	if q.group != nil {
		_, _ = buf.WriteString(" GROUP BY ")
		if err = q.group.SerializeSql(buf); err != nil {
			return
		}
	}

	if q.order != nil {
		_, _ = buf.WriteString(" ORDER BY ")
		if err = q.order.SerializeSql(buf); err != nil {
			return
		}
	}

	if q.limit >= 0 {
		if q.offset >= 0 {
			_, _ = buf.WriteString(fmt.Sprintf(" LIMIT %d, %d", q.offset, q.limit))
		} else {
			_, _ = buf.WriteString(fmt.Sprintf(" LIMIT %d", q.limit))
		}
	}

	if q.forUpdate {
		_, _ = buf.WriteString(" FOR UPDATE")
	} else if q.withSharedLock {
		_, _ = buf.WriteString(" LOCK IN SHARE MODE")
	}

	return buf.String(), nil
}
202022
func (b *backend) DB(ctx context.Context, s logical.Storage) (*sql.DB, error) {
	b.logger.Debug("postgres/db: enter")
	defer b.logger.Debug("postgres/db: exit")

	b.lock.Lock()
	defer b.lock.Unlock()

	// If we already have a DB, we got it!
	if b.db != nil {
		if err := b.db.Ping(); err == nil {
			return b.db, nil
		}
		// If the ping was unsuccessful, close it and ignore errors as we'll be
		// reestablishing anyways
		b.db.Close()
	}

	// Otherwise, attempt to make connection
	entry, err := s.Get(ctx, "config/connection")
	if err != nil {
		return nil, err
	}
	if entry == nil {
		return nil,
			fmt.Errorf("configure the DB connection with config/connection first")
	}

	var connConfig connectionConfig
	if err := entry.DecodeJSON(&connConfig); err != nil {
		return nil, err
	}

	conn := connConfig.ConnectionURL
	if len(conn) == 0 {
		conn = connConfig.ConnectionString
	}

	// Ensure timezone is set to UTC for all the connections
	if strings.HasPrefix(conn, "postgres://") || strings.HasPrefix(conn, "postgresql://") {
		if strings.Contains(conn, "?") {
			conn += "&timezone=utc"
		} else {
			conn += "?timezone=utc"
		}
	} else {
		conn += " timezone=utc"
	}

	b.db, err = sql.Open("postgres", conn)
	if err != nil {
		return nil, err
	}

	// Set some connection pool settings. We don't need much of this,
	// since the request rate shouldn't be high.
	b.db.SetMaxOpenConns(connConfig.MaxOpenConnections)
	b.db.SetMaxIdleConns(connConfig.MaxIdleConnections)

	return b.db, nil
}
1100097
func (obj *Doc) GetDatabaseInfo(ctx context.Context, connectionId string) (*DatabaseInfo, error) {
	result := &struct {
		Info *DatabaseInfo	`json:"qInfo"`
	} {}
	err := obj.rpc(ctx, "GetDatabaseInfo", result, connectionId)
	return result.Info, err 
}
189049
func (b *backend) DB(ctx context.Context, s logical.Storage) (*gocql.Session, error) {
	b.lock.Lock()
	defer b.lock.Unlock()

	// If we already have a DB, we got it!
	if b.session != nil {
		return b.session, nil
	}

	entry, err := s.Get(ctx, "config/connection")
	if err != nil {
		return nil, err
	}
	if entry == nil {
		return nil, fmt.Errorf("configure the DB connection with config/connection first")
	}

	config := &sessionConfig{}
	if err := entry.DecodeJSON(config); err != nil {
		return nil, err
	}

	session, err := createSession(config, s)
	//  Store the session in backend for reuse
	b.session = session

	return session, err

}
507837
func (conn *Connection) SelectDB(dbName string, auth Auth) *Database {
	return &Database{
		dbName:     dbName,
		connection: conn,
		auth:       auth,
	}
}
1135485
func (f *Queries) Escape(key string) (string, error) {
	s, err := f.String(key)
	if err != nil {
		return "", err
	}
	return template.HTMLEscapeString(s), nil
}
1217221
func (session *Session) SQL(query interface{}, args ...interface{}) *Session {
	session.statement.SQL(query, args...)
	return session
}
126473
func (kv *KeyValue) sql(sqlStmt string) string {
	// string manipulation is done only once
	kv.queriesInitOnce.Do(func() {
		kv.queries = make(map[string]string, 8) // we have 8 queries in this file
		kv.replacer = strings.NewReplacer("/*TPRE*/", kv.TablePrefix)
	})
	kv.queriesMu.RLock()
	sqlQuery, ok := kv.queries[sqlStmt]
	kv.queriesMu.RUnlock()
	if ok {
		return sqlQuery
	}
	kv.queriesMu.Lock()
	// check again, now holding the lock
	if sqlQuery, ok = kv.queries[sqlStmt]; ok {
		kv.queriesMu.Unlock()
		return sqlQuery
	}
	sqlQuery = sqlStmt
	if f := kv.PlaceHolderFunc; f != nil {
		sqlQuery = f(sqlQuery)
	}
	sqlQuery = kv.replacer.Replace(sqlQuery)
	kv.queries[sqlStmt] = sqlQuery
	kv.queriesMu.Unlock()
	return sqlQuery
}
842992
func (m *Miniredis) db(i int) *RedisDB {
	if db, ok := m.dbs[i]; ok {
		return db
	}
	db := newRedisDB(i, &m.Mutex) // the DB has our lock.
	m.dbs[i] = &db
	return &db
}
216881
func (t *dbTables) getJoinSQL() (join string) {
	Q := t.base.TableQuote()

	for _, jt := range t.tables {
		if jt.inner {
			join += "INNER JOIN "
		} else {
			join += "LEFT OUTER JOIN "
		}
		var (
			table  string
			t1, t2 string
			c1, c2 string
		)
		t1 = "T0"
		if jt.jtl != nil {
			t1 = jt.jtl.index
		}
		t2 = jt.index
		table = jt.mi.table

		switch {
		case jt.fi.fieldType == RelManyToMany || jt.fi.fieldType == RelReverseMany || jt.fi.reverse && jt.fi.reverseFieldInfo.fieldType == RelManyToMany:
			c1 = jt.fi.mi.fields.pk.column
			for _, ffi := range jt.mi.fields.fieldsRel {
				if jt.fi.mi == ffi.relModelInfo {
					c2 = ffi.column
					break
				}
			}
		default:
			c1 = jt.fi.column
			c2 = jt.fi.relModelInfo.fields.pk.column

			if jt.fi.reverse {
				c1 = jt.mi.fields.pk.column
				c2 = jt.fi.reverseFieldInfo.column
			}
		}

		join += fmt.Sprintf("%s%s%s %s ON %s.%s%s%s = %s.%s%s%s ", Q, table, Q, t2,
			t2, Q, c2, Q, t1, Q, c1, Q)
	}
	return
}
44215
func (se *SQLError) Error() string {
	buf := &bytes.Buffer{}
	buf.WriteString(se.Message)

	// Add MySQL errno and SQLSTATE in a format that we can later parse.
	// There's no avoiding string parsing because all errors
	// are converted to strings anyway at RPC boundaries.
	// See NewSQLErrorFromError.
	fmt.Fprintf(buf, " (errno %v) (sqlstate %v)", se.Num, se.State)

	if se.Query != "" {
		fmt.Fprintf(buf, " during query: %s", sqlparser.TruncateForLog(se.Query))
	}

	return buf.String()
}
1114426
func sqlExec(db SqlExecutor, stmt, execErrPrefix string, args ...interface{}) (int64, error) {
	res, err := db.Exec(stmt, args...)
	if err != nil {
		return 0, fmt.Errorf(execErrPrefix + " " + err.Error())
	}
	if res == nil {
		return 0, nil
	}

	var N int64
	N, err = res.RowsAffected()
	if err != nil {
		return 0, fmt.Errorf(`error in RowsAffected: %v`, err)
	}
	return N, err
}
412911
func (dbclient *CouchDatabase) GetDatabaseSecurity() (*DatabaseSecurity, error) {
	dbName := dbclient.DBName

	logger.Debugf("[%s] Entering GetDatabaseSecurity()", dbName)

	securityURL, err := url.Parse(dbclient.CouchInstance.conf.URL)
	if err != nil {
		logger.Errorf("URL parse error: %s", err)
		return nil, errors.Wrapf(err, "error parsing CouchDB URL: %s", dbclient.CouchInstance.conf.URL)
	}

	//get the number of retries
	maxRetries := dbclient.CouchInstance.conf.MaxRetries

	resp, _, err := dbclient.handleRequest(http.MethodGet, "GetDatabaseSecurity", securityURL, nil, "", "", maxRetries, true, nil, "_security")

	if err != nil {
		return nil, err
	}
	defer closeResponseBody(resp)

	//handle as JSON document
	jsonResponseRaw, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.Wrap(err, "error reading response body")
	}

	var jsonResponse = &DatabaseSecurity{}

	err2 := json.Unmarshal(jsonResponseRaw, jsonResponse)
	if err2 != nil {
		return nil, errors.Wrap(err2, "error unmarshalling json data")
	}

	logger.Debugf("[%s] Exiting GetDatabaseSecurity()", dbclient.DBName)

	return jsonResponse, nil

}
911772
func Get(c context.Context) *sql.DB {
	return c.Value(&dbKey).(*sql.DB)
}
173395
func (fmd *FakeMysqlDaemon) GetMysqlPort() (int32, error) {
	if fmd.MysqlPort == -1 {
		return 0, fmt.Errorf("FakeMysqlDaemon.GetMysqlPort returns an error")
	}
	return fmd.MysqlPort, nil
}
314803
func (q *Query) logSQL() string {
	s := q.sql
	for k, v := range q.params {
		if valuer, ok := v.(driver.Valuer); ok && valuer != nil {
			v, _ = valuer.Value()
		}
		var sv string
		if str, ok := v.(string); ok {
			sv = "'" + strings.Replace(str, "'", "''", -1) + "'"
		} else if bs, ok := v.([]byte); ok {
			sv = "'" + strings.Replace(string(bs), "'", "''", -1) + "'"
		} else {
			sv = fmt.Sprintf("%v", v)
		}
		s = strings.Replace(s, "{:"+k+"}", sv, -1)
	}
	return s
}
303740
func (p *Parser) parseCreateDatabase(ctx *parseCtx) (model.Database, error) {
	if t := ctx.next(); t.Type != DATABASE {
		return nil, errors.New(`expected DATABASE`)
	}

	ctx.skipWhiteSpaces()

	var notexists bool
	if ctx.peek().Type == IF {
		ctx.advance()
		if _, err := p.parseIdents(ctx, NOT, EXISTS); err != nil {
			return nil, err
		}
		notexists = true
	}

	ctx.skipWhiteSpaces()

	var database model.Database
	switch t := ctx.next(); t.Type {
	case IDENT, BACKTICK_IDENT:
		database = model.NewDatabase(t.Value)
	default:
		return nil, newParseError(ctx, t, "expected IDENT, BACKTICK_IDENT")
	}

	database.SetIfNotExists(notexists)
	p.eol(ctx)
	return database, nil
}