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 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 CacheKeyBuilder
- type Column
- type ColumnInfo
- type Config
- type DDLDialect
- type DatabaseConfig
- type DatabaseStats
- type Delete
- type DiffOptions
- type DirectiveType
- type EnumValue
- type Error
- type FS
- type FieldObject
- type FragmentDetails
- type FragmentInfo
- type FullType
- type Function
- type GraphEdge
- type GraphJin
- func (g *GraphJin) AuditAllRoles() ([]RoleAudit, error)
- func (g *GraphJin) AuditRolePermissions(role string) (*RoleAudit, error)
- 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) 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) 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) 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) IsProd() bool
- func (g *GraphJin) ListFragments() ([]FragmentInfo, error)
- func (g *GraphJin) ListSavedQueries() ([]SavedQueryInfo, error)
- 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 MediaType
- type Member
- 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 OptionSetNamespace(namespace string) Option
- func OptionSetResolver(name string, fn ResolverFn) Option
- func OptionSetResponseCache(cache ResponseCacheProvider) Option
- func OptionSetTrace(trace Tracer) Option
- type ParamInfo
- type Parameter
- type PathItem
- type PathStep
- type PoolStats
- type Query
- type QueryAnalysis
- type QueryExplanation
- type RelationInfo
- type RelationshipGraph
- type RequestBody
- type RequestConfig
- type Resolver
- type ResolverConfig
- type ResolverFn
- type ResolverProps
- type ResolverReq
- type Response
- type ResponseCacheProvider
- type ResponseProcessor
- type Result
- type Role
- type RoleAudit
- type RoleTable
- type RowRef
- type SavedQueryDetails
- type SavedQueryInfo
- type Schema
- type SchemaOperation
- type SelectInfo
- type ShortFullType
- 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 ( 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"}
SupportedDBTypes lists the database types supported for single-database mode
var SupportedMultiDBTypes = []string{"postgres", "mysql", "mariadb", "sqlite", "oracle", "mongodb", "mssql", "snowflake"}
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, ) string
BuildCacheKey is a convenience function that builds a cache key
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 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, ) string
Build creates a cache key from query parameters and context. The key is a SHA256 hash of: query identifier + query text + variables + user_id + role
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 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"`
}
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 `mapstructure:"secret_key" json:"secret_key" yaml:"secret_key" jsonschema:"title=Secret Key"`
// 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:"-"`
// All table specific configuration such as aliased tables and relationships
// between tables
Tables []Table `jsonschema:"title=Tables"`
// 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)
DBType string `` /* 173-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 */
// 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"`
// 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"`
// 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:"-"`
}
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) 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) RemoveRoleTable ¶
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
}
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)
Type string `` /* 166-byte string literal not displayed */
// Connection string for the database (alternative to individual params)
ConnString string `mapstructure:"connection_string" json:"connection_string" yaml:"connection_string" jsonschema:"title=Connection String"`
// 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 `mapstructure:"password" json:"password" yaml:"password" jsonschema:"title=Password"`
// 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 `mapstructure:"server_cert" json:"server_cert" yaml:"server_cert" jsonschema:"title=Server Certificate"`
ClientCert string `mapstructure:"client_cert" json:"client_cert" yaml:"client_cert" jsonschema:"title=Client Certificate"`
ClientKey string `mapstructure:"client_key" json:"client_key" yaml:"client_key" jsonschema:"title=Client Key"`
// 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 */
// 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"`
}
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 FieldObject ¶
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 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 (*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) 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) 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) 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) 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) 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) 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 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 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 OptionSetNamespace ¶
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 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 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 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 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 row-level indices for invalidation.
// refs contains (table, row_id) pairs for fine-grained cache invalidation.
// 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 specific rows.
// Called after mutations with the affected row IDs.
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 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 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 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
// 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"`
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"`
}
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"`
PrimaryKey string `json:"primary_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_key.go
- cache_response.go
- config.go
- core.go
- crypt.go
- database_join.go
- gstate.go
- init.go
- init_multidb.go
- intro.go
- mock.go
- openapi.go
- osfs.go
- plugin.go
- pretty.go
- remote_api.go
- remote_join.go
- resolve.go
- rolestmt.go
- schema.go
- schema_ddl.go
- schema_diff.go
- snowflake_bind.go
- subs.go
- trace.go
- types.go
- util.go
- watcher.go