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 NewOsFS(basePath string) *osFS
- type Cache
- type Column
- type Config
- type Delete
- type DirectiveType
- type EnumValue
- type Error
- type FS
- type FieldObject
- type FullType
- type GraphJin
- 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) Reload() error
- 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 GraphqlReq
- type GraphqlResponse
- type Header
- type InputValue
- type Insert
- type IntroResult
- type Introspection
- type IntrospectionSchema
- type Member
- type OpType
- type Option
- type Query
- type RequestConfig
- type Resolver
- type ResolverConfig
- type ResolverFn
- type ResolverProps
- type ResolverReq
- type Result
- type Role
- type RoleTable
- type ShortFullType
- type Spaner
- type StringAttr
- type Table
- 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"
)
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")
)
Functions ¶
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
type Column ¶
type Column struct { Name string Type string `jsonschema:"example=integer,example=text"` Primary bool Array bool ForeignKey string `` /* 138-byte string literal not displayed */ }
Configuration for a database table column
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"` // 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: mysql, postgres) DBType string `mapstructure:"db_type" json:"db_type" yaml:"db_type" jsonschema:"title=Database Type,enum=postgres,enum=mysql"` // 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 */ // 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:"-"` }
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) RemoveRoleTable ¶
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 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 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) 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) 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 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 Option ¶
type Option func(*graphjinEngine) error
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 OptionSetTrace ¶
OptionSetTrace sets the tracer to be used by GraphJin
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 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 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) 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 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 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 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