db

package
v0.31.10 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2024 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package db works with the rest of the orm to interface between a database and the ORM abstraction of reading and querying a database. It is architected so that both SQL and NoSQL databases can be used with the abstraction. This allows you to potentially write code that is completely agnostic to what kind of database you are using. Even if 100% portability is not achievable in your use case, the ORM and database abstraction layers should be able to handle most of your needs, such that if you ever did have to port to a different database, it would minimize the amount of custom code you would need to write.

Generally, SQL and NoSQL databases work very differently. However, many SQL databases have recently added NoSQL capabilities, like storing and searching JSON text. Similarly, NoSQL databases have added features to enable searching a database through relationships, similar to SQL capabilities. In addition, NoSQL design advice is often to flatten the database structure as much as possible, so that it looks a whole lot like a SQL database.

The general approach Goradd takes is to generally describe data with key/value pairs. This fits in well with SQL, as key/value pairs are just table-column/field pairs. NoSQL generally works with key-value pairs anyways.

Relationships between structures are described as relationships, either one-to-many, or many-to-many. By keeping the description at a higher level, we allow databases to implement those relationships in the way that works best.

SQL implements one-to-many relationships using foreign keys. In the data description, you will see a Reference type of relationship, which points from the many to the one, and a ReverseRelationship, which is a kind of virtual representation of pointing from the one side to the many. ReverseRelationship lists are populated at the time of a query. In SQL, Many-to-many relationships use an intermediate table, called an Association Table, that has foreign keys pointing in both directions.

NoSQL implements one-to-many relationships using foreign-keys as well, but both sides of the relationship store the foreign key, or keys, that point to the other side. This means that a ReverseRelationship will represent an actual field in the database structure that contains a list of all of the items pointing back at itself. This also means that when these relationships are created or destroyed, both sides of the relationship need to be updated. Similarly, NoSQL many-to-many relationships have lists of foreign keys stored on both sides of the relationship.

The other major difference between SQL and NoSQL databases is the built-in capabilities to do aggregate calculations. In SQL, you generally can create a filtered list of records and ask SQL to sum all the values from a particular field. Some NoSQL databases can do this, and some cannot. The ones that cannot expect the programmer to do their own filtering and summing. GoRADD handles this difference by allowing individual GORADD database drivers to be written that add some aggregate capabilities to a database, and also providing ways for individual developers to simply create their own custom queries that will be non-portable between databases. In any case, there is always a way to do what you want to do, just some databases are easier to work with. It depends what you want to do.

Index

Constants

View Source
const (
	LiteralNameOption   = "literalName"   // Used in tables only
	LiteralPluralOption = "literalPlural" // Used in tables only
	GoNameOption        = "goName"        // Used in tables and columns
	GoPluralOption      = "goPlural"      // Used in tables and columns
	MinOption           = "min"           // Used in numeric columns
	MaxOption           = "max"           // Used in number columns
)

These constants define the indexes used in the Options of Tables and Columns

Variables

This section is empty.

Functions

func AddDatabase

func AddDatabase(d DatabaseI, key string)

AddDatabase adds a database to the global database store. Only call this during app startup.

func ExecuteTransaction added in v0.9.0

func ExecuteTransaction(ctx context.Context, d DatabaseI, f func())

ExecuteTransaction wraps the function in a database transaction

func LowerCaseIdentifier added in v0.1.1

func LowerCaseIdentifier(s string) (i string)

func Nodes added in v0.19.0

func Nodes(b QueryBuilder) []NodeI

Nodes is used by the build process to return the nodes referred to in the query. Some nodes will be container nodes, and so will have nodes inside them, but every node is either referred to, or contained in the returned nodes. Only query builders normally need to call this.

func PutContext added in v0.27.3

func PutContext(ctx context.Context) context.Context

PutContext returns a new context with the database contexts inserted into the given context. Pass nil to return a BackgroundContext with the database contexts.

A database context is required by the various database calls to track results and transactions. Normally you would use the Goradd context passed to you by the Web server, but in situations where you do not have that, like in independent go routines or unit tests, you can call this so that you can access the databases.

func UpperCaseIdentifier added in v0.1.1

func UpperCaseIdentifier(s string) (i string)

Types

type AliasNodesType added in v0.19.1

type AliasNodesType = maps.SliceMap[string, Aliaser]

type Column added in v0.6.0

type Column struct {
	// DbName is the name of the column in the database. This is blank if this is a "virtual" table for sql tables like an association or virtual attribute query.
	DbName string
	// GoName is the name of the column in go code
	GoName string
	// NativeType is the type of the column as described by the database itself.
	NativeType string
	//  ColumnType is the equivalent Go type to the database column
	ColumnType GoColumnType
	// MaxCharLength is the maximum length of characters to allow in the column if a string type column.
	// If the database has the ability to specify this, this will correspond to what is specified.
	// In any case, we will generate code to prevent fields from getting bigger than this.
	MaxCharLength uint64
	// DefaultValue is the default value as specified by the database. We will initialize new ORM objects
	// with this value. Call DefaultValueAsValue
	DefaultValue interface{}
	// MaxValue is the maximum value allowed for numeric values. This can be used by UI objects to tell the user what the limits are.
	MaxValue interface{}
	// MinValue is the minimum value allowed for numeric values. This can be used by UI objects to tell the user what the limits are.
	MinValue interface{}
	// IsId is true if this column represents a unique identifier generated by the database
	IsId bool
	// IsPk is true if this is the single primary key column. PK's do not necessarily need to be ID columns, and if not, we will need to do our own work to generate unique PKs.
	IsPk bool
	// IsNullable is true if the column can be given a NULL value
	IsNullable bool
	// IsUnique is true if the column's table has a single unique index on the column.
	IsUnique bool
	// IsTimestamp is true if the field is a timestamp. Timestamps represent a specific point in world time.
	// By default, timestamps are treated as not editable by the user. To automatically update a timestamp
	// value when its saved, you should edit the Save method in the model.
	IsTimestamp bool
	// IsDateOnly indicates that we have a time type of column that should only be concerned about the date and not the time.
	IsDateOnly bool
	// IsTimeOnly indicates that we have a time type of column that should only be concerned about the time and not the date.
	IsTimeOnly bool
	// Comment is the contents of the comment associated with this field
	Comment string

	// Options are the options extracted from the comments string
	Options map[string]interface{}
	// ForeignKey is additional information describing a foreign key relationship
	ForeignKey *ForeignKeyInfo
	// contains filtered or unexported fields
}

Column describes a database column. Most of the information is either gleaned from the structure of the database, or is taken from a file that describes the relationships between different record types. Some information is filled in after analysis. Some information can be provided through information embedded in database comments.

func (*Column) DefaultConstantName added in v0.6.0

func (cd *Column) DefaultConstantName(tableName string) string

DefaultConstantName returns the name of the default value constant that will be used to refer to the default value

func (*Column) DefaultValueAsConstant added in v0.6.0

func (cd *Column) DefaultValueAsConstant() string

DefaultValueAsConstant returns the default value of the column as a Go constant

func (*Column) DefaultValueAsValue added in v0.6.0

func (cd *Column) DefaultValueAsValue() string

DefaultValueAsValue returns the default value of the column as a GO value

func (*Column) GoType added in v0.11.2

func (cd *Column) GoType() string

GoType returns the Go variable type corresponding to the column.

func (*Column) IsEnum added in v0.27.0

func (cd *Column) IsEnum() bool

IsEnum returns true if the column contains a type defined by a enum table.

func (*Column) IsReference added in v0.6.0

func (cd *Column) IsReference() bool

IsReference returns true if the column is a reference to an object in another table.

func (*Column) JsonKey added in v0.6.0

func (cd *Column) JsonKey() string

JsonKey returns the key used for the column when outputting JSON.

func (*Column) ModelName added in v0.6.0

func (cd *Column) ModelName() string

ModelName returns the name of the column

func (*Column) ReferenceFunction added in v0.6.0

func (cd *Column) ReferenceFunction() string

ReferenceFunction returns the function name that should be used to refer to the object that is referred to by a forward reference. It is extracted from the name of foreign key.

func (*Column) ReferenceJsonKey added in v0.6.0

func (cd *Column) ReferenceJsonKey(dd *Model) string

ReferenceJsonKey returns the key that will be used for the referenced object in JSON.

type ColumnDescription

type ColumnDescription struct {
	// Name is the name of the column in the database. This is blank if this is a "virtual" table for sql tables like an association or virtual attribute query.
	Name string
	// NativeType is the type of the column as described by the database itself.
	NativeType string
	//  GoType is the goradd defined column type
	GoType string
	// SubType has additional information to the type of column that can help control code generation
	// When column type is "time.Time", the column will default to both a date and time format. You can also make it:
	//   date (which means date only)
	//   time (time only)
	//   timestamp (not editable by the user)
	SubType string
	// MaxCharLength is the maximum length of characters to allow in the column if a string type column.
	// If the database has the ability to specify this, this will correspond to what is specified.
	// In any case, we will generate code to prevent fields from getting bigger than this. Zero indicates there is
	// no length checking or limiting.
	MaxCharLength uint64
	// DefaultValue is the default value as specified by the database. We will initialize new ORM objects
	// with this value. It will be cast to the corresponding GO type.
	DefaultValue interface{}
	// MaxValue is the maximum value allowed for numeric values. This can be used by UI objects to tell the user what the limits are.
	MaxValue interface{}
	// MinValue is the minimum value allowed for numeric values. This can be used by UI objects to tell the user what the limits are.
	MinValue interface{}
	// IsId is true if this column represents a unique identifier generated by the database.
	IsId bool
	// IsPk is true if this is a primary key column. PK's do not necessarily need to be ID columns, and if not,
	// we will need to do our own work to generate unique PKs.
	IsPk bool
	// IsNullable is true if the column can be given a NULL value
	IsNullable bool
	// IsUnique indicates that the column holds a single unique value. If this column
	// is part of a multi-column unique value, IsUnique will be false since its value
	// could be repeated.
	IsUnique bool
	// ForeignKey is additional information describing a foreign key relationship
	ForeignKey *ForeignKeyDescription
	// Comment is the contents of the comment associated with this column
	Comment string
	// Options are key-value settings that can be used to further describe code generation
	Options map[string]interface{}
}

ColumnDescription describes a field of a database object to GoRADD.

type Copier

type Copier interface {
	Copy() interface{}
}

Copier implements the copy interface, that returns a deep copy of an object.

type DatabaseDescription

type DatabaseDescription struct {
	// Tables are the tables in the database
	Tables []TableDescription
	// MM are the many-to-many links between tables. In SQL databases, these are actual tables,
	// but in NoSQL, these might be array fields on either side of the relationship.
	MM []ManyManyDescription
}

DatabaseDescription generically describes a database to GoRADD. It is sent to NewModel() to create a DB object that is used internally by GoRADD to access the database. DatabaseDescription should be able to be inferred by reading the structure of SQL databases, or read directly from an import file.

type DatabaseI

type DatabaseI interface {
	// Model returns a Model object, which is a description of the tables and fields in
	// a database and their relationships. SQL databases can, for the most part, generate this description
	// based on their structure. NoSQL databases would need to get this description some other way, like through
	// a configuration file.
	Model() *Model

	// NewBuilder returns a newly created query builder
	NewBuilder(ctx context.Context) QueryBuilderI

	// Update will put the given values into a record that already exists in the database. The "fields" value
	// should include only fields that have changed.
	Update(ctx context.Context, table string, fields map[string]interface{}, pkName string, pkValue interface{})
	// Insert will insert a new record into the database with the given values, and return the new record's primary key value.
	// The fields value should include all the required values in the database.
	Insert(ctx context.Context, table string, fields map[string]interface{}) string
	// Delete will delete the given record from the database
	Delete(ctx context.Context, table string, pkName string, pkValue interface{})
	// Associate sets a many-many relationship to the given values.
	// The values are taken from the ORM, and are treated differently depending on whether this is a SQL or NoSQL database.
	Associate(ctx context.Context,
		table string,
		column string,
		pk interface{},
		relatedTable string,
		relatedColumn string,
		relatedPks interface{})

	// Begin will begin a transaction in the database and return the transaction id
	Begin(ctx context.Context) TransactionID
	// Commit will commit the given transaction
	Commit(ctx context.Context, txid TransactionID)
	// Rollback will roll back the given transaction PROVIDED it has not been committed. If it has been
	// committed, it will do nothing. Rollback can therefore be used in a defer statement as a safeguard in case
	// a transaction fails.
	Rollback(ctx context.Context, txid TransactionID)
	// PutBlankContext is called early in the processing of a response to insert an empty context that the database can use if needed.
	PutBlankContext(ctx context.Context) context.Context
}

DatabaseI is the interface that describes the behaviors required for a database implementation.

func GetDatabase

func GetDatabase(key string) DatabaseI

GetDatabase returns the database given the database's key.

func GetDatabases

func GetDatabases() []DatabaseI

GetDatabases returns all databases in the datastore

type DatabaseMap added in v0.24.1

type DatabaseMap = maps.SliceMap[string, DatabaseI]

type EnumTable added in v0.27.0

type EnumTable struct {
	// DbKey is the key used to find the database in the global database cluster
	DbKey string
	// DbName is the name of the table in the database
	DbName string
	// LiteralName is the english name of the object when describing it to the world. Use the "literalName" option in the comment to override the default.
	LiteralName string
	// LiteralPlural is the plural english name of the object. Use the "literalPlural" option in the comment to override the default.
	LiteralPlural string
	// GoName is the name of the item as a go type name.
	GoName string
	// GoPlural is the plural of the go type
	GoPlural string
	// LcGoName is the lower case version of the go name
	LcGoName string
	// FieldNames are the names of the fields defined in the table. The first field name MUST be the name of the id field, and 2nd MUST be the name of the name field, the others are optional extra fields.
	FieldNames []string
	// FieldTypes are the go column types of the fields, indexed by field name
	FieldTypes map[string]GoColumnType
	// Values are the constant values themselves as defined in the table, mapped to field names in each row.
	Values []map[string]interface{}
	// PkField is the name of the private key field
	PkField string

	// Filled in by analyzer
	Constants map[int]string
}

EnumTable describes a enum table, which essentially defines an enumerated type. In the SQL world, they are a table with an integer key (starting index 1) and a "name" value, though they can have other values associated with them too. Goradd will maintain the relationships in SQL, but in a No-SQL situation, it will embed all the ids and values.

func (*EnumTable) FieldGoColumnType added in v0.27.0

func (tt *EnumTable) FieldGoColumnType(i int) GoColumnType

FieldGoColumnType returns the GoColumnType corresponding to the given field offset

func (*EnumTable) FieldGoName added in v0.27.0

func (tt *EnumTable) FieldGoName(i int) string

FieldGoName returns the go name corresponding to the given field offset

func (*EnumTable) FieldGoPlural added in v0.27.8

func (tt *EnumTable) FieldGoPlural(i int) string

FieldGoPlural returns the go plural name corresponding to the given field offset

func (*EnumTable) FileName added in v0.27.0

func (tt *EnumTable) FileName() string

FileName returns the default file name corresponding to the enum table.

type FKAction

type FKAction int

FKAction indicates how the database handles situations when one side of a relationship is deleted or the key is changed.

const (
	// FKActionNone indicates the database does not support foreign key actions, so we should deal with it ourselves.
	FKActionNone FKAction = iota
	// FKActionSetNull indicates the foreign key will be set to null
	FKActionSetNull
	// FKActionSetDefault indicates the foreign key will be set to a default value
	FKActionSetDefault
	// FKActionCascade indicates the foreign key will automatically update values during an update, and
	// automatically delete related records during a delete.
	FKActionCascade
	// FKActionRestrict indicates the database will prevent the action from happening by likely panicking with an error
	FKActionRestrict
)

The foreign key actions tell us what the database will do automatically if a foreign key object is changed. This allows us to do the appropriate thing when we detect in the ORM that a linked object is changing.

func FKActionFromString added in v0.6.0

func FKActionFromString(s string) FKAction

func (FKAction) String added in v0.6.0

func (a FKAction) String() string

type ForeignKeyDescription

type ForeignKeyDescription struct {
	// ReferencedTable is the name of the table on the other end of the foreign key
	ReferencedTable string
	// ReferencedColumn is the database column name in the linked table that matches this column. Often that is the primary key of the other table.
	ReferencedColumn string
	// UpdateAction indicates how the column will react when the referenced item's ID changes.
	UpdateAction FKAction
	// DeleteAction indicates how the column will react when the referenced item is deleted.
	DeleteAction FKAction
	// IsUnique is true if the reference is one-to-one
	IsUnique bool

	// GoName is the name we should use to refer to the related object. Leave blank to get a computed value.
	GoName string
	// ReverseName is the name that the reverse reference should use to refer to the collection of objects pointing to it.
	// Leave blank to get a "ThisAsThat" type default name. The lower-case version of this name will be used as a column name
	// to store the values if using a NoSQL database.
	ReverseName string
}

ForeignKeyDescription describes a pointer from one database column to another database column. Cross database foreign keys are not supported. Foreign keys between schemas for databases that support schemas ARE supported.

type ForeignKeyInfo added in v0.6.0

type ForeignKeyInfo struct {
	// ReferencedTable is the name of the table on the other end of the foreign key
	ReferencedTable string
	// ReferencedColumn is the database column name in the linked table that matches this column name.
	// Often that is the primary key of the other table.
	ReferencedColumn string
	// UpdateAction indicates how the column will react when the other end of the relationship's value changes.
	// Some databases react automatically, but databases or tables that do not support
	// foreign keys will need to be updated manually.
	UpdateAction FKAction
	// DeleteAction indicates how the column will react when the other end of the relationship's record is deleted.
	// Some databases react automatically, but databases or tables that do not support
	// foreign keys will need to be updated manually.
	DeleteAction FKAction
	// GoName is the name we should use to refer to the related object
	GoName string
	// GoType is the type of the related object
	GoType string
	// GoTypePlural is the plural version of the type when referring to groups of related objects
	GoTypePlural string
	// isEnum is true if this is a related type
	IsEnum bool
	// RR is filled in by the analyzer and represents a reverse reference relationship
	RR *ReverseReference
}

ForeignKeyInfo is additional information to describe what a foreign key points to. Cross database foreign keys are not supported.

func (*ForeignKeyInfo) GoVarName added in v0.6.0

func (fk *ForeignKeyInfo) GoVarName() string

GoVarName returns the name of the go object used to refer to the kind of object the foreign key points to.

type Index added in v0.6.0

type Index struct {
	// IsUnique indicates whether the index is for a unique index
	IsUnique bool
	// Columns are the columns that are part of the index
	Columns []*Column
}

Index is used by SQL analysis to extract details about an Index in the database. We can use indexes to know how to get to sorted data easily.

type IndexDescription

type IndexDescription struct {
	// IsUnique indicates whether the index is unique
	IsUnique bool
	// ColumnNames are the columns that are part of the index
	ColumnNames []string
}

IndexDescription gives us information about how columns are indexed. If a column has a unique index, it will get a corresponding "LoadBy" function in its table's model. Otherwise, it will get a corresponding "LoadSliceBy" function.

type LimitInfo added in v0.0.7

type LimitInfo struct {
	MaxRowCount int
	Offset      int
}

LimitInfo is the information needed to limit the rows being requested.

type ManyManyDescription added in v0.6.0

type ManyManyDescription struct {
	// Table1 is the name of the first table that is part of the relationship. The private key of that table will be referred to.
	Table1 string
	// Column1 is the database column name. For SQL databases, this is the name of the column in the assn table. For
	// NoSQL, this is the name of the column that will be used to store the ids of the other side. This is optional for
	// NoSQL, as one will be created based on the table names if left blank.
	Column1 string
	// GoName1 is the singular name of the object that Table2 will use to refer to Table1 objects.
	GoName1 string
	// GoPlural1 is the plural name of the object that Table2 will use to refer to Table1 objects.
	GoPlural1 string

	// Table2 is the name of the second table that is part of the relationship. The private key of that table will be referred to.
	Table2 string
	// Column2 is the database column name. For SQL databases, this is the name of the column in the assn table. For
	// NoSQL, this is the name of the column that will be used to store the ids of the other side. This is optional for
	// NoSQL, as one will be created based on the table names if left blank.
	Column2 string
	// GoName2 is the singular name of the object that Table1 will use to refer to Table2 objects.
	GoName2 string
	// GoPlural2 is the plural name of the object that Table1 will use to refer to Table2 objects.
	GoPlural2 string

	// AssnTableName is the name of the intermediate association table that will be used to create the relationship. This is
	// needed for SQL databases, but not for NoSQL, as NoSQL will create additional array columns on each side of the relationship.
	AssnTableName string
	// SupportsForeignKeys indicates that the database engine for the table will automatically take
	// care of updating foreign key pointers when the item pointed to has an updated key or is deleted.
	// If this is false, the code generator will need to do the updating.
	SupportsForeignKeys bool
}

ManyManyDescription describes a many-to-many relationship table that contains a two-way pointer between database objects.

type ManyManyReference

type ManyManyReference struct {
	// AssnTableName is the database table that links the two associated tables together.
	AssnTableName string
	// AssnSourceColumnName is the database column in the association table that points at the source table's primary key.
	AssnSourceColumnName string
	// AssnDestColumnName is the database column in the association table that points at the destination table's primary key.
	AssnDestColumnName string
	// DestinationTableName is the database table being linked (the table that we are joining to)
	DestinationTableName string

	// GoName is the name used to refer to an object on the other end of the reference.
	// It is not the same as the object type. For example TeamMember would refer to a Person type.
	// This is derived from the AssnDestColumnName but can be overridden by comments in the column.
	GoName string
	// GoPlural is the name used to refer to the group of objects on the other end of the reference.
	// For example, TeamMembers. This is derived from the AssnDestColumnName but can be overridden by
	// a comment in the table.
	GoPlural string

	// SupportsForeignKeys indicates that updates and deletes are automatically handled by the database engine.
	// If this is false, the code generator will need to manually update these items.
	SupportsForeignKeys bool

	// IsEnumAssociation is true if this is a many-many relationship with an enum table
	IsEnumAssociation bool

	// MM is the many-many reference on the other end of the relationship that points back to this one.
	MM *ManyManyReference
	// contains filtered or unexported fields
}

The ManyManyReference structure is used by the templates during the codegen process to describe a many-to-many relationship. Underlying the structure is an association table that has two values that are foreign keys pointing to the records that are linked. The names of these fields will determine the names of the corresponding accessors in each of the model objects. This allows multiple of these many-many relationships to exist on the same tables but for different purposes.

func (*ManyManyReference) JsonKey added in v0.1.1

func (m *ManyManyReference) JsonKey(dd *Model) string

JsonKey returns the key used when referring to the associated objects in JSON.

func (*ManyManyReference) ObjectType added in v0.27.5

func (m *ManyManyReference) ObjectType() string

ObjectType returns the name of the object type the association links to.

func (*ManyManyReference) ObjectTypes added in v0.27.5

func (m *ManyManyReference) ObjectTypes() string

ObjectTypes returns the plural name of the object type the association links to.

func (*ManyManyReference) PrimaryKey added in v0.27.5

func (m *ManyManyReference) PrimaryKey() string

PrimaryKey returns the database field name of the primary key of the object the association links to.

func (*ManyManyReference) PrimaryKeyType added in v0.27.5

func (m *ManyManyReference) PrimaryKeyType() string

PrimaryKeyType returns the Go type of the primary key of the object the association links to.

type Model added in v0.24.1

type Model struct {
	// The database key corresponding to its key in the global database cluster
	DbKey string
	// The name of the database or schema.
	DbName string
	// Tables are the tables in the database, keyed by database table name
	Tables map[string]*Table
	// EnumTables contains a description of the enumerated types from the enum tables in the database, keyed by database table name
	EnumTables map[string]*EnumTable

	// ForeignKeySuffix is the text to strip off the end of foreign key references when converting to names.
	// Defaults to "_id"
	ForeignKeySuffix string
	// EnumTableSuffix is the text to string off the end of an enum table when converting it to a type name.
	// Defaults to "_enum".
	EnumTableSuffix string
	// contains filtered or unexported fields
}

Model is the top level struct that contains a description of the database modeled as objects. It is used in code generation and query creation.

func NewModel added in v0.24.1

func NewModel(dbKey string,
	dbName string,
	foreignKeySuffix string,
	enumTableSuffix string,
	ignoreSchemas bool,
	desc DatabaseDescription) *Model

NewModel creates a new Model object from the given DatabaseDescription object.

dbKey is the unique key used throughout Goradd to refer to the database.

foreignKeySuffix is the name ending that will be used to indicate a field is a foreign key pointer.

ignoreSchemas indicates to ignore schema names when generating object names. If true and the database supports schemas, it will not use schema names to generate object names. If the database does not support schemas, this should be false

desc is the description of the database.

func (*Model) EnumTable added in v0.27.0

func (m *Model) EnumTable(name string) *EnumTable

EnumTable returns a EnumTable from the database given the table name.

func (*Model) IsEnumTable added in v0.27.0

func (m *Model) IsEnumTable(name string) bool

IsEnumTable returns true if the given name is the name of a enum table in the database

func (*Model) Table added in v0.24.1

func (m *Model) Table(name string) *Table

Table returns a Table from the database given the table name.

type QueryBuilder added in v0.0.7

type QueryBuilder struct {
	Ctx           context.Context // The context that will be used in all the queries
	Joins         []NodeI
	OrderBys      []NodeI
	ConditionNode NodeI
	IsDistinct    bool
	AliasNodes    *AliasNodesType
	// Adds a COUNT(*) to the select list
	GroupBys   []NodeI
	Selects    []NodeI
	LimitInfo  *LimitInfo
	HavingNode NodeI
	IsSubquery bool
}

QueryBuilder is a helper to implement the QueryBuilderI interface in various builder classes. It is designed to be embedded in a database specific implementation. It gathers the builder instructions as the query is built. It leaves the implementation of the functions that actually query a database -- Load, Delete, Count -- to the containing structure.

func (*QueryBuilder) Alias added in v0.0.7

func (b *QueryBuilder) Alias(name string, n NodeI)

Alias adds a node that is given a manual alias name. This is usually some kind of operation, but it can be any query.Aliaser kind of node.

func (*QueryBuilder) Condition added in v0.0.7

func (b *QueryBuilder) Condition(c NodeI)

Condition adds the condition of the Where clause. If a condition already exists, it will be anded to the previous condition.

func (*QueryBuilder) Context added in v0.10.0

func (b *QueryBuilder) Context() context.Context

Context returns the context.

func (*QueryBuilder) Count added in v0.0.7

func (b *QueryBuilder) Count(_ bool, _ ...NodeI) uint

Count is a stub that helps the QueryBuilder implement the query.QueryBuilderI interface so it can be included in sub-queries.

func (*QueryBuilder) Delete added in v0.0.7

func (b *QueryBuilder) Delete()

Delete is a stub that helps the QueryBuilder implement the query.QueryBuilderI interface so it can be included in sub-queries.

func (*QueryBuilder) Distinct added in v0.0.7

func (b *QueryBuilder) Distinct()

Distinct sets the distinct bit, causing the query to not return duplicates.

func (*QueryBuilder) Expand added in v0.0.7

func (b *QueryBuilder) Expand(n NodeI)

Expand expands an array type node so that it will produce individual rows instead of an array of items

func (*QueryBuilder) GroupBy added in v0.0.7

func (b *QueryBuilder) GroupBy(nodes ...NodeI)

GroupBy sets the nodes that are grouped. According to SQL rules, these then are the only nodes that can be selected, and they MUST be selected.

func (*QueryBuilder) Having added in v0.0.7

func (b *QueryBuilder) Having(node NodeI)

Having adds a HAVING condition, which is a filter that acts on the results of a query. In particular its useful for filtering after aggregate functions have done their work.

func (*QueryBuilder) Init added in v0.0.7

func (b *QueryBuilder) Init(ctx context.Context)

Init initializes the QueryBuilder.

func (*QueryBuilder) Join added in v0.0.7

func (b *QueryBuilder) Join(n NodeI, condition NodeI)

Join will attach the given reference node to the builder.

func (*QueryBuilder) Limit added in v0.0.7

func (b *QueryBuilder) Limit(maxRowCount int, offset int)

Limit sets the limit parameters of what is returned.

func (*QueryBuilder) Load added in v0.0.7

func (b *QueryBuilder) Load() []map[string]interface{}

Load is a stub that helps the QueryBuilder implement the query.QueryBuilderI interface so it can be included in sub-queries.

func (*QueryBuilder) LoadCursor added in v0.19.0

func (b *QueryBuilder) LoadCursor() CursorI

LoadCursor is a stub that helps the QueryBuilder implement the query.QueryBuilderI interface so it can be included in sub-queries.

func (*QueryBuilder) OrderBy added in v0.0.7

func (b *QueryBuilder) OrderBy(nodes ...NodeI)

OrderBy adds the order by nodes. If these are table type nodes, the primary key of the table will be used. These nodes can be modified using Ascending and Descending calls.

func (*QueryBuilder) Select added in v0.0.7

func (b *QueryBuilder) Select(nodes ...NodeI)

Select specifies what specific nodes are selected. This is an optimization in order to limit the amount of data returned by the query. Without this, the query will expand all the join items to return every column of each table joined.

func (*QueryBuilder) Subquery added in v0.0.7

func (b *QueryBuilder) Subquery() *SubqueryNode

Subquery adds a subquery node, which is like a mini query builder that should result in a single value.

type QueryExport added in v0.0.7

type QueryExport struct {
	Joins      []NodeI
	OrderBys   []NodeI
	Condition  NodeI
	Distinct   bool
	AliasNodes *AliasNodesType
	// Adds a COUNT(*) to the select list
	GroupBys   []NodeI
	Selects    []NodeI
	LimitInfo  *LimitInfo
	Having     NodeI
	IsSubquery bool
}

func ExportQuery added in v0.0.7

func ExportQuery(b *QueryBuilder) *QueryExport

type ReverseReference

type ReverseReference struct {
	// DbColumn is only used in NoSQL databases, and is the name of a column that will hold the pk(s) of the referring column(s)
	DbColumn string
	// AssociatedTableName is the table on the "many" end that is pointing to the table containing the ReverseReference.
	AssociatedTable *Table
	// AssociatedColumn is the column on the "many" end that is pointing to the table containing the ReverseReference. It is a foreign-key.
	AssociatedColumn *Column
	// GoName is the name used to represent an object in the reverse relationship
	GoName string
	// GoPlural is the name used to represent the group of objects in the reverse relationship
	GoPlural string
	// GoType is the type of object in the collection of "many" objects, which corresponds to the name of the struct corresponding to the table
	GoType string
	// GoTypePlural is the plural of the type of object in the collection of "many" objects
	GoTypePlural string
}

ReverseReference represents a kind of virtual column that is a result of a foreign-key pointing back to this column. This is the "one" side of a one-to-many relationship. Or, if the relationship is unique, this creates a one-to-one relationship. In SQL, since there is only a one-way foreign key, the side being pointed at does not have any direct data in a table indicating the relationship. We create a ReverseReference during data analysis and include it with the table description so that the table can know about the relationship and use it when doing queries.

func (*ReverseReference) AssociatedGoName added in v0.1.1

func (r *ReverseReference) AssociatedGoName() string

AssociatedGoName returns the name of the column that is pointing back to us. The name returned is the Go name that we could use to name the referenced object.

func (*ReverseReference) AssociatedTableName

func (r *ReverseReference) AssociatedTableName() string

func (*ReverseReference) IsNullable added in v0.7.0

func (r *ReverseReference) IsNullable() bool

func (*ReverseReference) IsUnique

func (r *ReverseReference) IsUnique() bool

func (*ReverseReference) JsonKey added in v0.1.1

func (r *ReverseReference) JsonKey(dd *Model) string

func (*ReverseReference) PrimaryKeyType added in v0.27.5

func (r *ReverseReference) PrimaryKeyType() string

type Table added in v0.6.0

type Table struct {
	// DbKey is the key used to find the database in the global database cluster
	DbKey string
	// DbName is the name of the database table or object in the database.
	DbName string
	// LiteralName is the name of the object when describing it to the world. Use the "literalName" option in the comment to override the default. Should be lower case.
	LiteralName string
	// LiteralPlural is the plural name of the object. Use the "literalPlural" option in the comment to override the default. Should be lower case.
	LiteralPlural string
	// GoName is the name of the struct when referring to it in go code. Use the "goName" option in the comment to override the default.
	GoName string
	// GoPlural is the name of a collection of these objects when referring to them in go code. Use the "goPlural" option in the comment to override the default.
	GoPlural string
	// LcGoName is the same as GoName, but with first letter lower case.
	LcGoName string
	// Columns is a list of ColumnDescriptions, one for each column in the table.
	Columns []*Column

	// Indexes are the indexes defined in the database. Unique indexes will result in LoadBy* functions.
	Indexes []Index
	// Options are key-value pairs of values that can be used to customize how code generation is performed
	Options map[string]interface{}

	// Comment is the general comment included in the database
	Comment string

	// ManyManyReferences describe the many-to-many references pointing to this table
	ManyManyReferences []*ManyManyReference
	// ReverseReferences describes the many-to-one references pointing to this table
	ReverseReferences []*ReverseReference

	// SupportsForeignKeys determines whether the table uses a storage engine that
	// supports foreign keys. Some examples: Postgres supports foreign keys across all tables,
	// while some MySQL database engines do not support foreign keys, and the engine
	// can be assigned on a table-by-table basis.
	//
	// If the table has foreign key support, the code generator will assume that the
	// database will automatically handle updates and deletes of foreign key values.
	// If not, the code generator will attempt to update the foreign keys as appropriate.
	SupportsForeignKeys bool
	// contains filtered or unexported fields
}

func (*Table) DefaultHtmlID added in v0.9.3

func (t *Table) DefaultHtmlID() string

DefaultHtmlID is the default id of corresponding form object when used in generated HTML.

func (*Table) FileName added in v0.27.0

func (t *Table) FileName() string

FileName is the base name of generated file names that correspond to this database table. Typically, Go files are lower case snake case by convention.

func (*Table) GetColumn added in v0.6.0

func (t *Table) GetColumn(name string) *Column

GetColumn returns a Column given the database name of a column

func (*Table) HasGetterName added in v0.27.5

func (t *Table) HasGetterName(name string) (hasName bool, desc string)

HasGetterName returns true if the given name is in use by one of the getters. This is used for detecting naming conflicts. Will also return an error string to display if there is a conflict.

func (*Table) PrimaryKeyColumn added in v0.6.0

func (t *Table) PrimaryKeyColumn() *Column

func (*Table) PrimaryKeyGoType added in v0.7.0

func (t *Table) PrimaryKeyGoType() string

type TableDescription

type TableDescription struct {
	// Name is the name of the database table or collection.
	// Schemas will be delineated with a period in the name.
	Name string
	// Columns is a list of ColumnDescriptions, one for each column in the table.
	// The first columns are the primary keys. Usually there is just one primary key.
	Columns []ColumnDescription
	// Indexes are the indexes defined in the database. Unique indexes will result in LoadBy* functions.
	Indexes []IndexDescription
	// EnumData is the data of the enum table if this is a enum table. The data structure must match that of the columns.
	EnumData []map[string]interface{}

	// Comment is an optional comment about the table
	Comment string
	// Options are key-value settings that can be used to further describe code generation
	Options map[string]interface{}
	// SupportsForeignKeys indicates that the engine for the table will automatically
	// update foreign keys per its internal constraints.
	SupportsForeignKeys bool
}

TableDescription describes a database object to GoRADD.

type TransactionID

type TransactionID int

type ValueMap

type ValueMap map[string]interface{}

func NewValueMap

func NewValueMap() ValueMap

func (ValueMap) Copy

func (m ValueMap) Copy() interface{}

Copy does a deep copy and supports the deep copy interface

Directories

Path Synopsis
sql
Package sql contains helper functions that connect a standard Go database/sql object to the GoRADD system.
Package sql contains helper functions that connect a standard Go database/sql object to the GoRADD system.

Jump to

Keyboard shortcuts

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