Documentation
¶
Overview ¶
Package core provides an API to include and use the GraphJin compiler with your own code. For detailed documentation visit https://graphjin.com
Index ¶
- Constants
- Variables
- func BuildCacheKey(ctx context.Context, opName string, apqKey string, query []byte, ...) string
- func BuildFederationSDL(schema *sdata.DBSchema, conf FederationConfig) (string, error)
- func CatalogRevisionFromSourceRevisions(source map[string]string) string
- func CatalogSourceRevisions(md *MetadataSnapshot, conf *Config, opts CatalogBuildOptions) map[string]string
- func GenerateDiffSQL(ops []SchemaOperation) []string
- func GenerateSchema(db *sql.DB, dbType string, blocklist []string) ([]byte, error)
- func NewOsFS(basePath string) *osFS
- func SchemaDiffMultiDB(connections map[string]*sql.DB, dbTypes map[string]string, schemaBytes []byte, ...) (map[string][]SchemaOperation, error)
- func ShouldCacheQuery(opName, apqKey string) bool
- func ValidateDBType(dbType string) error
- func ValidateMultiDBType(dbType string) error
- type Cache
- type CacheEntryOptions
- type CacheKeyBuilder
- type CatalogBuildOptions
- type CatalogCapability
- type CatalogCard
- type CatalogCardDetail
- type CatalogConfig
- type CatalogEdge
- type CatalogEntryPoint
- type CatalogFeature
- type CatalogFeatureArg
- type CatalogMatch
- type CatalogNode
- type CatalogQuery
- type CatalogQueryOutput
- type CatalogSnapshot
- func (s *CatalogSnapshot) Card(id string) (CatalogCard, bool)
- func (s *CatalogSnapshot) CardDetails(cardID string) []CatalogCardDetail
- func (s *CatalogSnapshot) CardEdges(cardID string) []CatalogEdge
- func (s *CatalogSnapshot) Query(q CatalogQuery) []CatalogCard
- func (s *CatalogSnapshot) QueryResult(q CatalogQuery) (CatalogQueryOutput, error)
- type CatalogWorkflow
- type CatalogWorkflowVariable
- type Column
- type ColumnInfo
- type Config
- func (c *Config) AddRoleTable(role, table string, conf interface{}) error
- func (c *Config) CatalogAutoCodeRelationsEnabled() bool
- func (c *Config) CatalogCodeDatabases() []string
- func (c *Config) CatalogDatabaseName() string
- func (c *Config) CatalogEnabled() bool
- func (c *Config) EffectiveAnalyticsMode(database string) bool
- func (c *Config) GraphJinSource() (SourceConfig, bool)
- func (c *Config) MetadataAutoCodeRelationsEnabled() bool
- func (c *Config) MetadataDatabaseName() string
- func (c *Config) MetadataEnabled() bool
- func (c *Config) NormalizeDatabases()
- func (c *Config) NormalizeSources() error
- func (c *Config) RemoveRoleTable(role, table string) error
- func (c *Config) SourceByName(name string) (SourceConfig, bool)
- func (c *Config) SourceMode() bool
- func (c *Config) Validate() error
- func (c *Config) ValidateSourceMode() error
- func (c *Config) WorkflowsSource() (SourceConfig, bool)
- type DDLDialect
- type DatabaseConfig
- type DatabaseStats
- type Delete
- type DiffOptions
- type DirectiveType
- type EnumValue
- type Error
- type FS
- type FederationConfig
- type FieldObject
- type FilesystemBackendFactory
- type FilesystemConfig
- type FragmentDetails
- type FragmentInfo
- type FullType
- type Function
- type FunctionInfo
- type FunctionParam
- type GraphEdge
- type GraphJin
- func (g *GraphJin) AuditAllRoles() ([]RoleAudit, error)
- func (g *GraphJin) AuditRolePermissions(role string) (*RoleAudit, error)
- func (g *GraphJin) CatalogSnapshot(exclude ...string) (*CatalogSnapshot, error)
- func (g *GraphJin) Close()
- func (g *GraphJin) DBForDatabase(database string) (*sql.DB, string, error)
- func (g *GraphJin) DatabaseNames() []string
- func (g *GraphJin) DefaultDatabase() string
- func (g *GraphJin) EffectiveAnalyticsMode(database string) bool
- func (g *GraphJin) ExplainQuery(query string, vars json.RawMessage, role string) (*QueryExplanation, error)
- func (g *GraphJin) ExploreRelationships(table string, depth int) (*RelationshipGraph, error)
- func (g *GraphJin) ExploreRelationshipsForDatabase(database, table string, depth int) (*RelationshipGraph, error)
- func (g *GraphJin) FilesystemBackend(name string) (fstable.Backend, bool)
- func (g *GraphJin) FindRelationshipPath(fromTable, toTable string) ([]PathStep, error)
- func (g *GraphJin) FindRelationshipPathForDatabase(database, fromTable, toTable string) ([]PathStep, error)
- func (g *GraphJin) GenerateOpenAPISpec() (*OpenAPIDocument, error)
- func (g *GraphJin) GetAllDatabaseStats() []DatabaseStats
- func (g *GraphJin) GetFragment(name string) (*FragmentDetails, error)
- func (g *GraphJin) GetFunctions() []FunctionInfo
- func (g *GraphJin) GetFunctionsForDatabase(database string) []FunctionInfo
- func (g *GraphJin) GetOpenAPISpec() ([]byte, error)
- func (g *GraphJin) GetSavedQuery(name string) (*SavedQueryDetails, error)
- func (g *GraphJin) GetTableSchema(tableName string) (*TableSchema, error)
- func (g *GraphJin) GetTableSchemaForDatabase(database, tableName string) (*TableSchema, error)
- func (g *GraphJin) GetTableSchemaForDatabaseSchema(database, schemaName, tableName string) (*TableSchema, error)
- func (g *GraphJin) GetTables() []TableInfo
- func (g *GraphJin) GetTablesForDatabase(database string) []TableInfo
- func (g *GraphJin) GraphQL(c context.Context, query string, vars json.RawMessage, rc *RequestConfig) (res *Result, err error)
- func (g *GraphJin) GraphQLByName(c context.Context, name string, vars json.RawMessage, rc *RequestConfig) (res *Result, err error)
- func (g *GraphJin) GraphQLByNameTx(c context.Context, tx *sql.Tx, name string, vars json.RawMessage, ...) (res *Result, err error)
- func (g *GraphJin) GraphQLTx(c context.Context, tx *sql.Tx, query string, vars json.RawMessage, ...) (res *Result, err error)
- func (g *GraphJin) InvalidateCacheRefs(ctx context.Context, refs []RowRef) error
- func (g *GraphJin) IsProd() bool
- func (g *GraphJin) ListFragments() ([]FragmentInfo, error)
- func (g *GraphJin) ListSavedQueries() ([]SavedQueryInfo, error)
- func (g *GraphJin) MetadataSnapshot(exclude ...string) (*MetadataSnapshot, error)
- func (g *GraphJin) OnSchemaChange(fn func(dbName string, hash string))
- func (g *GraphJin) Reload() error
- func (g *GraphJin) ReloadWithDB(db *sql.DB) error
- func (g *GraphJin) SchemaReady() bool
- func (g *GraphJin) SetOptions(opts ...Option)
- func (g *GraphJin) Subscribe(c context.Context, query string, vars json.RawMessage, rc *RequestConfig) (m *Member, err error)
- func (g *GraphJin) SubscribeByName(c context.Context, name string, vars json.RawMessage, rc *RequestConfig) (m *Member, err error)
- type GraphNode
- type GraphqlReq
- type GraphqlResponse
- type Header
- type InputValue
- type Insert
- type IntroResult
- type Introspection
- type IntrospectionSchema
- type ManagedColumn
- type ManagedMutationField
- type ManagedMutationHandler
- type ManagedMutationRequest
- type ManagedMutationRoot
- type ManagedOrderBy
- type ManagedQueryHandler
- type ManagedQueryRequest
- type ManagedQueryRoot
- type ManagedTable
- type MediaType
- type Member
- type MetadataColumn
- type MetadataConfig
- type MetadataDatabase
- type MetadataFunction
- type MetadataIndex
- type MetadataRelationship
- type MetadataSnapshot
- type MetadataTable
- type NanoColumn
- type NanoDB
- type NanoRow
- type NanoSnapshot
- type NanoTable
- type OpType
- type OpenAPIComponents
- type OpenAPIDocument
- type OpenAPIInfo
- type OpenAPIOperation
- type OpenAPIServer
- type OperationPermission
- type Option
- func OptionSetDatabases(connections map[string]*sql.DB) Option
- func OptionSetFS(fs FS) Option
- func OptionSetFilesystemBackend(name string, factory FilesystemBackendFactory) Option
- func OptionSetManagedMutationHandler(database string, handler ManagedMutationHandler) Option
- func OptionSetManagedQueryHandler(database string, handler ManagedQueryHandler) Option
- func OptionSetNamespace(namespace string) Option
- func OptionSetNanoDatabases(databases map[string]*NanoDB) Option
- func OptionSetResolver(name string, fn ResolverFn) Option
- func OptionSetResponseCache(cache ResponseCacheProvider) Option
- func OptionSetTrace(trace Tracer) Option
- type ParamInfo
- type Parameter
- type PartitionConfig
- type PathItem
- type PathStep
- type PoolStats
- type Query
- type QueryAnalysis
- type QueryExplanation
- type RefreshFn
- type RefreshFnWithOptions
- type RelationInfo
- type RelationshipConfig
- type RelationshipGraph
- type RequestBody
- type RequestConfig
- type Resolver
- type ResolverConfig
- type ResolverFn
- type ResolverProps
- type ResolverReq
- type Response
- type ResponseCacheProvider
- type ResponseCacheProviderWithOptions
- type ResponseProcessor
- type Result
- type Role
- type RoleAudit
- type RoleTable
- type RowRef
- func CodeSQLTableRefs(database string, tables []string) []RowRef
- func DBRowRef(database, table, id string) RowRef
- func DBTableRef(database, table string) RowRef
- func ExtractMutationRefs(qc *qcode.QCode, data []byte) []RowRef
- func FilesystemKeyRefs(name, key string) []RowRef
- func FilesystemPrefixRef(name, prefix string) RowRef
- func FilesystemPrefixRefs(name, prefix string) []RowRef
- func RemoteResolverRef(scope, id string) RowRef
- func RemoteResolverRefs(scope string, ids ...string) []RowRef
- type SWRRefresher
- type SWRRefresherWithOptions
- type SavedQueryDetails
- type SavedQueryInfo
- type Schema
- type SchemaOperation
- type SelectInfo
- type ShortFullType
- type SnowflakeKeyPairConfig
- type SourceConfig
- type Spaner
- type StringAttr
- type Table
- type TableInfo
- type TablePermissions
- type TableSchema
- type Tracer
- type TypeRef
- type Update
- type Upsert
Constants ¶
const ( // Name of the authentication provider. Eg. google, github, etc UserIDProviderKey contextkey = iota // The raw user id (jwt sub) value UserIDRawKey // User ID value for authenticated users UserIDKey // User role if pre-defined UserRoleKey )
Constants to set values on the context passed to the NewGraphJin function
const ( CacheSourceDB = "db" CacheSourceCodeSQL = "codesql" CacheSourceFS = "fs" CacheSourceRemote = "remote" CacheKindRow = "row" CacheKindTable = "table" CacheKindKey = "key" CacheKindPrefix = "prefix" CacheKindResolver = "resolver" )
const ( KIND_SCALAR = "SCALAR" KIND_OBJECT = "OBJECT" KIND_NONNULL = "NON_NULL" KIND_LIST = "LIST" KIND_UNION = "UNION" KIND_ENUM = "ENUM" KIND_INPUT_OBJ = "INPUT_OBJECT" LOC_QUERY = "QUERY" LOC_MUTATION = "MUTATION" LOC_SUBSCRIPTION = "SUBSCRIPTION" LOC_FIELD = "FIELD" SUFFIX_EXP = "Expression" SUFFIX_LISTEXP = "ListExpression" SUFFIX_INPUT = "Input" SUFFIX_ORDER_BY = "OrderByInput" SUFFIX_WHERE = "WhereInput" SUFFIX_ARGS = "ArgsInput" SUFFIX_ENUM = "Enum" )
const (
APQ_PX = "_apq"
)
const DefaultDBName = "default"
DefaultDBName is the canonical name used for the primary/default database after config normalization. It replaces the empty-string and "_default" sentinels.
Variables ¶
var ( TYPE_STRING = "String" TYPE_INT = "Int" TYPE_BOOLEAN = "Boolean" TYPE_FLOAT = "Float" TYPE_JSON = "JSON" )
var (
ErrNotFound = errors.New("not found in prepared statements")
)
var SupportedDBTypes = []string{"postgres", "mysql", "mariadb", "sqlite", "oracle", "mssql", "mongodb", "snowflake", "nanodb"}
SupportedDBTypes lists the database types supported for single-database mode
var SupportedMultiDBTypes = []string{"postgres", "mysql", "mariadb", "sqlite", "oracle", "mongodb", "mssql", "snowflake", "nanodb"}
SupportedMultiDBTypes lists the database types supported for multi-database mode
Functions ¶
func BuildCacheKey ¶ added in v3.2.0
func BuildCacheKey( ctx context.Context, opName string, apqKey string, query []byte, vars json.RawMessage, role string, databases ...string, ) string
BuildCacheKey is a convenience function that builds a cache key
func BuildFederationSDL ¶ added in v3.18.14
func BuildFederationSDL(schema *sdata.DBSchema, conf FederationConfig) (string, error)
BuildFederationSDL emits a Federation v2 subgraph SDL for the supplied schema. The output is intentionally compact and deterministic so it can be diffed across schema reloads and supergraph compositions.
Tables marked Blocked, alias-only tables, and tables with no primary key are skipped — Apollo entities require a @key directive.
func CatalogRevisionFromSourceRevisions ¶ added in v3.18.19
func CatalogSourceRevisions ¶ added in v3.18.19
func CatalogSourceRevisions(md *MetadataSnapshot, conf *Config, opts CatalogBuildOptions) map[string]string
func GenerateDiffSQL ¶ added in v3.2.0
func GenerateDiffSQL(ops []SchemaOperation) []string
GenerateDiffSQL converts operations to SQL strings
func GenerateSchema ¶ added in v3.3.0
GenerateSchema generates a db.graphql schema from database introspection
func SchemaDiffMultiDB ¶ added in v3.2.0
func SchemaDiffMultiDB( connections map[string]*sql.DB, dbTypes map[string]string, schemaBytes []byte, blocklist []string, opts DiffOptions, ) (map[string][]SchemaOperation, error)
SchemaDiffMultiDB computes schema diffs across multiple databases. Tables are assigned to databases based on the @database directive in the schema. Every table must have a @database directive when multiple databases are configured.
func ShouldCacheQuery ¶ added in v3.2.0
ShouldCacheQuery is a convenience function that checks if query should be cached
func ValidateDBType ¶ added in v3.2.7
ValidateDBType checks if the given database type is supported
func ValidateMultiDBType ¶ added in v3.2.7
ValidateMultiDBType checks if the given database type is supported for multi-database mode
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache provides local in-memory caching for APQ and introspection
type CacheEntryOptions ¶ added in v3.18.18
type CacheEntryOptions struct {
// HardTTL caps the provider hard TTL. Providers must not extend their
// configured TTL to satisfy this value.
HardTTL time.Duration
// FreshTTL caps the provider fresh TTL used for SWR. Providers must not
// extend their configured fresh TTL to satisfy this value.
FreshTTL time.Duration
// NoStore tells providers to skip storing this entry.
NoStore bool
}
CacheEntryOptions lets callers narrow cache lifetime for one entry without changing provider-wide defaults.
type CacheKeyBuilder ¶ added in v3.2.0
type CacheKeyBuilder struct{}
CacheKeyBuilder builds cache keys from query context
func NewCacheKeyBuilder ¶ added in v3.2.0
func NewCacheKeyBuilder() *CacheKeyBuilder
NewCacheKeyBuilder creates a new cache key builder
func (*CacheKeyBuilder) Build ¶ added in v3.2.0
func (b *CacheKeyBuilder) Build( ctx context.Context, opName string, apqKey string, query []byte, vars json.RawMessage, role string, databases ...string, ) string
Build creates a cache key from query parameters and context. The key is a SHA256 hash of: query identifier + query text + variables + database scope + user_id + role.
func (*CacheKeyBuilder) BuildFragment ¶ added in v3.18.18
func (b *CacheKeyBuilder) BuildFragment( ctx context.Context, kind string, role string, parts map[string]interface{}, ) string
BuildFragment creates a cache key for a source-owned execution fragment. Parts should fully describe the fragment's source, selection, variables, and compiled statement shape; the builder adds role/user isolation.
func (*CacheKeyBuilder) ShouldCache ¶ added in v3.2.0
func (b *CacheKeyBuilder) ShouldCache(opName, apqKey string) bool
ShouldCache determines if a query should be cached. Only named queries and APQ queries are cached (skip anonymous).
type CatalogBuildOptions ¶ added in v3.18.19
type CatalogBuildOptions = catalog.BuildOptions
type CatalogCapability ¶ added in v3.18.19
type CatalogCapability = catalog.Capability
type CatalogCard ¶ added in v3.18.19
type CatalogCardDetail ¶ added in v3.18.19
type CatalogCardDetail = catalog.CardDetail
type CatalogConfig ¶ added in v3.18.19
type CatalogConfig struct {
// Enabled controls whether GraphJin exposes catalog tables.
// When omitted, it defaults to enabled in dev and disabled in production.
Enabled any `` /* 156-byte string literal not displayed */
// Database is the virtual database name. Defaults to "graphjin".
Database string `mapstructure:"database" json:"database" yaml:"database" jsonschema:"title=Catalog Database,default=graphjin"`
// Samples controls whether live sample/profile data is inlined or fetched on
// demand. Default: on_demand.
Samples string `` /* 145-byte string literal not displayed */
// AutoCodeRelations controls automatic relationships from catalog/schema
// tables to CodeSQL's code_db_refs. When omitted, it follows Enabled.
AutoCodeRelations any `` /* 191-byte string literal not displayed */
// CodeDatabases optionally pins which CodeSQL database should be linked.
// Empty means auto-detect, but only when exactly one CodeSQL DB exists.
CodeDatabases []string `` /* 130-byte string literal not displayed */
}
CatalogConfig controls the managed AI-first catalog graph database.
type CatalogEdge ¶ added in v3.18.19
type CatalogEntryPoint ¶ added in v3.18.19
type CatalogEntryPoint = catalog.EntryPoint
type CatalogFeature ¶ added in v3.18.19
func LanguageFeatures ¶ added in v3.18.19
func LanguageFeatures() []CatalogFeature
LanguageFeatures returns the structured GraphJin language registry used by the AI catalog, MCP guidance, and drift tests.
type CatalogFeatureArg ¶ added in v3.18.19
type CatalogFeatureArg = catalog.FeatureArg
type CatalogMatch ¶ added in v3.18.19
type CatalogNode ¶ added in v3.18.19
type CatalogQuery ¶ added in v3.18.19
type CatalogQueryOutput ¶ added in v3.18.19
type CatalogQueryOutput = catalog.QueryResult
type CatalogSnapshot ¶ added in v3.18.19
func BuildCatalogSnapshot ¶ added in v3.18.19
func BuildCatalogSnapshot(md *MetadataSnapshot, conf *Config) *CatalogSnapshot
BuildCatalogSnapshot builds a catalog from an existing metadata snapshot. Service code uses this while refreshing the managed catalog database so schema metadata and catalog rows are produced from the same point-in-time snapshot.
func BuildCatalogSnapshotWithOptions ¶ added in v3.18.19
func BuildCatalogSnapshotWithOptions(md *MetadataSnapshot, conf *Config, opts CatalogBuildOptions) *CatalogSnapshot
func (*CatalogSnapshot) Card ¶ added in v3.18.19
func (s *CatalogSnapshot) Card(id string) (CatalogCard, bool)
func (*CatalogSnapshot) CardDetails ¶ added in v3.18.19
func (s *CatalogSnapshot) CardDetails(cardID string) []CatalogCardDetail
func (*CatalogSnapshot) CardEdges ¶ added in v3.18.19
func (s *CatalogSnapshot) CardEdges(cardID string) []CatalogEdge
func (*CatalogSnapshot) Query ¶ added in v3.18.19
func (s *CatalogSnapshot) Query(q CatalogQuery) []CatalogCard
func (*CatalogSnapshot) QueryResult ¶ added in v3.18.19
func (s *CatalogSnapshot) QueryResult(q CatalogQuery) (CatalogQueryOutput, error)
type CatalogWorkflow ¶ added in v3.18.19
type CatalogWorkflowVariable ¶ added in v3.18.19
type CatalogWorkflowVariable = catalog.WorkflowVariable
type Column ¶
type Column struct {
Name string
Type string `jsonschema:"example=integer,example=text"`
Primary bool
Array bool
FullText bool `mapstructure:"full_text" json:"full_text" yaml:"full_text" jsonschema:"title=Full Text Search"`
ForeignKey string `` /* 138-byte string literal not displayed */
}
Configuration for a database table column
type ColumnInfo ¶ added in v3.2.0
type ColumnInfo struct {
Name string `json:"name"`
Type string `json:"type"`
Nullable bool `json:"nullable"`
PrimaryKey bool `json:"primary_key"`
ForeignKey string `json:"foreign_key,omitempty"` // "schema.table.column" if FK
Array bool `json:"array,omitempty"`
Default string `json:"default,omitempty"`
UniqueKey bool `json:"unique_key,omitempty"`
Index bool `json:"index,omitempty"`
IndexName string `json:"index_name,omitempty"`
FullText bool `json:"full_text,omitempty"`
ForeignKeyDatabase string `json:"foreign_key_database,omitempty"`
ForeignKeyRecursive bool `json:"foreign_key_recursive,omitempty"`
}
ColumnInfo represents column information for MCP/API consumers
type Config ¶
type Config struct {
// Is used to encrypt opaque values such as the cursor. Auto-generated when not set
SecretKey string `` /* 140-byte string literal not displayed */
// When set to true it disables the allow list workflow
DisableAllowList bool `` /* 137-byte string literal not displayed */
// When set to true a database schema file will be generated in dev mode and
// used in production mode. Auto database discovery will be disabled
// in production mode.
EnableSchema bool `mapstructure:"enable_schema" json:"enable_schema" yaml:"enable_schema" jsonschema:"title=Enable Schema,default=false"`
// When set to true an introspection json file will be generated in dev mode.
// This file can be used with other GraphQL tooling to generate clients, enable
// autocomplete, etc
EnableIntrospection bool `` /* 152-byte string literal not displayed */
// Forces the database session variable 'user.id' to be set to the user id
SetUserID bool `mapstructure:"set_user_id" json:"set_user_id" yaml:"set_user_id" jsonschema:"title=Set User ID,default=false"`
// This ensures that for anonymous users (role 'anon') all tables are blocked
// from queries and mutations. To open access to tables for anonymous users
// they have to be added to the 'anon' role config
DefaultBlock bool `` /* 135-byte string literal not displayed */
// This is a list of variables that can be leveraged in your queries.
// (eg. variable admin_id will be $admin_id in the query)
Vars map[string]string `mapstructure:"variables" json:"variables" yaml:"variables" jsonschema:"title=Variables"`
// This is a list of variables that map to http header values
HeaderVars map[string]string `mapstructure:"header_variables" json:"header_variables" yaml:"header_variables" jsonschema:"title=Header Variables"`
// A list of tables and columns that should disallowed in any and all queries
Blocklist []string `jsonschema:"title=Block List"`
// The configs for custom resolvers. For example the `remote_api`
// resolver would join json from a remote API into your query response
Resolvers []ResolverConfig `jsonschema:"-"`
// Sources is the canonical graph provider config. When present, all SQL,
// CodeSQL, filesystem, OpenAPI, GraphJin system, and workflow providers must
// be declared here instead of legacy top-level sections.
Sources []SourceConfig `mapstructure:"sources" json:"sources" yaml:"sources" jsonschema:"title=Sources"`
// OpenAPISpecsDir is the directory that GraphJin scans at startup for
// OpenAPI 3 specification files (*.yaml / *.yml). Each spec dropped in
// is parsed, classified, and exposed as remote-joinable fields and/or
// top-level virtual tables. Defaults to "./config/specs" when empty.
OpenAPISpecsDir string `` /* 148-byte string literal not displayed */
// OpenAPI carries per-spec configuration keyed by the spec filename
// without extension (e.g. "interaction_studio" matches
// "config/specs/interaction_studio.yaml"). Operations classifiable from
// the spec are auto-exposed; entries here add credentials, base URL
// overrides, DB-to-API join wiring, and concurrency caps.
OpenAPI map[string]openapi.SpecConfig `mapstructure:"openapi" json:"openapi" yaml:"openapi" jsonschema:"-"`
// All table specific configuration such as aliased tables and relationships
// between tables
Tables []Table `jsonschema:"title=Tables"`
// Relationships adds graph edges between typed table columns. Cardinality is
// inferred from existing primary/unique metadata and reverse edges are still
// generated by the schema graph.
Relationships []RelationshipConfig `mapstructure:"relationships" json:"relationships" yaml:"relationships" jsonschema:"title=Relationships"`
// All function specific configuration such as return types
Functions []Function `jsonschema:"title=Functions"`
// An SQL query if set enables attribute based access control. This query is
// used to fetch the user attribute that then dynamically define the users role
RolesQuery string `mapstructure:"roles_query" json:"roles_query" yaml:"roles_query" jsonschema:"title=Roles Query"`
// Roles contains the configuration for all the roles you want to support 'user' and
// 'anon' are two default roles. The 'user' role is used when a user ID is available
// and 'anon' when it's not. Use the 'Roles Query' config to add more custom roles
Roles []Role
// Database type name Defaults to 'postgres' (options: postgres, mysql, mariadb, sqlite, oracle, mssql, nanodb)
DBType string `` /* 185-byte string literal not displayed */
// Log warnings and other debug information
Debug bool `jsonschema:"title=Debug,default=false"`
// Log SQL Query variable values
LogVars bool `mapstructure:"log_vars" json:"log_vars" yaml:"log_vars" jsonschema:"title=Log Variables,default=false"`
// Database polling duration (in seconds) used by subscriptions to
// query for updates.
SubsPollDuration time.Duration `` /* 145-byte string literal not displayed */
// Upper bound on how many subscribers a single subscription poll cycle
// will batch into one database query. The adaptive sizer never grows
// past this value. When zero a sensible default is used.
SubsMaxMembersPerWorker int `` /* 180-byte string literal not displayed */
// Lower bound on the adaptive subscription chunk size; prevents the
// sizer from shrinking down to per-row queries under sustained load.
// When zero a sensible default is used.
SubsMinMembersPerWorker int `` /* 178-byte string literal not displayed */
// Target query latency for the adaptive subscription chunk sizer.
// When zero it is auto-derived as one quarter of subs_poll_duration.
SubsTargetQueryLatency time.Duration `` /* 231-byte string literal not displayed */
// The default max limit (number of rows) when a limit is not defined in
// the query or the table role config.
DefaultLimit int `mapstructure:"default_limit" json:"default_limit" yaml:"default_limit" jsonschema:"title=Default Row Limit,default=20"`
AnalyticsMode bool `` /* 190-byte string literal not displayed */
// Disable all aggregation functions like count, sum, etc
DisableAgg bool `` /* 148-byte string literal not displayed */
// Disable all functions like count, length, etc
DisableFuncs bool `` /* 133-byte string literal not displayed */
// When set to true, GraphJin will not connect to a database and instead
// return mock data based on the query structure.
MockDB bool `mapstructure:"mock_db" json:"mock_db" yaml:"mock_db" jsonschema:"title=Mock DB,default=false"`
// Enable automatic coversion of camel case in GraphQL to snake case in SQL
EnableCamelcase bool `` /* 130-byte string literal not displayed */
// When enabled GraphJin runs with production level security defaults.
// For example allow lists are enforced.
Production bool `jsonschema:"title=Production Mode,default=false"`
// SecurityMode selects the secure-default matrix used for security
// reporting and agent-facing guidance. Empty derives from Production.
SecurityMode string `` /* 135-byte string literal not displayed */
// Duration for polling the database to detect schema changes
DBSchemaPollDuration time.Duration `` /* 172-byte string literal not displayed */
// When set to true it disables production security features like enforcing the allow list
DisableProdSecurity bool `` /* 159-byte string literal not displayed */
// The filesystem to use for this instance of GraphJin
FS interface{} `mapstructure:"-" jsonschema:"-" json:"-"`
// Multiple database configurations for multi-database support.
// When set, allows querying across multiple databases in a single GraphQL request.
// Each database gets its own connection pool, schema, and SQL compiler.
Databases map[string]DatabaseConfig `mapstructure:"databases" json:"databases" yaml:"databases" jsonschema:"title=Databases"`
// CacheTrackingEnabled enables injection of __gj_id fields for cache row tracking.
// This is set by the service layer when Redis caching is enabled.
CacheTrackingEnabled bool `mapstructure:"-" json:"-" yaml:"-" jsonschema:"-"`
// Federation opts the engine into Apollo Federation v2 subgraph mode.
// When Federation.Enabled is true, `_service { sdl }` returns a
// federation-flavoured SDL describing the schema's tables. See
// FederationConfig for the full surface.
Federation FederationConfig `mapstructure:"federation" json:"federation" yaml:"federation" jsonschema:"title=Apollo Federation v2"`
// Filesystems exposes object stores (local directories, S3, GCS) as
// virtual tables in the GraphQL schema. Each entry materialises one
// table with a fixed shape — key/size/content_type/etag/modified_at/url/data —
// and routes queries through a pluggable Backend.
Filesystems []FilesystemConfig `mapstructure:"filesystems" json:"filesystems" yaml:"filesystems" jsonschema:"title=Filesystem Tables"`
// Metadata exposes GraphJin-discovered database metadata for legacy
// internal helpers. Public GraphQL discovery should use gj_catalog
// catalog items instead of separate table/column roots.
Metadata MetadataConfig `mapstructure:"metadata" json:"metadata" yaml:"metadata" jsonschema:"title=Metadata Graph"`
// Catalog exposes GraphJin's AI-first self-model as a managed read-only
// database. It supersedes the older metadata-only graph.
Catalog CatalogConfig `mapstructure:"catalog" json:"catalog" yaml:"catalog" jsonschema:"title=Catalog Graph"`
// contains filtered or unexported fields
}
Configuration for the GraphJin compiler core
func (*Config) AddRoleTable ¶
AddRoleTable function is a helper function to make it easy to add per-table row-level config
func (*Config) CatalogAutoCodeRelationsEnabled ¶ added in v3.18.19
func (*Config) CatalogCodeDatabases ¶ added in v3.18.19
func (*Config) CatalogDatabaseName ¶ added in v3.18.19
func (*Config) CatalogEnabled ¶ added in v3.18.19
func (*Config) EffectiveAnalyticsMode ¶ added in v3.18.3
func (*Config) GraphJinSource ¶ added in v3.18.19
func (c *Config) GraphJinSource() (SourceConfig, bool)
func (*Config) MetadataAutoCodeRelationsEnabled ¶ added in v3.18.18
func (*Config) MetadataDatabaseName ¶ added in v3.18.18
func (*Config) MetadataEnabled ¶ added in v3.18.18
func (*Config) NormalizeDatabases ¶ added in v3.8.0
func (c *Config) NormalizeDatabases()
NormalizeDatabases ensures the primary database is represented as an entry in the Databases map, eliminating special-casing of empty targetDB strings. It is idempotent and should be called during core initialization.
func (*Config) NormalizeSources ¶ added in v3.18.19
NormalizeSources translates public sources into the existing runtime config fields consumed by the engine and service. It is intentionally idempotent.
func (*Config) RemoveRoleTable ¶
func (*Config) SourceByName ¶ added in v3.18.19
func (c *Config) SourceByName(name string) (SourceConfig, bool)
func (*Config) SourceMode ¶ added in v3.18.19
SourceMode returns true when the public config is using the new sources boundary. Without sources, GraphJin stays in legacy database-only mode.
func (*Config) ValidateSourceMode ¶ added in v3.18.19
ValidateSourceMode checks the public config mode boundary before any source entries are normalized into legacy runtime fields.
func (*Config) WorkflowsSource ¶ added in v3.18.19
func (c *Config) WorkflowsSource() (SourceConfig, bool)
type DDLDialect ¶ added in v3.2.0
type DDLDialect interface {
Name() string
QuoteIdentifier(s string) string
MapType(graphqlType string, notNull bool, primaryKey bool) string
MapDefault(defaultVal string) string
CreateTable(table sdata.DBTable) string
AddColumn(tableName string, col sdata.DBColumn) string
DropColumn(tableName, colName string) string
DropTable(tableName string) string
AddForeignKey(tableName string, col sdata.DBColumn) string
CreateSearchIndex(tableName string, col sdata.DBColumn) string
CreateUniqueIndex(tableName string, col sdata.DBColumn) string
CreateIndex(tableName string, col sdata.DBColumn) string
AlterClusteringKey(tableName string, keys []string) string
}
DDLDialect defines how to generate DDL for a specific database
type DatabaseConfig ¶ added in v3.2.0
type DatabaseConfig struct {
// Database type (postgres, mysql, mariadb, sqlite, oracle, mongodb, snowflake, nanodb)
Type string `` /* 191-byte string literal not displayed */
// ManagedType preserves the service-level logical database type after a
// managed database has been translated to its runtime driver.
ManagedType string `mapstructure:"-" json:"-" yaml:"-" jsonschema:"-"`
// Connection string for the database (alternative to individual params)
ConnString string `` /* 171-byte string literal not displayed */
// Database host
Host string `mapstructure:"host" json:"host" yaml:"host" jsonschema:"title=Host"`
// Database port
Port int `mapstructure:"port" json:"port" yaml:"port" jsonschema:"title=Port"`
// Database name
DBName string `mapstructure:"dbname" json:"dbname" yaml:"dbname" jsonschema:"title=Database Name"`
// Database user
User string `mapstructure:"user" json:"user" yaml:"user" jsonschema:"title=User"`
// Database password
Password string `` /* 131-byte string literal not displayed */
// File path for SQLite databases
Path string `mapstructure:"path" json:"path" yaml:"path" jsonschema:"title=File Path (SQLite)"`
// Maximum number of open connections
MaxOpenConns int `mapstructure:"max_open_conns" json:"max_open_conns" yaml:"max_open_conns" jsonschema:"title=Max Open Connections"`
// Maximum number of idle connections
MaxIdleConns int `mapstructure:"max_idle_conns" json:"max_idle_conns" yaml:"max_idle_conns" jsonschema:"title=Max Idle Connections"`
// Schema name to use (for databases that support schemas)
Schema string `mapstructure:"schema" json:"schema" yaml:"schema" jsonschema:"title=Schema"`
// Connection pool settings
PoolSize int `mapstructure:"pool_size" json:"pool_size" yaml:"pool_size" jsonschema:"title=Connection Pool Size"`
MaxConnections int `mapstructure:"max_connections" json:"max_connections" yaml:"max_connections" jsonschema:"title=Maximum Connections"`
MaxConnIdleTime time.Duration `` /* 143-byte string literal not displayed */
MaxConnLifeTime time.Duration `` /* 143-byte string literal not displayed */
// Health check
PingTimeout time.Duration `mapstructure:"ping_timeout" json:"ping_timeout" yaml:"ping_timeout" jsonschema:"title=Healthcheck Ping Timeout"`
// TLS settings
EnableTLS bool `mapstructure:"enable_tls" json:"enable_tls" yaml:"enable_tls" jsonschema:"title=Enable TLS"`
ServerName string `mapstructure:"server_name" json:"server_name" yaml:"server_name" jsonschema:"title=TLS Server Name"`
ServerCert string `` /* 155-byte string literal not displayed */
ClientCert string `` /* 155-byte string literal not displayed */
ClientKey string `` /* 145-byte string literal not displayed */
// MSSQL-specific: disable TLS encryption (go-mssqldb defaults to encrypt=true)
Encrypt *bool `mapstructure:"encrypt" json:"encrypt,omitempty" yaml:"encrypt,omitempty" jsonschema:"title=MSSQL Encrypt"`
// MSSQL-specific: trust server certificate without validation
TrustServerCertificate *bool `` /* 173-byte string literal not displayed */
// Snowflake key pair authentication (PKCS#8 PEM format).
// Generate key: openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8
PrivateKeyPath string `` /* 184-byte string literal not displayed */
PrivateKeyPEM string `` /* 177-byte string literal not displayed */
KeyPassphrase string `` /* 167-byte string literal not displayed */
// Read-only mode — blocks all mutations and DDL against this database.
// Once set in config, cannot be changed at runtime via MCP tools.
ReadOnly bool `mapstructure:"read_only" json:"read_only" yaml:"read_only" jsonschema:"title=Read Only"`
AnalyticsMode *bool `` /* 145-byte string literal not displayed */
// InferDBRefs controls CodeSQL's best-effort code-to-database reference
// inference. It is only used for databases with type: codesql.
InferDBRefs *bool `` /* 135-byte string literal not displayed */
}
DatabaseConfig defines configuration for a single database in multi-database mode
type DatabaseStats ¶ added in v3.2.0
type DatabaseStats struct {
Name string `json:"name"`
Type string `json:"type"`
IsDefault bool `json:"isDefault"`
ReadOnly bool `json:"readOnly"`
TableCount int `json:"tableCount"`
Pool *PoolStats `json:"pool,omitempty"`
}
DatabaseStats represents statistics and info for a database connection
type DiffOptions ¶ added in v3.2.0
type DiffOptions struct {
// Destructive enables DROP TABLE and DROP COLUMN operations
Destructive bool
}
DiffOptions controls what operations are included in the schema diff
type DirectiveType ¶
type DirectiveType struct {
Name string `json:"name"`
Description string `json:"description"`
Locations []string `json:"locations"`
Args []InputValue `json:"args"`
IsRepeatable bool `json:"isRepeatable"`
}
type FederationConfig ¶ added in v3.18.14
type FederationConfig struct {
Enabled bool `mapstructure:"enabled" json:"enabled" yaml:"enabled" jsonschema:"title=Enable Apollo Federation v2,default=false"`
// Version is the Federation spec version surfaced via @link.
// Defaults to "v2.5" when empty.
Version string `mapstructure:"version" json:"version" yaml:"version" jsonschema:"title=Federation Version,default=v2.5"`
// Keys overrides the auto-derived @key for the named table. Each
// entry is a list of column names that compose the key.
Keys map[string][]string `mapstructure:"keys" json:"keys" yaml:"keys" jsonschema:"title=Federation Keys"`
// Shareable, Inaccessible and Tags accept "Type.field" identifiers.
Inaccessible []string `mapstructure:"inaccessible" json:"inaccessible" yaml:"inaccessible" jsonschema:"title=Inaccessible Fields"`
Tags map[string][]string `mapstructure:"tags" json:"tags" yaml:"tags" jsonschema:"title=@tag Annotations"`
}
FederationConfig configures Apollo Federation v2 subgraph emission.
When Enabled is true the engine recognises the federation queries `_service { sdl }` and `_entities(representations: [_Any!]!)` on the root Query type and emits a federation-flavoured SDL describing every non-blocked table in the schema.
Keys lets you override the auto-derived `@key(fields: "<pk>")` directive for a table — useful when a logical entity uses a non-PK key (e.g. `email`) or a composite key (e.g. `["id", "tenant_id"]`).
Shareable, Inaccessible, and Tags accept fully-qualified field names formatted as "Type.field" (e.g. "User.email").
type FieldObject ¶
type FilesystemBackendFactory ¶ added in v3.18.14
type FilesystemBackendFactory func(conf FilesystemConfig) (fstable.Backend, error)
FilesystemBackendFactory builds a filesystem Backend from one of the engine's FilesystemConfig entries. Factories are registered by backend name (e.g. "local", "s3", "gcs") via OptionSetFilesystemBackend.
type FilesystemConfig ¶ added in v3.18.14
type FilesystemConfig struct {
// Name is the table name surfaced in GraphQL (e.g. "avatars").
Name string `mapstructure:"name" json:"name" yaml:"name" jsonschema:"title=Table Name"`
// Backend selects the implementation: "local", "s3", or "gcs".
// S3 and GCS are gated by build tags; on a slim build, configuring
// them produces a clear error.
Backend string `mapstructure:"backend" json:"backend" yaml:"backend" jsonschema:"title=Backend,enum=local,enum=s3,enum=gcs"`
// Bucket is the S3 bucket / GCS bucket name. Ignored for local.
Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket" jsonschema:"title=Bucket"`
// Region is the S3 region (e.g. "us-east-1"). Ignored for local/gcs.
Region string `mapstructure:"region" json:"region" yaml:"region" jsonschema:"title=Region"`
// Endpoint, when non-empty, overrides the S3 endpoint URL — useful
// for MinIO, localstack, or non-AWS S3-compatible services.
Endpoint string `mapstructure:"endpoint" json:"endpoint" yaml:"endpoint" jsonschema:"title=Endpoint Override"`
// Prefix is prepended to every key. Effective root for the table.
Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix" jsonschema:"title=Key Prefix"`
// Root is the local filesystem root directory. Required for the
// local backend; ignored otherwise.
Root string `mapstructure:"root" json:"root" yaml:"root" jsonschema:"title=Local Root Directory"`
// PresignTTL bounds how long generated presigned URLs are valid.
// Defaults to 15 minutes when zero. Local backend ignores this.
PresignTTL time.Duration `mapstructure:"presign_ttl" json:"presign_ttl" yaml:"presign_ttl" jsonschema:"title=Presigned URL TTL,default=15m"`
// PublicBaseURL, when set, replaces the presigned-URL host. Useful
// when objects are fronted by a CDN. The path is appended unchanged.
PublicBaseURL string `mapstructure:"public_base_url" json:"public_base_url" yaml:"public_base_url" jsonschema:"title=Public Base URL"`
// ReadOnly disables GraphJin-managed writes and local filesystem watch
// invalidation for this filesystem table.
ReadOnly bool `mapstructure:"read_only" json:"read_only" yaml:"read_only" jsonschema:"title=Read Only"`
// MaxListPageSize caps the number of entries returned per list call.
// Defaults to 1000 when zero.
MaxListPageSize int `` /* 136-byte string literal not displayed */
}
FilesystemConfig declares one filesystem-backed virtual table.
filesystems:
- name: avatars
backend: s3
bucket: my-bucket
prefix: avatars/
region: us-east-1
presign_ttl: 15m
- name: invoices
backend: gcs
bucket: invoices
prefix: 2026/
- name: uploads_local
backend: local
root: /var/lib/graphjin/uploads
Backend-specific options live alongside the common ones; unrecognised fields per backend produce a clear error at startup rather than being silently ignored.
type FragmentDetails ¶ added in v3.2.0
type FragmentDetails struct {
Name string `json:"name"`
Namespace string `json:"namespace,omitempty"`
Definition string `json:"definition"`
On string `json:"on,omitempty"` // The type the fragment is defined on
}
FragmentDetails represents full details of a fragment
type FragmentInfo ¶ added in v3.2.0
type FragmentInfo struct {
Name string `json:"name"`
Namespace string `json:"namespace,omitempty"`
}
FragmentInfo represents a fragment from the allow list
type FullType ¶
type FullType struct {
Kind string `json:"kind"`
Name string `json:"name"`
Description string `json:"description"`
Fields []FieldObject `json:"fields"`
InputFields []InputValue `json:"inputFields"`
EnumValues []EnumValue `json:"enumValues"`
Interfaces []TypeRef `json:"interfaces"`
PossibleTypes []TypeRef `json:"possibleTypes"`
}
type Function ¶ added in v3.2.0
type Function struct {
Name string
Schema string
ReturnType string `` /* 126-byte string literal not displayed */
}
Configuration for a database function
type FunctionInfo ¶ added in v3.16.0
type FunctionInfo struct {
Name string `json:"name"`
Schema string `json:"schema,omitempty"`
Type string `json:"type"`
Comment string `json:"comment,omitempty"`
Aggregate bool `json:"aggregate,omitempty"`
Inputs []FunctionParam `json:"inputs,omitempty"`
Outputs []FunctionParam `json:"outputs,omitempty"`
}
FunctionInfo represents a database function
type FunctionParam ¶ added in v3.16.0
type FunctionParam struct {
Name string `json:"name"`
Type string `json:"type"`
Array bool `json:"array,omitempty"`
}
FunctionParam represents a function input or output parameter
type GraphEdge ¶ added in v3.8.0
type GraphEdge struct {
From string `json:"from"`
To string `json:"to"`
Type string `json:"type"`
Weight int `json:"weight"`
ViaColumn string `json:"via_column,omitempty"`
}
GraphEdge represents a relationship edge in the graph
type GraphJin ¶
func NewGraphJin ¶
NewGraphJin creates the GraphJin struct, this involves querying the database to learn its schemas and relationships
func NewGraphJinWithFS ¶
NewGraphJinWithFS creates the GraphJin struct, this involves querying the database to learn its
func NewTestGraphJin ¶ added in v3.14.3
NewTestGraphJin creates a GraphJin instance backed by named test DB schemas, suitable for unit testing API and handler code without a real database. Each database name maps to a separate in-memory schema. Use "default" for the standard test schema, or "with_database" for the variant that includes a database field on tables (e.g. for the "events" table).
func (*GraphJin) AuditAllRoles ¶ added in v3.8.0
AuditAllRoles returns permission matrices for all configured roles.
func (*GraphJin) AuditRolePermissions ¶ added in v3.8.0
AuditRolePermissions returns a complete permission matrix for a single role.
func (*GraphJin) CatalogSnapshot ¶ added in v3.18.19
func (g *GraphJin) CatalogSnapshot(exclude ...string) (*CatalogSnapshot, error)
CatalogSnapshot returns the AI-first self-catalog for this GraphJin engine. It is intentionally read-only and is safe to expose through MCP/admin adapters after those adapters apply their own auth and availability rules.
func (*GraphJin) Close ¶ added in v3.14.1
func (g *GraphJin) Close()
Close stops GraphJin background tasks. It is safe to call multiple times.
func (*GraphJin) DBForDatabase ¶ added in v3.18.3
DBForDatabase returns the read-only connection pool and database type for `database`. Empty name resolves to the default database. Do not close the pool.
func (*GraphJin) DatabaseNames ¶ added in v3.15.1
DatabaseNames returns the names of all configured databases.
func (*GraphJin) DefaultDatabase ¶ added in v3.15.1
DefaultDatabase returns the name of the default (primary) database.
func (*GraphJin) EffectiveAnalyticsMode ¶ added in v3.18.3
func (*GraphJin) ExplainQuery ¶ added in v3.8.0
func (g *GraphJin) ExplainQuery(query string, vars json.RawMessage, role string) (*QueryExplanation, error)
ExplainQuery compiles a GraphQL query without executing it. Returns the compiled query, parameters, tables touched, join depth, and cache info.
func (*GraphJin) ExploreRelationships ¶ added in v3.8.0
func (g *GraphJin) ExploreRelationships(table string, depth int) (*RelationshipGraph, error)
ExploreRelationships returns a graph of all reachable tables from the given table up to the specified depth.
func (*GraphJin) ExploreRelationshipsForDatabase ¶ added in v3.8.0
func (g *GraphJin) ExploreRelationshipsForDatabase(database, table string, depth int) (*RelationshipGraph, error)
ExploreRelationshipsForDatabase returns a relationship graph for a table in a specific database.
func (*GraphJin) FilesystemBackend ¶ added in v3.18.14
FilesystemBackend returns the backend instance configured under the given filesystems[].name, or false if no such filesystem exists. Useful for callers that want to bypass the GraphQL surface — e.g. the multipart upload parser streaming directly to object storage.
func (*GraphJin) FindRelationshipPath ¶ added in v3.2.0
FindRelationshipPath finds the path between two tables. In multi-DB mode, searches across all databases.
func (*GraphJin) FindRelationshipPathForDatabase ¶ added in v3.8.0
func (g *GraphJin) FindRelationshipPathForDatabase(database, fromTable, toTable string) ([]PathStep, error)
FindRelationshipPathForDatabase finds the path between two tables in a specific database. If database is empty, searches across all databases.
func (*GraphJin) GenerateOpenAPISpec ¶ added in v3.1.1
func (g *GraphJin) GenerateOpenAPISpec() (*OpenAPIDocument, error)
GenerateOpenAPISpec generates a complete OpenAPI specification for all REST endpoints
func (*GraphJin) GetAllDatabaseStats ¶ added in v3.2.0
func (g *GraphJin) GetAllDatabaseStats() []DatabaseStats
GetAllDatabaseStats returns statistics for all configured databases.
func (*GraphJin) GetFragment ¶ added in v3.2.0
func (g *GraphJin) GetFragment(name string) (*FragmentDetails, error)
GetFragment returns details of a specific fragment
func (*GraphJin) GetFunctions ¶ added in v3.16.0
func (g *GraphJin) GetFunctions() []FunctionInfo
GetFunctions returns database functions across all databases.
func (*GraphJin) GetFunctionsForDatabase ¶ added in v3.16.0
func (g *GraphJin) GetFunctionsForDatabase(database string) []FunctionInfo
GetFunctionsForDatabase returns database functions for a specific database.
func (*GraphJin) GetOpenAPISpec ¶ added in v3.1.1
GetOpenAPISpec returns the OpenAPI specification as JSON
func (*GraphJin) GetSavedQuery ¶ added in v3.2.0
func (g *GraphJin) GetSavedQuery(name string) (*SavedQueryDetails, error)
GetSavedQuery returns details of a specific saved query
func (*GraphJin) GetTableSchema ¶ added in v3.2.0
func (g *GraphJin) GetTableSchema(tableName string) (*TableSchema, error)
GetTableSchema returns detailed schema for a specific table including relationships. In multi-DB mode, searches across all databases.
func (*GraphJin) GetTableSchemaForDatabase ¶ added in v3.8.0
func (g *GraphJin) GetTableSchemaForDatabase(database, tableName string) (*TableSchema, error)
GetTableSchemaForDatabase returns detailed schema for a table in a specific database. If database is empty, searches across all databases.
func (*GraphJin) GetTableSchemaForDatabaseSchema ¶ added in v3.18.5
func (g *GraphJin) GetTableSchemaForDatabaseSchema(database, schemaName, tableName string) (*TableSchema, error)
GetTableSchemaForDatabaseSchema returns detailed schema for a table in a specific configured database and database schema.
func (*GraphJin) GetTables ¶ added in v3.2.0
GetTables returns a list of all tables across all databases (in multi-DB mode) or from the default database (in single-DB mode)
func (*GraphJin) GetTablesForDatabase ¶ added in v3.8.0
GetTablesForDatabase returns tables from a specific database. If database is empty, returns tables from all databases.
func (*GraphJin) GraphQL ¶
func (g *GraphJin) GraphQL(c context.Context, query string, vars json.RawMessage, rc *RequestConfig, ) (res *Result, err error)
GraphQL function is our main function it takes a GraphQL query compiles it to SQL and executes returning the resulting JSON.
In production mode the compiling happens only once and from there on the compiled queries are directly executed.
In developer mode all named queries are saved into the queries folder and in production mode only queries from these saved queries can be used.
func (*GraphJin) GraphQLByName ¶
func (g *GraphJin) GraphQLByName(c context.Context, name string, vars json.RawMessage, rc *RequestConfig, ) (res *Result, err error)
GraphQLByName is similar to the GraphQL function except that queries saved in the queries folder can directly be used just by their name (filename).
func (*GraphJin) GraphQLByNameTx ¶
func (g *GraphJin) GraphQLByNameTx(c context.Context, tx *sql.Tx, name string, vars json.RawMessage, rc *RequestConfig, ) (res *Result, err error)
GraphQLByNameTx is similiar to the GraphQLByName function except that it can be used within a database transactions.
func (*GraphJin) GraphQLTx ¶
func (g *GraphJin) GraphQLTx(c context.Context, tx *sql.Tx, query string, vars json.RawMessage, rc *RequestConfig, ) (res *Result, err error)
GraphQLTx is similiar to the GraphQL function except that it can be used within a database transactions.
func (*GraphJin) InvalidateCacheRefs ¶ added in v3.18.18
InvalidateCacheRefs invalidates response-cache entries associated with the supplied dependency refs. It is a no-op when response caching is disabled.
func (*GraphJin) ListFragments ¶ added in v3.2.0
func (g *GraphJin) ListFragments() ([]FragmentInfo, error)
ListFragments returns all fragments from the allow list
func (*GraphJin) ListSavedQueries ¶ added in v3.2.0
func (g *GraphJin) ListSavedQueries() ([]SavedQueryInfo, error)
ListSavedQueries returns all saved queries from the allow list
func (*GraphJin) MetadataSnapshot ¶ added in v3.18.18
func (g *GraphJin) MetadataSnapshot(exclude ...string) (*MetadataSnapshot, error)
MetadataSnapshot returns a stable, queryable projection of the schemas that GraphJin discovered. Excluded database names are skipped, which the service uses to keep managed metadata and CodeSQL cache databases out of gj_* rows.
func (*GraphJin) OnSchemaChange ¶ added in v3.15.1
OnSchemaChange registers a callback that fires when the database schema changes. The callback receives the database name and a hex-encoded hash of the schema. Callbacks also fire once at startup after initial schema discovery.
func (*GraphJin) ReloadWithDB ¶ added in v3.10.3
ReloadWithDB redoes database discover with a new primary DB connection.
func (*GraphJin) SchemaReady ¶ added in v3.10.1
SchemaReady returns true if the engine has a usable schema. Use this to check before calling methods that access the schema to avoid nil pointer dereferences during partial initialization.
func (*GraphJin) SetOptions ¶ added in v3.10.3
SetOptions replaces the options slice so the next Reload picks them up.
func (*GraphJin) Subscribe ¶
func (g *GraphJin) Subscribe( c context.Context, query string, vars json.RawMessage, rc *RequestConfig, ) (m *Member, err error)
Subscribe function is called on the GraphJin struct to subscribe to query. Any database changes that apply to the query are streamed back in realtime.
In developer mode all named queries are saved into the queries folder and in production mode only queries from these saved queries can be used.
func (*GraphJin) SubscribeByName ¶
func (g *GraphJin) SubscribeByName( c context.Context, name string, vars json.RawMessage, rc *RequestConfig, ) (m *Member, err error)
SubscribeByName is similar to the Subscribe function except that queries saved in the queries folder can directly be used by their filename.
type GraphNode ¶ added in v3.8.0
type GraphNode struct {
Name string `json:"name"`
Schema string `json:"schema,omitempty"`
Database string `json:"database,omitempty"`
Type string `json:"type"`
ColumnCount int `json:"column_count"`
}
GraphNode represents a table node in the relationship graph
type GraphqlReq ¶
type GraphqlReq struct {
// contains filtered or unexported fields
}
func (*GraphqlReq) Set ¶
func (r *GraphqlReq) Set(item allow.Item)
Set is used to set the namespace, operation type, name and query for the GraphQL request
type GraphqlResponse ¶
type GraphqlResponse struct {
// contains filtered or unexported fields
}
type InputValue ¶
type IntroResult ¶
type IntroResult struct {
Schema IntrospectionSchema `json:"__schema"`
}
type Introspection ¶
type Introspection struct {
// contains filtered or unexported fields
}
type IntrospectionSchema ¶
type IntrospectionSchema struct {
Types []FullType `json:"types"`
QueryType *ShortFullType `json:"queryType"`
MutationType *ShortFullType `json:"mutationType"`
SubscriptionType *ShortFullType `json:"subscriptionType"`
Directives []DirectiveType `json:"directives"`
}
type ManagedColumn ¶ added in v3.18.19
ManagedColumn describes a synthetic service-owned table column.
type ManagedMutationField ¶ added in v3.18.18
ManagedMutationField describes one selected return field on a managed mutation root.
type ManagedMutationHandler ¶ added in v3.18.18
type ManagedMutationHandler interface {
ManagedMutationTables() []string
ExecuteManagedMutation(context.Context, ManagedMutationRequest) (json.RawMessage, error)
}
ManagedMutationHandler handles GraphQL mutations for service-managed tables.
type ManagedMutationRequest ¶ added in v3.18.18
type ManagedMutationRequest struct {
Database string
Operation string
Roots []ManagedMutationRoot
}
ManagedMutationRequest is passed to service-owned mutation handlers.
type ManagedMutationRoot ¶ added in v3.18.18
type ManagedMutationRoot struct {
FieldName string
Table string
Operation string
Input map[string]interface{}
Where map[string]interface{}
Fields []ManagedMutationField
}
ManagedMutationRoot describes one root mutation routed to a managed handler.
type ManagedOrderBy ¶ added in v3.18.19
ManagedOrderBy describes one order_by entry on a managed query root.
type ManagedQueryHandler ¶ added in v3.18.19
type ManagedQueryHandler interface {
ManagedQueryTables() []ManagedTable
ExecuteManagedQuery(context.Context, ManagedQueryRequest) (json.RawMessage, error)
}
ManagedQueryHandler handles GraphQL queries for service-managed tables.
type ManagedQueryRequest ¶ added in v3.18.19
type ManagedQueryRequest struct {
Database string
Roots []ManagedQueryRoot
}
ManagedQueryRequest is passed to service-owned query handlers.
type ManagedQueryRoot ¶ added in v3.18.19
type ManagedQueryRoot struct {
FieldName string
Table string
Fields []ManagedMutationField
Where map[string]interface{}
OrderBy []ManagedOrderBy
Limit int
Offset int
}
ManagedQueryRoot describes one root query routed to a managed handler.
type ManagedTable ¶ added in v3.18.19
type ManagedTable struct {
Name string
Columns []ManagedColumn
}
ManagedTable describes a synthetic service-owned GraphQL table.
type Member ¶
type Member struct {
Result chan *Result
// contains filtered or unexported fields
}
func (*Member) Unsubscribe ¶
func (m *Member) Unsubscribe()
Unsubscribe function is called on the member struct to unsubscribe.
type MetadataColumn ¶ added in v3.18.18
type MetadataColumn struct {
ID string
TableID string
DatabaseName string
SchemaName string
TableName string
ColumnName string
Type string
Array bool
NotNull bool
PrimaryKey bool
UniqueKey bool
Indexed bool
IndexName string
DefaultValue string
Comment string
Ordinal int
TableKey string
ColumnKey string
}
type MetadataConfig ¶ added in v3.18.18
type MetadataConfig struct {
// Enabled controls whether GraphJin exposes discovered metadata tables.
// When omitted, it defaults to enabled in dev and disabled in production.
Enabled *bool `mapstructure:"enabled" json:"enabled,omitempty" yaml:"enabled,omitempty" jsonschema:"title=Enable Metadata Graph"`
// Database is the virtual database name. Defaults to "graphjin".
Database string `mapstructure:"database" json:"database" yaml:"database" jsonschema:"title=Metadata Database,default=graphjin"`
// AutoCodeRelations controls automatic relationships from catalog items
// to CodeSQL's public gj_code projection. When omitted, it follows Enabled.
AutoCodeRelations *bool `` /* 147-byte string literal not displayed */
// CodeDatabases optionally pins which CodeSQL database should be linked.
// Empty means auto-detect, but only when exactly one CodeSQL DB exists.
CodeDatabases []string `` /* 130-byte string literal not displayed */
}
MetadataConfig controls the managed metadata graph database.
type MetadataDatabase ¶ added in v3.18.18
type MetadataFunction ¶ added in v3.18.18
type MetadataIndex ¶ added in v3.18.18
type MetadataRelationship ¶ added in v3.18.18
type MetadataRelationship struct {
ID string
FromDatabaseName string
FromSchemaName string
FromTableName string
FromColumnName string
FromColumnID string
ToDatabaseName string
ToSchemaName string
ToTableName string
ToColumnName string
ToColumnID string
RelType string
IsCrossDatabase bool
Source string
}
type MetadataSnapshot ¶ added in v3.18.18
type MetadataSnapshot struct {
Databases []MetadataDatabase
Tables []MetadataTable
Columns []MetadataColumn
Relationships []MetadataRelationship
Functions []MetadataFunction
Indexes []MetadataIndex
}
type MetadataTable ¶ added in v3.18.18
type NanoColumn ¶ added in v3.18.19
type NanoDB ¶ added in v3.18.19
func NewNanoDB ¶ added in v3.18.19
func NewNanoDB(snapshot NanoSnapshot) (*NanoDB, error)
type NanoSnapshot ¶ added in v3.18.19
type OpenAPIComponents ¶ added in v3.1.1
type OpenAPIDocument ¶ added in v3.1.1
type OpenAPIDocument struct {
OpenAPI string `json:"openapi"`
Info OpenAPIInfo `json:"info"`
Servers []OpenAPIServer `json:"servers,omitempty"`
Paths map[string]PathItem `json:"paths"`
Components *OpenAPIComponents `json:"components,omitempty"`
Security []map[string][]string `json:"security,omitempty"`
}
OpenAPI 3.0 Specification Types
type OpenAPIInfo ¶ added in v3.1.1
type OpenAPIOperation ¶ added in v3.1.2
type OpenAPIOperation struct {
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
OperationID string `json:"operationId,omitempty"`
Parameters []Parameter `json:"parameters,omitempty"`
RequestBody *RequestBody `json:"requestBody,omitempty"`
Responses map[string]Response `json:"responses"`
Tags []string `json:"tags,omitempty"`
}
type OpenAPIServer ¶ added in v3.1.1
type OperationPermission ¶ added in v3.8.0
type OperationPermission struct {
Allowed bool `json:"allowed"`
Blocked bool `json:"blocked,omitempty"`
Limit int `json:"limit,omitempty"`
Filters []string `json:"filters,omitempty"`
Columns []string `json:"columns,omitempty"`
Presets map[string]string `json:"presets,omitempty"`
DisableFunctions bool `json:"disable_functions,omitempty"`
}
OperationPermission represents the permission details for a single operation
type Option ¶
type Option func(*graphjinEngine) error
func OptionSetDatabases ¶ added in v3.2.0
OptionSetDatabases sets multiple database connections for multi-database mode. The connections map should use the same keys as Config.Databases. Only stores bare dbContexts — full initialization happens in discoverAllDatabases and finalizeAllDatabases.
func OptionSetFS ¶
OptionSetFS sets the file system to be used by GraphJin
func OptionSetFilesystemBackend ¶ added in v3.18.14
func OptionSetFilesystemBackend(name string, factory FilesystemBackendFactory) Option
OptionSetFilesystemBackend registers a filesystem backend factory by name. The engine ships with the "local" factory built in; "s3" and "gcs" are registered by the serv package (where their SDK dependencies live). Custom backends can be plugged in here too — e.g. an Azure Blob factory in user code:
gj, _ := core.NewGraphJin(conf, db,
core.OptionSetFilesystemBackend("azureblob", func(c core.FilesystemConfig) (fstable.Backend, error) {
return myazure.New(c.Bucket, c.Region)
}),
)
func OptionSetManagedMutationHandler ¶ added in v3.18.18
func OptionSetManagedMutationHandler(database string, handler ManagedMutationHandler) Option
OptionSetManagedMutationHandler registers a handler for service-managed mutation tables in a database.
func OptionSetManagedQueryHandler ¶ added in v3.18.19
func OptionSetManagedQueryHandler(database string, handler ManagedQueryHandler) Option
OptionSetManagedQueryHandler registers a handler for service-managed query tables in a database.
func OptionSetNamespace ¶
func OptionSetNanoDatabases ¶ added in v3.18.19
func OptionSetResolver ¶
func OptionSetResolver(name string, fn ResolverFn) Option
OptionSetResolver sets the resolver function to be used by GraphJin
func OptionSetResponseCache ¶ added in v3.2.0
func OptionSetResponseCache(cache ResponseCacheProvider) Option
OptionSetResponseCache sets the response cache provider for caching query results. The cache provider is typically the Redis cache from the serv package.
func OptionSetTrace ¶
OptionSetTrace sets the tracer to be used by GraphJin
type ParamInfo ¶ added in v3.8.0
type ParamInfo struct {
Name string `json:"name"`
Type string `json:"type"`
IsArray bool `json:"is_array,omitempty"`
}
ParamInfo represents a query parameter
type PartitionConfig ¶ added in v3.15.0
type PartitionConfig struct {
// Column is the partition key column name (e.g., "created_at").
Column string `mapstructure:"column" json:"column" yaml:"column" jsonschema:"title=Partition Column,example=created_at"`
// DefaultRangeDays is the number of days to auto-filter when no partition filter
// is present in the query. Set to 0 to only warn without injecting a filter.
DefaultRangeDays int `` /* 154-byte string literal not displayed */
None bool `mapstructure:"none" json:"none,omitempty" yaml:"none,omitempty" jsonschema:"title=Disable Partition Check"`
}
PartitionConfig declares the partition key for a warehouse table. When a query does not filter on the partition column:
- If DefaultRangeDays > 0, a filter is auto-injected (e.g., created_at >= now - 30 days)
- Otherwise, a warning is logged
type PathItem ¶ added in v3.1.1
type PathItem struct {
Get *OpenAPIOperation `json:"get,omitempty"`
Post *OpenAPIOperation `json:"post,omitempty"`
Put *OpenAPIOperation `json:"put,omitempty"`
Delete *OpenAPIOperation `json:"delete,omitempty"`
}
type PathStep ¶ added in v3.2.0
type PathStep struct {
From string `json:"from"`
To string `json:"to"`
Via string `json:"via,omitempty"` // Column or join table
Relation string `json:"relation"` // Relationship type
}
PathStep represents a step in a relationship path
type PoolStats ¶ added in v3.2.0
type PoolStats struct {
MaxOpen int `json:"maxOpen"`
Open int `json:"open"`
InUse int `json:"inUse"`
Idle int `json:"idle"`
WaitCount int64 `json:"waitCount"`
WaitDuration string `json:"waitDuration"`
MaxIdleClosed int64 `json:"maxIdleClosed"`
MaxLifetimeClosed int64 `json:"maxLifetimeClosed"`
}
PoolStats represents connection pool statistics
type Query ¶
type Query struct {
Limit int
// Use filters to enforce table wide things like { disabled: false } where you never want disabled users to be shown.
Filters []string
Columns []string
DisableFunctions bool `mapstructure:"disable_functions" json:"disable_functions" yaml:"disable_functions"`
Block bool
}
Table configuration for querying a table with a role
type QueryAnalysis ¶ added in v3.1.1
type QueryAnalysis struct {
Item allow.Item
Operation graph.Operation
QCode *qcode.QCode
HTTPMethods []string
Parameters []Parameter
ResponseSchema Schema
}
QueryAnalysis contains analyzed information about a GraphQL query
type QueryExplanation ¶ added in v3.8.0
type QueryExplanation struct {
CompiledQuery string `json:"compiled_query"`
Params []ParamInfo `json:"params"`
Operation string `json:"operation"`
Name string `json:"name,omitempty"`
Role string `json:"role"`
Database string `json:"database,omitempty"`
Tables []SelectInfo `json:"tables"`
JoinDepth int `json:"join_depth"`
CacheHeader string `json:"cache_header,omitempty"`
Errors []string `json:"errors,omitempty"`
MultiDatabase bool `json:"multi_database,omitempty"`
Queries []QueryExplanation `json:"queries,omitempty"`
}
QueryExplanation represents the compiled form of a GraphQL query
type RefreshFn ¶ added in v3.18.14
RefreshFn produces a fresh response for stale-while-revalidate. Implementations should run the original query and return cleaned response bytes plus row references suitable for cache indexing.
type RefreshFnWithOptions ¶ added in v3.18.18
type RefreshFnWithOptions func() (data []byte, refs []RowRef, opts CacheEntryOptions, err error)
RefreshFnWithOptions is the option-aware equivalent of RefreshFn.
type RelationInfo ¶ added in v3.2.0
type RelationInfo struct {
Name string `json:"name"` // Field name to use in queries
Table string `json:"table"` // Related table name
Type string `json:"type"` // one_to_one, one_to_many, many_to_many
ForeignKey string `json:"foreign_key"` // The FK column
Through string `json:"through,omitempty"` // Join table for many-to-many
}
RelationInfo represents a relationship between tables
type RelationshipConfig ¶ added in v3.18.19
type RelationshipGraph ¶ added in v3.8.0
type RelationshipGraph struct {
CenterTable string `json:"center_table"`
Depth int `json:"depth"`
Nodes []GraphNode `json:"nodes"`
Edges []GraphEdge `json:"edges"`
}
RelationshipGraph represents the data model neighborhood around a table
type RequestBody ¶ added in v3.1.1
type RequestConfig ¶
type RequestConfig struct {
// APQKey is set when using GraphJin with automatic persisted queries
APQKey string
// Pass additional variables complex variables such as functions that return string values.
Vars map[string]interface{}
// Execute this query as part of a transaction
Tx *sql.Tx
// contains filtered or unexported fields
}
RequestConfig is used to pass request specific config values to the GraphQL and Subscribe functions. Dynamic variables can be set here.
func (*RequestConfig) GetNamespace ¶
func (rc *RequestConfig) GetNamespace() (string, bool)
GetNamespace is used to get the namespace requests within a single instance of GraphJin
func (*RequestConfig) SetNamespace ¶
func (rc *RequestConfig) SetNamespace(ns string)
SetNamespace is used to set namespace requests within a single instance of GraphJin. For example queries with the same name
type Resolver ¶
type Resolver interface {
Resolve(context.Context, ResolverReq) ([]byte, error)
}
Resolver interface is used to create custom resolvers Custom resolvers must return a JSON value to be merged into the response JSON.
Example Redis Resolver:
type Redis struct {
Addr string
client redis.Client
}
func newRedis(v map[string]interface{}) (*Redis, error) {
re := &Redis{}
if err := mapstructure.Decode(v, re); err != nil {
return nil, err
}
re.client := redis.NewClient(&redis.Options{
Addr: re.Addr,
Password: "", // no password set
DB: 0, // use default DB
})
return re, nil
}
func (r *remoteAPI) Resolve(req ResolverReq) ([]byte, error) {
val, err := rdb.Get(ctx, req.ID).Result()
if err != nil {
return err
}
return val, nil
}
func main() {
conf := core.Config{
Resolvers: []Resolver{
Name: "cached_profile",
Type: "redis",
Table: "users",
Column: "id",
Props: []ResolverProps{
"addr": "localhost:6379",
},
},
}
redisRe := func(v ResolverProps) (Resolver, error) {
return newRedis(v)
}
gj, err := core.NewGraphJin(conf, db,
core.OptionSetResolver("redis" redisRe))
if err != nil {
log.Fatal(err)
}
}
type ResolverConfig ¶
type ResolverConfig struct {
Name string
Type string
Schema string
Table string
Column string
StripPath string `mapstructure:"strip_path" json:"strip_path" yaml:"strip_path"`
Props ResolverProps `mapstructure:",remain"`
}
ResolverConfig struct defines a custom resolver
type ResolverFn ¶
type ResolverFn func(v ResolverProps) (Resolver, error)
type ResolverProps ¶
type ResolverProps map[string]interface{}
ResolverProps is a map of properties from the resolver config to be passed to the customer resolver's builder (new) function
type ResolverReq ¶
type ResolverReq struct {
ID string
Sel *qcode.Select
Log *log.Logger
Vars map[string]json.RawMessage
*RequestConfig
}
type ResponseCacheProvider ¶ added in v3.2.0
type ResponseCacheProvider interface {
// Get retrieves a cached response by key.
// Returns (data, isStale, found). isStale is true if the entry is past soft TTL (SWR).
Get(ctx context.Context, key string) (data []byte, isStale bool, found bool)
// Set stores a response with dependency refs for invalidation.
// refs may represent DB rows/tables, filesystem keys/prefixes, or resolver outputs.
// queryStartTime is used for race condition detection.
Set(ctx context.Context, key string, data []byte, refs []RowRef, queryStartTime time.Time) error
// InvalidateRows invalidates cache entries for dependency refs.
InvalidateRows(ctx context.Context, refs []RowRef) error
}
ResponseCacheProvider defines the interface for response caching. This is implemented by the service layer (serv package) to provide Redis-based caching with row-level invalidation.
type ResponseCacheProviderWithOptions ¶ added in v3.18.18
type ResponseCacheProviderWithOptions interface {
SetWithOptions(
ctx context.Context,
key string,
data []byte,
refs []RowRef,
queryStartTime time.Time,
opts CacheEntryOptions,
) error
}
ResponseCacheProviderWithOptions is an optional extension implemented by providers that can honor per-entry cache lifetime options.
type ResponseProcessor ¶ added in v3.2.0
type ResponseProcessor struct {
// contains filtered or unexported fields
}
ResponseProcessor handles extraction and stripping of __gj_id fields for caching
func NewResponseProcessor ¶ added in v3.2.0
func NewResponseProcessor(qc *qcode.QCode) *ResponseProcessor
NewResponseProcessor creates a new response processor
func (*ResponseProcessor) ProcessForCache ¶ added in v3.2.0
func (rp *ResponseProcessor) ProcessForCache(data []byte) (cleaned []byte, refs []RowRef, err error)
ProcessForCache extracts row references and strips __gj_id from response. Returns the cleaned response and list of (table, row_id) pairs.
type Result ¶
type Result struct {
Vars json.RawMessage `json:"-"`
Data json.RawMessage `json:"data,omitempty"`
Hash [sha256.Size]byte `json:"-"`
Errors []Error `json:"errors,omitempty"`
Validation []qcode.ValidErr `json:"validation,omitempty"`
// contains filtered or unexported fields
}
Result struct contains the output of the GraphQL function this includes resulting json from the database query and any error information
func (*Result) CacheControl ¶
Returns the cache control header value for the query result
func (*Result) CacheHit ¶ added in v3.2.0
CacheHit returns true if the response was served from cache
func (*Result) OperationName ¶
Returns the operation name for the query result
type Role ¶
type Role struct {
Name string
Comment string
Match string `jsonschema:"title=Related To,example=other_table.id_column,example=users.id"`
Tables []RoleTable `jsonschema:"title=Table Configuration for Role"`
// contains filtered or unexported fields
}
Configuration for user role
type RoleAudit ¶ added in v3.8.0
type RoleAudit struct {
Name string `json:"name"`
Match string `json:"match,omitempty"`
Tables []TablePermissions `json:"tables"`
FixGuide string `json:"fix_guide"`
}
RoleAudit represents the complete permission audit for a role
type RoleTable ¶
type RoleTable struct {
Name string
Schema string
ReadOnly bool `mapstructure:"read_only" json:"read_only" yaml:"read_only" jsonschema:"title=Read Only"`
Query *Query
Insert *Insert
Update *Update
Upsert *Upsert
Delete *Delete
}
Table configuration for a specific role (user role)
type RowRef ¶ added in v3.2.0
RowRef represents a source-owned cache dependency. The legacy DB shape ({Table, ID}) is still valid and normalizes to db/row or db/table refs.
func CodeSQLTableRefs ¶ added in v3.18.18
CodeSQLTableRefs builds table refs for CodeSQL-managed source changes.
func DBTableRef ¶ added in v3.18.18
DBTableRef builds a table-level database cache ref.
func ExtractMutationRefs ¶ added in v3.2.0
ExtractMutationRefs extracts affected row IDs from a mutation response. Used for cache invalidation after INSERT/UPDATE/DELETE.
func FilesystemKeyRefs ¶ added in v3.18.18
FilesystemKeyRefs builds refs affected by a write/delete to key. Directory prefixes are included so list fragments for common prefix queries are evicted.
func FilesystemPrefixRef ¶ added in v3.18.18
FilesystemPrefixRef builds a cache ref for a filesystem list prefix.
func FilesystemPrefixRefs ¶ added in v3.18.18
FilesystemPrefixRefs builds refs for a filesystem list prefix. The root prefix is included so broad filesystem invalidations can evict all entries.
func RemoteResolverRef ¶ added in v3.18.18
RemoteResolverRef builds a cache ref for an external resolver/API result.
func RemoteResolverRefs ¶ added in v3.18.18
RemoteResolverRefs builds resolver refs for one or more external IDs.
func (RowRef) DependencyKey ¶ added in v3.18.18
DependencyKey returns the exact index key for this dependency ref.
func (RowRef) Normalize ¶ added in v3.18.18
Normalize returns the canonical source/kind form for this ref.
func (RowRef) TableDependency ¶ added in v3.18.18
TableDependency returns a table-level dependency matching this ref's source.
type SWRRefresher ¶ added in v3.18.14
SWRRefresher is an optional interface a ResponseCacheProvider can implement to support stale-while-revalidate background refreshes. When the cache returns isStale=true on Get, callers may submit a refresh job; the provider is responsible for de-duplicating concurrent submissions for the same key and bounding the worker pool to avoid runaway goroutines.
SubmitRefresh returns true if the job was accepted, false if the worker pool is full or shutting down. The cache provider runs the RefreshFn, stores the resulting data on success, and records the refresh in metrics.
type SWRRefresherWithOptions ¶ added in v3.18.18
type SWRRefresherWithOptions interface {
SubmitRefreshWithOptions(key string, fn RefreshFnWithOptions) bool
}
SWRRefresherWithOptions is an optional extension for providers that can store SWR refresh results with per-entry cache lifetime options.
type SavedQueryDetails ¶ added in v3.2.0
type SavedQueryDetails struct {
Name string `json:"name"`
Namespace string `json:"namespace,omitempty"`
Operation string `json:"operation"`
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
}
SavedQueryDetails represents full details of a saved query
type SavedQueryInfo ¶ added in v3.2.0
type SavedQueryInfo struct {
Name string `json:"name"`
Namespace string `json:"namespace,omitempty"`
Operation string `json:"operation"` // query or mutation
}
SavedQueryInfo represents a saved query from the allow list
type Schema ¶ added in v3.1.1
type Schema struct {
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Properties map[string]Schema `json:"properties,omitempty"`
Items *Schema `json:"items,omitempty"`
Required []string `json:"required,omitempty"`
AdditionalProperties interface{} `json:"additionalProperties,omitempty"`
OneOf []Schema `json:"oneOf,omitempty"`
Description string `json:"description,omitempty"`
Example interface{} `json:"example,omitempty"`
Ref string `json:"$ref,omitempty"`
}
type SchemaOperation ¶ added in v3.2.0
type SchemaOperation struct {
Type string // "create_table", "add_column", "drop_table", "drop_column", "add_index", "add_constraint"
Table string
Column string
SQL string
Danger bool // true if this is a destructive operation
}
SchemaOperation represents a schema change operation
func SchemaDiff ¶ added in v3.2.0
func SchemaDiff(db *sql.DB, dbType string, schemaBytes []byte, blocklist []string, opts DiffOptions) ([]SchemaOperation, error)
SchemaDiff computes the SQL statements needed to sync the database with the schema file
type SelectInfo ¶ added in v3.8.0
type SelectInfo struct {
Table string `json:"table"`
Schema string `json:"schema,omitempty"`
Database string `json:"database,omitempty"`
Singular bool `json:"singular,omitempty"`
Children int `json:"children,omitempty"`
}
SelectInfo represents a table selection in a compiled query
type ShortFullType ¶
type ShortFullType struct {
Name string `json:"name"`
}
type SnowflakeKeyPairConfig ¶ added in v3.14.4
type SnowflakeKeyPairConfig interface {
GetAccount() string
GetUser() string
GetPrivateKeyPEM() []byte
GetKeyPassphrase() string
GetWarehouse() string
GetDatabase() string
GetSchema() string
}
SnowflakeKeyPairConfig allows external services to inject Snowflake key pair credentials programmatically (e.g., separate pipelines for Marketo, Salesforce, etc.).
type SourceConfig ¶ added in v3.18.19
type SourceConfig struct {
Name string `mapstructure:"name" json:"name" yaml:"name" jsonschema:"title=Name"`
Kind string `` /* 147-byte string literal not displayed */
Default bool `mapstructure:"default" json:"default" yaml:"default" jsonschema:"title=Default Source"`
Type string `mapstructure:"type" json:"type" yaml:"type" jsonschema:"title=Database Type"`
ConnString string `` /* 171-byte string literal not displayed */
Host string `mapstructure:"host" json:"host" yaml:"host" jsonschema:"title=Host"`
Port int `mapstructure:"port" json:"port" yaml:"port" jsonschema:"title=Port"`
DBName string `mapstructure:"dbname" json:"dbname" yaml:"dbname" jsonschema:"title=Database Name"`
User string `mapstructure:"user" json:"user" yaml:"user" jsonschema:"title=User"`
Password string `` /* 131-byte string literal not displayed */
Path string `mapstructure:"path" json:"path" yaml:"path" jsonschema:"title=Path"`
MaxOpenConns int `mapstructure:"max_open_conns" json:"max_open_conns" yaml:"max_open_conns" jsonschema:"title=Max Open Connections"`
MaxIdleConns int `mapstructure:"max_idle_conns" json:"max_idle_conns" yaml:"max_idle_conns" jsonschema:"title=Max Idle Connections"`
Schema string `mapstructure:"schema" json:"schema" yaml:"schema" jsonschema:"title=Schema"`
PoolSize int `mapstructure:"pool_size" json:"pool_size" yaml:"pool_size" jsonschema:"title=Connection Pool Size"`
MaxConnections int `mapstructure:"max_connections" json:"max_connections" yaml:"max_connections" jsonschema:"title=Maximum Connections"`
MaxConnIdleTime time.Duration `` /* 143-byte string literal not displayed */
MaxConnLifeTime time.Duration `` /* 143-byte string literal not displayed */
PingTimeout time.Duration `mapstructure:"ping_timeout" json:"ping_timeout" yaml:"ping_timeout" jsonschema:"title=Healthcheck Ping Timeout"`
EnableTLS bool `mapstructure:"enable_tls" json:"enable_tls" yaml:"enable_tls" jsonschema:"title=Enable TLS"`
ServerName string `mapstructure:"server_name" json:"server_name" yaml:"server_name" jsonschema:"title=TLS Server Name"`
ServerCert string `` /* 155-byte string literal not displayed */
ClientCert string `` /* 155-byte string literal not displayed */
ClientKey string `` /* 145-byte string literal not displayed */
Encrypt *bool `mapstructure:"encrypt" json:"encrypt,omitempty" yaml:"encrypt,omitempty" jsonschema:"title=MSSQL Encrypt"`
TrustServerCertificate *bool `` /* 173-byte string literal not displayed */
PrivateKeyPath string `` /* 184-byte string literal not displayed */
PrivateKeyPEM string `` /* 177-byte string literal not displayed */
KeyPassphrase string `` /* 167-byte string literal not displayed */
ReadOnly bool `mapstructure:"read_only" json:"read_only" yaml:"read_only" jsonschema:"title=Read Only"`
AnalyticsMode *bool `` /* 127-byte string literal not displayed */
InferDBRefs *bool `` /* 135-byte string literal not displayed */
Backend string `mapstructure:"backend" json:"backend" yaml:"backend" jsonschema:"title=Filesystem Backend"`
Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket" jsonschema:"title=Bucket"`
Region string `mapstructure:"region" json:"region" yaml:"region" jsonschema:"title=Region"`
Endpoint string `mapstructure:"endpoint" json:"endpoint" yaml:"endpoint" jsonschema:"title=Endpoint"`
Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix" jsonschema:"title=Prefix"`
Root string `mapstructure:"root" json:"root" yaml:"root" jsonschema:"title=Root"`
PresignTTL time.Duration `mapstructure:"presign_ttl" json:"presign_ttl" yaml:"presign_ttl" jsonschema:"title=Presigned URL TTL"`
PublicBaseURL string `mapstructure:"public_base_url" json:"public_base_url" yaml:"public_base_url" jsonschema:"title=Public Base URL"`
MaxListPageSize int `mapstructure:"max_list_page_size" json:"max_list_page_size" yaml:"max_list_page_size" jsonschema:"title=Max List Page Size"`
SpecsDir string `mapstructure:"specs_dir" json:"specs_dir" yaml:"specs_dir" jsonschema:"title=OpenAPI Specs Directory"`
Specs map[string]openapi.SpecConfig `mapstructure:"specs" json:"specs" yaml:"specs" jsonschema:"-"`
Catalog *bool `mapstructure:"catalog" json:"catalog,omitempty" yaml:"catalog,omitempty" jsonschema:"title=Catalog"`
Metadata *bool `mapstructure:"metadata" json:"metadata,omitempty" yaml:"metadata,omitempty" jsonschema:"title=Metadata"`
ControlPlane *bool `mapstructure:"control_plane" json:"control_plane,omitempty" yaml:"control_plane,omitempty" jsonschema:"title=Control Plane"`
Runtime string `mapstructure:"runtime" json:"runtime" yaml:"runtime" jsonschema:"title=Workflow Runtime"`
}
SourceConfig declares one graph provider in source mode.
type Spaner ¶
type Spaner interface {
SetAttributesString(attrs ...StringAttr)
IsRecording() bool
Error(err error)
End()
}
type StringAttr ¶
type Table ¶
type Table struct {
Name string
Schema string
Table string // Inherits Table
Type string
// Source is required in source mode and points at one sources[].name.
Source string `mapstructure:"source" json:"source" yaml:"source" jsonschema:"title=Source"`
// Database name for multi-database support. References a key in Config.Databases.
// If empty, uses the default database.
Database string `mapstructure:"database" json:"database" yaml:"database" jsonschema:"title=Database"`
ReadOnly bool `mapstructure:"read_only" json:"read_only" yaml:"read_only" jsonschema:"title=Read Only"`
Blocklist []string
Columns []Column
// Permitted order by options
OrderBy map[string][]string `mapstructure:"order_by" json:"order_by" yaml:"order_by" jsonschema:"title=Order By Options,example=created_at desc"`
// Partition configuration for warehouse-optimized queries (Snowflake, BigQuery).
// When set, queries without a filter on the partition column will either get a
// default time-range filter injected or produce a warning.
Partition *PartitionConfig `mapstructure:"partition" json:"partition,omitempty" yaml:"partition,omitempty" jsonschema:"title=Partition Configuration"`
}
Configuration for a database table
type TableInfo ¶ added in v3.2.0
type TableInfo struct {
Name string `json:"name"`
Schema string `json:"schema,omitempty"`
Database string `json:"database,omitempty"`
Type string `json:"type"` // table, view, etc.
Comment string `json:"comment,omitempty"`
ColumnCount int `json:"column_count"`
}
TableInfo represents basic table information for MCP/API consumers
type TablePermissions ¶ added in v3.8.0
type TablePermissions struct {
TableName string `json:"table_name"`
Schema string `json:"schema,omitempty"`
ReadOnly bool `json:"read_only,omitempty"`
Query *OperationPermission `json:"query"`
Insert *OperationPermission `json:"insert"`
Update *OperationPermission `json:"update"`
Upsert *OperationPermission `json:"upsert"`
Delete *OperationPermission `json:"delete"`
}
TablePermissions represents per-table permission details for a role
type TableSchema ¶ added in v3.2.0
type TableSchema struct {
Name string `json:"name"`
Schema string `json:"schema,omitempty"`
Database string `json:"database,omitempty"`
Type string `json:"type"`
Comment string `json:"comment,omitempty"`
Blocked bool `json:"blocked,omitempty"`
PrimaryKey string `json:"primary_key,omitempty"`
PrimaryKeys []string `json:"primary_keys,omitempty"`
FullTextColumns []string `json:"full_text_columns,omitempty"`
PartitionKey string `json:"partition_key,omitempty"`
ImplicitPartitionKey string `json:"implicit_partition_key,omitempty"`
Columns []ColumnInfo `json:"columns"`
Relationships struct {
Outgoing []RelationInfo `json:"outgoing"` // Tables this table references
Incoming []RelationInfo `json:"incoming"` // Tables that reference this table
} `json:"relationships"`
}
TableSchema represents full table schema with relationships
Source Files
¶
- api.go
- args.go
- cache.go
- cache_fragment.go
- cache_key.go
- cache_response.go
- catalog.go
- config.go
- core.go
- crypt.go
- database_join.go
- federation.go
- fstable_bridge.go
- fstable_cache.go
- gstate.go
- init.go
- init_multidb.go
- intro.go
- managed_handler_mux.go
- managed_mutation.go
- managed_query.go
- metadata.go
- mock.go
- nanodb.go
- nanodb_exec.go
- openapi.go
- openapi_bridge.go
- osfs.go
- plugin.go
- pretty.go
- read_only.go
- remote_api.go
- remote_join.go
- resolve.go
- retry.go
- rolestmt.go
- schema.go
- schema_ddl.go
- schema_diff.go
- snowflake_bind.go
- subs.go
- testing.go
- trace.go
- types.go
- util.go
- watcher.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package fstable defines a minimal, uniform abstraction over object stores (local filesystem, S3, GCS) so the GraphJin engine can expose them as virtual tables with a single shape.
|
Package fstable defines a minimal, uniform abstraction over object stores (local filesystem, S3, GCS) so the GraphJin engine can expose them as virtual tables with a single shape. |
|
internal
|
|
|
jsn
Package jsn provides fast and no-allocation functions to extract values and modify JSON data
|
Package jsn provides fast and no-allocation functions to extract values and modify JSON data |
|
Package openapi consumes OpenAPI 3 specifications dropped into a config directory and exposes their GET operations as remote-joinable fields and top-level virtual tables.
|
Package openapi consumes OpenAPI 3 specifications dropped into a config directory and exposes their GET operations as remote-joinable fields and top-level virtual tables. |