super-graph/jsn/test7.json
2020-03-30 10:03:47 -04:00

1 line
61 KiB
JSON

{"data":{"published":true,"body":"---\nsidebar: auto\n---\n# Guide to Super Graph\n\nSuper Graph is a service that instantly and without code gives you a high performance and secure GraphQL API. Your GraphQL queries are auto translated into a single fast SQL query. No more spending weeks or months writing backend API code. Just make the query you need and Super Graph will do the rest. \n\nSuper Graph has a rich feature set like integrating with your existing Ruby on Rails apps, joining your DB with data from remote APIs, Role and Attribute based access control, Support for JWT tokens, DB migrations, seeding and a lot more.\n\n\n## Features\n\n* Role and Attribute based access control\n* Works with existing Ruby\\-On\\-Rails apps\n* Automatically learns database schemas and relationships\n* Full text search and aggregations\n* Rails authentication supported \\(Redis, Memcache, Cookie\\)\n* JWT tokens supported \\(Auth0, etc\\)\n* Join database with remote REST APIs\n* Highly optimized and fast Postgres SQL queries\n* GraphQL queries and mutations\n* A simple config file\n* High performance GO codebase\n* Tiny docker image and low memory requirements\n* Fuzz tested for security\n* Database migrations tool\n* Database seeding tool\n\n\n## Try the demo app\n\n```bash\n# clone the repository\ngit clone https://github.com/dosco/super-graph\n\n# setup the demo rails app & database and run it\ndocker-compose run rails_app rake db:create db:migrate db:seed\n\n# run the demo\ndocker-compose up\n\n# signin to the demo app (user1@demo.com / 123456)\nopen http://localhost:3000\n\n# try the super graph web ui\nopen http://localhost:8080\n\n```\n\n::: tip DEMO REQUIREMENTS\nThis demo requires `docker` you can either install it using `brew` or from the\ndocker website [https://docs.docker.com/docker\\-for\\-mac/install/](https://docs.docker.com/docker-for-mac/install/)\n:::\n\n#### Trying out GraphQL\n\nWe fully support queries and mutations. For example the below GraphQL query would fetch two products that belong to the current user where the price is greater than 10.\n\n#### GQL Query\n\n```graphql\nquery {\n users {\n id\n email\n picture : avatar\n password\n full_name\n products(limit: 2, where: { price: { gt: 10 } }) {\n id\n name\n description\n price\n }\n }\n}\n\n```\n\n#### JSON Result\n\n```json\n{\n \"data\": {\n \"users\": [\n {\n \"id\": 1,\n \"email\": \"odilia@west.info\",\n \"picture\": \"https://robohash.org/simur.png?size=300x300\",\n \"full_name\": \"Edwin Orn\",\n \"products\": [\n {\n \"id\": 16,\n \"name\": \"Sierra Nevada Style Ale\",\n \"description\": \"Belgian Abbey, 92 IBU, 4.7%, 17.4°Blg\",\n \"price\": 16.47\n },\n ...\n ]\n }\n ]\n }\n}\n\n```\n\n::: tip Testing with a user\nIn development mode you can use the `X-User-ID: 4` header to set a user id so you don't have to worries about cookies etc. This can be set using the _HTTP Headers_ tab at the bottom of the web UI.\n:::\n\nIn another example the below GraphQL mutation would insert a product into the database. The first part of the below example is the variable data and the second half is the GraphQL mutation. For mutations data has to always ben passed as a variable.\n\n```json\n{\n \"data\": { \n \"name\": \"Art of Computer Programming\",\n \"description\": \"The Art of Computer Programming (TAOCP) is a comprehensive monograph written by computer scientist Donald Knuth\",\n \"price\": 30.5\n }\n}\n\n```\n\n```graphql\nmutation {\n product(insert: $data) {\n id\n name\n }\n}\n\n```\n\n## Why Super Graph\n\nLet's take a simple example say you want to fetch 5 products priced over 12 dollars along with the photos of the products and the users that owns them. Additionally also fetch the last 10 of your own purchases along with the name and ID of the product you purchased. This is a common type of query to render a view in say an ecommerce app. Lets be honest it's not very exciting write and maintain. Keep in mind the data needed will only continue to grow and change as your app evolves. Developers might find that most ORMs will not be able to do all of this in a single SQL query and will require n\\+1 queries to fetch all the data and assembly it into the right JSON response.\n\nWhat if I told you Super Graph will fetch all this data with a single SQL query and without you having to write a single line of code. Also as your app evolves feel free to evolve the query as you like. In our experience Super Graph saves us hundreds or thousands of man hours that we can put towards the more exciting parts of our app.\n\n#### GraphQL Query\n\n```graphql\nquery {\n products(limit 5, where: { price: { gt: 12 } }) {\n id\n name\n description\n price\n photos {\n url\n }\n user {\n id\n email\n picture : avatar\n full_name\n }\n }\n purchases(\n limit 10, \n order_by: { created_at: desc } , \n where: { user_id: { eq: $user_id } }\n ) {\n id \n created_at\n product {\n id\n name\n }\n }\n}\n\n```\n\n#### JSON Result\n\n```json\n\n \"data\": {\n \"products\": [\n {\n \"id\": 1,\n \"name\": \"Oaked Arrogant Bastard Ale\",\n \"description\": \"Coors lite, European Amber Lager, Perle, 1272 - American Ale II, 38 IBU, 6.4%, 9.7°Blg\",\n \"price\": 20,\n \"photos: [{\n \"url\": \"https://www.scienceworld.ca/wp-content/uploads/science-world-beer-flavours.jpg\"\n }],\n \"user\": {\n \"id\": 1,\n \"email\": \"user0@demo.com\",\n \"picture\": \"https://robohash.org/sitaliquamquaerat.png?size=300x300&set=set1\",\n \"full_name\": \"Mrs. Wilhemina Hilpert\"\n }\n },\n ...\n ]\n },\n \"purchases\": [\n {\n \"id\": 5,\n \"created_at\": \"2020-01-24T05:34:39.880599\",\n \"product\": {\n \"id\": 45,\n \"name\": \"Brooklyn Black\",\n }\n },\n ...\n ]\n}\n\n```\n\n## Get Started\n\nSuper Graph can generate your initial app for you. The generated app will have config files, database migrations and seed files among other things like docker related files.\n\nYou can then add your database schema to the migrations, maybe create some seed data using the seed script and launch Super Graph. You're now good to go and can start working on your UI frontend in React, Vue or whatever.\n\n```bash\n# Download and install Super Graph. You will need Go 1.13 or above\ngit clone https://github.com/dosco/super-graph && cd super-graph && make install\n\n```\n\nAnd then create and launch you're new app\n\n```bash\n# create a new app and change to it's directory\nsuper-graph new blog; cd blog\n\n# setup the app database and seed it with fake data. Docker compose will start a Postgres database for your app\ndocker-compose run blog_api ./super-graph db:setup\n\n# and finally launch Super Graph configured for your app\ndocker-compose up\n\n```\n\nLets take a look at the files generated by Super Graph when you create a new app\n\n```bash\nsuper-graph new blog\n\n> created 'blog'\n> created 'blog/Dockerfile'\n> created 'blog/docker-compose.yml'\n> created 'blog/config'\n> created 'blog/config/dev.yml'\n> created 'blog/config/prod.yml'\n> created 'blog/config/seed.js'\n> created 'blog/config/migrations'\n> created 'blog/config/migrations/100_init.sql'\n> app 'blog' initialized\n\n```\n\n### Docker files\n\nDocker Compose is a great way to run multiple services while developing on your desktop or laptop. In our case we need Postgres and Super Graph to both be running and the `docker-compose.yml` is configured to do just that. The Super Graph service is named after your app postfixed with `_api`. The Dockerfile can be used build a containr of your app for production deployment.\n\n```bash\ndocker-compose run blog_api ./super-graph help\n\n```\n\n### Config files\n\nAll the config files needs to configure Super Graph for your app are contained in this folder for starters you have two `dev.yaml` and `prod.yaml`. When the `GO_ENV` environment variable is set to `development` then `dev.yaml` is used and the prod one when it's set to `production`. Stage and Test are the other two environment options, but you can set the `GO_ENV` to whatever you like \\(eg. `alpha-test`\\) and Super Graph will look for a yaml file with that name to load config from.\n\n### Seed\\.js\n\nHaving data flowing through your API makes building your frontend UI so much easier. When creafting say a user profile wouldn't it be nice for the API to return a fake user with name, picture and all. This is why having the ability to seed your database is important. Seeding cn also be used in production to setup some initial users like the admins or to add an initial set of products to a ecommerce store.\n\nSuper Graph makes this easy by allowing you to write your seeding script in plan old Javascript. The below file that auto\\-generated for new apps uses our built\\-in functions `fake` and `graphql` to generate fake data and use GraphQL mutations to insert it into the database.\n\n```javascript\n// Example script to seed database\n\nvar users = [];\n\nfor (i = 0; i < 10; i++) {\n var data = {\n full_name: fake.name(),\n email: fake.email()\n }\n\n var res = graphql(\" \\\n mutation { \\\n user(insert: $data) { \\\n id \\\n } \\\n }\", { data: data })\n\n users.push(res.user)\n}\n\n```\n\nYou can generate the following fake data for your seeding purposes. Below is the list of fake data functions supported by the built\\-in fake data library. For example `fake.image_url()` will generate a fake image url or `fake.shuffle_strings(['hello', 'world', 'cool'])` will generate a randomly shuffled version of that array of strings or `fake.rand_string(['hello', 'world', 'cool'])` will return a random string from the array provided.\n\n```\n// Person\nperson\nname\nname_prefix\nname_suffix\nfirst_name\nlast_name\ngender\nssn\ncontact\nemail\nphone\nphone_formatted\nusername\npassword\n\n// Address\naddress\ncity\ncountry\ncountry_abr\nstate\nstate_abr\nstatus_code\nstreet\nstreet_name\nstreet_number\nstreet_prefix\nstreet_suffix\nzip\nlatitude\nlatitude_in_range\nlongitude\nlongitude_in_range\n\n// Beer\nbeer_alcohol\nbeer_hop\nbeer_ibu\nbeer_blg\nbeer_malt\nbeer_name\nbeer_style\nbeer_yeast\n\n// Cars\nvehicle\nvehicle_type\ncar_maker\ncar_model\nfuel_type\ntransmission_gear_type\n\n// Text\nword\nsentence\nparagraph\nquestion\nquote\n\n// Misc\ngenerate\nboolean\nuuid\n\n// Colors\ncolor\nhex_color\nrgb_color\nsafe_color\n\n// Internet\nurl\nimage_url\ndomain_name\ndomain_suffix\nipv4_address\nipv6_address\nsimple_status_code\nhttp_method\nuser_agent\nuser_agent_firefox\nuser_agent_chrome\nuser_agent_opera\nuser_agent_safari\n\n// Date / Time\ndate\ndate_range\nnano_second\nsecond\nminute\nhour\nmonth\nday\nweekday\nyear\ntimezone\ntimezone_abv\ntimezone_full\ntimezone_offset\n\n// Payment\nprice\ncredit_card\ncredit_card_cvv\ncredit_card_number\ncredit_card_number_luhn\ncredit_card_type\ncurrency\ncurrency_long\ncurrency_short\n\n// Company\nbs\nbuzzword\ncompany\ncompany_suffix\njob\njob_description\njob_level\njob_title\n\n// Hacker\nhacker_abbreviation\nhacker_adjective\nhacker_ingverb\nhacker_noun\nhacker_phrase\nhacker_verb\n\n//Hipster\nhipster_word\nhipster_paragraph\nhipster_sentence\n\n// File\nextension\nmine_type\n\n// Numbers\nnumber\nnumerify\nint8\nint16\nint32\nint64\nuint8\nuint16\nuint32\nuint64\nfloat32\nfloat32_range\nfloat64\nfloat64_range\nshuffle_ints\nmac_address\n\n//String\ndigit\nletter\nlexify\nrand_string\nshuffle_strings\nnumerify\n\n```\n\n### Migrations\n\nEasy database migrations is the most important thing when building products backend by a relational database. We make it super easy to manage and migrate your database.\n\n```bash\nsuper-graph db:new create_users\n> created migration 'config/migrations/101_create_users.sql'\n\n```\n\nMigrations in Super Graph are plain old Postgres SQL. Here's an example for the above migration.\n\n```sql\n-- Write your migrate up statements here\n\nCREATE TABLE public.users (\n id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n full_name text,\n email text UNIQUE NOT NULL CHECK (length(email) < 255),\n created_at timestamptz NOT NULL NOT NULL DEFAULT NOW(),\n updated_at timestamptz NOT NULL NOT NULL DEFAULT NOW()\n);\n\n---- create above / drop below ----\n\n-- Write your down migrate statements here. If this migration is irreversible\n-- then delete the separator line above.\n\nDROP TABLE public.users\n\n```\n\nWe would encourage you to leverage triggers to maintain consistancy of your data for example here are a couple triggers that you can add to you init migration and across your tables.\n\n```sql\n-- This trigger script will set the updated_at column everytime a row is updated\nCREATE OR REPLACE FUNCTION trigger_set_updated_at()\nRETURNS TRIGGER SET SCHEMA 'public' LANGUAGE 'plpgsql' AS $$\nBEGIN\n new.updated_at = now();\n RETURN new;\nEND;\n$$;\n\n...\n\n-- An exmple of adding this trigger to the users table\nCREATE TRIGGER set_updated_at BEFORE UPDATE ON public.users\n FOR EACH ROW EXECUTE PROCEDURE trigger_set_updated_at();\n\n```\n\n```sql\n-- This trigger script will set the user_id column to the current\n-- Super Graph user.id value everytime a row is created or updated\nCREATE OR REPLACE FUNCTION trigger_set_user_id()\nRETURNS TRIGGER SET SCHEMA 'public' LANGUAGE 'plpgsql' AS $$\nBEGIN\n IF TG_OP = 'UPDATE' THEN\n new.user_id = old.user_id;\n ELSE\n new.user_id = current_setting('user.id')::int;\n END IF;\n\n RETURN new;\nEND;\n$$;\n\n...\n\n-- An exmple of adding this trigger to the blog_posts table\nCREATE TRIGGER set_user_id BEFORE INSERT OR UPDATE ON public.blog_posts\n FOR EACH ROW EXECUTE PROCEDURE trigger_set_user_id();\n\n```\n\n## How to GraphQL\n\nGraphQL \\(GQL\\) is a simple query syntax that's fast replacing REST APIs. GQL is great since it allows web developers to fetch the exact data that they need without depending on changes to backend code. Also if you squint hard enough it looks a little bit like JSON :smiley:\n\nThe below query will fetch an `users` name, email and avatar image \\(renamed as picture\\). If you also need the users `id` then just add it to the query.\n\n```graphql\nquery {\n user {\n full_name\n email\n picture : avatar\n }\n}\n\n```\n\nMultiple tables can also be fetched using a single GraphQL query. This is very fast since the entire query is converted into a single SQL query which the database can efficiently run.\n\n```graphql\nquery {\n user {\n full_name\n email\n }\n products {\n name\n description\n }\n}\n\n```\n\n### Fetching data\n\nTo fetch a specific `product` by it's ID you can use the `id` argument\\. The real name id field will be resolved automatically so this query will work even if your id column is named something like `product_id`.\n\n```graphql\nquery {\n products(id: 3) {\n name\n }\n}\n\n```\n\nPostgres also supports full text search using a TSV index. Super Graph makes it easy to use this full text search capability using the `search` argument\\.\n\n```graphql\nquery {\n products(search: \"ale\") {\n name\n }\n}\n\n```\n\n### Sorting\n\nTo sort or ordering results just use the `order_by` argument\\. This can be combined with `where`, `search`, etc to build complex queries to fit you needs.\n\n```graphql\nquery {\n products(order_by: { cached_votes_total: desc }) {\n id\n name\n }\n}\n\n```\n\n### Filtering\n\nSuper Graph support complex queries where you can add filters, ordering,offsets and limits on the query. For example the below query will list all products where the price is greater than 10 and the id is not 5.\n\n```graphql\nquery {\n products(where: { \n and: { \n price: { gt: 10 }, \n not: { id: { eq: 5 } } \n } \n }) {\n name\n price\n }\n}\n\n```\n\n#### Nested where clause targeting related tables\n\nSometimes you need to query a table based on a condition that applies to a related table. For example say you need to list all users who belong to an account. This query below will fetch the id and email or all users who belong to the account with id 3.\n\n```graphql\nquery {\n users(where: { \n accounts: { id: { eq: 3 } }\n }) {\n id\n email\n }\n}`\n\n```\n\n#### Logical Operators\n\n| Name | Example | Explained |\n|:--- |:--- |:--- |\n| and | price : \\{ and : \\{ gt: 10.5, lt: 20 \\} | price \\> 10.5 AND price < 20 |\n| or | or : \\{ price : \\{ greater\\_than : 20 \\}, quantity: \\{ gt : 0 \\} \\} | price \\>= 20 OR quantity \\> 0 |\n| not | not: \\{ or : \\{ quantity : \\{ eq: 0 \\}, price : \\{ eq: 0 \\} \\} \\} | NOT \\(quantity = 0 OR price = 0\\) |\n\n#### Other conditions\n\n| Name | Example | Explained |\n|:--- |:--- |:--- |\n| eq, equals | id : \\{ eq: 100 \\} | id = 100 |\n| neq, not\\_equals | id: \\{ not\\_equals: 100 \\} | id \\!= 100 |\n| gt, greater\\_than | id: \\{ gt: 100 \\} | id \\> 100 |\n| lt, lesser\\_than | id: \\{ gt: 100 \\} | id < 100 |\n| gte, greater\\_or\\_equals | id: \\{ gte: 100 \\} | id \\>= 100 |\n| lte, lesser\\_or\\_equals | id: \\{ lesser\\_or\\_equals: 100 \\} | id <= 100 |\n| in | status: \\{ in: \\[ \"A\", \"B\", \"C\" \\] \\} | status IN \\('A', 'B', 'C\\) |\n| nin, not\\_in | status: \\{ in: \\[ \"A\", \"B\", \"C\" \\] \\} | status IN \\('A', 'B', 'C\\) |\n| like | name: \\{ like \"phil%\" \\} | Names starting with 'phil' |\n| nlike, not\\_like | name: \\{ nlike \"v%m\" \\} | Not names starting with 'v' and ending with 'm' |\n| ilike | name: \\{ ilike \"%wOn\" \\} | Names ending with 'won' case\\-insensitive |\n| nilike, not\\_ilike | name: \\{ nilike \"%wOn\" \\} | Not names ending with 'won' case\\-insensitive |\n| similar | name: \\{ similar: \"%\\(b\\|d\\)%\" \\} | [Similar Docs](https://www.postgresql.org/docs/9/functions-matching.html#FUNCTIONS-SIMILARTO-REGEXP) |\n| nsimilar, not\\_similar | name: \\{ nsimilar: \"%\\(b\\|d\\)%\" \\} | [Not Similar Docs](https://www.postgresql.org/docs/9/functions-matching.html#FUNCTIONS-SIMILARTO-REGEXP) |\n| has\\_key | column: \\{ has\\_key: 'b' \\} | Does JSON column contain this key |\n| has\\_key\\_any | column: \\{ has\\_key\\_any: \\[ a, b \\] \\} | Does JSON column contain any of these keys |\n| has\\_key\\_all | column: \\[ a, b \\] | Does JSON column contain all of this keys |\n| contains | column: \\{ contains: \\[1, 2, 4\\] \\} | Is this array/json column a subset of value |\n| contained\\_in | column: \\{ contains: \"\\{'a':1, 'b':2\\}\" \\} | Is this array/json column a subset of these value |\n| is\\_null | column: \\{ is\\_null: true \\} | Is column value null or not |\n\n### Aggregations\n\nYou will often find the need to fetch aggregated values from the database such as `count`, `max`, `min`, etc. This is simple to do with GraphQL, just prefix the aggregation name to the field name that you want to aggregrate like `count_id`. The below query will group products by name and find the minimum price for each group. Notice the `min_price` field we're adding `min_` to price.\n\n```graphql\nquery {\n products {\n name\n min_price\n }\n}\n\n```\n\n| Name | Explained |\n|:--- |:--- |\n| avg | Average value |\n| count | Count the values |\n| max | Maximum value |\n| min | Minimum value |\n| stddev | [Standard Deviation](https://en.wikipedia.org/wiki/Standard_deviation) |\n| stddev\\_pop | Population Standard Deviation |\n| stddev\\_samp | Sample Standard Deviation |\n| variance | [Variance](https://en.wikipedia.org/wiki/Variance) |\n| var\\_pop | Population Standard Variance |\n| var\\_samp | Sample Standard variance |\n\nAll kinds of queries are possible with GraphQL. Below is an example that uses a lot of the features available. Comments `# hello` are also valid within queries.\n\n```graphql\nquery {\n products(\n # returns only 30 items\n limit: 30,\n\n # starts from item 10, commented out for now\n # offset: 10,\n\n # orders the response items by highest price\n order_by: { price: desc },\n\n # no duplicate prices returned\n distinct: [ price ]\n\n # only items with an id >= 30 and < 30 are returned\n where: { id: { and: { greater_or_equals: 20, lt: 28 } } }) {\n id\n name\n price\n }\n}\n\n```\n\nIn GraphQL mutations is the operation type for when you need to modify data. Super Graph supports the `insert`, `update`, `upsert` and `delete`. You can also do complex nested inserts and updates.\n\nWhen using mutations the data must be passed as variables since Super Graphs compiles the query into an prepared statement in the database for maximum speed. Prepared statements are are functions in your code when called they accept arguments and your variables are passed in as those arguments.\n\n### Insert\n\n```json\n{\n \"data\": { \n \"name\": \"Art of Computer Programming\",\n \"description\": \"The Art of Computer Programming (TAOCP) is a comprehensive monograph written by computer scientist Donald Knuth\",\n \"price\": 30.5\n }\n}\n\n```\n\n```graphql\nmutation {\n product(insert: $data) {\n id\n name\n }\n}\n\n```\n\n#### Bulk insert\n\n```json\n{\n \"data\": [{ \n \"name\": \"Art of Computer Programming\",\n \"description\": \"The Art of Computer Programming (TAOCP) is a comprehensive monograph written by computer scientist Donald Knuth\",\n \"price\": 30.5\n },\n { \n \"name\": \"Compilers: Principles, Techniques, and Tools\",\n \"description\": \"Known to professors, students, and developers worldwide as the 'Dragon Book' is available in a new edition\",\n \"price\": 93.74\n }]\n}\n\n```\n\n```graphql\nmutation {\n product(insert: $data) {\n id\n name\n }\n}\n\n```\n\n### Update\n\n```json\n{\n \"data\": { \n \"price\": 200.0\n },\n \"product_id\": 5\n}\n\n```\n\n```graphql\nmutation {\n product(update: $data, id: $product_id) {\n id\n name\n }\n}\n\n```\n\n#### Bulk update\n\n```json\n{\n \"data\": { \n \"price\": 500.0\n },\n \"gt_product_id\": 450.0,\n \"lt_product_id:\": 550.0\n}\n\n```\n\n```graphql\nmutation {\n product(update: $data, where: { \n price: { gt: $gt_product_id, lt: lt_product_id } \n }) {\n id\n name\n }\n}\n\n```\n\n### Delete\n\n```json\n{\n \"data\": { \n \"price\": 500.0\n },\n \"product_id\": 5\n}\n\n```\n\n```graphql\nmutation {\n product(delete: true, id: $product_id) {\n id\n name\n }\n}\n\n```\n\n#### Bulk delete\n\n```json\n{\n \"data\": { \n \"price\": 500.0\n }\n}\n\n```\n\n```graphql\nmutation {\n product(delete: true, where: { price: { eq: { 500.0 } } }) {\n id\n name\n }\n}\n\n```\n\n### Upsert\n\n```json\n{\n \"data\": { \n \"id\": 5,\n \"name\": \"Art of Computer Programming\",\n \"description\": \"The Art of Computer Programming (TAOCP) is a comprehensive monograph written by computer scientist Donald Knuth\",\n \"price\": 30.5\n }\n}\n\n```\n\n```graphql\nmutation {\n product(upsert: $data) {\n id\n name\n }\n}\n\n```\n\n#### Bulk upsert\n\n```json\n{\n \"data\": [{ \n \"id\": 5,\n \"name\": \"Art of Computer Programming\",\n \"description\": \"The Art of Computer Programming (TAOCP) is a comprehensive monograph written by computer scientist Donald Knuth\",\n \"price\": 30.5\n },\n { \n \"id\": 6,\n \"name\": \"Compilers: Principles, Techniques, and Tools\",\n \"description\": \"Known to professors, students, and developers worldwide as the 'Dragon Book' is available in a new edition\",\n \"price\": 93.74\n }]\n}\n\n```\n\n```graphql\nmutation {\n product(upsert: $data) {\n id\n name\n }\n}\n\n```\n\nOften you will need to create or update multiple related items at the same time. This can be done using nested mutations. For example you might need to create a product and assign it to a user, or create a user and his products at the same time. You just have to use simple json to define you mutation and Super Graph takes care of the rest.\n\n### Nested Insert\n\nCreate a product item first and then assign it to a user\n\n```json\n{\n \"data\": {\n \"name\": \"Apple\",\n \"price\": 1.25,\n \"created_at\": \"now\",\n \"updated_at\": \"now\",\n \"user\": {\n \"connect\": { \"id\": 5 }\n }\n }\n}\n\n```\n\n```graphql\nmutation {\n product(insert: $data) {\n id\n name\n user {\n id\n full_name\n email\n }\n }\n}\n\n```\n\nOr it's reverse, create the user first and then his product\n\n```json\n{\n \"data\": {\n \"email\": \"thedude@rug.com\",\n \"full_name\": \"The Dude\",\n \"created_at\": \"now\",\n \"updated_at\": \"now\",\n \"product\": {\n \"name\": \"Apple\",\n \"price\": 1.25,\n \"created_at\": \"now\",\n \"updated_at\": \"now\"\n }\n }\n}\n\n```\n\n```graphql\nmutation {\n user(insert: $data) {\n id\n full_name\n email\n product {\n id\n name\n price\n }\n }\n}\n\n```\n\n### Nested Update\n\nUpdate a product item first and then assign it to a user\n\n```json\n{\n \"data\": {\n \"name\": \"Apple\",\n \"price\": 1.25,\n \"user\": {\n \"connect\": { \"id\": 5 }\n }\n }\n}\n\n```\n\n```graphql\nmutation {\n product(update: $data, id: 5) {\n id\n name\n user {\n id\n full_name\n email\n }\n }\n}\n\n```\n\nOr it's reverse, update a user first and then his product\n\n```json\n{\n \"data\": {\n \"email\": \"newemail@me.com\",\n \"full_name\": \"The Dude\",\n \"product\": {\n \"name\": \"Banana\",\n \"price\": 1.25,\n }\n }\n}\n\n```\n\n```graphql\nmutation {\n user(update: $data, id: 1) {\n id\n full_name\n email\n product {\n id\n name\n price\n }\n }\n}\n\n```\n\n### Pagination\n\nThis is a must have feature of any API. When you want your users to go thought a list page by page or implement some fancy infinite scroll you're going to need pagination. There are two ways to paginate in Super Graph.\n\n Limit\\-Offset\nThis is simple enough but also inefficient when working with a large number of total items. Limit, limits the number of items fetched and offset is the point you want to fetch from. The below query will fetch 10 results at a time starting with the 100th item. You will have to keep updating offset \\(110, 120, 130, etc \\) to walk thought the results so make offset a variable.\n\n```graphql\nquery {\n products(limit: 10, offset: 100) {\n id\n slug\n name\n }\n}\n\n```\n\n#### Cursor\n\nThis is a powerful and highly efficient way to paginate though a large number of results. Infact it does not matter how many total results there are this will always be lighting fast. You can use a cursor to walk forward of backward though the results. If you plan to implement infinite scroll this is the option you should choose. \n\nWhen going this route the results will contain a cursor value this is an encrypted string that you don't have to worry about just pass this back in to the next API call and you'll received the next set of results. The cursor value is encrypted since its contents should only matter to Super Graph and not the client. Also since the primary key is used for this feature it's possible you might not want to leak it's value to clients. \n\nYou will need to set this config value to ensure the encrypted cursor data is secure. If not set a random value is used which will change with each deployment breaking older cursor values that clients might be using so best to set it.\n\n```yaml\n# Secret key for general encryption operations like \n# encrypting the cursor data\nsecret_key: supercalifajalistics\n\n```\n\nPaginating forward through your results\n\n```json\n{\n \"variables\": { \n \"cursor\": \"MJoTLbQF4l0GuoDsYmCrpjPeaaIlNpfm4uFU4PQ=\"\n }\n}\n\n```\n\n```graphql\nquery {\n products(first: 10, after: $cursor) {\n slug\n name\n }\n}\n\n```\n\nPaginating backward through your results\n\n```graphql\nquery {\n products(last: 10, before: $cursor) {\n slug\n name\n }\n}\n\n```\n\n```graphql\n\"data\": {\n \"products\": [\n {\n \"slug\": \"eius-nulla-et-8\",\n \"name\" \"Pale Ale\"\n },\n {\n \"slug\": \"sapiente-ut-alias-12\",\n \"name\" \"Brown Ale\"\n }\n ...\n ],\n \"products_cursor\": \"dJwHassm5+d82rGydH2xQnwNxJ1dcj4/cxkh5Cer\"\n}\n\n```\n\nNested tables can also have cursors. Requesting multiple cursors are supported on a single request but when paginating using a cursor only one table is currently supported. To explain this better, you can only use a `before` or `after` argument with a cursor value to paginate a single table in a query.\n\n```graphql\nquery {\n products(last: 10) {\n slug\n name\n customers(last: 5) {\n email\n full_name\n }\n }\n}\n\n```\n\nMultiple order\\-by arguments are supported. Super Graph is smart enough to allow cursor based pagination when you also need complex sort order like below.\n\n```graphql\nquery {\n products(\n last: 10\n before: $cursor\n order_by: [ price: desc, total_customers: asc ]) {\n slug\n name\n }\n}\n\n```\n\n\n## Using Variables\n\nVariables \\(`$product_id`\\) and their values \\(`\"product_id\": 5`\\) can be passed along side the GraphQL query. Using variables makes for better client side code as well as improved server side SQL query caching. The build\\-in web\\-ui also supports setting variables. Not having to manipulate your GraphQL query string to insert values into it makes for cleaner\nand better client side code.\n\n```javascript\n// Define the request object keeping the query and the variables seperate\nvar req = { \n query: '{ product(id: $product_id) { name } }' ,\n variables: { \"product_id\": 5 }\n}\n\n// Use the fetch api to make the query\nfetch('http://localhost:8080/api/v1/graphql', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(req),\n})\n.then(res => res.json())\n.then(res => console.log(res.data));\n\n```\n\n## GraphQL with React\n\nThis is a quick simple example using `graphql.js` [https://github.com/f/graphql.js/](https://github.com/f/graphql.js/)\n\n```js\nimport React, { useState, useEffect } from 'react'\nimport graphql from 'graphql.js'\n\n// Create a GraphQL client pointing to Super Graph\nvar graph = graphql(\"http://localhost:3000/api/v1/graphql\", { asJSON: true })\n\nconst App = () => {\n const [user, setUser] = useState(null)\n\n useEffect(() => {\n async function action() {\n // Use the GraphQL client to execute a graphQL query\n // The second argument to the client are the variables you need to pass\n const result = await graph(`{ user { id first_name last_name picture_url } }`)()\n setUser(result)\n }\n action()\n }, []);\n\n return (\n <div className=\"App\">\n <h1>{ JSON.stringify(user) }</h1>\n </div>\n );\n}\n\n```\n\nexport default App;\n\n## Advanced Columns\n\nThe ablity to have `JSON/JSONB` and `Array` columns is often considered in the top most useful features of Postgres. There are many cases where using an array or a json column saves space and reduces complexity in your app. The only issue with these columns is the really that your SQL queries can get harder to write and maintain. \n\nSuper Graph steps in here to help you by supporting these columns right out of the box. It allows you to work with these columns just like you would with tables. Joining data against or modifying array columns using the `connect` or `disconnect` keywords in mutations is fully supported. Another very useful feature is the ability to treat `json` or `binary json (jsonb)` columns as seperate tables, even using them in nested queries joining against related tables. To replicate these features on your own will take a lot of complex SQL. Using Super Graph means you don't have to deal with any of this it just works.\n\n### Array Columns\n\nConfigure a relationship between an array column `tag_ids` which contains integer id's for tags and the column `id` in the table `tags`.\n\n```yaml\ntables:\n - name: posts\n columns:\n - name: tag_ids\n related_to: tags.id\n\n```\n\n```graphql\nquery {\n posts {\n title\n tags {\n name\n image\n }\n }\n}\n\n```\n\n### JSON Column\n\nConfigure a JSON column called `tag_count` in the table `products` into a seperate table. This JSON column contains a json array of objects each with a tag id and a count of the number of times the tag was used. As a seperate table you can nest it into your GraphQL query and treat it like table using any of the standard features like `order_by`, `limit`, `where clauses`, etc.\n\nThe configuration below tells Super Graph to create a synthetic table called `tag_count` using the column `tag_count` from the `products` table\\. And that this new table has two columns `tag_id` and `count` of the listed types and with the defined relationships.\n\n```yaml\ntables:\n - name: tag_count\n table: products\n columns:\n - name: tag_id\n type: bigint\n related_to: tags.id\n - name: count\n type: int\n\n```\n\n```graphql\nquery {\n products {\n name\n tag_counts {\n count\n tag {\n name\n }\n }\n }\n}\n\n```\n\n\n## Full text search\n\nEvery app these days needs search. Enought his often means reaching for something heavy like Solr. While this will work why add complexity to your infrastructure when Postgres has really great\nand fast full text search built\\-in. And since it's part of Postgres it's also available in Super Graph.\n\n```graphql\nquery {\n products(\n # Search for all products that contain 'ale' or some version of it\n search: \"ale\"\n\n # Return only matches where the price is less than 10\n where: { price: { lt: 10 } }\n\n # Use the search_rank to order from the best match to the worst\n order_by: { search_rank: desc }) {\n id\n name\n search_rank\n search_headline_description\n }\n}\n\n```\n\nThis query will use the `tsvector` column in your database table to search for products that contain the query phrase or some version of it. To get the internal relevance ranking for the search results using the `search_rank` field\\. And to get the highlighted context within any of the table columns you can use the `search_headline_` field prefix. For example `search_headline_name` will return the contents of the products name column which contains the matching query marked with the `<b></b>` html tags.\n\n```json\n{\n \"data\": {\n \"products\": [\n {\n \"id\": 11,\n \"name\": \"Maharaj\",\n \"search_rank\": 0.243171,\n \"search_headline_description\": \"Blue Moon, Vegetable Beer, Willamette, 1007 - German <b>Ale</b>, 48 IBU, 7.9%, 11.8°Blg\"\n },\n {\n \"id\": 12,\n \"name\": \"Schneider Aventinus\",\n \"search_rank\": 0.243171,\n \"search_headline_description\": \"Dos Equis, Wood-aged Beer, Magnum, 1099 - Whitbread <b>Ale</b>, 15 IBU, 9.5%, 13.0°Blg\"\n },\n ...\n\n```\n\n#### Adding search to your Rails app\n\nIt's really easy to enable Postgres search on any table within your database schema. All it takes is to create the following migration. In the below example we add a full\\-text search to the `products` table\\.\n\n```ruby\nclass AddSearchColumn < ActiveRecord::Migration[5.1]\n def self.up\n add_column :products, :tsv, :tsvector\n add_index :products, :tsv, using: \"gin\"\n\n say_with_time(\"Adding trigger to update the ts_vector column\") do\n execute <<-SQL\n CREATE FUNCTION products_tsv_trigger() RETURNS trigger AS $$\n begin\n new.tsv :=\n setweight(to_tsvector('pg_catalog.english', coalesce(new.name,'')), 'A') ||\n setweight(to_tsvector('pg_catalog.english', coalesce(new.description,'')), 'B');\n return new;\n end\n $$ LANGUAGE plpgsql;\n\n CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE ON products FOR EACH ROW EXECUTE PROCEDURE products_tsv_trigger();\n SQL\n end\n end\n\n def self.down\n say_with_time(\"Removing trigger to update the tsv column\") do\n execute <<-SQL\n DROP TRIGGER tsvectorupdate\n ON products\n SQL\n end\n\n remove_index :products, :tsv\n remove_column :products, :tsv\n end\nend\n\n```\n\n## API Security\n\nOne of the the most common questions I get asked is what happens if a user out on the internet sends queries\nthat we don't want run. For example how do we stop him from fetching all users or the emails of users. Our answer to this is that it is not an issue as this cannot happen, let me explain.\n\nSuper Graph runs in one of two modes `development` or `production`, this is controlled via the config value `production: false` when it's false it's running in development mode and when true, production. In development mode all the **named** queries \\(including mutations\\) are saved to the allow list `./config/allow.list`. While in production mode when Super Graph starts only the queries from this allow list file are registered with the database as [prepared statements](https://stackoverflow.com/questions/8263371/how-can-prepared-statements-protect-from-sql-injection-attacks). \n\nPrepared statements are designed by databases to be fast and secure. They protect against all kinds of sql injection attacks and since they are pre\\-processed and pre\\-planned they are much faster to run then raw sql queries. Also there's no GraphQL to SQL compiling happening in production mode which makes your queries lighting fast as they are directly sent to the database with almost no overhead.\n\nIn short in production only queries listed in the allow list file `./config/allow.list` can be used, all other queries will be blocked. \n\n::: tip How to think about the allow list?\nThe allow list file is essentially a list of all your exposed API calls and the data that passes within them. It's very easy to build tooling to do things like parsing this file within your tests to ensure fields like `credit_card_no` are not accidently leaked. It's a great way to build compliance tooling and ensure your user data is always safe.\n:::\n\nThis is an example of a named query, `getUserWithProducts` is the name you've given to this query it can be anything you like but should be unique across all you're queries. Only named queries are saved in the allow list in development mode.\n\n\n```graphql\nquery getUserWithProducts {\n users {\n id\n name\n products {\n id\n name\n price\n }\n }\n}\n\n```\n\n\n\n## Authentication\n\nYou can only have one type of auth enabled either Rails or JWT. \n\n### Ruby on Rails\n\nAlmost all Rails apps use Devise or Warden for authentication. Once the user is\nauthenticated a session is created with the users ID. The session can either be\nstored in the users browser as a cookie, memcache or redis. If memcache or redis is used then a cookie is set in the users browser with just the session id.\n\nSuper Graph can handle all these variations including the old and new session formats. Just enable the right `auth` config based on how your rails app is configured.\n\n#### Cookie session store\n\n```yaml\nauth:\n type: rails\n cookie: _app_session\n\n rails:\n # Rails version this is used for reading the\n # various cookies formats.\n version: 5.2\n\n # Found in 'Rails.application.config.secret_key_base'\n secret_key_base: 0a248500a64c01184edb4d7ad3a805488f8097ac761b76aaa6c17c01dcb7af03a2f18ba61b2868134b9c7b79a122bc0dadff4367414a2d173297bfea92be5566\n\n```\n\n#### Memcache session store\n\n```yaml\nauth:\n type: rails\n cookie: _app_session\n\n rails:\n # Memcache remote cookie store.\n url: memcache://127.0.0.1\n\n```\n\n#### Redis session store\n\n```yaml\nauth:\n type: rails\n cookie: _app_session\n\n rails:\n # Redis remote cookie store\n url: redis://127.0.0.1:6379\n password: \"\"\n max_idle: 80\n max_active: 12000\n\n```\n\n### JWT Tokens\n\n```yaml\nauth:\n type: jwt\n\n jwt:\n # the two providers are 'auth0' and 'none'\n provider: auth0 \n secret: abc335bfcfdb04e50db5bb0a4d67ab9\n public_key_file: /secrets/public_key.pem\n public_key_type: ecdsa #rsa\n\n```\n\nFor JWT tokens we currently support tokens from a provider like Auth0 or if you have a custom solution then we look for the `user_id` in the `subject` claim of of the `id token`. If you pick Auth0 then we derive two variables from the token `user_id` and `user_id_provider` for to use in your filters.\n\nWe can get the JWT token either from the `authorization` header where we expect it to be a `bearer` token or if `cookie` is specified then we look there.\n\nFor validation a `secret` or a public key \\(ecdsa or rsa\\) is required. When using public keys they have to be in a PEM format file.\n\n### HTTP Headers\n\n```yaml\nheader:\n name: X-AppEngine-QueueName\n exists: true\n #value: default\n\n```\n\nHeader auth is usually the best option to authenticate requests to the action endpoints. For example you\nmight want to use an action to refresh a materalized view every hour and only want a cron service like the Google AppEngine Cron service to make that request in this case a config similar to the one above will do. \n\nThe `exists: true` parameter ensures that only the existance of the header is checked not its value. The `value` parameter lets you confirm that the value matches the one assgined to the parameter. This helps in the case you are using a shared secret to protect the endpoint.\n\n### Named Auth\n\n```yaml\n# You can add additional named auths to use with actions\n# In this example actions using this auth can only be\n# called from the Google Appengine Cron service that\n# sets a special header to all it's requests\nauths:\n - name: from_taskqueue\n type: header\n header:\n name: X-Appengine-Cron\n exists: true\n\n```\n\nIn addition to the default auth configuration you can create additional named auth configurations to be used\nwith features like `actions`. For example while your main GraphQL endpoint uses JWT for authentication you may want to use a header value to ensure your actions can only be called by clients having access to a shared secret\nor security header.\n\n## Actions\n\nActions is a very useful feature that is currently work in progress. For now the best use case for actions is to\nrefresh database tables like materialized views or call a database procedure to refresh a cache table, etc. An action creates an http endpoint that anyone can call to have the SQL query executed. The below example will create an endpoint `/api/v1/actions/refresh_leaderboard_users` any request send to that endpoint will cause the sql query to be executed. the `auth_name` points to a named auth that should be used to secure this endpoint. In future we have big plans to allow your own custom code to run using actions.\n\n```yaml\nactions:\n - name: refresh_leaderboard_users\n sql: REFRESH MATERIALIZED VIEW CONCURRENTLY \"leaderboard_users\"\n auth_name: from_taskqueue\n\n```\n\n#### Using CURL to test a query\n\n```bash\n# fetch the response json directly from the endpoint using user id 5\ncurl 'http://localhost:8080/api/v1/graphql' \\\n -H 'content-type: application/json' \\\n -H 'X-User-ID: 5' \\\n --data-binary '{\"query\":\"{ products { name price users { email }}}\"}'\n\n```\n\n## Access Control\n\nIt's common for APIs to control what information they return or insert based on the role of the user. In Super Graph we have two primary roles `user` and `anon` the first for users where a `user_id` is available the latter for users where it's not.\n\n::: tip\nAn authenticated request is one where Super Graph can extract an `user_id` based on the configured authentication method \\(jwt, rails cookies, etc\\).\n:::\n\nThe `user` role can be divided up into further roles based on attributes in the database. For example when fetching a list of users, a normal user can only fetch his own entry while an admin can fetch all the users within a company and an admin user can fetch everyone. In some places this is called Attribute based access control. So in way we support both. Role based access control and Attribute based access control.\n\nSuper Graph allows you to create roles dynamically using a `roles_query` and `match` config values.\n\n### Configure RBAC\n\n```yaml\nroles_query: \"SELECT * FROM users WHERE users.id = $user_id\"\n\nroles:\n - name: user\n tables:\n - name: users\n query:\n filters: [\"{ id: { _eq: $user_id } }\"]\n\n insert:\n filters: [\"{ user_id: { eq: $user_id } }\"]\n columns: [\"id\", \"name\", \"description\" ]\n presets:\n - created_at: \"now\"\n\n update:\n filters: [\"{ user_id: { eq: $user_id } }\"]\n columns:\n - id\n - name\n presets:\n - updated_at: \"now\"\n\n delete:\n block: true\n\n - name: admin\n match: users.id = 1\n tables:\n - name: users\n query:\n filters: []\n\n```\n\nThis configuration is relatively simple to follow the `roles_query` parameter is the query that must be run to help figure out a users role. This query can be as complex as you like and include joins with other tables. \n\nThe individual roles are defined under the `roles` parameter and this includes each table the role has a custom setting for. The role is dynamically matched using the `match` parameter for example in the above case `users.id = 1` means that when the `roles_query` is executed a user with the id `1` willbe assigned the admin role and those that don't match get the `user` role if authenticated successfully or the `anon` role\\.\n\n## Remote Joins\n\nIt often happens that after fetching some data from the DB we need to call another API to fetch some more data and all this combined into a single JSON response. For example along with a list of users you need their last 5 payments from Stripe. This requires you to query your DB for the users and Stripe for the payments. Super Graph handles all this for you also only the fields you requested from the Stripe API are returned. \n\n::: tip Is this fast?\nSuper Graph is able fetch remote data and merge it with the DB response in an efficient manner. Several optimizations such as parallel HTTP requests and a zero\\-allocation JSON merge algorithm makes this very fast. All of this without you having to write a line of code.\n:::\n\nFor example you need to list the last 3 payments made by a user. You will first need to look up the user in the database and then call the Stripe API to fetch his last 3 payments. For this to work your user table in the db has a `customer_id` column that contains his Stripe customer ID.\n\nSimiliarly you could also fetch the users last tweet, lead info from Salesforce or whatever else you need. It's fine to mix up several different `remote joins` into a single GraphQL query.\n\n### Stripe API example\n\nThe configuration is self explanatory. A `payments` field has been added under the `customers` table\\. This field is added to the `remotes` subsection that defines fields associated with `customers` that are remote and not real database columns.\n\nThe `id` parameter maps a column from the `customers` table to the `$id` variable\\. In this case it maps `$id` to the `customer_id` column\\.\n\n```yaml\ntables:\n - name: customers\n remotes:\n - name: payments\n id: stripe_id\n url: http://rails_app:3000/stripe/$id\n path: data\n # debug: true\n # pass_headers: \n # - cookie\n # - host\n set_headers:\n - name: Authorization\n value: Bearer <stripe_api_key>\n\n```\n\n#### How do I make use of this?\n\nJust include `payments` like you would any other GraphQL selector under the `customers` selector\\. Super Graph will call the configured API for you and stitch \\(merge\\) the JSON the API sends back with the JSON generated from the database query. GraphQL features like aliases and fields all work.\n\n```graphql\nquery {\n customers {\n id\n email\n payments {\n customer_id\n amount\n billing_details\n }\n }\n}\n\n```\n\nAnd voila here is the result. You get all of this advanced and honestly complex querying capability without writing a single line of code.\n\n```json\n\"data\": {\n \"customers\": [\n {\n \"id\": 1,\n \"email\": \"linseymertz@reilly.co\",\n \"payments\": [\n {\n \"customer_id\": \"cus_YCj3ndB5Mz\",\n \"amount\": 100,\n \"billing_details\": {\n \"address\": \"1 Infinity Drive\",\n \"zipcode\": \"94024\"\n }\n },\n ...\n\n```\n\nEven tracing data is availble in the Super Graph web UI if tracing is enabled in the config. By default it is enabled in development. Additionally there you can set `debug: true` to enable http request / response dumping to help with debugging.\n\n![Query Tracing](/tracing.png)\n\n## Database Relationships\n\nIn most cases you don't need this configuration, Super Graph will discover and learn\nthe relationship graph within your database automatically. It does this using `Foreign Key` relationships that you have defined in your database schema.\n\nThe below configs are only needed in special cases such as when you don't use foreign keys or when you want to create a relationship between two tables where a foreign key is not defined or cannot be defined.\n\nFor example in the sample below a relationship is defined between the `tags` column on the `posts` table with the `slug` column on the `tags` table\\. This cannot be defined as using foreign keys since the `tags` column is of type array `text[]` and Postgres for one does not allow foreign keys with array columns.\n\n```yaml\ntables:\n - name: posts\n columns:\n - name: tags\n related_to: tags.slug\n\n```\n\n\n## Configuration\n\nConfiguration files can either be in YAML or JSON their names are derived from the `GO_ENV` variable, for example `GO_ENV=prod` will cause the `prod.yaml` config file to be used. or `GO_ENV=dev` will use the `dev.yaml`. A path to look for the config files in can be specified using the `-path <folder>` command line argument.\n\nWe're tried to ensure that the config file is self documenting and easy to work with.\n\n```yaml\n# Inherit config from this other config file\n# so I only need to overwrite some values\ninherits: base\n\napp_name: \"Super Graph Development\"\nhost_port: 0.0.0.0:8080\nweb_ui: true\n\n# debug, info, warn, error, fatal, panic\nlog_level: \"debug\"\n\n# enable or disable http compression (uses gzip)\nhttp_compress: true\n\n# When production mode is 'true' only queries \n# from the allow list are permitted.\n# When it's 'false' all queries are saved to the\n# the allow list in ./config/allow.list\nproduction: false\n\n# Throw a 401 on auth failure for queries that need auth\nauth_fail_block: false\n\n# Latency tracing for database queries and remote joins\n# the resulting latency information is returned with the\n# response\nenable_tracing: true\n\n# Watch the config folder and reload Super Graph\n# with the new configs when a change is detected\nreload_on_config_change: true\n\n# File that points to the database seeding script\n# seed_file: seed.js\n\n# Path pointing to where the migrations can be found\nmigrations_path: ./config/migrations\n\n# Postgres related environment Variables\n# SG_DATABASE_HOST\n# SG_DATABASE_PORT\n# SG_DATABASE_USER\n# SG_DATABASE_PASSWORD\n\n# Auth related environment Variables\n# SG_AUTH_RAILS_COOKIE_SECRET_KEY_BASE\n# SG_AUTH_RAILS_REDIS_URL\n# SG_AUTH_RAILS_REDIS_PASSWORD\n# SG_AUTH_JWT_PUBLIC_KEY_FILE\n\n# inflections:\n# person: people\n# sheep: sheep\n\nauth:\n # Can be 'rails' or 'jwt'\n type: rails\n cookie: _app_session\n\n # Comment this out if you want to disable setting\n # the user_id via a header for testing. \n # Disable in production\n creds_in_header: true\n\n rails:\n # Rails version this is used for reading the\n # various cookies formats.\n version: 5.2\n\n # Found in 'Rails.application.config.secret_key_base'\n secret_key_base: 0a248500a64c01184edb4d7ad3a805488f8097ac761b76aaa6c17c01dcb7af03a2f18ba61b2868134b9c7b79a122bc0dadff4367414a2d173297bfea92be5566\n\n # Remote cookie store. (memcache or redis)\n # url: redis://redis:6379\n # password: \"\"\n # max_idle: 80\n # max_active: 12000\n\n # In most cases you don't need these\n # salt: \"encrypted cookie\"\n # sign_salt: \"signed encrypted cookie\"\n # auth_salt: \"authenticated encrypted cookie\"\n\n # jwt:\n # provider: auth0\n # secret: abc335bfcfdb04e50db5bb0a4d67ab9\n # public_key_file: /secrets/public_key.pem\n # public_key_type: ecdsa #rsa\n\n # header:\n # name: dnt\n # exists: true\n # value: localhost:8080\n\n# You can add additional named auths to use with actions\n# In this example actions using this auth can only be\n# called from the Google Appengine Cron service that\n# sets a special header to all it's requests\nauths:\n - name: from_taskqueue\n type: header\n header:\n name: X-Appengine-Cron\n exists: true\n\ndatabase:\n type: postgres\n host: db\n port: 5432\n dbname: app_development\n user: postgres\n password: ''\n\n #schema: \"public\"\n #pool_size: 10\n #max_retries: 0\n #log_level: \"debug\"\n\n # Set session variable \"user.id\" to the user id\n # Enable this if you need the user id in triggers, etc\n set_user_id: false\n\n # Define additional variables here to be used with filters\n variables:\n admin_account_id: \"5\"\n\n # Field and table names that you wish to block\n blocklist:\n - ar_internal_metadata\n - schema_migrations\n - secret\n - password\n - encrypted\n - token\n\n# Create custom actions with their own api endpoints\n# For example the below action will be available at /api/v1/actions/refresh_leaderboard_users\n# A request to this url will execute the configured SQL query\n# which in this case refreshes a materialized view in the database.\n# The auth_name is from one of the configured auths\nactions:\n - name: refresh_leaderboard_users\n sql: REFRESH MATERIALIZED VIEW CONCURRENTLY \"leaderboard_users\"\n auth_name: from_taskqueue\n\n\ntables:\n - name: customers\n remotes:\n - name: payments\n id: stripe_id\n url: http://rails_app:3000/stripe/$id\n path: data\n # debug: true\n pass_headers: \n - cookie\n set_headers:\n - name: Host\n value: 0.0.0.0\n # - name: Authorization\n # value: Bearer <stripe_api_key>\n\n - # You can create new fields that have a\n # real db table backing them\n name: me\n table: users\n\nroles_query: \"SELECT * FROM users WHERE id = $user_id\"\n\nroles:\n - name: anon\n tables:\n - name: products\n limit: 10\n\n query:\n columns: [\"id\", \"name\", \"description\" ]\n aggregation: false\n\n insert:\n allow: false\n\n update:\n allow: false\n\n delete:\n allow: false\n\n - name: user\n tables:\n - name: users\n query:\n filters: [\"{ id: { _eq: $user_id } }\"]\n\n - name: products\n query:\n limit: 50\n filters: [\"{ user_id: { eq: $user_id } }\"]\n columns: [\"id\", \"name\", \"description\" ]\n disable_functions: false\n\n insert:\n filters: [\"{ user_id: { eq: $user_id } }\"]\n columns: [\"id\", \"name\", \"description\" ]\n set:\n - created_at: \"now\"\n\n update:\n filters: [\"{ user_id: { eq: $user_id } }\"]\n columns:\n - id\n - name\n set:\n - updated_at: \"now\"\n\n delete:\n block: true\n\n - name: admin\n match: id = 1000\n tables:\n - name: users\n filters: []\n\n```\n\nIf deploying into environments like Kubernetes it's useful to be able to configure things like secrets and hosts though environment variables therfore we expose the below environment variables. This is escpecially useful for secrets since they are usually injected in via a secrets management framework ie. Kubernetes Secrets\n\nKeep in mind any value can be overwritten using environment variables for example `auth.jwt.public_key_type` converts to `SG_AUTH_JWT_PUBLIC_KEY_TYPE`. In short prefix `SG_`, upper case and all `.` should changed to `_`.\n\n#### Postgres environment variables\n\n```bash\nSG_DATABASE_HOST\nSG_DATABASE_PORT\nSG_DATABASE_USER\nSG_DATABASE_PASSWORD\n\n```\n\n#### Auth environment variables\n\n```bash\nSG_AUTH_RAILS_COOKIE_SECRET_KEY_BASE\nSG_AUTH_RAILS_REDIS_URL\nSG_AUTH_RAILS_REDIS_PASSWORD\nSG_AUTH_JWT_PUBLIC_KEY_FILE\n\n```\n\n## YugabyteDB\n\nYugabyte is an open\\-source, geo\\-distrubuted cloud\\-native relational DB that scales horizontally. Super Graph works with Yugabyte right out of the box. If you think you're data needs will outgrow Postgres and you don't really want to deal with sharding then Yugabyte is the way to go. Just point Super Graph to your Yugabyte DB and everything will just work including running migrations, seeding, querying, mutations, etc.\n\nTo use Yugabyte in your local development flow just uncomment the following lines in the `docker-compose.yml` file that is part of your Super Graph app. Also remember to comment out the originl postgres `db` config\\.\n\n```yaml\n # Postgres DB\n # db:\n # image: postgres:latest\n # ports:\n # - \"5432:5432\"\n\n #Standard config to run a single node of Yugabyte\n yb-master: \n image: yugabytedb/yugabyte:latest \n container_name: yb-master-n1 \n command: [ \"/home/yugabyte/bin/yb-master\", \n \"--fs_data_dirs=/mnt/disk0,/mnt/disk1\", \n \"--master_addresses=yb-master-n1:7100\", \n \"--replication_factor=1\", \n \"--enable_ysql=true\"] \n ports: \n - \"7000:7000\" \n environment: \n SERVICE_7000_NAME: yb-master \n\n db: \n image: yugabytedb/yugabyte:latest \n container_name: yb-tserver-n1 \n command: [ \"/home/yugabyte/bin/yb-tserver\", \n \"--fs_data_dirs=/mnt/disk0,/mnt/disk1\", \n \"--start_pgsql_proxy\", \n \"--tserver_master_addrs=yb-master-n1:7100\"] \n ports: \n - \"9042:9042\" \n - \"6379:6379\" \n - \"5433:5433\" \n - \"9000:9000\" \n environment: \n SERVICE_5433_NAME: ysql \n SERVICE_9042_NAME: ycql \n SERVICE_6379_NAME: yedis \n SERVICE_9000_NAME: yb-tserver \n depends_on: \n - yb-master\n\n # Environment variables to point Super Graph to Yugabyte\n # This is required since it uses a different user and port number\n yourapp_api:\n image: dosco/super-graph:latest\n environment:\n GO_ENV: \"development\"\n Uncomment below for Yugabyte DB\n SG_DATABASE_PORT: 5433\n SG_DATABASE_USER: yugabyte\n SG_DATABASE_PASSWORD: yugabyte\n volumes:\n - ./config:/config\n ports:\n - \"8080:8080\"\n depends_on:\n - db\n\n```\n\n## Developing Super Graph\n\nIf you want to build and run Super Graph from code then the below commands will build the web ui and launch Super Graph in developer mode with a watcher to rebuild on code changes. And the demo rails app is also launched to make it essier to test changes.\n\n```bash\n\n# yarn is needed to build the web ui\nbrew install yarn\n\n# yarn install dependencies and build the web ui\n(cd web && yarn install && yarn build)\n\n# do this the only the time to setup the database\ndocker-compose run rails_app rake db:create db:migrate db:seed\n\n# start super graph in development mode with a change watcher\ndocker-compose up\n\n```\n\n## Learn how the code works\n\n[Super Graph codebase explained](https://supergraph.dev/internals.html)\n\n## Apache License 2.0\n\nApache Public License 2.0 \\| Copyright © 2018\\-present Vikram Rangnekar"}