core

package module
v3.0.0-...-91d9d01 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2023 License: Apache-2.0 Imports: 36 Imported by: 7

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

View Source
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

View Source
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"
)
View Source
const (
	APQ_PX = "_apq"
)

Variables

View Source
var (
	TYPE_STRING  = "String"
	TYPE_INT     = "Int"
	TYPE_BOOLEAN = "Boolean"
	TYPE_FLOAT   = "Float"
	TYPE_JSON    = "JSON"
)
View Source
var (
	ErrNotFound = errors.New("not found in prepared statements")
)

Functions

func NewOsFS

func NewOsFS(basePath string) *osFS

Types

type Cache

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

func (Cache) Get

func (c Cache) Get(key string) (val []byte, fromCache bool)

func (Cache) Set

func (c Cache) Set(key string, val []byte)

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"`

	// 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

func (c *Config) AddRoleTable(role, table string, conf interface{}) error

AddRoleTable function is a helper function to make it easy to add per-table row-level config

func (*Config) RemoveRoleTable

func (c *Config) RemoveRoleTable(role, table string) error

type Delete

type Delete struct {
	Filters []string
	Columns []string
	Block   bool
}

Table configuration for deleting from a table with a role

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 EnumValue

type EnumValue struct {
	Name              string  `json:"name"`
	Description       string  `json:"description"`
	IsDeprecated      bool    `json:"isDeprecated"`
	DeprecationReason *string `json:"deprecationReason"`
}

type Error

type Error struct {
	Message string `json:"message"`
}

type FS

type FS interface {
	Get(path string) (data []byte, err error)
	Put(path string, data []byte) error
	Exists(path string) (exists bool, err error)
}

type FieldObject

type FieldObject struct {
	Name              string       `json:"name"`
	Description       string       `json:"description"`
	Args              []InputValue `json:"args"`
	Type              *TypeRef     `json:"type"`
	IsDeprecated      bool         `json:"isDeprecated"`
	DeprecationReason *string      `json:"deprecationReason"`
}

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

type GraphJin struct {
	atomic.Value
	// contains filtered or unexported fields
}

func NewGraphJin

func NewGraphJin(conf *Config, db *sql.DB, options ...Option) (g *GraphJin, err error)

NewGraphJin creates the GraphJin struct, this involves querying the database to learn its schemas and relationships

func NewGraphJinWithFS

func NewGraphJinWithFS(conf *Config, db *sql.DB, fs FS, options ...Option) (g *GraphJin, err error)

func (*GraphJin) GraphQL

func (g *GraphJin) GraphQL(c context.Context,
	query string,
	vars json.RawMessage,
	rc *ReqConfig,
) (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 *ReqConfig,
) (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 *ReqConfig,
) (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 *ReqConfig,
) (res *Result, err error)

GraphQLTx is similiar to the GraphQL function except that it can be used within a database transactions.

func (*GraphJin) IsProd

func (g *GraphJin) IsProd() bool

IsProd return true for production mode or false for development mode

func (*GraphJin) Reload

func (g *GraphJin) Reload() error

Reload redoes database discover and reinitializes GraphJin.

func (*GraphJin) Subscribe

func (g *GraphJin) Subscribe(
	c context.Context,
	query string,
	vars json.RawMessage,
	rc *ReqConfig,
) (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 *ReqConfig,
) (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 Header struct {
	Type OpType
	Name string
}

func Operation

func Operation(query string) (h Header, err error)

Operation function return the operation type and name from the query. It uses a very fast algorithm to extract the operation without having to parse the query.

type InputValue

type InputValue struct {
	Name         string   `json:"name"`
	Description  string   `json:"description"`
	Type         *TypeRef `json:"type"`
	DefaultValue *string  `json:"defaultValue"`
}

type Insert

type Insert struct {
	Filters []string
	Columns []string
	Presets map[string]string
	Block   bool
}

Table configuration for inserting into a table with a role

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) ID

func (m *Member) ID() uint64

func (*Member) String

func (m *Member) String() string

func (*Member) Unsubscribe

func (m *Member) Unsubscribe()

type OpType

type OpType int
const (
	OpUnknown OpType = iota
	OpQuery
	OpSubscription
	OpMutation
)

type Option

type Option func(*graphjin) error

func OptionSetFS

func OptionSetFS(fs FS) Option

func OptionSetNamespace

func OptionSetNamespace(namespace string) Option

func OptionSetResolver

func OptionSetResolver(name string, fn ResolverFn) Option

func OptionSetTrace

func OptionSetTrace(trace Tracer) Option

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 ReqConfig

type ReqConfig 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
}

ReqConfig is used to pass request specific config values to the GraphQL and Subscribe functions. Dynamic variables can be set here.

func (*ReqConfig) GetNamespace

func (rc *ReqConfig) GetNamespace() (string, bool)

GetNamespace is used to get the namespace requests within a single instance of GraphJin

func (*ReqConfig) SetNamespace

func (rc *ReqConfig) 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
	*ReqConfig
}

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

func (r *Result) CacheControl() string

Returns the cache control header value for the query result

func (*Result) Namespace

func (r *Result) Namespace() string

Returns the namespace for the query result

func (*Result) Operation

func (r *Result) Operation() OpType

Returns the operation type for the query result

func (*Result) OperationName

func (r *Result) OperationName() string

Returns the operation name for the query result

func (*Result) QueryName

func (r *Result) QueryName() string

Returns the query name for the query result

func (*Result) Role

func (r *Result) Role() string

Returns the role used to execute the query

func (*Result) SQL

func (r *Result) SQL() string

Returns the SQL query string 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

func (*Role) GetTable

func (r *Role) GetTable(schema, name string) *RoleTable

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 StringAttr struct {
	Name  string
	Value string
}

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

type Tracer

type Tracer interface {
	Start(c context.Context, name string) (context.Context, Spaner)
	NewHTTPClient() *http.Client
}

type TypeRef

type TypeRef struct {
	Kind   string   `json:"kind"`
	Name   *string  `json:"name"`
	OfType *TypeRef `json:"ofType"`
}

type Update

type Update struct {
	Filters []string
	Columns []string
	Presets map[string]string
	Block   bool
}

Table configuration for updating a table with a role

type Upsert

type Upsert struct {
	Filters []string
	Columns []string
	Presets map[string]string
	Block   bool
}

Table configuration for creating/updating (upsert) a table with a role

Directories

Path Synopsis
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

Jump to

Keyboard shortcuts

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