github.com/erda-project/erda-infra@v1.0.9/providers/mysql/v2/plugins/fields/uuid.go (about)

     1  // Copyright (c) 2021 Terminus, 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  // 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 fields
    16  
    17  import (
    18  	"database/sql"
    19  	"database/sql/driver"
    20  
    21  	"github.com/google/uuid"
    22  	"gorm.io/gorm"
    23  	"gorm.io/gorm/clause"
    24  	"gorm.io/gorm/schema"
    25  )
    26  
    27  // UUID auto generate an uuid on creating record.
    28  type UUID sql.NullString
    29  
    30  // Scan .
    31  func (u *UUID) Scan(value interface{}) error {
    32  	return (*sql.NullString)(u).Scan(value)
    33  }
    34  
    35  // Value .
    36  func (u UUID) Value() (driver.Value, error) {
    37  	return sql.NullString(u).Value()
    38  }
    39  
    40  // MustValue returns u.String
    41  func (u UUID) MustValue() string {
    42  	return u.String
    43  }
    44  
    45  // CreateClauses .
    46  func (UUID) CreateClauses(f *schema.Field) []clause.Interface {
    47  	return []clause.Interface{UUIDCreateClause{Field: f}}
    48  }
    49  
    50  // UUIDCreateClause .
    51  type UUIDCreateClause struct {
    52  	Field *schema.Field
    53  }
    54  
    55  // Name .
    56  func (cc UUIDCreateClause) Name() string {
    57  	return ""
    58  }
    59  
    60  // Build .
    61  func (cc UUIDCreateClause) Build(clause.Builder) {
    62  }
    63  
    64  // MergeClause .
    65  func (cc UUIDCreateClause) MergeClause(*clause.Clause) {
    66  }
    67  
    68  // ModifyStatement .
    69  func (cc UUIDCreateClause) ModifyStatement(stmt *gorm.Statement) {
    70  	stmt.SetColumn(cc.Field.Name, UUID{
    71  		String: uuid.New().String(),
    72  		Valid:  true,
    73  	})
    74  }