Documentation
¶
Overview ¶
Package schema describes a database schema in a human-readable way.
Index ¶
- Constants
- func SanitizeIdentifier(input string) string
- func SanitizePackageName(input string) string
- func WriteJsonFile(schema *Database, outFile string)
- type AssociationReference
- type AssociationTable
- type Column
- type ColumnSubType
- type ColumnType
- type Database
- type EnumField
- type EnumTable
- type Index
- type IndexLevel
- type Reference
- type Table
Constants ¶
const ( ColumnDefaultNow = "now" ColumnDefaultUpdate = "update" ColumnDefaultUUIDV1 = "uuidv1" ColumnDefaultUUIDV4 = "uuidv4" ColumnDefaultUUIDV7 = "uuidv7" ColumnDefaultRecordId )
const GroLockColumnName = "gro_lock"
GroLockColumnName is the convention for the name of a ColSubTypeLock column that will also be used to perform optimistic locking by the ORM.
const GroTimestampColumnName = "gro_timestamp"
GroTimestampColumnName is the convention for the name of a ColSubTypeTimestamp column that will automatically be updated with the UnixMicro time upon saving of the record.
const KeyKey = "key"
const LabelKey = "label"
const NameKey = "name"
const ValueKey = "value"
const Version = 1
Variables ¶
This section is empty.
Functions ¶
func SanitizeIdentifier ¶
SanitizeIdentifier will sanitize Go identifiers, allowing CamelCase and camelCase, but converting all other characters to underscores.
func SanitizePackageName ¶
SanitizePackageName returns a string that is valid as a Go package name. It only allows lowercase letters and digits, replacing all other characters with underscores. Uppercase letters are converted to lowercase. If the result starts with a non-letter or is a reserved keyword, it prepends an underscore.
func WriteJsonFile ¶
Types ¶
type AssociationReference ¶
type AssociationReference struct {
// Table is the name of the table being referenced.
// If Table is the same as the column's table, it creates a parent-child relationship.
// Should match a Table.Name value in another table.
Table string `json:"table"`
// Schema is the schema that Table is in.
Schema string `json:"schema,omitempty"`
// Column is the name of the column created in the association table to hold a duplicate of the private key in Table.
// It will default to a name based on Table and the name of the primary key column in Table.
Column string `json:"column,omitempty"`
// Identifier is the Go name used for the referenced object.
// If not specified, will be based on Column.
Identifier string `json:"identifier,omitempty"`
// IdentifierPlural is the plural of Identifier.
// Will be based on Identifier if left blank.
IdentifierPlural string `json:"identifierPlural,omitempty"`
// Label is the human-readable name for the referenced object.
// If not specified, will be based on Identifier.
Label string `json:"label,omitempty"`
// LabelPlural is the plural of Label
LabelPlural string `json:"labelPlural,omitempty"`
}
AssociationReference describes a link from an association table.
func (*AssociationReference) QualifiedTableName ¶
func (r *AssociationReference) QualifiedTableName() string
type AssociationTable ¶
type AssociationTable struct {
// Table is the name of the association table in the database. It should be lower_snake_case and end
// with the Database.AssnTableSuffix value.
// Example: "project_team_member_assn"
Table string `json:"name"`
// For databases that support schemas, this is the name of the schema of the table.
// Leave blank for the default schema.
// Databases that do not support schemas will have this prepended to the name of the table if this is present.
Schema string `json:"schema,omitempty"`
// Ref1 references the first table in the many-many relationship
Ref1 AssociationReference `json:"ref1"`
// Ref2 references the second table in the many-many relationship
Ref2 AssociationReference `json:"ref2"`
// Comment is a place to put a comment in the JSON schema file.
// If the database driver supports it, it may be put in the database.
Comment string `json:"comment,omitempty"`
}
AssociationTable describes a table in the database that will be used to create a many-to-many relationship between two tables.
func (*AssociationTable) QualifiedTableName ¶
func (t *AssociationTable) QualifiedTableName() string
type Column ¶
type Column struct {
// Name is the name of the column in the database.
//
// If an enum column, by convention the name can be one of the following forms:
// - enumtype
// - tablename_enumtype
// - enumtype_enum
// - tablename_enumtype_enum
// For example, if this table is named "person", and the enum table is named "status",
// then by convention the name can be: status, person_status, status_enum, or person_status_enum.
// If this convention is not followed, then the EnumTable should include the name of the enum table.
Name string `json:"name"`
// Type is the type of column. See the doc for ColumnType for more info.
Type ColumnType `json:"type"`
// SubType further describes how the database treats the type.
SubType ColumnSubType `json:"sub_type,omitempty"`
// If a string column, Size is the maximum length of runes that the column can accommodate.
// If a []byte column, Size is the maximum number of bytes allowed in the column.
// If an int, unsigned int, or float, Size is the number of bits allowed in the number and will also
// determine the Go number type that will represent the column. This can be a zero in order to use the default,
// which will be 32-bits for ints (the SQL default), or 64-bits for floats.
Size uint64 `json:"size,omitempty"`
// DefaultValue is the value that this field will be initialized to when a new object is created.
// If not specified, it will be the zero value of the column's type.
// Non-nullable columns that do not have a default value are required to be set by the application
// before the object is saved.
// Time columns can use the string "now" to set the value to the current time when the object
// is first saved, and "update" to also set the value to the current time every time the object
// is modified and saved.
DefaultValue interface{} `json:"default_value,omitempty"`
// IsNullable is true if the column can be given a NULL value.
IsNullable bool `json:"nullable,omitempty"`
// IndexLevel indicates what kind of single-column index is associated with this column.
// ColTypeAutoPrimaryKey columns by default will be given a single primary key index.
// At least one primary key index must be specified.
// See Table.Indexes for specifying a multi-column index.
IndexLevel IndexLevel `json:"index_level,omitempty"`
// Identifier is the name of the column in Go code. Leave blank to base it on the Name.
// Should be CamelCase. For example: "LastName".
Identifier string `json:"identifier,omitempty"`
// Label is the human-readable description of the item. Leave blank to base it on the Identifier.
// Should be title case.
// For example: "Last Name".
Label string `json:"label,omitempty"`
// DatabaseDefinition contains database specific extra information on the column that helps the database driver
// recreate the column in the database if needed. The top key is a db.DriverType constant, and the secondary key is the
// type of information. For example, a DECIMAL field might look like this:
// {"mysql":{"type":"decimal(5,2)"},"sqllite":{"type":"string"}}
// This would indicate that in Mysql, the column is defined as DECIMAL(5,2), but in Sqllite, as a string.
// The information recognized is specific to the database driver.
DatabaseDefinition map[string]map[string]interface{} `json:"database_def,omitempty"`
// Comment is a place to put a comment in the JSON description file. If the database driver supports it, it may be put in the database..
Comment string `json:"comment,omitempty"`
// EnumTable is the enum table if the Type is ColTypeEnum.
EnumTable string `json:"enum_table,omitempty"`
}
Column represents a database column with its attributes and associated metadata.
type ColumnSubType ¶
type ColumnSubType int
ColumnSubType provides more description to a particular type
const ( // ColSubTypeNone indicates no subtype and is the default ColSubTypeNone ColumnSubType = iota // ColSubTypeDateOnly is for time columns that only contain a date. // The time will be in UTC and will have zero values for hour, minute, seconds, and nanoseconds ColSubTypeDateOnly // ColSubTypeTimeOnly is for time columns that have no date component. // Date components will be 1-1-1 at timezone will be UTC. // Care must be taken when converting string times, since time.Parse will return a time with date component 1-1-0, // however, some database drivers will not accept a 1-1-0 time, even when setting a time-only column. ColSubTypeTimeOnly // ColSubTypeTimestamp is an int64 column that will automatically be given the UnixMicro value when a record is // successfully inserted or updated. ColSubTypeTimestamp // ColSubTypeLock is an int64 column that contains a record version number that will be used to optimistically // lock the record while saving. The value is automatically generated and will be unique even across multiple // instances of the application. ColSubTypeLock // ColSubTypeNumeric is a string that only accepts numeric values, as in positive or negative numbers with // a decimal point, and represents an arbitrary precision value. // Some SQL databases use a NUMERIC or DECIMAL column to represent these, // and NoSQL generally just supports this natively. // This is not a floating point number, as those numbers can have precision limitations. // Because of this, numeric values are preferred when storing currency values. // See the math/big package for working with these types of values in Go. // // Note: Although SQLite has a NUMERIC type, it // is not actually an arbitrary precision value, but rather in some cases could be converted to a REAL with // a loss of precision, so the ORM will store these as a string in SQLite. One result of this is that database numeric // operations will panic if attempted on these in SQLite. ColSubTypeNumeric // ColSubTypeRandom initializes UUID or ULID values to random values. ColSubTypeRandom )
func (ColumnSubType) MarshalJSON ¶
func (cst ColumnSubType) MarshalJSON() ([]byte, error)
MarshalJSON customizes how ColumnType is serialized to JSON.
func (ColumnSubType) String ¶
func (ct ColumnSubType) String() string
String returns the string representation of a ColumnType.
func (*ColumnSubType) UnmarshalJSON ¶
func (cst *ColumnSubType) UnmarshalJSON(data []byte) error
UnmarshalJSON customizes how ColumnType is deserialized from JSON.
type ColumnType ¶
type ColumnType int
ColumnType is a general specifier for the type of column in a database.
Mapping data types in Go to data types in databases is tricky, and necessarily puts limitations on what kinds of data can be represented and how it is stored. The ORM provides some flexibility by allowing each column to specify its database type, while also specifying its Go type by using a combination of the DatabaseType, VariableType and Size fields as described below.
ColTypeUnknown ¶
This is a column type that is unknown to the orm and that will be provided to Go as a []byte slice. Many databases have non-standard or custom data types or types that simply don't fit well in Go. For example, the NUMERIC or DECIMAL type in many databases is an exact precision decimal number for which there is no equivalent in Go, since Go uses floating point numbers to represent decimal numbers. To provide data of this type to your application, you can create a custom type in Go, and then create accessor functions that translate between the database representation and your custom type.
See Column.DatabaseDefinition for a way to specify the database specific type info for this column.
ColTypeBytes ¶
This is known as a BLOB type in many SQL databases, and is represented as a []byte slice in Go. If Column.Size is non-zero, the data definition will use this in the schema definition. Different databases treat this differently, and may or may not truncate the data internally.
Attempting to insert a byte blob with a size bigger than Column.Size will panic in order to protect the integrity of the database. However, if a process outside the ORM sets the value to a size bigger than Column.Size, the value can be read by the ORM and it will not be truncated.
ColTypeString ¶
ColTypeString is always represented as a string in Go, but may have a variety of representations in the database depending on the Size value and the database.
In order to protect data integrity, if a Column.Size is non-zero, the generated code will panic if an attempt is made to set the value to a string whose rune size is greater than Column.Size. Note that rune size is not the same as byte size. If a process outside the ORM sets the value larger than Column.Size runes, the value can be read by the ORM and will not be truncated.
Postgres doc states the TEXT type is the fastest and most efficient text storage type, and by default this will always be the corresponding data type in Postgres.
MySQL will use a VarChar(Size) if a Column.Size is present, and a Text if not. Mysql stores VarChar variables inside the table, and Text data outside of the table with a reference, so VarChar is more efficient.
By default, collation will be by UTF8 case-sensitive rules. Set the Sort to case-insensitive to change this to case-insensitive. Other collations are outside the capabilities of the ORM and you should directly edit the database to set those up.
ColTypeInt and ColTypeUint ¶
These integer column types will be represented in Go as int or uint, and in the database as a 32-bit integer or unsigned integer by default. To specifically set the storage size, specify either 8, 16, 32 or 64 in the Size value, and the corresponding Go type will be used, as well as the corresponding type in the database. Not all databases support 8-bit integers. Check your database vendor to be sure.
An int64 column may have the subtype of ColSubTypeTimestamp or ColSubTypeLock. ColSubTypeTimestamp indicates that the column will be filled in with time.Now().UnixMicro() when the record is saved. However, if a new value is computed, and the old value is greater than the new value, the new value will add one to the value. This prevents the scenario where separate systems with unsynchronized clocks might create a later value that would appear earlier, in case the timestamp is being used for UI synchronization. Combine with another column with ColSubTypeLock to make sure a race condition between systems will not possibly break this process, though if the app is not running scaled on multiple systems, this is unnecessary. ColSubTypeLock columns will store a version number and be used by the ORM to implement optimistic locking. Convention is to name these columns "gro_timestamp" and "gro_lock".
ColTypeTime ¶
This corresponds to a datetime in most databases. The value is stored in UTC time in the database, and when read back from the database, will initially be in UTC time. Usually this is what is wanted, since it allows times from different timezones to be correctly sorted, and javascript and other libraries are capable of converting UTC time to local time in the client locale for display purposes. MySQL will store the value as a DateTime and not a Timestamp, since Timestamps are assumed to be in server local time and not UTC time and get time shifted in transit. Also, some MySQLs have the yr2038 bug. Postgres uses Timestamp without timezone (which is the default). See the Column.DefaultValue doc for time specific behavior of default values.
ColTypeFloat ¶
By default, this will be a float64 value in Go, and double precision float in the database. Specify a MaxSize of 32 to make this a float32 and single precision float in the database (if supported). Note float32 only has 7 digits of precision, while float64 has 15.
ColTypeBool ¶
ColTypeBool is a bool in Go, and is database dependent in the database. MySQL uses a BIT column, and Postgres uses a boolean.
ColTypeAutoPrimaryKey ¶
This is a unique value generated by the database, if the mechanism is provided for by the database, or the database driver if not. It is up to the database driver to ensure that the value is unique. This column is also the single primary key for the table. In many SQL databases, this is a serialized integer. Be careful about exposing serialized private keys to the world. If this number may be exposed over the internet, consider a UUID or ULID primary key instead, or an additional UUID column that will be the public key of the record.
ColTypeJSON ¶
This special type is supported by many databases and allows querying and data retrieval from within JSON documents stored in a field in a database. In Go, querying the entire field will result in a string type value.
ColTypeReference ¶
This is a column that contains the value of a primary key of a table, creating a reference to the object in that table. This is known as a foreign key in SQL databases or an edge in graph databases. The actual column type will mirror the type of the primary key in the referenced table. The column will automatically be indexed.
ColTypeEnum ¶
Enum columns contain values of enumerated types that are described by Enum tables in the schema. ColTypeEnum is an integer value in the database. There is no ColTypeEnumArray because it is difficult to model cross-platform, and is better modeled as a series of ColTypeBool values.
ColTypeUUID ¶
UUID columns contain a UUID value. It is up to the database driver to determine the best way to store this in the database. For example, in MySQL, it is a binary(16), whereas in Postrgres a dedicated UUID type. When a record is newly created, a UUID column will be assigned a new value by the framework. By default, this will be a v7 UUID, but use ColSubTypeRandom to generate a v4 UUID.
ColTypeULID ¶
ULID columns contain a ULID, which is similar to a v7 UUID, but is expressed as a base32 string rather than a hex string. Use ColSubTypeRandom to turn this into an RULID, which is still expressed as a base32 string, but is similar to a v4 UUID in that it is completely random.
const ( ColTypeUnknown ColumnType = iota ColTypeBytes ColTypeString ColTypeInt ColTypeUint ColTypeTime ColTypeFloat ColTypeBool ColTypeAutoPrimaryKey ColTypeJSON ColTypeEnum ColTypeUUID ColTypeULID )
func (ColumnType) MarshalJSON ¶
func (ct ColumnType) MarshalJSON() ([]byte, error)
MarshalJSON customizes how ColumnType is serialized to JSON.
func (ColumnType) String ¶
func (ct ColumnType) String() string
String returns the string representation of a ColumnType.
func (*ColumnType) UnmarshalJSON ¶
func (ct *ColumnType) UnmarshalJSON(data []byte) error
UnmarshalJSON customizes how ColumnType is deserialized from JSON.
type Database ¶
type Database struct {
// Key is the database key corresponding to its key in the global database cluster.
// Should be unique among the other databases in use.
Key string `json:"key"`
// Package is the name of the root package for top level code sent to the output directory.
// Should be all lower case, with no hyphens or underscores.
// Will be the name of the output directory if omitted.
Package string `json:"package,omitempty"`
// ImportPath is the import path that refers to the output directory.
// This value will be used to refer to files across packages.
// If omitted, it will be calculated based on the output directory by looking for the go.mod
// file that applies to the output directory.
ImportPath string `json:"import_path,omitempty"`
// WriteTimeout is used to wrap write transactions with a timeout on their contexts.
// Leaving it as zero will turn off timeout wrapping, allowing you to wrap individual calls as you
// see fit. This only applies to code generated transactions. See also table.WriteTimeout to set
// a timeout value on an individual table.
// Use a duration format understood by time.ParseDuration.
WriteTimeout string `json:"write_timeout,omitempty"`
// ReadTimeout is used to wrap read transactions with a timeout on their contexts.
// Leaving it as zero will turn off timeout wrapping, allowing you to wrap individual calls as you
// see fit. This only applies to code generated transactions. See also table.ReadTimeout to set
// a timeout value on an individual table.
// Use a duration format understood by time.ParseDuration.
ReadTimeout string `json:"read_timeout,omitempty"`
// EnumTableSuffix is the text to strip off the end of an enum table name when converting it to a type name.
// Defaults to "_enum". Will be added to enum table names if missing.
EnumTableSuffix string `json:"enum_table_suffix,omitempty"`
// AssnTableSuffix is the suffix for association table names.
AssnTableSuffix string `json:"assn_table_suffix,omitempty"`
// Tables are the standard tables in the database.
Tables []*Table `json:"tables"`
// EnumTables contains a description of the enumerated types from the enum tables in the database.
EnumTables []*EnumTable `json:"enum_tables"`
// AssociationTables form many-to-many relationships between tables in the database.
AssociationTables []*AssociationTable `json:"association_tables"`
}
Database is a description of the structure of the data in a database that is agnostic of the type of the database, including whether its SQL or NoSQL.
The purpose is to create a structure that is as easy as possible to be specified by humans, with many of the values being optional as they can be inferred from other values.
See model.Database for the structure that is presented to the code generator and that is based on this structure.
func ReadJsonFile ¶
func (*Database) Clean ¶
Clean modifies the structure to prepare it for creating a schema in a database.
func (*Database) FillDefaults ¶
func (db *Database) FillDefaults()
FillDefaults will fill all the undeclared values in the database structure with default values in preparation for building the model.Database structure.
func (*Database) FindEnumTable ¶
FindEnumTable finds the enum table by name. Returns nil if not found. name should be schema.table if the table has a schema specified.
type EnumField ¶
type EnumField struct {
// Identifier is the name used in Go code to access the data.
Identifier string `json:"identifier,omitempty"`
// IdentifierPlural is the plural of the Identifier.
IdentifierPlural string `json:"identifier_plural,omitempty"`
// Type is the type of the column.
// It is inferred from the data, but can be specifically identified if needed, like if integer data
// should be presented as floating point.
Type ColumnType `json:"type"`
}
type EnumTable ¶
type EnumTable struct {
// Name is the name of the table in the database.
// By convention, the name should have the Database.EnumTableSuffix value as a suffix.
// This suffix will be stripped off for items below that use Name as the basis for a default value.
Name string `json:"name"`
// For databases that support schemas, this is the name of the schema of the table.
// Leave blank for the default schema.
// Databases that do not support schemas will have this prepended to the name of the table.
Schema string `json:"schema,omitempty"`
// Values are the enum values themselves.
// At a minimum, each entry must have a "name" field. This should be a CamelCase string that will be
// used to build the constant value in the Go code.
// By default, numbers for values will be assigned in order. If you set a "value" value, it will override this default.
// By default, a "label" value will be assigned based on "name". This should be a Title Case string that will
// represent the value to humans. Set "label" to override the default.
// Alternatively specify a "key" value to be used as the json key and other appropriate contexts. This
// should be a lower_snake_case value and will be generated if missing.
// Additional entries will create accessor functions for those values. The type and identifiers will be
// inferred from the entries, or you can use Fields to specify these values for the additional fields.
Values []map[string]any `json:"values"`
// Fields provides descriptions for additional values found in Values.
// If the entries are omitted, a default will be generated.
// Keys are the same as the keys in the Values entries.
// "label" field will be generated automatically and should not be included on import.
Fields map[string]EnumField `json:"fields,omitempty"`
// Label is the name of the object when describing it to humans.
// If creating a multi-language app, your app would provide translation from this string to the language of choice.
// Can be multiple words. Should be Title Case.
// If left blank, the app will base this on the Name of the table.
Label string `json:"label,omitempty"`
// LabelPlural is the plural form of the Label.
LabelPlural string `json:"label_plural,omitempty"`
// Identifier is the corresponding Go object name. It must obey Go identifier labeling rules.
// Should be CamelCase.
// Leave blank to base it on the Name.
Identifier string `json:"identifier,omitempty"`
// IdentifierPlural is the plural form of Identifier.
IdentifierPlural string `json:"identifier_plural,omitempty"`
// Comment is a place to put a comment in the JSON description file.
// If the database driver supports it, it may be put in the database.
Comment string `json:"comment,omitempty"`
}
EnumTable describes a table that contains enumerated values. The resulting Go code will be a named integer type with constants for each value. An EnumTable is processed with its data at compile time and cannot be modified by the application. The values are stored in the database, but are not accessed by database queries.
func (*EnumTable) FieldKeys ¶
FieldKeys returns the keys of the fields in deterministic order, with label first
func (*EnumTable) QualifiedTableName ¶
QualifiedTableName returns the name of the table in the database, including its schema if applicable.
type Index ¶
type Index struct {
// Columns are the Column.Name values of the columns in the table that will be used to access the data.
Columns []string `json:"columns"`
// IndexLevel will specify the type of index, and possibly a constraint to put on the columns.
IndexLevel IndexLevel `json:"index_level"`
// Name is the name given to the index in the database, if the database requires a name.
// The name will be concatenated with the name of the table and "idx".
// Should be a snake_case word
Name string `json:"name,omitempty"`
// Identifier is the identifier used to create accessor functions.
// Should be CamelCase.
// A default will be generated from the column names if none is provided.
Identifier string `json:"identifier,omitempty"`
}
Index declares that a Get or Load function should be created on the given columns in the table and gives direction to the database to create an index on the columns.
Databases that support indexes will have a matching index on the given columns. See also Column.IndexLevel as another way to specify a single-column index.
Note On Uniqueness:
Not all databases natively enforce uniqueness. The generated ORM will attempt to check for existence before adding the data to the database to minimize collisions, but it is possible to still have a collision if two processes are trying to add the same value to two different records at the same time.
The way to completely prevent it is to do one of the following:
- Use a database that enforces uniqueness, and then check for database errors specific to your database that indicate a collision was detected during Save().
- Create a service that all instances of your application will use that implements a go channel to lock values on columns during an insert or update, and that will prevent two clients from obtaining a lock on the same value-column combinations. That service might need a timeout in case the requester goes offline and never releases the lock, although leaving the lock just means the value is permanently locked until the requester answers back, which might be fine.
- Whenever requesting a record by the unique value, you use a Query operation to detect if there are duplicate records with the same value, and then respond accordingly if so.
type IndexLevel ¶
type IndexLevel int
IndexLevel indicates the type of index the column should have. Not all databases have indexes, and some databases index everything, so this doesn't precisely translate to an eventual index in the database. What this DOES do is determine the primary key and LoadByXXX functions that will be generated in the API.
IndexLevelNone is the default indicating no special treatment for the column ¶
IndexLevelIndexed will result in a LoadByXXX function in the generated ORM that will return a group of objects containing the given value in the column's field. This will be for a single column. To create an index on multiple columns, use an Index.
IndexLevelUnique will result in a LoadByXXX function in the ORM that will return a single object with the given value in the column's field. Uniqueness is up to the database or database driver to ensure. Note that some databases (aka MongoDB) do not allow unique constraints on nullable fields to have more than one null value in the database, in which case the application will need custom logic to enforce uniqueness, rather than relying on the database. See also the comment on uniqueness in Index.
IndexLevelPrimaryKey indicates that this is a private key. Only one column or one index can be specified with this index level, in a table. Use an Index to specify a composite primary key.
const ( IndexLevelNone IndexLevel = iota IndexLevelIndexed IndexLevelUnique IndexLevelPrimaryKey )
func (IndexLevel) MarshalJSON ¶
func (il IndexLevel) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON serialization for IndexLevel
func (IndexLevel) String ¶
func (il IndexLevel) String() string
func (*IndexLevel) UnmarshalJSON ¶
func (il *IndexLevel) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON deserialization for IndexLevel
type Reference ¶
type Reference struct {
// Table is the name of the table being referenced.
// If Table is the same as the column's table, it creates a parent-child relationship.
// Should match a Table.Name value in another table.
Table string `json:"table"`
// Schema is the schema that Table belongs to. If empty, will use the default schema.
Schema string `json:"schema,omitempty"`
// Column is the name of the local column created in this table to hold a duplicate of the private key in Table,
// and is also known as a foreign key.
// It will default to a name based on Table and the name of the primary key column in Table.
Column string `json:"column,omitempty"`
// ColumnIdentifier is the name that Go will use to identify the column
ColumnIdentifier string `json:"column_identifier,omitempty"`
// ColumnLabel is the human-readable name of the column.
ColumnLabel string `json:"column_label,omitempty"`
// ObjectIdentifier is the Go name used for the referenced object.
// If not specified, will be based on Column.
ObjectIdentifier string `json:"object_identifier,omitempty"`
// Label is the human-readable name for the referenced object.
// If not specified, will be based on Identifier.
ObjectLabel string `json:"object_label,omitempty"`
// IndexLevel specifies the index to be created on the foreign key column.
// If a primary key or unique key, will create a one-to-one relationship.
// If left empty, will default to IndexLevelIndexed.
IndexLevel IndexLevel `json:"index_level,omitempty"`
// IsNullable indicates that the reference is not required and can be represented as a null value in the database.
// If not nullable, then the reference is required to be present and valid when the record is saved.
// This would also mean that if the referenced object is deleted, or changes its reverse
// relationship, then this object will be deleted.
// The foreign key column will be nullable if this is nullable.
IsNullable bool `json:"nullable,omitempty"`
// The singular Go identifier that will be used for the reverse relationship objects.
// If not specified, will be based on Table.Name.
// Should be CamelCase with no spaces.
// For example, "ManagedProject".
ReverseIdentifier string `json:"reverse_identifier,omitempty"`
// The plural Go identifier that will be used for the reverse relationship objects.
// If not specified, the ReverseIdentifier will be pluralized.
ReverseIdentifierPlural string `json:"reverse_identifier_plural,omitempty"`
// The singular description of the Table objects as referred to by the referenced table.
// If not specified, will be based on ReverseIdentifier.
// For example, "Managed Project", or "Project I Manage".
ReverseLabel string `json:"reverse_label,omitempty"`
// The plural description of Table objects as referred to by the referenced table.
// If not specified, the ReverseLabel will be pluralized.
ReverseLabelPlural string `json:"reverse_label_plural,omitempty"`
}
Reference represents a forward link to an object described by a table. In SQL databases these are known as foreign-keys. The link will be a one-to-one link if IsUnique is true, or a one-to-many link. Reference will create a column in this table that holds a duplicate of the primary key from the referenced table. Reference automatically creates a reverse link in the referenced table. That reverse link may create a column in the other table, or may be a kind of virtual column that only gets populated during a query using an index.
References to tables with composite keys are not currently supported.
type Table ¶
type Table struct {
// Name is the name of the table or object as used in the database.
// Must be unique within the table or schema if one is provided.
// Should be lower_snake_case.
Name string `json:"name"`
// For databases that support schemas, this is the name of the schema of the table.
// Leave blank for the default schema.
// Databases that do not support schemas will have this prepended to the name of the table.
Schema string `json:"schema,omitempty"`
// WriteTimeout is used to wrap write transactions with a timeout on their contexts.
// Leaving it as zero will use the Database.WriteTimeout value.
// Use a duration format understood by time.ParseDuration.
WriteTimeout string `json:"write_timeout,omitempty"`
// ReadTimeout is used to wrap read transactions with a timeout on their contexts.
// Leaving it as zero will use the Database.ReadTimeout value.
// Use a duration format understood by time.ParseDuration.
ReadTimeout string `json:"read_timeout,omitempty"`
// NoTest indicates that the table should NOT have an automated test generated for it.
NoTest bool `json:"no_test,omitempty"`
// Columns is a list of Column objects, one for each column in the table.
// This does not include columns associated with references.
// Use AllColumns() to get the list of all columns, including the foreign key columns.
Columns []*Column `json:"columns"`
// References is a list of links to other tables, also known as foreign keys.
References []*Reference `json:"references,omitempty"`
// Indexes will be used to generate additional indexes and getter functions.
// Single-column indexes can also be defined in Column and Reference.
// You can use this to specify multiple types of indexes on the same column(s), including a
// composite primary key. Note that some databases do not support composite primary keys and
// will convert a composite primary key to a composite unique key, and then will automatically
// generate a single unique primary key.
// Composite primary keys with an auto generated primary key is not supported in the orm. To
// implement this, you will need to manually generate or assign the primary key columns.
Indexes []*Index `json:"indexes,omitempty"`
// Identifier is the corresponding Go object name.
// It must obey Go identifier labeling rules.
// Should be CamelCase.
// If empty, will be based on Name.
Identifier string `json:"identifier,omitempty"`
// IdentifierPlural is the plural form of Identifier.
// If blank, will be base on Identifier.
IdentifierPlural string `json:"identifier_plural,omitempty"`
// Label is the name of the object when describing it to humans.
// If creating a multi-language app, your app would provide translation from this string to the language of choice.
// Can be multiple words.
// If left blank, will be base on Identifier.
Label string `json:"label,omitempty"`
// LabelPlural is the plural form of the Label.
// If left blank, will be based on Label.
LabelPlural string `json:"label_plural,omitempty"`
// Comment is a place to put a comment in the json description file.
// If the database driver supports it, it may be put in the database.
Comment string `json:"comment,omitempty"`
}
Table represents the metadata for a table in the database.
func (*Table) Clean ¶
Clean fills in defaults and does some processing on the references and indexes.
func (*Table) FindColumn ¶
FindColumn returns the named column of the table, or nil if not found. This does not include columns in references.
func (*Table) PrimaryKeyColumns ¶
PrimaryKeyColumns returns the names of the primary key columns of the table, or nil if not found. Note that these names may refer to reference columns. This only works after Clean has been called.
func (*Table) QualifiedName ¶
QualifiedName returns the name to use to refer to the table in the database, including the schema if one is provided.