github.com/matrixorigin/matrixone@v0.7.0/pkg/vm/engine/tae/db/task.go (about)

     1  // Copyright 2021 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package db
    16  
    17  import (
    18  	"github.com/matrixorigin/matrixone/pkg/logutil"
    19  	"github.com/matrixorigin/matrixone/pkg/vm/engine/tae/common"
    20  	"github.com/matrixorigin/matrixone/pkg/vm/engine/tae/tasks"
    21  )
    22  
    23  type ScheduledTxnTask struct {
    24  	*tasks.BaseTask
    25  	db      *DB
    26  	factory tasks.TxnTaskFactory
    27  	scopes  []common.ID
    28  }
    29  
    30  func NewScheduledTxnTask(ctx *tasks.Context, db *DB, taskType tasks.TaskType, scopes []common.ID, factory tasks.TxnTaskFactory) (task *ScheduledTxnTask) {
    31  	task = &ScheduledTxnTask{
    32  		db:      db,
    33  		factory: factory,
    34  		scopes:  scopes,
    35  	}
    36  	task.BaseTask = tasks.NewBaseTask(task, taskType, ctx)
    37  	return
    38  }
    39  
    40  func (task *ScheduledTxnTask) Scopes() []common.ID { return task.scopes }
    41  func (task *ScheduledTxnTask) Scope() *common.ID {
    42  	if task.scopes == nil || len(task.scopes) == 0 {
    43  		return nil
    44  	}
    45  	return &task.scopes[0]
    46  }
    47  
    48  func (task *ScheduledTxnTask) Execute() (err error) {
    49  	txn, err := task.db.StartTxn(nil)
    50  	if err != nil {
    51  		return
    52  	}
    53  	txnTask, err := task.factory(nil, txn)
    54  	if err != nil {
    55  		err2 := txn.Rollback()
    56  		if err2 != nil {
    57  			panic(err2)
    58  		}
    59  		logutil.Warnf("Execute ScheduleTxnTask: %v. Rollbacked", err)
    60  		return
    61  	}
    62  	err = txnTask.OnExec()
    63  	if err != nil {
    64  		err2 := txn.Rollback()
    65  		if err2 != nil {
    66  			panic(err)
    67  		}
    68  	} else {
    69  		err = txn.Commit()
    70  		if err != nil {
    71  			return
    72  		}
    73  		err = txn.GetError()
    74  	}
    75  	return
    76  }