// grantColumnPriv manipulates mysql.tables_priv table.
354484
func (e *GrantExec) grantColumnPriv(priv *ast.PrivElem, user *ast.UserSpec) error {
	dbName, tbl, err := getTargetSchemaAndTable(e.ctx, e.Level.DBName, e.Level.TableName, e.is)
	if err != nil {
		return err
	}

	for _, c := range priv.Cols {
		col := table.FindCol(tbl.Cols(), c.Name.L)
		if col == nil {
			return errors.Errorf("Unknown column: %s", c)
		}
		asgns, err := composeColumnPrivUpdateForGrant(e.ctx, priv.Priv, user.User.Username, user.User.Hostname, dbName, tbl.Meta().Name.O, col.Name.O)
		if err != nil {
			return err
		}
		sql := fmt.Sprintf(`UPDATE %s.%s SET %s WHERE User='%s' AND Host='%s' AND DB='%s' AND Table_name='%s' AND Column_name='%s';`, mysql.SystemDB, mysql.ColumnPrivTable, asgns, user.User.Username, user.User.Hostname, dbName, tbl.Meta().Name.O, col.Name.O)
		_, _, err = e.ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(e.ctx, sql)
		if err != nil {
			return err
		}
	}
	return nil
}
307883
func (conn *Conn) Privmsgln(t string, a ...interface{}) {
	msg := fmt.Sprintln(a...)
	// trimming the new-line character added by the fmt.Sprintln function,
	// since it's irrelevant.
	msg = msg[:len(msg)-1]
	conn.Privmsg(t, msg)
}
323527
func (vf *vindexFunc) SupplyCol(col *sqlparser.ColName) (rc *resultColumn, colnum int) {
	c := col.Metadata.(*column)
	for i, rc := range vf.resultColumns {
		if rc.column == c {
			return rc, i
		}
	}

	vf.resultColumns = append(vf.resultColumns, &resultColumn{column: c})
	vf.eVindexFunc.Fields = append(vf.eVindexFunc.Fields, &querypb.Field{
		Name: col.Name.String(),
		Type: querypb.Type_VARBINARY,
	})

	// columns that reference vindexFunc will have their colnum set.
	// Let's use it here.
	vf.eVindexFunc.Cols = append(vf.eVindexFunc.Cols, c.colnum)
	return rc, len(vf.resultColumns) - 1
}
676573
func (p *UserPrivileges) UserPrivilegesTable() [][]types.Datum {
	mysqlPriv := p.Handle.Get()
	return mysqlPriv.UserPrivilegesTable()
}
1262695
func GetPermissions(mysqld MysqlDaemon) (*tabletmanagerdatapb.Permissions, error) {
	ctx := context.TODO()
	permissions := &tabletmanagerdatapb.Permissions{}

	// get Users
	qr, err := mysqld.FetchSuperQuery(ctx, "SELECT * FROM mysql.user ORDER BY host, user")
	if err != nil {
		return nil, err
	}
	for _, row := range qr.Rows {
		permissions.UserPermissions = append(permissions.UserPermissions, tmutils.NewUserPermission(qr.Fields, row))
	}

	// get Dbs
	qr, err = mysqld.FetchSuperQuery(ctx, "SELECT * FROM mysql.db ORDER BY host, db, user")
	if err != nil {
		return nil, err
	}
	for _, row := range qr.Rows {
		permissions.DbPermissions = append(permissions.DbPermissions, tmutils.NewDbPermission(qr.Fields, row))
	}

	return permissions, nil
}
844008
func (p *ExtensionManagerClient) GetQueryColumns(ctx context.Context, sql string) (r *ExtensionResponse, err error) {
  var _args31 ExtensionManagerGetQueryColumnsArgs
  _args31.Sql = sql
  var _result32 ExtensionManagerGetQueryColumnsResult
  if err = p.Client_().Call(ctx, "getQueryColumns", &_args31, &_result32); err != nil {
    return
  }
  return _result32.GetSuccess(), nil
}
61933
func (kern *Kernel) LoadTendermintFromConfig(conf *config.BurrowConfig, privVal tmTypes.PrivValidator) (err error) {
	if conf.Tendermint == nil || !conf.Tendermint.Enabled {
		return nil
	}

	authorizedPeersProvider := conf.Tendermint.DefaultAuthorizedPeersProvider()
	kern.database.Stats()

	kern.info = fmt.Sprintf("Burrow_%s_%s_ValidatorID:%X", project.History.CurrentVersion().String(),
		kern.Blockchain.ChainID(), privVal.GetPubKey().Address())

	app := abci.NewApp(kern.info, kern.Blockchain, kern.State, kern.checker, kern.committer, kern.txCodec,
		authorizedPeersProvider, kern.Panic, kern.Logger)

	// We could use this to provide/register our own metrics (though this will register them with us). Unfortunately
	// Tendermint currently ignores the metrics passed unless its own server is turned on.
	metricsProvider := node.DefaultMetricsProvider(&tmConfig.InstrumentationConfig{
		Prometheus:           false,
		PrometheusListenAddr: "",
	})

	genesisDoc := kern.Blockchain.GenesisDoc()

	// find node key
	var nodeKey *crypto.PrivateKey
	for _, v := range genesisDoc.Validators {
		thisAddress, err := crypto.AddressFromHexString(privVal.GetPubKey().Address().String())
		if err != nil {
			break
		}
		if v.Address == thisAddress && v.NodeAddress != nil {
			k, err := kern.keyStore.GetKey("", v.NodeAddress.Bytes())
			if err == nil {
				nodeKey = &k.PrivateKey
			}
			break
		}
	}

	tmGenesisDoc := tendermint.DeriveGenesisDoc(&genesisDoc, kern.Blockchain.AppHashAfterLastBlock())
	heightValuer := log.Valuer(func() interface{} { return kern.Blockchain.LastBlockHeight() })
	tmLogger := kern.Logger.With(structure.CallerKey, log.Caller(LoggingCallerDepth+1)).With("height", heightValuer)
	kern.Node, err = tendermint.NewNode(conf.TendermintConfig(), privVal, tmGenesisDoc, app, metricsProvider, nodeKey, tmLogger)
	return err
}
974826
func Int64Column(w int, v int64) string {
	s := strconv.FormatInt(v, 10)
	return Column(w, s)
}
427700
func newV3ResolverFromTableDefinition(keyspaceSchema *vindexes.KeyspaceSchema, td *tabletmanagerdatapb.TableDefinition) (keyspaceIDResolver, error) {
	if td.Type != tmutils.TableBaseTable {
		return nil, vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "a keyspaceID resolver can only be created for a base table, got %v", td.Type)
	}
	tableSchema, ok := keyspaceSchema.Tables[td.Name]
	if !ok {
		return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "no vschema definition for table %v", td.Name)
	}
	// use the lowest cost unique vindex as the sharding key
	colVindex, err := vindexes.FindVindexForSharding(td.Name, tableSchema.ColumnVindexes)
	if err != nil {
		return nil, err
	}

	// Find the sharding key column index.
	columnIndex, ok := tmutils.TableDefinitionGetColumn(td, colVindex.Columns[0].String())
	if !ok {
		return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "table %v has a Vindex on unknown column %v", td.Name, colVindex.Columns[0])
	}

	return &v3Resolver{
		shardingColumnIndex: columnIndex,
		vindex:              colVindex.Vindex,
	}, nil
}
759229
func (mysqld *Mysqld) GetPrimaryKeyColumns(dbName, table string) ([]string, error) {
	conn, err := getPoolReconnect(context.TODO(), mysqld.dbaPool)
	if err != nil {
		return nil, err
	}
	defer conn.Recycle()
	qr, err := conn.ExecuteFetch(fmt.Sprintf("SHOW INDEX FROM %s.%s", sqlescape.EscapeID(dbName), sqlescape.EscapeID(table)), 100, true)
	if err != nil {
		return nil, err
	}
	keyNameIndex := -1
	seqInIndexIndex := -1
	columnNameIndex := -1
	for i, field := range qr.Fields {
		switch field.Name {
		case "Key_name":
			keyNameIndex = i
		case "Seq_in_index":
			seqInIndexIndex = i
		case "Column_name":
			columnNameIndex = i
		}
	}
	if keyNameIndex == -1 || seqInIndexIndex == -1 || columnNameIndex == -1 {
		return nil, fmt.Errorf("unknown columns in 'show index' result: %v", qr.Fields)
	}

	columns := make([]string, 0, 5)
	var expectedIndex int64 = 1
	for _, row := range qr.Rows {
		// skip non-primary keys
		if row[keyNameIndex].ToString() != "PRIMARY" {
			continue
		}

		// check the Seq_in_index is always increasing
		seqInIndex, err := sqltypes.ToInt64(row[seqInIndexIndex])
		if err != nil {
			return nil, err
		}
		if seqInIndex != expectedIndex {
			return nil, fmt.Errorf("unexpected index: %v != %v", seqInIndex, expectedIndex)
		}
		expectedIndex++

		columns = append(columns, row[columnNameIndex].ToString())
	}
	return columns, err
}
118592
func (clnt *Client) GrantRoles(policy *AdminPolicy, user string, roles []string) error {
	policy = clnt.getUsableAdminPolicy(policy)

	command := newAdminCommand(nil)
	return command.grantRoles(clnt.cluster, policy, user, roles)
}
549920
func GenSecpPrivKeys(n int) privKeys {
	res := make(privKeys, n)
	for i := range res {
		res[i] = secp256k1.GenPrivKey()
	}
	return res
}
1102172
func (ds *DataSource) getColumnNDV(colID int64) (ndv float64) {
	hist, ok := ds.statisticTable.Columns[colID]
	if ok && hist.Count > 0 {
		factor := float64(ds.statisticTable.Count) / float64(hist.Count)
		ndv = float64(hist.NDV) * factor
	} else {
		ndv = float64(ds.statisticTable.Count) * distinctFactor
	}
	return ndv
}
1010606
func modifyColumnFromNull2NotNull(w *worker, t *meta.Meta, dbInfo *model.DBInfo, tblInfo *model.TableInfo, job *model.Job, oldCol, newCol *model.ColumnInfo) (ver int64, _ error) {
	// Get sessionctx from context resource pool.
	var ctx sessionctx.Context
	ctx, err := w.sessPool.get()
	if err != nil {
		return ver, errors.Trace(err)
	}
	defer w.sessPool.put(ctx)

	// If there is a null value inserted, it cannot be modified and needs to be rollback.
	err = checkForNullValue(ctx, oldCol.Tp == newCol.Tp, dbInfo.Name, tblInfo.Name, oldCol.Name, newCol.Name)
	if err != nil {
		job.State = model.JobStateRollingback
		return ver, errors.Trace(err)
	}

	// Prevent this field from inserting null values.
	tblInfo.Columns[oldCol.Offset].Flag |= mysql.PreventNullInsertFlag
	ver, err = updateVersionAndTableInfo(t, job, tblInfo, true)
	return ver, errors.Trace(err)
}
931436
func PgAmprocByAmprocfamilyAmproclefttypeAmprocrighttypeAmprocnum(db XODB, amprocfamily pgtypes.Oid, amproclefttype pgtypes.Oid, amprocrighttype pgtypes.Oid, amprocnum int16) (*PgAmproc, error) {
	var err error

	// sql query
	const sqlstr = `SELECT ` +
		`tableoid, cmax, xmax, cmin, xmin, oid, ctid, amprocfamily, amproclefttype, amprocrighttype, amprocnum, amproc ` +
		`FROM pg_catalog.pg_amproc ` +
		`WHERE amprocfamily = $1 AND amproclefttype = $2 AND amprocrighttype = $3 AND amprocnum = $4`

	// run query
	XOLog(sqlstr, amprocfamily, amproclefttype, amprocrighttype, amprocnum)
	pa := PgAmproc{}

	err = db.QueryRow(sqlstr, amprocfamily, amproclefttype, amprocrighttype, amprocnum).Scan(&pa.Tableoid, &pa.Cmax, &pa.Xmax, &pa.Cmin, &pa.Xmin, &pa.Oid, &pa.Ctid, &pa.Amprocfamily, &pa.Amproclefttype, &pa.Amprocrighttype, &pa.Amprocnum, &pa.Amproc)
	if err != nil {
		return nil, err
	}

	return &pa, nil
}
1070775
func NewDbPermission(fields []*querypb.Field, values []sqltypes.Value) *tabletmanagerdatapb.DbPermission {
	up := &tabletmanagerdatapb.DbPermission{
		Privileges: make(map[string]string),
	}
	for i, field := range fields {
		switch field.Name {
		case "Host":
			up.Host = values[i].ToString()
		case "Db":
			up.Db = values[i].ToString()
		case "User":
			up.User = values[i].ToString()
		default:
			up.Privileges[field.Name] = values[i].ToString()
		}
	}
	return up
}
576691
func (coll *HistColl) GetRowCountByColumnRanges(sc *stmtctx.StatementContext, colID int64, colRanges []*ranger.Range) (float64, error) {
	c, ok := coll.Columns[colID]
	if !ok || c.IsInvalid(sc, coll.Pseudo) {
		return GetPseudoRowCountByColumnRanges(sc, float64(coll.Count), colRanges, 0)
	}
	result, err := c.GetColumnRowCount(sc, colRanges, coll.ModifyCount)
	result *= c.GetIncreaseFactor(coll.Count)
	return result, errors.Trace(err)
}