// runBQL attempts to execute the provided query against the given store.
186749
func runBQL(ctx context.Context, bql string, s storage.Store, chanSize, bulkSize int, w io.Writer) (*table.Table, error) {
	tracer.Trace(w, func() []string {
		return []string{fmt.Sprintf("Executing query: %s", bql)}
	})
	pln, err := planBQL(ctx, bql, s, chanSize, bulkSize, w)
	if err != nil {
		return nil, err
	}
	if pln == nil {
		return nil, nil
	}
	res, err := pln.Execute(ctx)
	if err != nil {
		msg := fmt.Errorf("planner.Execute: failed to execute; %v", err)
		tracer.Trace(w, func() []string {
			return []string{msg.Error()}
		})
		return nil, msg
	}
	tracer.Trace(w, func() []string {
		return []string{fmt.Sprintf("planner execute returned %d rows", res.NumRows())}
	})
	return res, nil
}
797444
func (c *Client) ExecQuery(query string) ([]byte, error) {
	req := Query(query)
	return c.Exec(req)
}
41592
func (context *ElasticRuntime) RunDbAction(dbInfoList []cfbackup.SystemDump, action int) (err error) {

	for _, info := range dbInfoList {
		lo.G.Debug(fmt.Sprintf("RunDbAction info: %v %v", info.Get("Product"), info.Get("Component")))

		if err = info.Error(); err == nil {
			err = context.readWriterArchive(info, context.TargetDir, action)

		} else {
			lo.G.Error("readWriterArchive err: ", err)
			break
		}
	}
	return
}
148600
func (s *serverConfig) bqlHandler(w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		w.WriteHeader(http.StatusMethodNotAllowed)
		reportError(w, r, err)
		return
	}
	if r.Method != http.MethodPost {
		reportError(w, r, fmt.Errorf("invalid %s request on %q endpoint. Only POST request are accepted", r.Method, r.URL.Path))
		log.Printf("[%s] Invalid request: %#v\n", time.Now(), r)
		return
	}

	// Run the query.
	var (
		ctx    context.Context
		cancel context.CancelFunc
	)
	timeout, err := time.ParseDuration(r.FormValue("timeout"))
	if err == nil {
		// The request has a timeout, so create a context that is
		// canceled automatically when the timeout expires.
		ctx, cancel = context.WithTimeout(context.Background(), timeout)
	} else {
		ctx, cancel = context.WithCancel(context.Background())
	}
	defer cancel() // Cancel ctx as soon as handleSearch returns.

	var res []*result
	for _, q := range getQueries(r.PostForm["bqlQuery"]) {
		if nq, err := url.QueryUnescape(q); err == nil {
			q = strings.Replace(strings.Replace(nq, "\n", " ", -1), "\r", " ", -1)
		}
		t, err := BQL(ctx, q, s.store, s.chanSize, s.bulkSize)
		r := &result{
			Q: q,
			T: t,
		}
		if err != nil {
			log.Printf("[%s] %q failed; %v", time.Now(), q, err.Error())
			r.Msg = err.Error()
		} else {
			r.Msg = "[OK]"
		}
		res = append(res, r)
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write([]byte(`[`))
	cnt := len(res)
	for _, r := range res {
		w.Write([]byte(`{ "query": "`))
		w.Write([]byte(strings.Replace(r.Q, `"`, `\"`, -1)))
		w.Write([]byte(`", "msg": "`))
		w.Write([]byte(strings.Replace(r.Msg, `"`, `\"`, -1)))
		w.Write([]byte(`", "table": `))
		if r.T == nil {
			w.Write([]byte(`{}`))
		} else {
			r.T.ToJSON(w)
		}
		w.Write([]byte(` }`))
		if cnt > 1 {
			w.Write([]byte(`, `))
		}
		cnt--
	}
	w.Write([]byte(`]`))

}
1343876
func (q Query) toSQLBuilder(model *Model, addColumns ...string) *sqlBuilder {
	if len(q.addColumns) != 0 {
		addColumns = q.addColumns
	}
	return newSQLBuilder(q, model, addColumns...)
}
62094
func (api *DatabaseAPI) IsDatabaseRunning(id int64) (bool, error) {
	db, err := api.Status(id)
	if err != nil {
		return false, err
	}
	return db.IsUp(), nil

}
306230
func BuildSqlJob(ctx *plan.Context) (*JobExecutor, error) {
	job := NewExecutor(ctx, plan.NewPlanner(ctx))
	task, err := BuildSqlJobPlanned(job.Planner, job.Executor, ctx)
	if err != nil {
		return nil, err
	}
	taskRunner, ok := task.(TaskRunner)
	if !ok {
		return nil, fmt.Errorf("Expected TaskRunner but was %T", task)
	}
	job.RootTask = taskRunner
	return job, err
}
565522
func (d *domainClient) ExecuteSQL(ctx context.Context, args *ExecuteSQLArgs) (reply *ExecuteSQLReply, err error) {
	reply = new(ExecuteSQLReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "Database.executeSQL", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Database.executeSQL", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Database", Op: "ExecuteSQL", Err: err}
	}
	return
}
987268
func (db *database) RunTransactionFor(modelUUID string, ops []txn.Op) error {
	newDB, dbcloser := db.CopyForModel(modelUUID)
	defer dbcloser()
	runner, closer := newDB.TransactionRunner()
	defer closer()
	return runner.RunTransaction(&jujutxn.Transaction{Ops: ops})
}
522529
func (c *UDPClient) runRequestQueue() error {

	for {
		select {
		case <-c.t.Dying():
			return nil
		case req := <-c.requestQueue:
			message := req.message
			responseCh := req.responseCh

			msg, err := c.execRequest(message)

			responseCh <- response{msg, err}
		}

	}
}
439841
func (d *commandSyncDb) Run() error {
	var drops []string
	if d.force {
		drops = getDbDropSQL(d.al)
	}

	db := d.al.DB

	if d.force {
		for i, mi := range modelCache.allOrdered() {
			query := drops[i]
			if !d.noInfo {
				fmt.Printf("drop table `%s`\n", mi.table)
			}
			_, err := db.Exec(query)
			if d.verbose {
				fmt.Printf("    %s\n\n", query)
			}
			if err != nil {
				if d.rtOnError {
					return err
				}
				fmt.Printf("    %s\n", err.Error())
			}
		}
	}

	sqls, indexes := getDbCreateSQL(d.al)

	tables, err := d.al.DbBaser.GetTables(db)
	if err != nil {
		if d.rtOnError {
			return err
		}
		fmt.Printf("    %s\n", err.Error())
	}

	for i, mi := range modelCache.allOrdered() {
		if tables[mi.table] {
			if !d.noInfo {
				fmt.Printf("table `%s` already exists, skip\n", mi.table)
			}

			var fields []*fieldInfo
			columns, err := d.al.DbBaser.GetColumns(db, mi.table)
			if err != nil {
				if d.rtOnError {
					return err
				}
				fmt.Printf("    %s\n", err.Error())
			}

			for _, fi := range mi.fields.fieldsDB {
				if _, ok := columns[fi.column]; ok == false {
					fields = append(fields, fi)
				}
			}

			for _, fi := range fields {
				query := getColumnAddQuery(d.al, fi)

				if !d.noInfo {
					fmt.Printf("add column `%s` for table `%s`\n", fi.fullName, mi.table)
				}

				_, err := db.Exec(query)
				if d.verbose {
					fmt.Printf("    %s\n", query)
				}
				if err != nil {
					if d.rtOnError {
						return err
					}
					fmt.Printf("    %s\n", err.Error())
				}
			}

			for _, idx := range indexes[mi.table] {
				if d.al.DbBaser.IndexExists(db, idx.Table, idx.Name) == false {
					if !d.noInfo {
						fmt.Printf("create index `%s` for table `%s`\n", idx.Name, idx.Table)
					}

					query := idx.SQL
					_, err := db.Exec(query)
					if d.verbose {
						fmt.Printf("    %s\n", query)
					}
					if err != nil {
						if d.rtOnError {
							return err
						}
						fmt.Printf("    %s\n", err.Error())
					}
				}
			}

			continue
		}

		if !d.noInfo {
			fmt.Printf("create table `%s` \n", mi.table)
		}

		queries := []string{sqls[i]}
		for _, idx := range indexes[mi.table] {
			queries = append(queries, idx.SQL)
		}

		for _, query := range queries {
			_, err := db.Exec(query)
			if d.verbose {
				query = "    " + strings.Join(strings.Split(query, "\n"), "\n    ")
				fmt.Println(query)
			}
			if err != nil {
				if d.rtOnError {
					return err
				}
				fmt.Printf("    %s\n", err.Error())
			}
		}
		if d.verbose {
			fmt.Println("")
		}
	}

	return nil
}
686280
func (c *Connection) Execute(ex *ExecuteRequest) (*ExecuteResponse, error) {
	c.dbMu.RLock()
	defer c.dbMu.RUnlock()
	if c.db == nil {
		return nil, ErrConnectionDoesNotExist
	}
	return c.store.execute(c, ex)
}
354498
func (s *DB) Exec(sql string, values ...interface{}) *DB {
	scope := s.NewScope(nil)
	generatedSQL := scope.buildCondition(map[string]interface{}{"query": sql, "args": values}, true)
	generatedSQL = strings.TrimSuffix(strings.TrimPrefix(generatedSQL, "("), ")")
	scope.Raw(generatedSQL)
	return scope.Exec().db
}
1239111
func (s *SQLStore) newSQLSubStore(channelID int64, limits *SubStoreLimits) *SQLSubStore {
	subStore := &SQLSubStore{
		sqlStore:  s,
		channelID: channelID,
		maxSubID:  &s.maxSubID,
		limits:    *limits,
	}
	subStore.log = s.log
	if s.opts.NoCaching {
		subStore.subLastSent = make(map[uint64]uint64)
	} else {
		subStore.cache = &sqlSubAcksPendingCache{
			subs: make(map[uint64]*sqlSubAcksPending),
		}
	}
	return subStore
}
1283210
func Run(db *sql.DB) {
	// Readline
	reader := bufio.NewReader(os.Stdin)

	for {
		fmt.Printf("ramsql> ")
		buffer, err := reader.ReadBytes(';')
		if err != nil {
			if err == io.EOF {
				fmt.Printf("exit\n")
				return
			}

			fmt.Printf("Reading error\n")
			return
		}

		buffer = buffer[:len(buffer)-1]

		if len(buffer) == 0 {
			continue
		}

		stmt := string(buffer)
		stmt = strings.Replace(stmt, "\n", "", -1)

		// Do things here
		if strings.HasPrefix(stmt, "SELECT") {
			query(db, stmt)
		} else if strings.HasPrefix(stmt, "SHOW") {
			query(db, stmt)
		} else if strings.HasPrefix(stmt, "DESCRIBE") {
			query(db, stmt)
		} else {
			exec(db, stmt)
		}
	}
}
1183192
func newBaseQuery() baseQuery {
	return baseQuery{
		storeLimit:    DefaultMaxResultsPerColumnFamily,
		fromTimestamp: MinTimestamp,
		toTimestamp:   MaxTimestamp,
		maxVersions:   DefaultMaxVersions,
	}
}
918699
func (s *Service) Run(c context.Context, f func(context.Context) error) {
	// Log to Stdout using JSON log lines.
	c = teelogger.Use(c, gkelogger.GetFactory(os.Stdout))

	// If a service name isn't specified, default to the base of the current
	// executable.
	if s.Name == "" {
		s.Name = filepath.Base(os.Args[0])
	}
	s.useDatastoreConfig = true // If available, use datastore config.

	rc := 0
	if err := s.runImpl(c, f); err != nil {
		log.WithError(err).Errorf(c, "Application exiting with error.")
		rc = 1
	}
	os.Exit(rc)
}