gorm

package module
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 20, 2024 License: Apache-2.0 Imports: 12 Imported by: 5

README

go-gorm-spanner

go.dev reference

Google Cloud Spanner ORM for Go's GORM implementation.

import (
    "gorm.io/gorm"
    _ "github.com/googleapis/go-sql-spanner"

    spannergorm "github.com/googleapis/go-gorm-spanner"
)

db, err := gorm.Open(spannergorm.New(spannergorm.Config{
    DriverName: "spanner",
    DSN:        "projects/PROJECT/instances/INSTANCE/databases/DATABASE",
}), &gorm.Config{PrepareStmt: true})
if err != nil {
    log.Fatal(err)
}

// Print singers with more than 500 likes.
type Singer struct {
    gorm.Model
    Text         string
    Likes        int
}
var singers []Singer
if err := db.Where("likes > ?", 500).Find(&singers).Error; err != nil {
    log.Fatal(err)
}
for s := range singers {
    fmt.Println(s.ID, s.Text)
}
Connection URL Properties

The Cloud Spanner GORM supports the following connection URL properties

Commonly Used Properties
  • credentials (String): File name for the credentials to use. The connection will use the default credentials of the environment if no credentials file is specified in the connection string. Example: projects/my-project/instances/my-instance/databases/my-db;credentials=/path/to/credentials.json
  • optimizerVersion (String): Sets the default query optimizer version to use for this connection. See also https://cloud.google.com/spanner/docs/query-optimizer/query-optimizer-versions.
Advanced Properties
  • minSessions (int): Sets the minimum number of sessions in the backing session pool. Defaults to 100.
  • maxSessions (int): Sets the maximum number of sessions in the backing session pool. Defaults to 400.
  • numChannels (int): Sets the number of gRPC channels to use. Defaults to 4.
  • retryAbortsInternally (boolean): Boolean that indicates whether the connection should automatically retry aborted errors. The default is true.
  • disableRouteToLeader (boolean): Boolean that indicates if all the requests of type read-write and PDML need to be routed to the leader region. The default is false.
  • usePlainText (boolean): : Boolean that indicates whether the connection should use plain text communication or not. Set this to true to connect to local mock servers that do not use SSL. Example: projects/test-project/instances/test-instance/databases/test-db;usePlainText=true

Example: projects/my-project/instances/my-instance/databases/my-db;minSessions=100;maxSessions=400;numChannels=4;retryAbortsInternally=true;disableRouteToLeader=false;usePlainText=false

Emulator

See the Google Cloud Spanner Emulator support to learn how to start the emulator. When the emulator has been started and the environment variable has been set, gorm will automatically connect to the emulator instead of Cloud Spanner.

$ gcloud emulators spanner start
$ export SPANNER_EMULATOR_HOST=localhost:9010

Go Versions Supported

Our libraries are compatible with at least the three most recent, major Go releases. They are currently compatible with:

  • Go 1.21
  • Go 1.20
  • Go 1.19

Data Types

Cloud Spanner supports the following data types in combination with gorm.

Cloud Spanner Type gorm / go type
bool bool, sql.NullBool
int64 uint, int64, sql.NullInt64
string string, sql.NullString
json string, sql.NullString
float64 float64, sql.NullFloat64
float32 float32, spanner.NullFloat32
numeric decimal.NullDecimal
timestamp with time zone time.Time, sql.NullTime
date datatypes.Date
bytes []byte

Limitations

The Cloud Spanner gorm dialect has the following known limitations:

Limitation Workaround
OnConflict OnConflict clauses are not supported
Nested transactions Nested transactions and savepoints are not supported. It is therefore recommended to set the configuration option DisableNestedTransaction: true,
Locking Lock clauses (e.g. clause.Locking{Strength: "UPDATE"}) are not supported. These are generally speaking also not required, as the default isolation level that is used by Cloud Spanner is serializable.
Auto-save associations Auto saved associations are not supported, as these will automatically use an OnConflict clause
gorm.Automigrate with interleaved tables Interleaved tables are supported by the Cloud Spanner gorm dialect, but Auto-Migration does not support interleaved tables. It is therefore recommended to create interleaved tables manually.
Cloud Spanner stale reads Stale reads are not supported by gorm.

For the complete list of the limitations, see the Cloud Spanner GORM limitations.

OnConflict Clauses

OnConflict clauses are not supported by Cloud Spanner and should not be used. The following will therefore not work.

user := User{
    ID:   1,
    Name: "User Name",
}
// OnConflict is not supported and this will return an error.
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&user)
Auto-save Associations

Auto-saving associations will automatically use an OnConflict clause in gorm. These are not supported. Instead, the parent entity of the association must be created before the child entity is created.

blog := Blog{
    ID:     1,
    Name:   "",
    UserID: 1,
    User: User{
        ID:   1,
        Name: "User Name",
    },
}
// This will fail, as the insert statement for User will use an OnConflict clause.
db.Create(&blog).Error

Instead, do the following:

user := User{
    ID:   1,
    Name: "User Name",
    Age:  20,
}
blog := Blog{
    ID:     1,
    Name:   "",
    UserID: 1,
}
db.Create(&user)
db.Create(&blog)
Nested Transactions

gorm uses savepoints for nested transactions. Savepoints are currently not supported by Cloud Spanner. Nested transactions can therefore not be used with GORM.

Locking

Locking clauses, like clause.Locking{Strength: "UPDATE"}, are not supported. These are generally speaking also not required, as Cloud Spanner uses isolation level serializable for read/write transactions.

Authorization

By default, each API will use Google Application Default Credentials for authorization credentials used in calling the API endpoints. This will allow your application to run in many environments without requiring explicit configuration.

Contributing

Contributions are welcome. Please, see the CONTRIBUTING document for details.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See Contributor Code of Conduct for more information.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BeforeUpdate

func BeforeUpdate(db *gorm.DB)

func New

func New(config Config) gorm.Dialector

func Open

func Open(dsn string) gorm.Dialector

Types

type Column

type Column struct {
	// contains filtered or unexported fields
}

func (Column) DatabaseTypeName

func (c Column) DatabaseTypeName() string

func (Column) DecimalSize

func (c Column) DecimalSize() (int64, int64, bool)

DecimalSize return precision int64, scale int64, ok bool

func (Column) Length

func (c Column) Length() (int64, bool)

func (Column) Name

func (c Column) Name() string

func (Column) Nullable

func (c Column) Nullable() (bool, bool)

type CommitTimestamp

type CommitTimestamp struct {
	Timestamp sql.NullTime
}

CommitTimestamp can be used for columns that should write the PENDING_COMMIT_TIMESTAMP(). Use it as the type for a field in a model. The corresponding database column must be of type TIMESTAMP, and the option `allow_commit_timestamp=true` must have been set. The Spanner gorm migrator will automatically create a TIMESTAMP column with the `allow_commit_timestamp=true` option enabled for any field that has type CommitTimestamp.

Note that the commit timestamp is not returned directly after inserting/updating a row. Instead, the value can only be read after the transaction has been committed.

Example:

type Singer struct {
  ID          int64
  Name        string
  LastUpdated CommitTimestamp
}

func (CommitTimestamp) GormDataType

func (ct CommitTimestamp) GormDataType() string

GormDataType implements gorm.GormDataTypeInterface.

func (CommitTimestamp) GormValue

func (ct CommitTimestamp) GormValue(ctx context.Context, db *gorm.DB) clause.Expr

GormValue implements the gorm.Valuer interface.

func (*CommitTimestamp) Scan

func (ct *CommitTimestamp) Scan(v interface{}) error

Scan implements the sql.Scanner interface

type Config

type Config struct {
	DriverName string
	DSN        string
	Conn       gorm.ConnPool

	// DisableAutoMigrateBatching turns off DDL batching for AutoMigrate calls.
	// Cloud Spanner by default uses DDL batching when AutoMigrate is called, as
	// executing multiple DDL statements in a single batch is a lot more efficient
	// than executing each statement separately. You should only use this option
	// if you are experiencing problems with the automatic batching of DDL
	// statements when calling AutoMigrate.
	DisableAutoMigrateBatching bool
}

type Dialector

type Dialector struct {
	*Config
}

func (Dialector) BindVarTo

func (dialector Dialector) BindVarTo(writer clause.Writer, stmt *gorm.Statement, v interface{})

func (Dialector) DataTypeOf

func (dialector Dialector) DataTypeOf(field *schema.Field) string

func (Dialector) DefaultValueOf

func (dialector Dialector) DefaultValueOf(field *schema.Field) clause.Expression

func (Dialector) Explain

func (dialector Dialector) Explain(sql string, vars ...interface{}) string

func (Dialector) Initialize

func (dialector Dialector) Initialize(db *gorm.DB) (err error)

func (Dialector) Migrator

func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator

func (Dialector) Name

func (dialector Dialector) Name() string

func (Dialector) QuoteTo

func (dialector Dialector) QuoteTo(writer clause.Writer, str string)

type Exprs

type Exprs []clause.Expression

func (Exprs) Build

func (exprs Exprs) Build(builder clause.Builder)

type IndexHint

type IndexHint struct {
	Type string
	Key  string
}

func ForceIndex

func ForceIndex(name string) IndexHint

func (IndexHint) Build

func (indexHint IndexHint) Build(builder clause.Builder)

func (IndexHint) ModifyStatement

func (indexHint IndexHint) ModifyStatement(stmt *gorm.Statement)

type SpannerMigrator

type SpannerMigrator interface {
	gorm.Migrator

	StartBatchDDL() error
	RunBatch() error
	AbortBatch() error
}

Directories

Path Synopsis
samples module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL