sqlcommon

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: 23 Imported by: 0

Documentation

Index

Constants

View Source
const SQLUserProjectAccessGranted = `(invite_status IS NULL OR invite_status = '' OR invite_status = 'accepted')`

SQLUserProjectAccessGranted filters user_projects to accepted (or legacy empty) grants.

View Source
const SQLUserProjectAccessGrantedAliased = `(up.invite_status IS NULL OR up.invite_status = '' OR up.invite_status = 'accepted')`

SQLUserProjectAccessGrantedAliased is the same predicate for JOIN alias `up`.

Variables

This section is empty.

Functions

func AcceptGrantsByInviteToken

func AcceptGrantsByInviteToken(ctx context.Context, orm *bun.DB, hash, acceptedAt string) error

AcceptGrantsByInviteToken sets matching invited (or already-accepted) rows to accepted.

func BuildPostgresDSN

func BuildPostgresDSN(c *models.DriverCredentials) (string, error)

BuildPostgresDSN builds a libpq URL for pgdriver from credentials.

func CountUserProjects

func CountUserProjects(ctx context.Context, db *bun.DB, userIDs []string) (map[string]int, error)

CountUserProjects returns project membership counts for the given user IDs.

func DeleteUserProjectGrant

func DeleteUserProjectGrant(ctx context.Context, orm *bun.DB, projectID, userID string) error

DeleteUserProjectGrant removes one membership row.

func DropObsoleteTeamOrgTables

func DropObsoleteTeamOrgTables(ctx context.Context, orm *bun.DB) error

DropObsoleteTeamOrgTables drops the unused named Team/Organization graph. user_projects is kept. Safe on fresh installs (IF EXISTS).

func EmailEqFromParams

func EmailEqFromParams(param *models.CommonSystemParams) string

EmailEqFromParams returns where.email.eq from a system search param, or empty.

func EnsureApitoFunctionsCompositePK

func EnsureApitoFunctionsCompositePK(ctx context.Context, orm *bun.DB) error

EnsureApitoFunctionsCompositePK migrates legacy apito_functions tables that only had project_id as PK (or missing name column) to the composite (project_id, name) key used by ModelType. Safe to call on every RunMigration (idempotent).

func EnsureModelTypeUniqueKeysColumn

func EnsureModelTypeUniqueKeysColumn(ctx context.Context, db *bun.DB) error

EnsureModelTypeUniqueKeysColumn adds model_types.unique_keys on databases created before composite unique keys existed. CreateTable IF NOT EXISTS does not alter them.

func EnsureProjectIconColumn

func EnsureProjectIconColumn(ctx context.Context, db *bun.DB) error

EnsureProjectIconColumn adds projects.project_icon (branding URL for receipts). Bun CreateTable().IfNotExists() does not alter existing tables, so SELECT after Project.ProjectIcon growth fails with "no such column: project.project_icon".

func EnsureProjectPlanSeedOmissionsColumn

func EnsureProjectPlanSeedOmissionsColumn(ctx context.Context, db *bun.DB) error

EnsureProjectPlanSeedOmissionsColumn adds projects.plan_seed_omissions (JSON string array).

func EnsureProjectPlansColumn

func EnsureProjectPlansColumn(ctx context.Context, db *bun.DB) error

EnsureProjectPlansColumn adds projects.plans (JSON map of Plan ceilings). Bun CreateTable().IfNotExists() does not alter existing tables, so SELECT after Project.Plans growth fails with "no such column: project.plans".

func EnsureProjectTempBannedColumn

func EnsureProjectTempBannedColumn(ctx context.Context, db *bun.DB) error

EnsureProjectTempBannedColumn adds projects.temp_banned for grace/read-only freeze.

func EnsureProjectTokensMetadataColumns

func EnsureProjectTokensMetadataColumns(ctx context.Context, db *bun.DB) error

EnsureProjectTokensMetadataColumns adds token_id / token_prefix / token_fingerprint / created_at on existing project_tokens tables. Bun CreateTable().IfNotExists() does not alter existing tables, so SELECT after ProjectToken struct growth fails with "no such column: …token_id".

func EnsureProjectUsersOAuthSubColumn

func EnsureProjectUsersOAuthSubColumn(ctx context.Context, db *bun.DB) error

EnsureProjectUsersOAuthSubColumn adds project_users.oauth_sub for existing databases. Bun CreateTable().IfNotExists() does not alter existing tables, so multi-provider OAuth (and Pro createUser uniqueness SELECTs) fail with "no such column: pu.oauth_sub" until this runs.

func EnsureSystemUserAccessTokensColumn

func EnsureSystemUserAccessTokensColumn(ctx context.Context, db *bun.DB) error

EnsureSystemUserAccessTokensColumn adds system_users.access_tokens for existing databases. Bun CreateTable().IfNotExists() does not alter existing tables, so apt_ token storage would panic on SELECT until this runs.

func EnsureSystemUserIsSuperAdminColumn

func EnsureSystemUserIsSuperAdminColumn(ctx context.Context, db *bun.DB) error

EnsureSystemUserIsSuperAdminColumn adds system_users.is_super_admin for existing databases. Bun CreateTable().IfNotExists() does not alter existing tables.

func EnsureUserProjectInviteColumns

func EnsureUserProjectInviteColumns(ctx context.Context, db *bun.DB) error

EnsureUserProjectInviteColumns adds invite lifecycle columns on existing DBs.

func ErrCredentialsRequired

func ErrCredentialsRequired() error

ErrCredentialsRequired is returned when driver credentials are missing.

func ExecAlterIgnoreDuplicate

func ExecAlterIgnoreDuplicate(ctx context.Context, db *bun.DB, sql string) error

ExecAlterIgnoreDuplicate runs ALTER DDL and ignores duplicate-column errors.

func ExpireInvitesByToken

func ExpireInvitesByToken(ctx context.Context, orm *bun.DB, hash, nowRFC3339 string) error

ExpireInvitesByToken marks past-due invited rows expired.

func FullAdminPermissionsJSON

func FullAdminPermissionsJSON() string

FullAdminPermissionsJSON is the creator grant payload for user_projects.

func GetUserProjectGrant

func GetUserProjectGrant(ctx context.Context, orm *bun.DB, userID, projectID string) (*models.UserProject, error)

GetUserProjectGrant returns the raw membership row including pending invites.

func IsDuplicateColumnError

func IsDuplicateColumnError(err error) bool

IsDuplicateColumnError reports duplicate column DDL errors.

func IsSQLUniqueViolation

func IsSQLUniqueViolation(err error) bool

IsSQLUniqueViolation reports primary/unique constraint violations across SQL engines.

func ListProjectMembers

func ListProjectMembers(ctx context.Context, orm *bun.DB, projectID string) ([]*models.SystemUser, error)

ListProjectMembers lists console operators on a project from user_projects.

func ListUserProjects

func ListUserProjects(ctx context.Context, db *bun.DB, userIDs []string) (map[string][]UserProjectRow, error)

ListUserProjects returns project memberships for the given user IDs.

func LookupGrantsByInviteToken

func LookupGrantsByInviteToken(ctx context.Context, orm *bun.DB, hash string) ([]*models.UserProject, error)

LookupGrantsByInviteToken finds all user_projects rows for one invite batch.

func MapString

func MapString(m map[string]interface{}, key string) string

MapString reads a TEXT column from a bun map scan (string or []byte).

func NormalizeAllProjectPlanSystemFlags

func NormalizeAllProjectPlanSystemFlags(ctx context.Context, db *bun.DB) error

NormalizeAllProjectPlanSystemFlags walks every project row and persists:

  • free → system_generated=true (required default)
  • every other plan → system_generated=false (operator-owned, deletable)

Idempotent; safe on every RunMigration. Does not add/remove product tiers — that stays in Console / MCP / upsert-*-plans scripts.

func NormalizeEngine

func NormalizeEngine(engine string) string

NormalizeEngine returns the canonical engine constant.

func NowRFC3339

func NowRFC3339() string

NowRFC3339 is UTC RFC3339 for invite expiry compares.

func OpenMariaDB

func OpenMariaDB(cred *models.DriverCredentials) (*bun.DB, error)

OpenMariaDB opens a MariaDB system database (same driver as MySQL).

func OpenMySQL

func OpenMySQL(cred *models.DriverCredentials) (*bun.DB, error)

OpenMySQL opens a MySQL system database.

func OpenPostgres

func OpenPostgres(cred *models.DriverCredentials) (*bun.DB, error)

OpenPostgres opens a PostgreSQL system database.

func OpenSQLite

func OpenSQLite(cfg *models.Config, cred *models.DriverCredentials) (*bun.DB, error)

OpenSQLite opens a local SQLite system database. When SQLITE_DATA_DIR is set, the file is {SQLITE_DATA_DIR}/sqlite/system/system.db. That directory must be the public engine's own data folder.

func PersistProjectFunctionsTx

func PersistProjectFunctionsTx(ctx context.Context, tx bun.Tx, projectID string, schemaFunctions []*models.ApitoFunction) error

PersistProjectFunctionsTx deletes apito_functions rows for projectID whose name is not in schemaFunctions, then inserts or updates each function row. nil means no-op; empty slice deletes all.

func RegisterSystemSQLSchemaModels

func RegisterSystemSQLSchemaModels(orm *bun.DB)

RegisterSystemSQLSchemaModels registers m2m join types (user_projects, etc.) on this *bun.DB. Required for any query touching models with bun m2m tags — not only during RunMigration. Call once per opened system DB connection (idempotent).

func RetiredAddTeamMetaInfo

func RetiredAddTeamMetaInfo(docs []*models.SystemUser) ([]*models.SystemUser, error)

RetiredAddTeamMetaInfo is a no-op; membership metadata lives on user_projects.

func RetiredCreateOrganization

func RetiredCreateOrganization(org *models.Organization) (*models.Organization, error)

RetiredCreateOrganization keeps the ApitoSystemDB method compiling after the named Organization table is dropped. It does not persist.

func RetiredCreateTeam

func RetiredCreateTeam(team *models.Team) (*models.Team, error)

RetiredCreateTeam keeps CreateTeam compiling after the named Team table is dropped.

func RetiredFindOrganizationAdmin

func RetiredFindOrganizationAdmin() (*models.SystemUser, error)

RetiredFindOrganizationAdmin returns no admin after the org graph is retired.

func RetiredFindUserOrganizations

func RetiredFindUserOrganizations() ([]*models.Organization, error)

RetiredFindUserOrganizations returns no organizations.

func RetiredGetOrganizations

func RetiredGetOrganizations() (*models.SearchResponse[models.Organization], error)

RetiredGetOrganizations returns an empty search payload.

func RetiredGetProjectTeams

func RetiredGetProjectTeams() (*models.Team, error)

RetiredGetProjectTeams returns no named team.

func RetiredNoop

func RetiredNoop() error

RetiredNoop is Assign/Remove on the retired org graph.

func SearchSystemUsers

func SearchSystemUsers(ctx context.Context, db *bun.DB, param *models.CommonSystemParams) (*models.SearchResponse[models.SystemUser], error)

SearchSystemUsers lists console operators. Unscoped dumps require AllowUnscopedSystemUserList (searchPlatformAccounts). Team invite search must supply an email/name filter or it returns empty.

func SupportedEngine

func SupportedEngine(engine string) bool

SupportedEngine reports whether the engine string is a supported open-core system SQL engine.

func SystemSQLSchemaModels

func SystemSQLSchemaModels() []interface{}

SystemSQLSchemaModels returns the full ordered list of tables for RunMigration. Team/Organization and their join tables are still created so bun can walk m2m tags on SystemUser/Project; DropObsoleteTeamOrgTables removes them after.

func UpsertUserProjectGrant

func UpsertUserProjectGrant(ctx context.Context, orm *bun.DB, req *models.TeamMemberAddRequest) error

UpsertUserProjectGrant writes one console membership row. Permissions are JSON.

Types

type Base

type Base struct {
	Conf             *models.Config
	ORM              *bun.DB
	DriverCredential *models.DriverCredentials
}

Base holds shared Bun ORM state for all SQL system drivers.

func (*Base) AcceptGrantsByInviteToken

func (b *Base) AcceptGrantsByInviteToken(ctx context.Context, hash, acceptedAt string) error

func (*Base) ExpireInvitesByToken

func (b *Base) ExpireInvitesByToken(ctx context.Context, hash, nowRFC3339 string) error

func (*Base) FunctionLifecycleStore

func (b *Base) FunctionLifecycleStore() interfaces.FunctionLifecycleStore

FunctionLifecycleStore returns the store for sqlcommon.Base embedders.

func (*Base) GetUserProjectGrant

func (b *Base) GetUserProjectGrant(ctx context.Context, userID, projectID string) (*models.UserProject, error)

func (*Base) LookupGrantsByInviteToken

func (b *Base) LookupGrantsByInviteToken(ctx context.Context, hash string) ([]*models.UserProject, error)

type Driver

type Driver struct {
	Base
}

Driver embeds Base for system SQL drivers.

type OrganizationProjectRow

type OrganizationProjectRow struct {
	bun.BaseModel `bun:"table:organization_projects"`

	OrganizationID string `bun:"organization_id,type:uuid,pk"`
	ProjectID      string `bun:"project_id,type:uuid,pk"`
	AssignedBy     string `bun:"assigned_by,type:uuid,nullzero"`
	AssignedAt     string `bun:"assigned_at,type:timestamp,nullzero"`
}

type ProjectTeamRow

type ProjectTeamRow struct {
	bun.BaseModel `bun:"table:project_teams"`

	ProjectID string `bun:"project_id,type:uuid,pk"`
	UserID    string `bun:"user_id,type:uuid,pk"`
}

type RawDataRow

type RawDataRow struct {
	bun.BaseModel `bun:"table:raw_data"`

	ID         string `bun:"id,pk,type:uuid"`
	Collection string `bun:"collection,type:text"`
	Data       string `bun:"data,type:text"`
}

type SQLFunctionLifecycleStore

type SQLFunctionLifecycleStore struct {
	// contains filtered or unexported fields
}

SQLFunctionLifecycleStore persists function_* lifecycle tables via bun.

func NewSQLFunctionLifecycleStore

func NewSQLFunctionLifecycleStore(orm *bun.DB) *SQLFunctionLifecycleStore

NewSQLFunctionLifecycleStore wraps a bun DB.

func (*SQLFunctionLifecycleStore) GetRevision

func (s *SQLFunctionLifecycleStore) GetRevision(ctx context.Context, projectID, revisionID string) (*models.FunctionRevision, error)

func (*SQLFunctionLifecycleStore) ListDeployments

func (s *SQLFunctionLifecycleStore) ListDeployments(ctx context.Context, projectID, functionName string, limit int) ([]*models.FunctionDeployment, error)

func (*SQLFunctionLifecycleStore) ListRevisions

func (s *SQLFunctionLifecycleStore) ListRevisions(ctx context.Context, projectID, functionName string, limit int) ([]*models.FunctionRevision, error)

func (*SQLFunctionLifecycleStore) MarkDeploymentsSuperseded

func (s *SQLFunctionLifecycleStore) MarkDeploymentsSuperseded(ctx context.Context, projectID, functionName, exceptID string) error

func (*SQLFunctionLifecycleStore) SaveBuild

func (*SQLFunctionLifecycleStore) SaveDeployment

func (*SQLFunctionLifecycleStore) SaveInvocation

func (*SQLFunctionLifecycleStore) SaveRevision

type TeamMetadataRow

type TeamMetadataRow struct {
	bun.BaseModel `bun:"table:team_metadata"`

	ID   string `bun:"id,pk,type:uuid"`
	Data string `bun:"data,type:text"`
}

type TokenBlacklistRow

type TokenBlacklistRow struct {
	bun.BaseModel `bun:"table:token_blacklist"`

	TokenID string `bun:"token_id,pk,type:text"`
	Data    string `bun:"data,type:text"`
}

type UserMetadataRow

type UserMetadataRow struct {
	bun.BaseModel `bun:"table:user_metadata"`

	ID   string `bun:"id,pk,type:uuid"`
	Data string `bun:"data,type:text"`
}

type UserProjectRow

type UserProjectRow struct {
	UserID    string
	ProjectID string
	Name      string
	Role      string
}

UserProjectRow is a user_projects row plus the project name.

Jump to

Keyboard shortcuts

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