sqlquery

package
v1.0.28 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var FilterSuffix = map[string]string{
	"eq":     "==",
	"ne":     "!=",
	"lt":     "<",
	"lte":    "<=",
	"gt":     ">",
	"gte":    ">=",
	"in":     "IN",
	"not_in": "NOT IN",
}

Functions

func AlterTableAddFieldSQL

func AlterTableAddFieldSQL(engine, tableName string, f *models.FieldInfo) ([]string, error)

AlterTableAddFieldSQL returns DDL statements to add physical column(s) for one FieldInfo (locals expand to multiple columns). Engine must match DriverCredentials.Engine (e.g. postgresql, sqlite, libsql, mysql).

func ApplyStaleOneToOne

func ApplyStaleOneToOne(engine string, from, to *models.ConnectionType, exec func(string) error) error

ApplyStaleOneToOne drops the has_one/has_one unique rule and leaves the foreign-key column in place.

func ApplyUniqueKeyDDL

func ApplyUniqueKeyDDL(engine string, sharedSaaS bool, modelsList []*models.ModelType, drops []models.UniqueIndexDrop, exec func(string) error) error

ApplyUniqueKeyDDL drops removed composite indexes, then creates the keys still on the schema. A nil model list only drops. Duplicate rows surface as the database error.

func BuildCombinedMetaQuery

func BuildCombinedMetaQuery(keys dataloader.Keys, param *QueryBuilderParam) ([]byte, error)

func BuildCombinedRelationQuery

func BuildCombinedRelationQuery(cfg *models.Config, relationType string, parentModel string, arg *models.CommonSystemParams) (string, []interface{}, *string, error)

func ChildTableDDL

func ChildTableDDL(tableName string, subfields []*models.FieldInfo, sharedSaaS bool) string

ChildTableDDL creates a normalized search table for indexed repeated subfields.

func ChildTableNameForRepeated

func ChildTableNameForRepeated(modelName, repeatedField string) string

ChildTableNameForRepeated returns `<table>__<repeated_field>` physical name.

func CommonDocTransformation

func CommonDocTransformation(model *models.ModelType, local string, result map[string]interface{}, classification *FieldClassification) (*types.DefaultDocumentStructure, error)

func CommonModelExcludeDeletedSQL

func CommonModelExcludeDeletedSQL() string

CommonModelExcludeDeletedSQL hides soft-deleted common-model rows (meta.status).

func ConditionBuilder

func ConditionBuilder(variable string, args map[string]interface{}, modelType *models.ModelType, sqlArgs *[]interface{}) (map[string][]string, error)

func CreateIndexDDL

func CreateIndexDDL(tableName, indexName string, columns ...string) string

CreateIndexDDL builds CREATE INDEX IF NOT EXISTS for one or more columns.

func DocumentIsSoftDeleted

func DocumentIsSoftDeleted(doc *types.DefaultDocumentStructure) bool

DocumentIsSoftDeleted reports whether a document's meta status is deleted.

func DropSQLColumn

func DropSQLColumn(ctx context.Context, db *bun.DB, engine, table, column string) error

DropSQLColumn drops a foreign-key column on PostgreSQL, MySQL, or MariaDB. SQLite-like engines use the driver's rebuild helper instead.

func FilterBuilder

func FilterBuilder(variable string, where map[string]interface{}, modelType *models.ModelType, sqlArgs *[]interface{}) ([]string, error)

func GeneratedColumnDDL

func GeneratedColumnDDL(tableName, parentColumn string, subPath []string) string

GeneratedColumnDDL returns ALTER TABLE ADD COLUMN ... AS (json_extract(...)) STORED for object subfields.

func HideDeletedCommonDocument

func HideDeletedCommonDocument(model *models.ModelType, doc *types.DefaultDocumentStructure) *types.DefaultDocumentStructure

HideDeletedCommonDocument returns nil when a common-model document is soft-deleted.

func IndexedNestedSubfields

func IndexedNestedSubfields(f *models.FieldInfo, parentPath string) []indexedSubfield

IndexedNestedSubfields collects subfields with EnableIndexing in object/repeated trees.

func InsertShadowIDSQL

func InsertShadowIDSQL(engine, table, id string) (string, []interface{})

InsertShadowIDSQL returns an idempotent insert of a single id into a shadow table.

func IsIgnorableIndexDrop

func IsIgnorableIndexDrop(err error) bool

IsIgnorableIndexDrop reports a missing-index error from DROP INDEX.

func IsJSONStoredListField

func IsJSONStoredListField(f *models.FieldInfo) bool

IsJSONStoredListField reports whether a list field is stored as a JSON array column (dynamic / multi-select lists). Single-choice fixed dropdowns use plain TEXT.

func JSONExtractPath

func JSONExtractPath(subPath ...string) string

JSONExtractPath builds a SQLite json_extract path ($.a.b).

func LimitBuilder

func LimitBuilder(param *graphql.ResolveParams) (int, int)

func MapDocumentDataForSQLInsert

func MapDocumentDataForSQLInsert(docData map[string]interface{}, fields []*models.FieldInfo) (map[string]interface{}, error)

MapDocumentDataForSQLInsert normalizes doc.Data for SQL INSERT (JSON-encode list/repeated/gallery slices).

func MediaDocTransformation

func MediaDocTransformation(docType string, result map[string]interface{}) (*models.FileDetails, error)

func MergeQueryFilterHookSQL

func MergeQueryFilterHookSQL(cfg *models.Config, param *models.CommonSystemParams, filters map[string][]string, rowAlias string, sqlArgs *[]interface{}) error

MergeQueryFilterHookSQL appends hook-produced equality predicates to filters["AND"] for raw SQL.

func MigrateRelationCardinality

func MigrateRelationCardinality(session SQLSession, req relationmigrate.Request) (relationmigrate.Receipt, error)

MigrateRelationCardinality copies valid pairs, verifies the sets, then drops obsolete storage.

func ModelUserFieldColumnsDDL

func ModelUserFieldColumnsDDL(engine string, model *models.ModelType) ([]string, error)

ModelUserFieldColumnsDDL returns DDL statements to add physical columns for model fields.

func NestedGeneratedColumnName

func NestedGeneratedColumnName(parentField string, subPath ...string) string

NestedGeneratedColumnName returns the physical STORED column for an indexed object subpath.

func NestedIndexDDLStatements

func NestedIndexDDLStatements(model *models.ModelType, sharedSaaS bool) []string

NestedIndexDDLStatements emits generated columns / child tables + indexes for a model.

func OneToOneUniqueIndexDrops

func OneToOneUniqueIndexDrops(from, to *models.ConnectionType) []models.UniqueIndexDrop

OneToOneUniqueIndexDrops lists idx_<table>_<fk>_unique indexes that must go when a relation is no longer 1:1. Column placement matches AddRelationFields.

func PhysicalSQLColumnForSystemRelationField

func PhysicalSQLColumnForSystemRelationField(identifier string, modelType *models.ModelType) string

PhysicalSQLColumnForSystemRelationField maps GraphQL/schema synthetic relation keys (system_<model>_id or system_<model>_as_<known>_id) to physical FK column names created by AddRelationFields. Pass modelType when available so legacy collapsed ids (e.g. system_foodcategory_id vs system_food_category_id) resolve to the same SQL column.

func PreviewRelationCardinality

func PreviewRelationCardinality(session SQLSession, req relationmigrate.Request) (relationmigrate.Preview, error)

PreviewRelationCardinality reads storage and returns the shared preview. It does not write.

func ProjectAuthUserMetaSelectSQL

func ProjectAuthUserMetaSelectSQL() string

ProjectAuthUserMetaSelectSQL returns meta column projections for the flat users auth table.

func ProjectAuthUserSelectColumns

func ProjectAuthUserSelectColumns(local string, modelType *models.ModelType, returnCount bool) []string

ProjectAuthUserSelectColumns builds SELECT fragments for the auth users table (no meta join).

func ProjectAuthUserSingleDocQuery

func ProjectAuthUserSingleDocQuery(tableName string, local string, modelType *models.ModelType) string

ProjectAuthUserSingleDocQuery builds a SELECT for one auth user row by id.

func RelationDocumentMetaJoinSQL

func RelationDocumentMetaJoinSQL(modelType *models.ModelType) string

RelationDocumentMetaJoinSQL returns the meta join for relation target loads, or empty for auth users.

func RelationEnsureNeeded

func RelationEnsureNeeded(param *models.CommonSystemParams) bool

RelationEnsureNeeded reports whether a read should materialise relation artifacts and composite unique indexes. A published unique key must apply even when the query does not ask for a relation.

func RelationFieldsDDLStatements

func RelationFieldsDDLStatements(from, to *models.ConnectionType) []string

RelationFieldsDDLStatements returns SQLite/D1 DDL for a relation pair (idempotent where supported).

func RelationMetaJoinFragment

func RelationMetaJoinFragment(modelType *models.ModelType) string

RelationMetaJoinFragment returns a newline-prefixed meta join for relation SQL, or empty for auth users.

func RootConnectionResolverQueryBuilder

func RootConnectionResolverQueryBuilder(cfg *models.Config, param *models.CommonSystemParams) (string, error)

func RootListOrderByFromArgs

func RootListOrderByFromArgs(param *models.CommonSystemParams) string

RootListOrderByFromArgs builds ORDER BY from GraphQL `sort` args when present. Only FieldIsSortable model fields are applied. Falls back to RootListOrderBySQL.

func RootListOrderBySQL

func RootListOrderBySQL(modelType *models.ModelType) string

RootListOrderBySQL returns the default list ORDER BY clause for RootResolverQueryBuilder.

func RootResolverMediaQueryBuilder

func RootResolverMediaQueryBuilder(param *graphql.ResolveParams) (string, error)

func RootResolverQueryBuilder

func RootResolverQueryBuilder(cfg *models.Config, param *models.CommonSystemParams, returnCount bool) (string, []interface{}, error)

func SchemaModelByName

func SchemaModelByName(modelsList []*models.ModelType, name string) *models.ModelType

SchemaModelByName finds a schema model by name (case-insensitive).

func SelectBuilder

func SelectBuilder(mv string, local string, modelType *models.ModelType, returnCount bool) []string

func TenantFirstIndexColumns

func TenantFirstIndexColumns(sharedSaaS bool, columns ...string) []string

TenantFirstIndexColumns prefixes tenant_id for shared SaaS composite indexes.

func VerifyRelationCardinality

func VerifyRelationCardinality(session SQLSession, req relationmigrate.Request) (relationmigrate.Receipt, error)

VerifyRelationCardinality checks the target shape and pair degree without writing.

Types

type FieldClassification

type FieldClassification struct {
	MultilineFields []string
	PictureField    []string
	GalleryField    []string
	ListFields      []string
	RepeatedFields  map[string][]*models.FieldInfo
	ObjectField     []string
	BooleanFields   []string
	DateFields      []string
}

FieldClassification groups model fields by storage shape for document transformation.

func BuildFieldClassification

func BuildFieldClassification(fields []*models.FieldInfo) *FieldClassification

BuildFieldClassification groups model fields for CommonDocTransformation.

type QueryBuilderParam

type QueryBuilderParam struct {
	CollectionName string
	RelationName   string
	Args           map[string]interface{}
	ParentModel    string
	ModelType      *models.ModelType
}

type SQLSession

type SQLSession struct {
	Engine     string
	ScopeKey   string
	Exec       func(query string) error
	ExecArgs   func(query string, args ...interface{}) error
	Query      func(query string) ([][]string, error)
	DropColumn func(table, column string) error
}

SQLSession is the dialect-neutral executor used by every SQL project driver.

func NewBunSession

func NewBunSession(ctx context.Context, engine, scope string, db *bun.DB, dropColumn func(table, column string) error) SQLSession

NewBunSession binds a Bun database to SQLSession. dropColumn handles SQLite rebuilds.

type ShadowRefSource

type ShadowRefSource struct {
	Table  string
	Column string
}

ShadowRefSource is a tenant table/column that stores IDs of a common model.

func CommonModelShadowRefSources

func CommonModelShadowRefSources(schemaModels []*models.ModelType, common *models.ModelType) []ShadowRefSource

CommonModelShadowRefSources lists tenant FK and pivot columns that reference common.

type ShadowTarget

type ShadowTarget struct {
	Table string
	ID    string
}

ShadowTarget is an id-only upsert into a common-model shadow table.

func CommonShadowTargets

func CommonShadowTargets(modelsList []*models.ModelType, rootModel *models.ModelType, cdp *models.ConnectDisconnectParam) []ShadowTarget

CommonShadowTargets returns id-only upserts for common-model endpoints of a connect. ForwardConnectionID is always the mutating document (root model). ActionIDs are the related documents. Pairing ForwardConnectionType.Model with ForwardConnectionID is wrong — that field names the peer, not the owner of the uid.

Jump to

Keyboard shortcuts

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