Help us shape the future of Go! Take the 2026 Go Developer Survey

model

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 33 Imported by: 12

README

Yao Model Module

A Go module for database model operations with TypeScript API support.

Quick Example

Here's a simple example showing common model operations:

// Find a record by ID
const user = Process("models.user.Find", 1, {});

// Get records with query parameters
const users = Process("models.user.Get", {
  wheres: [{ column: "status", value: "active" }],
  limit: 10,
});

// Create a new record
const newUser = Process("models.user.Create", {
  name: "John Doe",
  email: "john@example.com",
  status: "active",
});

// Update a record
Process("models.user.Update", 1, { status: "inactive" });

// Delete a record
Process("models.user.Delete", 1);

Usage in TypeScript

You can use the Model module in TypeScript through the Process API. Below are examples of common operations with return type descriptions.

Model Instance Operations
Find a record by ID
/**
 * Finds a record by its ID
 * @param id - Record ID
 * @param params - Query parameters (optional)
 * @returns Record - The found record
 */
const user = Process("models.user.Find", 1, {
  select: ["id", "name", "email"],
  withs: { posts: {} },
});
Get records with query parameters
/**
 * Gets records with the given query parameters
 * @param params - Query parameters
 * @returns Record[] - Array of records
 */
const users = Process("models.user.Get", {
  select: ["id", "name", "email"],
  wheres: [{ column: "status", value: "active" }],
  orders: [{ column: "created_at", direction: "desc" }],
  limit: 10,
});
Paginate records
/**
 * Gets paginated records
 * @param params - Query parameters
 * @param page - Page number (1-based)
 * @param pageSize - Number of records per page
 * @returns object - Pagination result with data and pagination info
 */
const result = Process(
  "models.user.Paginate",
  {
    wheres: [{ column: "status", value: "active" }],
  },
  1,
  10
);
// Returns: { data: [...], pagination: { total: 100, page: 1, pagesize: 10, ... } }
Create a new record
/**
 * Creates a new record
 * @param data - Record data
 * @returns Record - The created record with ID
 */
const newUser = Process("models.user.Create", {
  name: "John Doe",
  email: "john@example.com",
  status: "active",
});
Update a record
/**
 * Updates a record by ID
 * @param id - Record ID
 * @param data - Data to update
 * @returns null
 */
Process("models.user.Update", 1, {
  name: "Updated Name",
  status: "inactive",
});
Save a record (Create or Update)
/**
 * Saves a record (creates if no ID present, updates if ID exists)
 * @param data - Record data
 * @returns Record - The saved record with ID
 */
const user = Process("models.user.Save", {
  id: 1, // If ID exists, record will be updated
  name: "John Doe",
  email: "john@example.com",
});
Delete a record (Soft Delete)
/**
 * Soft deletes a record by ID (sets deleted_at)
 * @param id - Record ID
 * @returns null
 */
Process("models.user.Delete", 1);
Destroy a record (Hard Delete)
/**
 * Hard deletes a record by ID (removes from database)
 * @param id - Record ID
 * @returns null
 */
Process("models.user.Destroy", 1);
Insert multiple records
/**
 * Inserts multiple records at once
 * @param columns - Array of column names
 * @param rows - Array of row data arrays
 * @returns null
 */
Process(
  "models.user.Insert",
  ["name", "email", "status"],
  [
    ["John Doe", "john@example.com", "active"],
    ["Jane Doe", "jane@example.com", "active"],
  ]
);
Update records with query
/**
 * Updates records matching the query
 * @param params - Query parameters
 * @param data - Data to update
 * @returns number - Number of updated records
 */
const count = Process(
  "models.user.UpdateWhere",
  {
    wheres: [{ column: "status", value: "pending" }],
  },
  {
    status: "active",
  }
);
Delete records with query (Soft Delete)
/**
 * Soft deletes records matching the query
 * @param params - Query parameters
 * @returns number - Number of deleted records
 */
const count = Process("models.user.DeleteWhere", {
  wheres: [{ column: "status", value: "inactive" }],
});
Destroy records with query (Hard Delete)
/**
 * Hard deletes records matching the query
 * @param params - Query parameters
 * @returns number - Number of destroyed records
 */
const count = Process("models.user.DestroyWhere", {
  wheres: [{ column: "status", value: "inactive" }],
});
Save multiple records
/**
 * Saves multiple records at once
 * @param rows - Array of records
 * @param commonData - Common data to apply to all records (optional)
 * @returns Record[] - The saved records with IDs
 */
const users = Process(
  "models.user.EachSave",
  [
    { name: "John", email: "john@example.com" },
    { name: "Jane", email: "jane@example.com" },
  ],
  {
    status: "active", // Will be applied to all records
  }
);
Delete and save records
/**
 * Deletes records with specified IDs and then saves new records
 * @param ids - Array of IDs to delete
 * @param rows - Array of records to save
 * @param commonData - Common data to apply to all records (optional)
 * @returns Record[] - The saved records with IDs
 */
const users = Process(
  "models.user.EachSaveAfterDelete",
  [1, 2, 3], // IDs to delete
  [
    { name: "John", email: "john@example.com" },
    { name: "Jane", email: "jane@example.com" },
  ],
  { status: "active" } // Optional common data
);
Upsert a record
/**
 * Inserts a record if it doesn't exist, updates it if it exists
 * @param data - Record data
 * @param uniqueBy - Column name(s) to check uniqueness
 * @param updateColumns - Columns to update if record exists (optional)
 * @returns any - ID of the upserted record
 */
const id = Process(
  "models.user.Upsert",
  { email: "john@example.com", name: "John Doe", status: "active" },
  "email", // Can be a string or array of strings
  ["name", "status"] // Optional columns to update
);
Model Schema Operations
Migrate a model
/**
 * Migrates the model schema to database
 * @param force - Whether to force recreation (optional, default: false)
 * @returns any - Migration result
 */
Process("models.user.Migrate", false);
Load a model
/**
 * Loads a model from file or source
 * @param file - Model file path
 * @param source - Optional model source code (if provided)
 * @returns any - Load result
 */
// Load from file
Process("models.user.Load", "user.mod.yao");

// Load from source
const source = `{
  "name": "User",
  "table": { "name": "users", "comment": "Users table" },
  "columns": [
    { "label": "ID", "name": "id", "type": "ID" },
    { "label": "Name", "name": "name", "type": "string", "length": 80 }
  ]
}`;
Process("models.user.Load", "user.mod.yao", source);
Reload a model
/**
 * Reloads a model from its file
 * @returns null
 */
Process("models.user.Reload");
Get model metadata
/**
 * Gets the model metadata
 * @returns object - Model metadata
 */
const metadata = Process("models.user.Metadata");
Read model source
/**
 * Reads the model source code
 * @returns string - Model source code
 */
const source = Process("models.user.Read");
Check if model exists
/**
 * Checks if a model is loaded
 * @returns boolean - Whether the model exists
 */
const exists = Process("models.user.Exists");
Snapshot Operations
Take a snapshot
/**
 * Creates a snapshot of the model
 * @param inMemory - Whether to store in memory only (true) or in database (false)
 * @returns string - Snapshot name
 */
const snapshot = Process("models.user.TakeSnapshot", false);
Restore a snapshot
/**
 * Restores a model from a snapshot
 * @param name - Snapshot name
 * @returns null
 */
Process("models.user.RestoreSnapshot", "user_snapshot_20230101");
Restore a snapshot by rename
/**
 * Restores a model from a snapshot by renaming tables
 * @param name - Snapshot name
 * @returns null
 */
Process("models.user.RestoreSnapshotByRename", "user_snapshot_20230101");
Drop a snapshot
/**
 * Drops a snapshot table
 * @param name - Snapshot name
 * @returns null
 */
Process("models.user.DropSnapshot", "user_snapshot_20230101");
Check if snapshot exists
/**
 * Checks if a snapshot exists
 * @param name - Snapshot name
 * @returns boolean - Whether the snapshot exists
 */
const exists = Process("models.user.SnapshotExists", "user_snapshot_20230101");
Global Model Operations
List all models
/**
 * Lists all loaded models
 * @param options - List options
 * @returns object[] - Array of model information
 */
const models = Process("model.List", {
  metadata: true, // Include metadata (optional)
  columns: true, // Include columns (optional)
});
Get model DSL
/**
 * Gets the model DSL (Domain Specific Language) definition
 * @param id - Model ID
 * @param options - DSL options
 * @returns object - Model DSL information
 */
const dsl = Process("model.DSL", "user", {
  metadata: true, // Include metadata (optional)
  columns: true, // Include columns (optional)
});
Check if model exists globally
/**
 * Checks if a model exists in the global registry
 * @param id - Model ID
 * @returns boolean - Whether the model exists
 */
const exists = Process("model.Exists", "user");
Reload a model globally
/**
 * Reloads a model in the global registry
 * @param id - Model ID
 * @returns null
 */
Process("model.Reload", "user");
Migrate a model globally
/**
 * Migrates a model in the global registry
 * @param id - Model ID
 * @param force - Whether to force recreation (optional)
 * @returns any - Migration result
 */
Process("model.Migrate", "user", false);
Load a model globally
/**
 * Loads a model in the global registry
 * @param id - Model ID
 * @param source - Model source code
 * @returns any - Load result
 */
Process("model.Load", "user", modelSourceJSON);
Unload a model globally
/**
 * Unloads a model from the global registry
 * @param id - Model ID
 * @returns null
 */
Process("model.Unload", "user");

Query Parameters Format

The query parameters object structure used in many operations:

interface QueryParam {
  // Columns to select
  select?: string[] | any[];

  // Where conditions
  wheres?: QueryWhere[];

  // Order specifications
  orders?: QueryOrder[];

  // Related models to include
  withs?: { [key: string]: QueryParam };

  // Number of records to return
  limit?: number;

  // Number of records to skip
  offset?: number;

  // Group by columns
  groups?: string[];

  // Having conditions
  havings?: QueryWhere[];
}

interface QueryWhere {
  column: string;
  op?: string; // Default: "="
  value: any;
}

interface QueryOrder {
  column: string;
  direction?: string; // "asc" or "desc", default: "asc"
}

Complete Workflow Example

// Migration
Process("models.user.Migrate", false);

// Create a record
const user = Process("models.user.Create", {
  name: "John Doe",
  email: "john@example.com",
  status: "active",
});

// Find by ID
const foundUser = Process("models.user.Find", user.id, {});

// Update
Process("models.user.Update", user.id, { status: "vip" });

// Take a snapshot
const snapshot = Process("models.user.TakeSnapshot", false);
console.log("Snapshot created:", snapshot);

// Make more changes
Process("models.user.Update", user.id, { name: "John Smith" });

// Restore from snapshot
Process("models.user.RestoreSnapshot", snapshot);

// Query to verify restoration
const restoredUser = Process("models.user.Find", user.id, {});
console.log("Restored user:", restoredUser); // Should have original name

// Clean up snapshot
Process("models.user.DropSnapshot", snapshot);

// Delete the user
Process("models.user.Delete", user.id);

Notes

  • The model module supports both soft deletes (via Delete and DeleteWhere) and hard deletes (via Destroy and DestroyWhere).
  • Use the appropriate snapshot operations carefully as they can affect database structure.
  • When using Upsert, make sure to provide meaningful uniqueBy columns to determine record existence.

Documentation

Index

Constants

View Source
const (
	RelHasOne         = "hasOne"         // 1 v 1
	RelHasMany        = "hasMany"        // 1 v n
	RelBelongsTo      = "belongsTo"      // inverse  1 v 1 / 1 v n / n v n
	RelHasOneThrough  = "hasOneThrough"  // 1 v 1 ( t1 <-> t2 <-> t3)
	RelHasManyThrough = "hasManyThrough" // 1 v n ( t1 <-> t2 <-> t3)
	RelBelongsToMany  = "belongsToMany"  // 1 v1 / 1 v n / n v n
	RelMorphOne       = "morphOne"
	RelMorphMany      = "morphMany"
	RelMorphToMany    = "morphToMany"
	RelMorphByMany    = "morphByMany"
	RelMorphMap       = "morphMap"
)

Relationship types

Variables

View Source
var Encryptors = map[string]*Encryptor{}

Encryptors 已加载加密器

View Source
var IEncryptors = map[string]IEncryptor{
	"AES":      &EncryptorAES{},
	"PASSWORD": &EncryptorPassword{},
}

IEncryptors 加密码器接口映射

View Source
var ModelHandlers = map[string]process.Handler{

	"find":                processFind,
	"get":                 processGet,
	"paginate":            processPaginate,
	"count":               processCount,
	"create":              processCreate,
	"update":              processUpdate,
	"save":                processSave,
	"delete":              processDelete,
	"destroy":             processDestroy,
	"insert":              processInsert,
	"updatewhere":         processUpdateWhere,
	"deletewhere":         processDeleteWhere,
	"destroywhere":        processDestroyWhere,
	"eachsave":            processEachSave,
	"eachsaveafterdelete": processEachSaveAfterDelete,
	"upsert":              processUpsert,

	"selectoption": processSelectOption,

	"takesnapshot":            processTakeSnapshot,
	"restoresnapshot":         processRestoreSnapshot,
	"restoresnapshotbyrename": processRestoreSnapshotByRename,
	"dropsnapshot":            processDropSnapshot,
	"snapshotexists":          processSnapshotExists,

	"migrate":  processMigrate,
	"load":     processLoad,
	"reload":   processReload,
	"metadata": processGetMetaData,
	"read":     processRead,
	"exists":   processExists,
}

ModelHandlers 模型运行器

View Source
var Models = map[string]*Model{}

Models 已载入模型

View Source
var Validations = map[string]func(value interface{}, row maps.MapStrAny, args ...interface{}) bool{
	"typof":     ValidationTypeof,
	"min":       ValidationMin,
	"max":       ValidationMax,
	"enum":      ValidationEnum,
	"pattern":   ValidationPattern,
	"minLength": ValidationMinLength,
	"maxLength": ValidationMaxLength,
	"email":     ValidationEmail,
	"mobile":    ValidationMobile,
}

Validations 数据校验函数

Functions

func Exists added in v1.0.0

func Exists(id string) bool

Exists checks if model exists

func Read added in v1.0.0

func Read(id string) []byte

Read reads model source

func ValidationEmail

func ValidationEmail(value interface{}, _ maps.MapStrAny, _ ...interface{}) bool

ValidationEmail 验证邮箱

func ValidationEnum

func ValidationEnum(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationEnum 枚举型

func ValidationMax

func ValidationMax(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationMax 最大值

func ValidationMaxLength

func ValidationMaxLength(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationMaxLength 最大长度

func ValidationMin

func ValidationMin(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationMin 最小值

func ValidationMinLength

func ValidationMinLength(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationMinLength 最小长度

func ValidationMobile

func ValidationMobile(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationMobile 验证手机号

func ValidationPattern

func ValidationPattern(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationPattern 正则匹配

func ValidationTypeof

func ValidationTypeof(value interface{}, _ maps.MapStrAny, args ...interface{}) bool

ValidationTypeof 校验数值类型

Types

type AccessScope added in v1.0.0

type AccessScope struct {
	CreatedBy string `json:"__yao_created_by,omitempty"` // The user ID who created the record
	UpdatedBy string `json:"__yao_updated_by,omitempty"` // The user ID who updated the record
	TeamID    string `json:"__yao_team_id,omitempty"`    // The team ID
	TenantID  string `json:"__yao_tenant_id,omitempty"`  // The tenant ID
}

AccessScope the data access scope for permission filtering

func NewAccessScope added in v1.0.0

func NewAccessScope(data ...interface{}) *AccessScope

NewAccessScope creates a new AccessScope instance Supports both maps.MapStr and map[string]interface{}

func (*AccessScope) Append added in v1.0.0

func (scope *AccessScope) Append(data interface{}) map[string]interface{}

Append appends AccessScope fields to data map for database insertion Supports both maps.MapStr and map[string]interface{}, returns map[string]interface{}

func (*AccessScope) Wheres added in v1.0.0

func (scope *AccessScope) Wheres(wheres []QueryWhere) []QueryWhere

Wheres converts AccessScope to QueryWhere conditions (includes all non-empty fields with AND logic)

func (*AccessScope) WheresCreatorAndEditor added in v1.0.0

func (scope *AccessScope) WheresCreatorAndEditor(wheres []QueryWhere) []QueryWhere

WheresCreatorAndEditor adds both creator and editor filters (AND logic) along with team/tenant

func (*AccessScope) WheresCreatorOnly added in v1.0.0

func (scope *AccessScope) WheresCreatorOnly(wheres []QueryWhere) []QueryWhere

WheresCreatorOnly adds only creator filter along with team/tenant

func (*AccessScope) WheresCreatorOrEditor added in v1.0.0

func (scope *AccessScope) WheresCreatorOrEditor(wheres []QueryWhere) []QueryWhere

WheresCreatorOrEditor adds creator or editor filter (OR logic) along with team/tenant

func (*AccessScope) WheresCreatorOrTeamOrEditor added in v1.0.0

func (scope *AccessScope) WheresCreatorOrTeamOrEditor(wheres []QueryWhere) []QueryWhere

WheresCreatorOrTeamOrEditor adds creator, team, or editor filter (OR logic) along with tenant

func (*AccessScope) WheresEditorOnly added in v1.0.0

func (scope *AccessScope) WheresEditorOnly(wheres []QueryWhere) []QueryWhere

WheresEditorOnly adds only editor filter along with team/tenant

func (*AccessScope) WheresTeamOnly added in v1.0.0

func (scope *AccessScope) WheresTeamOnly(wheres []QueryWhere) []QueryWhere

WheresTeamOnly adds only team and tenant filters

func (*AccessScope) WheresTeamOrCreator added in v1.0.0

func (scope *AccessScope) WheresTeamOrCreator(wheres []QueryWhere) []QueryWhere

WheresTeamOrCreator adds team or creator filter (OR logic) along with tenant

func (*AccessScope) WheresTeamOrEditor added in v1.0.0

func (scope *AccessScope) WheresTeamOrEditor(wheres []QueryWhere) []QueryWhere

WheresTeamOrEditor adds team or editor filter (OR logic) along with tenant

type Column

type Column struct {
	Label       string       `json:"label,omitempty"`
	Name        string       `json:"name"`
	Type        string       `json:"type,omitempty"`
	Title       string       `json:"title,omitempty"`
	Description string       `json:"description,omitempty"`
	Comment     string       `json:"comment,omitempty"`
	Length      int          `json:"length,omitempty"`
	Precision   int          `json:"precision,omitempty"`
	Scale       int          `json:"scale,omitempty"`
	Nullable    bool         `json:"nullable,omitempty"`
	Option      []string     `json:"option,omitempty"`
	Default     interface{}  `json:"default,omitempty"`
	DefaultRaw  string       `json:"default_raw,omitempty"`
	Example     interface{}  `json:"example,omitempty"`
	Generate    string       `json:"generate,omitempty"` // Increment, UUID,...
	Crypt       string       `json:"crypt,omitempty"`    // AES, PASSWORD, AES-256, AES-128, PASSWORD-HASH, ...
	Validations []Validation `json:"validations,omitempty"`
	Index       bool         `json:"index,omitempty"`
	Unique      bool         `json:"unique,omitempty"`
	Primary     bool         `json:"primary,omitempty"`
	// contains filtered or unexported fields
}

Column the field description struct

func (*Column) FliterIn

func (column *Column) FliterIn(value interface{}, row maps.MapStrAny)

FliterIn 输入过滤器

func (*Column) FliterOut

func (column *Column) FliterOut(value interface{}, row maps.MapStrAny, export ...string)

FliterOut 输出过滤器

func (*Column) Map

func (column *Column) Map() map[string]interface{}

Map 转换为Map

func (Column) SetOption

func (column Column) SetOption(col *schema.Column)

SetOption 设置字段选项

func (Column) SetType

func (column Column) SetType(table schema.Blueprint) *schema.Column

SetType 设置字段类型

func (*Column) Validate

func (column *Column) Validate(value interface{}, row maps.MapStrAny) (bool, []string)

Validate 数值有效性验证

type ColumnMap

type ColumnMap struct {
	Column *Column
	Model  *Model
	Export string // 取值时的变量名
}

ColumnMap ColumnMap 字段映射

type Encryptor

type Encryptor struct {
	Name   string `json:"-"`                // 名称
	Salt   string `json:"salt,omitempty"`   // 盐
	Key    string `json:"key,omitempty"`    // 钥匙
	Secret string `json:"secret,omitempty"` // 密钥
}

Encryptor 加密器

func WithCrypt

func WithCrypt(data []byte, name string) (*Encryptor, error)

WithCrypt 载入数据加密器

type EncryptorAES

type EncryptorAES struct{ *Encryptor }

EncryptorAES AES

func (EncryptorAES) Decode

func (aes EncryptorAES) Decode(field string) (string, error)

Decode AES Decode

func (EncryptorAES) Encode

func (aes EncryptorAES) Encode(value string) (string, error)

Encode AES Encode

func (*EncryptorAES) Set

func (aes *EncryptorAES) Set(crypt *Encryptor)

Set AES Encode

func (EncryptorAES) Validate

func (aes EncryptorAES) Validate(hash string, field string) bool

Validate AES Decode

type EncryptorAES128

type EncryptorAES128 struct{ Encryptor }

EncryptorAES128 AES 128

type EncryptorAES256

type EncryptorAES256 struct{ Encryptor }

EncryptorAES256 AES 256

type EncryptorPGCrypto added in v1.0.0

type EncryptorPGCrypto struct{ *Encryptor }

EncryptorPGCrypto uses PostgreSQL pgcrypto extension for AES-equivalent encryption

func (EncryptorPGCrypto) Decode added in v1.0.0

func (pg EncryptorPGCrypto) Decode(field string) (string, error)

Decode PGCrypto Decode — returns SQL expression using pgp_sym_decrypt + hex decoding

func (EncryptorPGCrypto) Encode added in v1.0.0

func (pg EncryptorPGCrypto) Encode(value string) (string, error)

Encode PGCrypto Encode — returns SQL expression using pgp_sym_encrypt + hex encoding

func (*EncryptorPGCrypto) Set added in v1.0.0

func (pg *EncryptorPGCrypto) Set(crypt *Encryptor)

Set PGCrypto Encryptor

func (EncryptorPGCrypto) Validate added in v1.0.0

func (pg EncryptorPGCrypto) Validate(hash string, field string) bool

Validate PGCrypto Validate

type EncryptorPassword

type EncryptorPassword struct{ *Encryptor }

EncryptorPassword 密码加密

func (EncryptorPassword) Decode

func (pwd EncryptorPassword) Decode(value string) (string, error)

Decode PASSWORD Decode

func (EncryptorPassword) Encode

func (pwd EncryptorPassword) Encode(value string) (string, error)

Encode PASSWORD Encode

func (*EncryptorPassword) Set

func (pwd *EncryptorPassword) Set(crypt *Encryptor)

Set AES Encode

func (EncryptorPassword) Validate

func (pwd EncryptorPassword) Validate(hash string, value string) bool

Validate PASSWORD Decode

type ExportData

type ExportData struct {
	Model   string          `json:"model"`
	Columns []string        `json:"columns"`
	Values  [][]interface{} `json:"values"`
}

ExportData the export data struct

type IEncryptor

type IEncryptor interface {
	Set(crypt *Encryptor)
	Encode(value string) (string, error)
	Decode(value string) (string, error)
	Validate(hash string, value string) bool
}

IEncryptor 加密器接口

func SelectCrypt

func SelectCrypt(name string) (IEncryptor, error)

SelectCrypt 选择加密器

type Index

type Index struct {
	Comment string   `json:"comment,omitempty"`
	Name    string   `json:"name,omitempty"`
	Columns []string `json:"columns,omitempty"`
	Type    string   `json:"type,omitempty"` // primary,unique,index,match
}

Index the search index struct

func (Index) SetIndex

func (index Index) SetIndex(table schema.Blueprint)

SetIndex 设置索引

type MetaData

type MetaData struct {
	types.MetaInfo
	Name      string              `json:"name,omitempty"`      // 元数据名称
	Connector string              `json:"connector,omitempty"` // Bind a connector, MySQL, SQLite, Postgres, Clickhouse, Tidb, Oracle support. default is SQLite
	Table     Table               `json:"table,omitempty"`     // 数据表选项
	Columns   []Column            `json:"columns,omitempty"`   // 字段定义
	Indexes   []Index             `json:"indexes,omitempty"`   // 索引定义
	Relations map[string]Relation `json:"relations,omitempty"` // 映射关系定义
	Values    []maps.MapStrAny    `json:"values,omitempty"`    // 初始数值
	Option    Option              `json:"option,omitempty"`    // 元数据配置
}

MetaData 元数据

func GetMetaData added in v1.0.0

func GetMetaData(id string) MetaData

GetMetaData gets model metadata

type MigrateOption added in v1.0.0

type MigrateOption func(*MigrateOptions)

MigrateOption Migrate option

func WithDonotInsertValues added in v1.0.0

func WithDonotInsertValues(v bool) MigrateOption

WithDonotInsertValues with donot insert values

type MigrateOptions added in v1.0.0

type MigrateOptions struct {
	DonotInsertValues bool `json:"donot_insert_values"`
}

MigrateOptions Migrate options

type Model

type Model struct {
	ID            string
	Name          string
	File          string
	Driver        string // Driver
	MetaData      MetaData
	Columns       map[string]*Column // 字段映射表
	ColumnNames   []interface{}      // 字段名称清单
	PrimaryKey    string             // 主键(单一主键)
	PrimaryKeys   []string           // 主键(联合主键)
	UniqueColumns []*Column          // 唯一字段清单
	// contains filtered or unexported fields
}

Model 数据模型

func Get added in v1.0.0

func Get(id string) (*Model, error)

Get gets a model by id, returns error if not found (instead of panic)

func Load

func Load(file string, id string) (*Model, error)

Load load model

func LoadSource added in v1.0.0

func LoadSource(source []byte, id string, file string) (*Model, error)

LoadSource load model from source

func LoadSourceSync added in v1.0.0

func LoadSourceSync(source []byte, id string, file string) (*Model, error)

LoadSourceSync load model sync

func LoadSync added in v1.0.0

func LoadSync(file string, id string) (*Model, error)

LoadSync load model sync

func Select

func Select(id string) *Model

Select selects a model

func (*Model) Blueprint

func (mod *Model) Blueprint() (types.Blueprint, error)

Blueprint cast to the blueprint struct

func (*Model) Count added in v1.0.0

func (mod *Model) Count(param QueryParam) (int, error)

Count count records with the given conditions

func (*Model) Create

func (mod *Model) Create(row maps.MapStrAny) (int, error)

Create 创建单条数据, 返回新创建数据ID

func (*Model) CreateTable

func (mod *Model) CreateTable() error

CreateTable create the table of the model

func (*Model) Delete

func (mod *Model) Delete(id interface{}) error

Delete 删除单条记录

func (*Model) DeleteWhere

func (mod *Model) DeleteWhere(param QueryParam) (int, error)

DeleteWhere 批量删除数据, 返回更新行数

func (*Model) Destroy

func (mod *Model) Destroy(id interface{}) error

Destroy 真删除单条记录

func (*Model) DestroyWhere

func (mod *Model) DestroyWhere(param QueryParam) (int, error)

DestroyWhere 批量真删除数据, 返回更新行数

func (*Model) DropSnapshotTable added in v1.0.0

func (mod *Model) DropSnapshotTable(name string) error

DropSnapshotTable Drop the snapshot table

func (*Model) DropTable

func (mod *Model) DropTable() error

DropTable drop the table of the model

func (*Model) EachSave

func (mod *Model) EachSave(rows []map[string]interface{}, eachrow ...maps.MapStrAny) ([]interface{}, error)

EachSave 批量保存数据, 返回数据ID集合

func (*Model) Export

func (mod *Model) Export(chunkSize int, process func(curr, total int)) ([]string, error)

Export the model

func (*Model) Filterselect

func (mod *Model) Filterselect(alias string, columns []interface{}, cmap map[string]ColumnMap, exportPrefix string) []interface{}

Filterselect 选择字段

func (*Model) Find

func (mod *Model) Find(id interface{}, param QueryParam) (maps.MapStr, error)

Find 查询单条记录

func (*Model) FliterIn

func (mod *Model) FliterIn(row maps.MapStrAny)

FliterIn 输入前过滤解码

func (*Model) FliterOut

func (mod *Model) FliterOut(row maps.MapStrAny)

FliterOut 输出前过滤解码

func (*Model) FliterWhere

func (mod *Model) FliterWhere(alias string, col interface{}) interface{}

FliterWhere 选项

func (*Model) Get

func (mod *Model) Get(param QueryParam) ([]maps.MapStr, error)

Get 按条件查询, 不分页

func (*Model) GetMetaInfo added in v1.0.0

func (mod *Model) GetMetaInfo() types.MetaInfo

GetMetaInfo returns the meta information of the model

func (*Model) HasTable

func (mod *Model) HasTable() (bool, error)

HasTable check if the table of the model is exists

func (*Model) Import

func (mod *Model) Import(file string) error

Import the data

func (*Model) Insert

func (mod *Model) Insert(columns []string, rows [][]interface{}) error

Insert 插入多条数据

func (*Model) InsertValues

func (mod *Model) InsertValues() ([]int, []error)

InsertValues insert the default values of the model

func (*Model) Migrate

func (mod *Model) Migrate(force bool, opts ...MigrateOption) error

Migrate 数据迁移

func (*Model) MustCount added in v1.0.0

func (mod *Model) MustCount(param QueryParam) int

MustCount count records with the given conditions, throw exception on error

func (*Model) MustCreate

func (mod *Model) MustCreate(row maps.MapStrAny) int

MustCreate 创建单条数据, 返回新创建数据ID, 失败抛出异常

func (*Model) MustDelete

func (mod *Model) MustDelete(id interface{})

MustDelete 删除单条记录, 失败抛出异常

func (*Model) MustDeleteWhere

func (mod *Model) MustDeleteWhere(param QueryParam) int

MustDeleteWhere 批量删除数据, 返回更新行数, 失败抛出异常

func (*Model) MustDestroy

func (mod *Model) MustDestroy(id interface{})

MustDestroy 真删除单条记录, 失败抛出异常

func (*Model) MustDestroyWhere

func (mod *Model) MustDestroyWhere(param QueryParam) int

MustDestroyWhere 批量真删除数据, 返回更新行数, 失败抛出异常

func (*Model) MustEachSave

func (mod *Model) MustEachSave(rows []map[string]interface{}, eachrow ...maps.MapStrAny) []interface{}

MustEachSave 批量保存数据, 返回数据ID集合, 失败抛出异常

func (*Model) MustFind

func (mod *Model) MustFind(id interface{}, param QueryParam) maps.MapStr

MustFind 查询单条记录

func (*Model) MustGet

func (mod *Model) MustGet(param QueryParam) []maps.MapStr

MustGet 按条件查询, 不分页, 失败抛出异常

func (*Model) MustInsert

func (mod *Model) MustInsert(columns []string, rows [][]interface{})

MustInsert 插入多条数据, 失败抛出异常

func (*Model) MustPaginate

func (mod *Model) MustPaginate(param QueryParam, page int, pagesize int) maps.MapStr

MustPaginate 按条件查询, 分页, 失败抛出异常

func (*Model) MustSave

func (mod *Model) MustSave(row maps.MapStrAny) interface{}

MustSave 保存单条数据, 返回数据ID, 失败抛出异常

func (*Model) MustUpdate

func (mod *Model) MustUpdate(id interface{}, row maps.MapStrAny)

MustUpdate 更新单条数据, 失败抛出异常

func (*Model) MustUpdateWhere

func (mod *Model) MustUpdateWhere(param QueryParam, row maps.MapStrAny) int

MustUpdateWhere 按条件更新记录, 返回更新行数, 失败抛出异常

func (*Model) MustUpsert added in v1.0.0

func (mod *Model) MustUpsert(row maps.MapStrAny, uniqueBy []interface{}, updateColumns []interface{}) int

MustUpsert Create or update a record matching the attributes, and fill it with values.

func (*Model) Paginate

func (mod *Model) Paginate(param QueryParam, page int, pagesize int) (maps.MapStr, error)

Paginate 按条件查询, 分页

func (*Model) QuoteIdentifier added in v1.0.0

func (mod *Model) QuoteIdentifier(name string) string

QuoteIdentifier wraps a column/table name with the correct quote character for the active driver. Handles dotted names like "alias.column" by quoting each segment individually (e.g. "alias"."column" for postgres).

func (*Model) Reload

func (mod *Model) Reload() (*Model, error)

Reload updates the model

func (*Model) RestoreSnapshot added in v1.0.0

func (mod *Model) RestoreSnapshot(name string) error

RestoreSnapshot Restore the model from the snapshot

func (*Model) RestoreSnapshotByRename added in v1.0.0

func (mod *Model) RestoreSnapshotByRename(name string) error

RestoreSnapshotByRename Restore the model from the snapshot by renaming the snapshot table

func (*Model) Save

func (mod *Model) Save(row maps.MapStrAny) (interface{}, error)

Save 保存单条数据, 不存在创建记录, 存在更新记录, 返回数据ID

func (*Model) SaveTable

func (mod *Model) SaveTable() error

SaveTable update or create the table of the model

func (*Model) SnapshotExists added in v1.0.0

func (mod *Model) SnapshotExists(name string) (bool, error)

SnapshotExists Check if the snapshot table exists

func (*Model) TakeSnapshot added in v1.0.0

func (mod *Model) TakeSnapshot(inMemory bool) (string, error)

TakeSnapshot Create a snapshot of the model

func (*Model) Update

func (mod *Model) Update(id interface{}, row maps.MapStrAny) error

Update 更新单条数据

func (*Model) UpdateWhere

func (mod *Model) UpdateWhere(param QueryParam, row maps.MapStrAny) (int, error)

UpdateWhere 按条件更新记录, 返回更新行数

func (*Model) Upsert added in v1.0.0

func (mod *Model) Upsert(row maps.MapStrAny, uniqueBy []interface{}, updateColumns []interface{}) (int, error)

Upsert new records or update the existing ones.

func (*Model) Validate

func (mod *Model) Validate(row maps.MapStrAny) []ValidateResponse

Validate 数值校验

type Option

type Option struct {
	Timestamps  bool `json:"timestamps,omitempty"`   // + created_at, updated_at 字段
	SoftDeletes bool `json:"soft_deletes,omitempty"` // + deleted_at 字段
	Trackings   bool `json:"trackings,omitempty"`    // + created_by, updated_by, deleted_by 字段
	Constraints bool `json:"constraints,omitempty"`  // + 约束定义
	Permission  bool `json:"permission,omitempty"`   // + __permission 字段
	Logging     bool `json:"logging,omitempty"`      // + __logging_id 字段
	Readonly    bool `json:"read_only,omitempty"`    // Ignore the migrate operation
}

Option 模型配置选项

type QueryOrder

type QueryOrder struct {
	Rel    string `json:"rel,omitempty"` // Relation Name
	Column string `json:"column"`
	Option string `json:"option,omitempty"` // desc, asc
}

QueryOrder Order 查询排序

type QueryParam

type QueryParam struct {
	Debug    bool            `json:"debug,omitempty"` // Whether to debug the query.
	Model    string          `json:"model,omitempty"`
	Table    string          `json:"table,omitempty"`
	Alias    string          `json:"alias,omitempty"`
	Export   string          `json:"export,omitempty"` // 导出前缀
	Select   []interface{}   `json:"select,omitempty"` // string | dbal.Raw
	Wheres   []QueryWhere    `json:"wheres,omitempty"`
	Orders   []QueryOrder    `json:"orders,omitempty"`
	Limit    int             `json:"limit,omitempty"`
	Page     int             `json:"page,omitempty"`
	PageSize int             `json:"pagesize,omitempty"`
	Withs    map[string]With `json:"withs,omitempty"`
}

QueryParam 数据查询器参数

func AnyToQueryParam

func AnyToQueryParam(v interface{}) (QueryParam, bool)

AnyToQueryParam interface 转换为 QueryParams

func URLToQueryParam

func URLToQueryParam(values url.Values) QueryParam

URLToQueryParam url.Values 转换为 QueryParams

func (QueryParam) NewQuery

func (param QueryParam) NewQuery() *QueryStack

NewQuery 新建查询栈

func (QueryParam) Order

func (param QueryParam) Order(order QueryOrder, qb query.Query, mod *Model)

Order 排序条件

func (QueryParam) Query

func (param QueryParam) Query(stack *QueryStack, stackParams ...QueryStackParam) *QueryStack

Query 构建查询栈(本版先实现,下一版本根据实际应用场景迭代)

func (QueryParam) Where

func (param QueryParam) Where(where QueryWhere, qb query.Query, mod *Model)

Where 查询条件

func (QueryParam) With

func (param QueryParam) With(name string, stack *QueryStack, with With, mod *Model)

With 关联查询

type QueryStack

type QueryStack struct {
	Builders []QueryStackBuilder
	Params   []QueryStackParam
	Current  int
}

QueryStack 查询栈

func MakeQueryStack

func MakeQueryStack() *QueryStack

MakeQueryStack 创建查询栈

func NewQueryStack

func NewQueryStack(param QueryParam) *QueryStack

NewQueryStack 新建查询栈

func (*QueryStack) Builder

func (stack *QueryStack) Builder() *QueryStackBuilder

Builder 返回当前查询构建器

func (*QueryStack) Count added in v1.0.0

func (stack *QueryStack) Count() (int64, error)

Count 统计记录数

func (*QueryStack) FirstQuery

func (stack *QueryStack) FirstQuery() query.Query

FirstQuery 返回第一个查询器

func (*QueryStack) Len

func (stack *QueryStack) Len() int

Len 查询器数量

func (*QueryStack) Merge

func (stack *QueryStack) Merge(new *QueryStack)

Merge 合并 Stack

func (*QueryStack) Next

func (stack *QueryStack) Next() int

Next 返回下一个查询器

func (*QueryStack) Paginate

func (stack *QueryStack) Paginate(page int, pagesize int) maps.MapStrAny

Paginate 执行查询栈(分页查询)

func (*QueryStack) Push

func (stack *QueryStack) Push(builder QueryStackBuilder, param QueryStackParam)

Push 添加查询器

func (*QueryStack) Query

func (stack *QueryStack) Query() query.Query

Query 返回当前查询器

func (*QueryStack) QueryParam

func (stack *QueryStack) QueryParam() QueryParam

QueryParam 返回当前查询参数

func (*QueryStack) Relation

func (stack *QueryStack) Relation() Relation

Relation 返回当前查询参数

func (*QueryStack) Run

func (stack *QueryStack) Run() []maps.MapStrAny

Run 执行查询栈

type QueryStackBuilder

type QueryStackBuilder struct {
	Model     *Model
	Query     query.Query
	ColumnMap map[string]ColumnMap
}

QueryStackBuilder 查询构建器

type QueryStackParam

type QueryStackParam struct {
	QueryParam   QueryParam
	Relation     Relation
	ExportPrefix string // 字段导出前缀
}

QueryStackParam QueryStack 查询参数

type QueryWhere

type QueryWhere struct {
	Rel    string       `json:"rel,omitempty"` // Relation Name
	Column interface{}  `json:"column,omitempty"`
	Value  interface{}  `json:"value,omitempty"`
	Method string       `json:"method,omitempty"` // where,orwhere, wherein, orwherein...
	OP     string       `json:"op,omitempty"`     // 操作 eq/gt/lt/ge/le/like...
	Wheres []QueryWhere `json:"wheres,omitempty"` // 分组查询
}

QueryWhere Where 查询条件

type Relation

type Relation struct {
	Name    string     `json:"-"`
	Type    string     `json:"type"`
	Key     string     `json:"key,omitempty"`
	Model   string     `json:"model,omitempty"`
	Foreign string     `json:"foreign,omitempty"`
	Links   []Relation `json:"links,omitempty"`
	Query   QueryParam `json:"query,omitempty"`
}

Relation the new xun model relation

type Table

type Table struct {
	Name        string   `json:"name,omitempty"`   // optional, if not set, the default is generate from model name. eg name.space.user, table name is name_space_user
	Prefix      string   `json:"prefix,omitempty"` // optional, the table prefix
	Comment     string   `json:"comment,omitempty"`
	Engine      string   `json:"engine,omitempty"` // InnoDB,MyISAM ( MySQL Only )
	Collation   string   `json:"collation"`
	Charset     string   `json:"charset"`
	PrimaryKeys []string `json:"primarykeys"`
}

Table the model mapping table in DB

type ValidateResponse

type ValidateResponse struct {
	Line     int      `json:"line,omitempty"`
	Column   string   `json:"column,omitempty"`
	Messages []string `json:"messages,omitempty"`
}

ValidateResponse 数据校验返回结果

type Validation

type Validation struct {
	Method  string        `json:"method"`
	Args    []interface{} `json:"args,omitempty"`
	Message string        `json:"message,omitempty"`
}

Validation the field validation struct

type With

type With struct {
	Name  string     `json:"name"`
	Query QueryParam `json:"query,omitempty"`
}

With relations 关联查询

Jump to

Keyboard shortcuts

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