github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/engine/pkg/orm/mock.go (about)

     1  // Copyright 2022 PingCAP, Inc.
     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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package orm
    15  
    16  import (
    17  	"context"
    18  	"fmt"
    19  	"time"
    20  
    21  	"github.com/pingcap/log"
    22  	"github.com/pingcap/tiflow/engine/pkg/meta/mock"
    23  	metaModel "github.com/pingcap/tiflow/engine/pkg/meta/model"
    24  	"github.com/pingcap/tiflow/pkg/uuid"
    25  	"go.uber.org/zap"
    26  )
    27  
    28  func randomDBFile() string {
    29  	return uuid.NewGenerator().NewString() + ".db"
    30  }
    31  
    32  // NewMockClient creates a mock orm client
    33  func NewMockClient() (Client, error) {
    34  	// ref:https://www.sqlite.org/inmemorydb.html
    35  	// using dsn(file:%s?mode=memory&cache=shared) format here to
    36  	// 1. Create different DB for different TestXXX() to enable concurrent execution
    37  	// 2. Enable DB shared for different connection
    38  	dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", randomDBFile())
    39  	cc, err := mock.NewClientConnForSQLite(dsn)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    45  	defer cancel()
    46  	if err := InitAllFrameworkModels(ctx, cc); err != nil {
    47  		log.Error("initialize all framework models fail", zap.Error(err))
    48  		cc.Close()
    49  		return nil, err
    50  	}
    51  
    52  	cli, err := NewClient(cc)
    53  	if err != nil {
    54  		log.Error("new mock client fail", zap.Error(err))
    55  		cc.Close()
    56  		return nil, err
    57  	}
    58  
    59  	return &sqliteClient{
    60  		Client: cli,
    61  		conn:   cc,
    62  	}, nil
    63  }
    64  
    65  type sqliteClient struct {
    66  	Client
    67  	conn metaModel.ClientConn
    68  }
    69  
    70  func (c *sqliteClient) Close() error {
    71  	if c.Client != nil {
    72  		c.Client.Close()
    73  	}
    74  
    75  	if c.conn != nil {
    76  		c.conn.Close()
    77  	}
    78  
    79  	return nil
    80  }