func (p *TnCommandContextHandler) Execute(args []interface{}, tx *sql.Tx, behavior *Behavior) interface{} {

	p.sql = (*p.CommandContext).getSql()
	//	fmt.Printf("getBindVariables %v\n",(*p.CommandContext).getBindVariables())
	//	p.logSql((*p.CommandContext).getBindVariables(),
	//		(*p.CommandContext).getBindVariableTypes())
	//	log.Flush()
	//	fmt.Printf("statementFactory %v \n",p.statementFactory)
	bindVariables := (*p.CommandContext).getBindVariables()
	bindVariableTypes := (*p.CommandContext).getBindVariableTypes()
	dbc := (*(*behavior).GetBaseBehavior().GetBehaviorCommandInvoker().InvokerAssistant).GetDBCurrent()

	ps := (*p.statementFactory).PrepareStatement(p.sql, tx, dbc)
	defer ps.Close()
	bindVar := (*p.statementFactory).ModifyBindVariables(bindVariables, bindVariableTypes)
	p.logSql(bindVariables, bindVariableTypes)
	log.Flush()
	res, err := tx.Stmt(ps).Exec(bindVar.data...)
	if err != nil {
		panic(err.Error())
	}

	updateno, _ := res.RowsAffected()
	log.InternalDebug(fmt.Sprintln("result no:", updateno))
	return updateno
}
Beispiel #2
0
// TxStmt convert a prepared statement to a transaction specific prepared
// statement.
func TxStmt(sql string, tx *sql.Tx) *sql.Stmt {
	dbStmt, ok := StmtMap[sql]
	if !ok {
		log.Fatalf("No Prepared SQL statement for: %s", sql)
	}
	return tx.Stmt(dbStmt)
}
Beispiel #3
0
func (t *Table) cascadeDelete(txn *sql.Tx, pk interface{}) error {
	for _, child := range t.Children {
		child.cascadeDelete(txn, pk)
	}
	stmt := txn.Stmt(t.stmts.stmtDelete)
	_, e := stmt.Exec(pk)
	return e
}
Beispiel #4
0
func execInsert(db *sql.DB, query string, parameters ...interface{}) {
	var err error
	var tx *sql.Tx
	var stmt *sql.Stmt
	stmt, err = db.Prepare(query)
	tx, err = db.Begin()
	_, err = tx.Stmt(stmt).Exec(parameters...)
	err = tx.Commit()
	if err != nil {
		log.Fatalf("Insert error %q\n", err)
	}
}
Beispiel #5
0
func (s *querysrv) updateDevice(tx *sql.Tx, device protocol.DeviceID) error {
	res, err := tx.Stmt(s.prep["updateDevice"]).Exec(device.String())
	if err != nil {
		return err
	}

	if rows, _ := res.RowsAffected(); rows == 0 {
		_, err := tx.Stmt(s.prep["insertDevice"]).Exec(device.String())
		if err != nil {
			return err
		}
	}

	return nil
}
Beispiel #6
0
func (s *querysrv) updateAddress(ctx context.Context, tx *sql.Tx, device protocol.DeviceID, uri string) error {
	res, err := tx.Stmt(s.prep["updateAddress"]).Exec(device.String(), uri)
	if err != nil {
		return err
	}

	if rows, _ := res.RowsAffected(); rows == 0 {
		_, err := tx.Stmt(s.prep["insertAddress"]).Exec(device.String(), uri)
		if err != nil {
			return err
		}
	}

	return nil
}
func (t *TnBasicSelectHandler) execute(bindVariables *List, bindVariableTypes *StringList, tx *sql.Tx, behavior *Behavior) interface{} {
	dbc := (*(*behavior).GetBaseBehavior().GetBehaviorCommandInvoker().InvokerAssistant).GetDBCurrent()

	ps := (*t.statementFactory).PrepareStatement(t.sql, tx, dbc)
	defer ps.Close()
	bindVar := (*t.statementFactory).ModifyBindVariables(bindVariables, bindVariableTypes)
	//ps := t.prepareStatement(tx, dbc)
	//	ns:=new(sql.NullString)
	//	ns.Valid=true
	//	ns.String="2"
	//	var itest interface{}=ns
	t.logSql(bindVariables, bindVariableTypes)
	var rows *sql.Rows
	var err error
	if bindVariables == nil {
		rows, err = tx.Stmt(ps).Query()
		if err != nil {
			panic(err.Error())
		}
	} else {
		rows, err = tx.Stmt(ps).Query(bindVar.data...)
		if err != nil {
			panic(err.Error())
		}
	}

	log.InternalDebug(fmt.Sprintln("ResultType:", t.ResultType))
	rh := new(ResultSetHandler)
	//l := BhvUtil_I.GetListResultBean(rows, t.ResultType,t.SqlClause)
	l := rh.GetListResultBean(rows, t.ResultType, t.SqlClause)
	log.InternalDebug(fmt.Sprintln("result no:", l.List.Size()))
	log.InternalDebug(fmt.Sprintf("data %v\n", l.List.Get(0)))
	//        logSql(args, argTypes);
	//        PreparedStatement ps = null;
	//        try {
	//            ps = prepareStatement(conn);
	//            bindArgs(conn, ps, args, argTypes);
	//            return queryResult(ps);
	//        } catch (SQLException e) {
	//            final SQLExceptionResource resource = createSQLExceptionResource();
	//            resource.setNotice("Failed to execute the SQL for select.");
	//            handleSQLException(e, resource);
	//            return null; // unreachable
	//        } finally {
	//            close(ps);
	//        }
	return l
}
func (s *Storage) addSCTFeedbackIfNotExists(tx *sql.Tx, chainID, sctID int64) error {
	stmt := tx.Stmt(s.insertSCTFeedback)
	_, err := stmt.Exec(chainID, sctID)
	if err != nil {
		switch err.(type) {
		case sqlite3.Error:
			// If this is a dupe that's fine, no need to return an error
			if err.(sqlite3.Error).Code != sqlite3.ErrConstraint {
				return err
			}
		default:
			return err
		}
	}
	return nil
}
// insertThingOrSelectID will attempt to execute the insert Statement (under transaction tx), if that fails due to
// a unique primary key constraint, it will look up that primary key by executing the getID Statement.
// Returns the ID associated with persistent thing, or an error describing the failure.
func insertThingOrSelectID(tx *sql.Tx, insert *sql.Stmt, getID *sql.Stmt, thing interface{}) (int64, error) {
	txInsert := tx.Stmt(insert)
	txGetID := tx.Stmt(getID)
	r, err := txInsert.Exec(thing)
	if err != nil {
		switch e := err.(type) {
		case sqlite3.Error:
			if e.Code == sqlite3.ErrConstraint {
				return selectThingID(txGetID, thing)
			}
		}
		return -1, err
	}
	id, err := r.LastInsertId()
	if err != nil {
		return -1, err
	}
	return id, nil
}
func (s *Storage) addSTHIfNotExists(tx *sql.Tx, sth ct.SignedTreeHead) error {
	stmt := tx.Stmt(s.insertSTHPollination)
	sigB64, err := sth.TreeHeadSignature.Base64String()
	if err != nil {
		return fmt.Errorf("Failed to base64 sth signature: %v", err)
	}
	_, err = stmt.Exec(sth.Version, sth.TreeSize, sth.Timestamp, sth.SHA256RootHash.Base64String(), sigB64, sth.LogID.Base64String())
	if err != nil {
		switch err.(type) {
		case sqlite3.Error:
			// If this is a dupe that's fine, no need to return an error
			if err.(sqlite3.Error).Code != sqlite3.ErrConstraint {
				return err
			}
		default:
			return err
		}
	}
	return nil
}
Beispiel #11
0
func (p *prepareds) Tx(tx *sql.Tx) (px *prepareds, err error) {
	px = &prepareds{}
	t := reflect.TypeOf(p).Elem()
	v := reflect.Indirect(reflect.ValueOf(p))
	v2 := reflect.Indirect(reflect.ValueOf(px))
	nf := t.NumField()
	for i := 0; i < nf; i++ {
		f := t.Field(i)
		if f.Tag == "" {
			continue
		}
		fv := v.Field(i)
		fv2 := v2.Field(i)
		fvi := fv.Interface()
		if fvi != nil {
			if stmt, ok := fvi.(*sql.Stmt); ok {
				fv2.Set(reflect.ValueOf(tx.Stmt(stmt)))
			}
		}
	}
	return
}
func (t *TnAbstractEntityHandler) execute(entity *Entity, tx *sql.Tx) int64 {
	//        processBefore(bean);
	(*t.BasicSqlHander).setupBindVariables(entity)
	t.logSql(t.bindVariables, t.bindVariableValueTypes)
	ps := (*t.statementFactory).PrepareStatement(t.sql, tx, (*(*entity).GetDBMeta()).GetDbCurrent())
	defer ps.Close()
	bindVar := (*t.statementFactory).ModifyBindVariables(t.bindVariables, t.bindVariableValueTypes)
	//        RuntimeException sqlEx = null;
	//        final int ret;
	//        try {
	//            bindArgs(conn, ps, _bindVariables, _bindVariableValueTypes);
	//            ret = executeUpdate(ps);
	//fmt.Printf("tx %v ps %v bindVar %v\n", tx, ps, bindVar)
	res, err := tx.Stmt(ps).Exec(bindVar.data...)
	if err != nil {
		panic(err.Error())
	}
	updateno, _ := res.RowsAffected()
	idno, _ := res.LastInsertId()
	log.InternalDebug(fmt.Sprintf("idno %d \n", idno))
	t.handleUpdateResultWithOptimisticLock(entity, updateno)
	//        } catch (RuntimeException e) {
	//            // not SQLFailureException because the JDBC wrapper may throw an other exception
	//            sqlEx = e;
	//            throw e;
	//        } finally {
	//            close(ps);
	//            processFinally(bean, sqlEx);
	//        }
	//        // a value of exclusive control column should be synchronized
	//        // after handling optimistic lock
	//        processSuccess(bean, ret);
	//        return ret;
	//fmt.Printf("BasicSqlHander %v entity %v updateno %v\n", t.BasicSqlHander, entity, updateno)
	(*t.BasicSqlHander).processSuccess(entity, updateno, idno)
	return updateno
}
Beispiel #13
0
func (store *DBStore) CreateUserInTx(tx *sql.Tx, email, password string) (user *User, err error) {

	createdAt := time.Now()

	salt, hash := crypto.Base64SaltAndHash(password, 64)

	var userId int64
	if err = tx.Stmt(store.insertUserStmt).QueryRow(email, salt, hash, createdAt, createdAt).Scan(&userId); err != nil {
		// and error "sql: no rows in result set" is returned when the insert fails
		// for example, because there is a unique index collision (e.g) email
		return
	}

	user = &User{
		Id:           userId,
		Email:        strings.ToLower(email),
		PasswordSalt: salt,
		PasswordHash: hash,
		CreatedAt:    createdAt,
		UpdatedAt:    createdAt,
	}

	return
}
func (t *TnBasicUpdateHandler) execute(bindVariables *List, bindVariableTypes *StringList, tx *sql.Tx, behavior *Behavior) interface{} {
	dbc := (*(*behavior).GetBaseBehavior().GetBehaviorCommandInvoker().InvokerAssistant).GetDBCurrent()

	ps := (*t.statementFactory).PrepareStatement(t.sql, tx, dbc)
	defer ps.Close()
	bindVar := (*t.statementFactory).ModifyBindVariables(bindVariables, bindVariableTypes)
	//ps := t.prepareStatement(tx, dbc)
	//	ns:=new(sql.NullString)
	//	ns.Valid=true
	//	ns.String="2"
	//	var itest interface{}=ns
	t.logSql(bindVariables, bindVariableTypes)
	res, err := tx.Stmt(ps).Exec(bindVar.data...)
	if err != nil {
		panic(err.Error())
	}

	updateno, _ := res.RowsAffected()
	log.InternalDebug(fmt.Sprintln("result no:", updateno))

	//        logSql(args, argTypes);
	//        PreparedStatement ps = null;
	//        try {
	//            ps = prepareStatement(conn);
	//            bindArgs(conn, ps, args, argTypes);
	//            return queryResult(ps);
	//        } catch (SQLException e) {
	//            final SQLExceptionResource resource = createSQLExceptionResource();
	//            resource.setNotice("Failed to execute the SQL for select.");
	//            handleSQLException(e, resource);
	//            return null; // unreachable
	//        } finally {
	//            close(ps);
	//        }
	return updateno
}
Beispiel #15
0
func StoreEvent(event *data.Event) (err error) {

	// insert the tags and bail if we get an error
	// TODO, do this within a transaction
	var tagIds []int64
	if tagIds, err = findOrCreateTags(event.Tags); err != nil {
		return
	}

	var tx *sql.Tx

	if tx, err = pg.Begin(); err != nil {
		return
	}

	defer /* panic-recover */ func() {

		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()

	if err = tx.Stmt(insertEventStmt).QueryRow(event.Desc).Scan(&event.Id); err != nil {
		return
	}

	if err = tagEvents(tx, event.Id, tagIds); err != nil {
		return
	}

	newEvents.Events <- event

	return
}
Beispiel #16
0
func (s *querysrv) updateDevice(ctx context.Context, tx *sql.Tx, device protocol.DeviceID) error {
	reqID := ctx.Value("id").(requestID)
	t0 := time.Now()
	res, err := tx.Stmt(s.prep["updateDevice"]).Exec(device.String())
	if err != nil {
		return err
	}
	if debug {
		log.Println(reqID, "updateDevice in", time.Since(t0))
	}

	if rows, _ := res.RowsAffected(); rows == 0 {
		t0 = time.Now()
		_, err := tx.Stmt(s.prep["insertDevice"]).Exec(device.String())
		if err != nil {
			return err
		}
		if debug {
			log.Println(reqID, "insertDevice in", time.Since(t0))
		}
	}

	return nil
}
Beispiel #17
0
func (s *cleansrv) cleanOldEntries() (err error) {
	var tx *sql.Tx
	tx, err = s.db.Begin()
	if err != nil {
		return err
	}

	defer func() {
		if err == nil {
			err = tx.Commit()
		} else {
			tx.Rollback()
		}
	}()

	res, err := tx.Stmt(s.prep["cleanAddress"]).Exec()
	if err != nil {
		return err
	}
	if rows, _ := res.RowsAffected(); rows > 0 {
		log.Printf("Clean: %d old addresses", rows)
	}

	res, err = tx.Stmt(s.prep["cleanDevice"]).Exec()
	if err != nil {
		return err
	}
	if rows, _ := res.RowsAffected(); rows > 0 {
		log.Printf("Clean: %d old devices", rows)
	}

	var devs, addrs int
	row := tx.Stmt(s.prep["countDevice"]).QueryRow()
	if err = row.Scan(&devs); err != nil {
		return err
	}
	row = tx.Stmt(s.prep["countAddress"]).QueryRow()
	if err = row.Scan(&addrs); err != nil {
		return err
	}

	log.Printf("Database: %d devices, %d addresses", devs, addrs)
	return nil
}
Beispiel #18
0
Datei: db.go Projekt: postfix/arx
func doTx(tx *sql.Tx, qid int) *sql.Stmt {
	return tx.Stmt(dbStmt[qid])
}
Beispiel #19
0
func (t *Table) storeRow(txn *sql.Tx, row reflect.Value, logger entityInfo) error {
	var res sql.Result
	var stmt *sql.Stmt
	var e error
	var pk int64

	pkValue := row.FieldByIndex(t.PrimaryKey.ClassIdx)
	switch pkValue.Kind() {
	case reflect.Int, reflect.Int32, reflect.Int64:
		pk = pkValue.Int()
	case reflect.Uint, reflect.Uint32, reflect.Uint64:
		pk = int64(pkValue.Uint())
	default:
		return fmt.Errorf("Unsupported Primary Key type")
	}

	var isUpdate bool = pk != 0
	if !t.IsPkSerial {
		isUpdate = logger.hasRow(t.tableNo, pk)
	}

	var flds []interface{} = make([]interface{}, 0, len(t.Fields))
	for _, f := range t.Fields {
		if f != t.PrimaryKey {
			fv := row.FieldByIndex(f.ClassIdx)
			if fv.Kind() == reflect.Ptr {
				if !fv.IsNil() {
					fv = fv.Elem()
				}
			}
			fvi := fv.Interface()
			switch p := fvi.(type) {
			case time.Time:
				fvi = p.UTC()
			case nil:

			}
			flds = append(flds, fvi)
		}
	}

	if isUpdate {
		flds = append(flds, pk)
		stmt = t.stmts.stmtUpdate
		if txn != nil {
			stmt = txn.Stmt(stmt)
		}
	} else {
		if !t.IsPkSerial {
			flds = append([]interface{}{pk}, flds...)
		}
		stmt = t.stmts.stmtInsert
		if txn != nil {
			stmt = txn.Stmt(stmt)
		}
	}
	res, e = stmt.Exec(flds...)
	if e != nil {
		return e
	}

	var rowsAffected int64
	rowsAffected, e = res.RowsAffected()
	if e != nil {
		return e
	}
	if rowsAffected > 1 {
		fmt.Errorf("Insert/Update: expected 0 or 1 row to be affected: %d", rowsAffected)
	}

	if isUpdate {
		if rowsAffected == 0 {
			logger.rowSkipped(t.tableNo, pk)
		} else {
			logger.rowUpdated(t.tableNo, pk)
		}
	} else {
		pk, e = res.LastInsertId()
		if e == nil {
			switch pkValue.Kind() {
			case reflect.Int, reflect.Int32, reflect.Int64:
				pkValue.SetInt(pk)
			case reflect.Uint, reflect.Uint32, reflect.Uint64:
				pkValue.SetUint(uint64(pk))
			}
			logger.rowInserted(t.tableNo, pk)
		}
	}

	if e != nil {
		return e
	}
	for _, child := range t.Children {
		childStorage := row.FieldByIndex(child.ClassIdx)
		if childStorage.IsNil() {
			continue
		}
		var childRow reflect.Value
		switch child.ChildClass.Kind() {
		case reflect.Ptr:
			{
				childRow = childStorage.Elem()
				e = child.storeChildRow(txn, childRow, pk, logger)
			}
		case reflect.Slice:
			{
				for i := 0; i < childStorage.Len(); i++ {
					childRow = childStorage.Index(i)
					if !childRow.IsValid() {
						continue
					}
					if childRow.Kind() == reflect.Ptr {
						if childRow.IsNil() {
							continue
						}
						childRow = childRow.Elem()
					}
					e = child.storeChildRow(txn, childRow, pk, logger)
					if e != nil {
						break
					}
				}
			}
		case reflect.Map:
			{
				for _, key := range childStorage.MapKeys() {
					childRow = childStorage.MapIndex(key)
					if childRow.Kind() == reflect.Ptr {
						childRow = childRow.Elem()
					}
					e = child.storeChildRow(txn, childRow, pk, logger)
					if e != nil {
						break
					}
				}
			}
		}

		if e != nil {
			break
		}
	}

	return e
}
Beispiel #20
0
func (conn *GorbManager) EntityPut(entity interface{}) error {
	if conn.db == nil {
		return fmt.Errorf("Database connection is not set")
	}

	var ent *Entity
	eType := reflect.TypeOf(entity)
	var isPtr = eType.Kind() == reflect.Ptr
	if isPtr {
		eType = eType.Elem()
	}
	ent = conn.LookupEntity(eType)
	if ent == nil {
		return fmt.Errorf("Unsupported entity %s", eType.Name())
	}

	var e error

	initf, ok := entity.(interface {
		OnEntitySave() (bool, error)
	})
	if ok {
		ok, e = initf.OnEntitySave()
		if !ok {
			return e
		}
	}

	var eData entityData

	eValue := reflect.ValueOf(entity)
	if isPtr {
		eValue = eValue.Elem()
	}
	pkValue := eValue.FieldByIndex(ent.PrimaryKey.ClassIdx)
	switch pkValue.Kind() {
	case reflect.Int, reflect.Int32, reflect.Int64:
		eData.pk = pkValue.Int()
	case reflect.Uint, reflect.Uint32, reflect.Uint64:
		eData.pk = int64(pkValue.Uint())
	default:
		return fmt.Errorf("Unsupported Primary Key type")
	}
	if eData.pk != 0 {
		eData.children = make([]rowData, 0, 16)
		e := ent.populateData(&eData, eData.pk)
		if e != nil {
			return e
		}
		if len(eData.children) > 0 {
			sort.Sort(eData.children)
		}

		if ent.TokenField != nil {
			var token int64 = eValue.FieldByIndex(ent.TokenField.ClassIdx).Int()
			if token != int64(eData.token) {
				return fmt.Errorf("Invalid Edit Token")
			}
		}
	}

	var txn *sql.Tx = nil
	if len(ent.Children) > 0 {
		txn, e = conn.db.Begin()
		if e != nil {
			return e
		}
	}

	var t *Table = &((*ent).Table)
	e = t.storeRow(txn, eValue, &eData)

	if e == nil {
		if len(eData.children) > eData.updated+eData.skipped {
			chlds := ent.FlattenChildren()
			var lastTableNo int32 = 0
			var stmt *sql.Stmt = nil
			var res sql.Result
			var rowsAffected int64
			for i := len(eData.children) - 1; i >= 0; i-- {
				rd := eData.children[i]
				if rd.tableNo > 0 && rd.status == RowRead {
					child := chlds[rd.tableNo-1]
					if child.tableNo == rd.tableNo {
						if lastTableNo != child.tableNo {
							stmt = child.stmts.stmtRemove
							if txn != nil {
								stmt = txn.Stmt(stmt)
							}
							lastTableNo = child.tableNo
						}
						res, e = stmt.Exec(rd.pk)
						if e != nil {
							break
						}
						rowsAffected, e = res.RowsAffected()
						if e != nil {
							break
						}
						if rowsAffected == 1 {
							(&eData).rowDeleted(rd.tableNo, rd.pk)
						}
					}
				}
			}
		}
	}

	if e == nil && txn != nil {
		if e == nil {
			e = txn.Commit()
		} else {
			txn.Rollback()
		}
	}

	return e
}
Beispiel #21
0
func (conn *GorbManager) EntityDelete(eType reflect.Type, pk interface{}) error {
	if conn.db == nil {
		return fmt.Errorf("Database connection is not set")
	}

	if pk == nil {
		return fmt.Errorf("EntityGet: parameters cannot be nil")
	}

	var ent *Entity
	if eType.Kind() == reflect.Ptr {
		eType = eType.Elem()
	}
	ent = conn.LookupEntity(eType)
	if ent == nil {
		return fmt.Errorf("Unsupported entity %s", eType.Name())
	}

	var e error = nil
	var txn *sql.Tx = nil

	if len(ent.Children) > 0 {
		txn, e = conn.db.Begin()
		if e != nil {
			return e
		}
	}

	var stmt *sql.Stmt

	chldns := ent.FlattenChildren()
	for i := len(chldns) - 1; i >= 0; i-- {
		child := chldns[i]
		stmt = child.stmts.stmtDelete
		if txn != nil {
			stmt = txn.Stmt(stmt)
		}

		_, e = stmt.Exec(pk)
		if txn != nil {
			stmt.Close()
			stmt = nil
		}
		if e != nil {
			break
		}
	}

	stmt = ent.stmts.stmtDelete
	if txn != nil {
		stmt = txn.Stmt(stmt)
	}

	_, e = stmt.Exec(pk)
	if txn != nil {
		stmt.Close()
		stmt = nil
	}

	if txn != nil {
		if e == nil {
			e = txn.Commit()
		} else {
			txn.Rollback()
		}
	}

	return e
}