gorm_datatypes.go

Overview

The gorm_datatypes.go file defines custom data types that facilitate the serialization and deserialization of JSON-like data structures for storage in SQL databases using the GORM ORM library. It provides two primary custom types—stateMap and dynamicJSON—that implement the necessary interfaces to allow seamless reading and writing of JSON data to various SQL dialects supported by GORM, including PostgreSQL, MySQL, and Google Spanner.

These types abstract away database-specific JSON handling by implementing GORM's Serializer interfaces and Go's standard driver.Valuer and sql.Scanner interfaces, ensuring JSON data is encoded/decoded correctly and stored using the optimal data type for each database. This improves data integrity and portability across different database backends.

Types and Their Implementations

stateMap

stateMap is a custom type defined as an alias for map[string]any, representing a flexible JSON-like structure with string keys and arbitrary value types.

type stateMap map[string]any

Purpose

Methods

Usage Example

var sm stateMap
err := db.First(&model).Error
if err != nil {
    // handle error
}
jsonValue, err := sm.Value()
if err != nil {
    // handle error
}
fmt.Println("Serialized JSON:", jsonValue)

dynamicJSON

dynamicJSON is a type alias for json.RawMessage, which represents raw encoded JSON data as a byte slice.

type dynamicJSON json.RawMessage

Purpose

Methods

Usage Example

var dj dynamicJSON
err := db.First(&model).Error
if err != nil {
    // handle error
}
fmt.Println("Raw JSON string:", dj.String())

Important Implementation Details


Interaction with Other System Components


Structure Diagram

classDiagram
class stateMap {
+GormDataType()
+GormDBDataType(db, field)
+Value()
+Scan(value)
+GormValue(ctx, db)
}
class dynamicJSON {
+GormDataType()
+GormDBDataType(db, field)
+Value()
+Scan(value)
+String()
+GormValue(ctx, db)
}

The diagram illustrates the two main types stateMap and dynamicJSON with their primary methods responsible for JSON serialization, deserialization, and database type specification. Both types implement similar interfaces but differ in internal data representation and validation approach.