Exemple #1
0
func (c *Conn) handleQuery(sql string) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("execute %s error %v", sql, e)
			return
		}
	}()

	sql = strings.TrimRight(sql, ";")

	var stmt sqlparser.Statement
	stmt, err = sqlparser.Parse(sql)
	if err != nil {
		return fmt.Errorf(`parse sql "%s" error`, sql)
	}

	switch v := stmt.(type) {
	case *sqlparser.Select:
		return c.handleSelect(v, sql, nil)
	case *sqlparser.Insert:
		return c.handleExec(stmt, sql, nil)
	case *sqlparser.Update:
		return c.handleExec(stmt, sql, nil)
	case *sqlparser.Delete:
		return c.handleExec(stmt, sql, nil)
	case *sqlparser.Replace:
		return c.handleExec(stmt, sql, nil)
	case *sqlparser.Set:
		return c.handleSet(v)
	case *sqlparser.Begin:
		return c.handleBegin()
	case *sqlparser.Commit:
		return c.handleCommit()
	case *sqlparser.Rollback:
		return c.handleRollback()
	case *sqlparser.SimpleSelect:
		return c.handleSimpleSelect(sql, v)
	case *sqlparser.Show:
		return c.handleShow(sql, v)
	case *sqlparser.Admin:
		return c.handleAdmin(v)
	default:
		return fmt.Errorf("statement %T not support now", stmt)
	}

	return nil
}
Exemple #2
0
func (c *Conn) handleStmtPrepare(sql string) error {
	if c.schema == nil {
		return NewDefaultError(ER_NO_DB_ERROR)
	}

	s := new(Stmt)

	sql = strings.TrimRight(sql, ";")

	var err error
	s.s, err = sqlparser.Parse(sql)
	if err != nil {
		return fmt.Errorf(`parse sql "%s" error`, sql)
	}

	s.sql = sql

	var tableName string
	switch s := s.s.(type) {
	case *sqlparser.Select:
		tableName = nstring(s.From)
	case *sqlparser.Insert:
		tableName = nstring(s.Table)
	case *sqlparser.Update:
		tableName = nstring(s.Table)
	case *sqlparser.Delete:
		tableName = nstring(s.Table)
	case *sqlparser.Replace:
		tableName = nstring(s.Table)
	default:
		return fmt.Errorf(`unsupport prepare sql "%s"`, sql)
	}

	r := c.schema.rule.GetRule(tableName)

	n := c.server.getNode(r.Nodes[0])

	if co, err := n.getMasterConn(); err != nil {
		return fmt.Errorf("prepare error %s", err)
	} else {
		defer co.Close()

		if err = co.UseDB(c.schema.db); err != nil {
			return fmt.Errorf("parepre error %s", err)
		}

		if t, err := co.Prepare(sql); err != nil {
			return fmt.Errorf("parepre error %s", err)
		} else {

			s.params = t.ParamNum()
			s.columns = t.ColumnNum()
		}
	}

	s.id = c.stmtId
	c.stmtId++

	if err = c.writePrepare(s); err != nil {
		return err
	}

	s.ResetParams()

	c.stmts[s.id] = s

	return nil
}