Esempio n. 1
0
// DoPrepare prepares the statement, it can be called multiple times without
// side effect.
func (e *PrepareExec) DoPrepare() {
	vars := variable.GetSessionVars(e.Ctx)
	if e.ID != 0 {
		// Must be the case when we retry a prepare.
		// Make sure it is idempotent.
		_, ok := vars.PreparedStmts[e.ID]
		if ok {
			return
		}
	}
	charset, collation := variable.GetCharsetInfo(e.Ctx)
	stmts, err := parser.Parse(e.SQLText, charset, collation)
	if err != nil {
		e.Err = errors.Trace(err)
		return
	}
	if len(stmts) != 1 {
		e.Err = ErrPrepareMulti
		return
	}
	stmt := stmts[0]
	var extractor paramMarkerExtractor
	stmt.Accept(&extractor)

	// The parameter markers are appended in visiting order, which may not
	// be the same as the position order in the query string. We need to
	// sort it by position.
	sorter := &paramMarkerSorter{markers: extractor.markers}
	sort.Sort(sorter)
	e.ParamCount = len(sorter.markers)
	prepared := &Prepared{
		Stmt:          stmt,
		Params:        sorter.markers,
		SchemaVersion: e.IS.SchemaMetaVersion(),
	}

	if optimizer.IsSupported(stmt) {
		err := optimizer.Prepare(e.IS, e.Ctx, stmt)
		if err != nil {
			e.Err = errors.Trace(err)
			return
		}
		if resultSetNode, ok := stmt.(ast.ResultSetNode); ok {
			e.ResultFields = convertResultFields(resultSetNode.GetResultFields())
		}
	}

	if e.ID == 0 {
		e.ID = vars.GetNextPreparedStmtID()
	}
	if e.Name != "" {
		vars.PreparedStmtNameToID[e.Name] = e.ID
	}
	vars.PreparedStmts[e.ID] = prepared
}
Esempio n. 2
0
func (*testSessionSuite) TestSession(c *C) {
	ctx := mock.NewContext()

	variable.BindSessionVars(ctx)

	v := variable.GetSessionVars(ctx)
	c.Assert(v, NotNil)

	// For AffectedRows
	v.AddAffectedRows(1)
	c.Assert(v.AffectedRows, Equals, uint64(1))
	v.AddAffectedRows(1)
	c.Assert(v.AffectedRows, Equals, uint64(2))

	// For FoundRows
	v.AddFoundRows(1)
	c.Assert(v.FoundRows, Equals, uint64(1))
	v.AddFoundRows(1)
	c.Assert(v.FoundRows, Equals, uint64(2))

	// For last insert id
	v.SetLastInsertID(uint64(1))
	c.Assert(v.LastInsertID, Equals, uint64(1))

	v.SetSystemVar("autocommit", types.NewStringDatum("1"))
	val := v.GetSystemVar("autocommit")
	c.Assert(val.GetString(), Equals, "1")
	c.Assert(v.SetSystemVar("autocommit", types.Datum{}), NotNil)

	v.SetSystemVar("sql_mode", types.NewStringDatum("strict_trans_tables"))
	val = v.GetSystemVar("sql_mode")
	c.Assert(val.GetString(), Equals, "STRICT_TRANS_TABLES")
	c.Assert(v.StrictSQLMode, IsTrue)
	v.SetSystemVar("sql_mode", types.NewStringDatum(""))
	c.Assert(v.StrictSQLMode, IsFalse)

	v.SetSystemVar("character_set_connection", types.NewStringDatum("utf8"))
	v.SetSystemVar("collation_connection", types.NewStringDatum("utf8_general_ci"))
	charset, collation := variable.GetCharsetInfo(ctx)
	c.Assert(charset, Equals, "utf8")
	c.Assert(collation, Equals, "utf8_general_ci")

	c.Assert(v.SetSystemVar("character_set_results", types.Datum{}), IsNil)
}