docs: add MS SQL server docs (#1568)

* copy pg -> mssql

* .

* .

* Removes features that are not compatible in schema/index.rst

* delete extra files

* fix refs

* update sidebar link

* mssql schema updates

* Optimised images with calibre/image-actions

* schema updates clear

* MSSQL Queries

* removed distinct queries & aggregate nodes

* updated table basics blank api

* Adds a getting started guide for Hasura Cloud and with Docker for SQL
Server

* fix stuff

Co-authored-by: Tanmai Gopal <tanmaig@hasura.io>
Co-authored-by: VaishnaviGVS <vaishnavi@hasura.io>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
GitOrigin-RevId: d0869ee48e459054c54d3ed3523c32bf4994ddba
This commit is contained in:
Rikin Kachhia 2021-06-17 17:16:54 +05:30 committed by hasura-bot
parent bad2d4190d
commit 835900cf30
35 changed files with 6654 additions and 118 deletions

View File

@ -72,6 +72,8 @@ To use an existing database, choose ``Connect existing database`` and enter your
recommended to use env vars for better security *(as connection details are part of Hasura metadata)* as well as
to allow configuring different databases in different environments *(like staging/production)* easily.
.. _cloud_projects_create_allow_nat_ip:
Allowing connections from Hasura Cloud IP
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

View File

@ -0,0 +1,119 @@
.. meta::
:description: Hasura Cloud for MS SQL Server
:keywords: hasura, docs, databases, ms sql, sql server, hasura-cloud
.. _database_ms_sql_server_cloud:
Get Started with Hasura Cloud & MS SQL Server
=============================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
Try it out
----------
Step 1: Create an account on Hasura Cloud and create a new Hasura Project
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Once you create a project on Hasura Cloud, hit the "Launch Console" button
to open the Hasura Console for your project.
.. thumbnail:: /img/graphql/cloud/getting-started/create-project.png
:alt: Connect new or existing database
:width: 556px
Step 2: Add your SQL Server database as a source to Hasura
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Head to the ``Data > Manage databases`` section on the console to add
your MS SQL Server as a source to Hasura. You'll need your ODBC connection string. Make sure that
your ODBC driver is set to version 17.
Here's an example of what your connection strings might look like with a SQL server database on Azure SQL Serverless:
.. raw:: html
<code>
Driver={ODBC Driver 17 for SQL Server};Server=tcp:<b>hasura-test.database.windows.net</b>,<b>1433</b>;Database=<b>db-name</b>;Uid=<b>username</b>;Pwd=<b>password</b>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;
</code>
.. admonition:: Make sure your SQL server database is reachable by Hasura Cloud:
1. Allow public connections or :ref:`whitelist the Hasura Cloud IP<cloud_projects_create_allow_nat_ip>` on your SQL Server firewall: This is good for testing and will allow you to try Hasura out with your database quickly!
2. VPC peering: VPC peering and private network access is available on Hasura Cloud paid tiers: Reccommended for production. Get in touch with us if you'd like to try this out against your existing databases!
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/1-manage-databases.png
:alt: Manage databases
:width: 1000px
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/2-add-source.png
:alt: Add source
:width: 1000px
Once you add the database, you'll see your database pop up on the sidebar.
Step 5: Option 1: Track existing tables
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you have existing tables, head to the database page by clicking on the database name on the sidebar. You should see a list of tables.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/3-manage-mydb.png
:alt: Manage my-db
:width: 1000px
Track tables selectively or all of them so that Hasura can introspect the tables and create the corresponding GraphQL schema.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/4-track-tables.png
:alt: Track tables
:width: 1000px
If you have foreign keys, you'll also see suggested relationships. Again, you can choose to track them selectively or all at once.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/5-track-rels.png
:alt: Track relationships
:width: 1000px
Step 5: Option 2: Create new tables
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you don't have existing tables, head to the Run SQL window
to run SQL against your SQL Server database and create tables or hit the Create Table button
to create a table.
If you're running raw SQL queries to create your tables, Don't forget to check "track metadata"
at the bottom of the Run SQL window to make sure Hasura tracks your new database objects
in its GraphQL schema.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/7-run-sql.png
:alt: Run SQL to create table
:width: 1000px
Step 6: Try out a GraphQL query
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Head to the ``GraphiQL`` tab in the console and try running a GraphQL query! Use the explorer sidebar on GraphQL to get help in creating a GraphQL query.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/6-make-graphql-query.png
:alt: Make GraphQL query
:width: 1000px
Keep up to date
---------------
Hasura supports queries, subscriptions, relationships and permissions on MS SQL Server.
Please watch this space to get the latest docs on how you can try these features out via the console or by manipulating metadata in JSON/YAML directly.
If you'd like to stay informed about the status of SQL Server support, subscribe to our newsletter and join our discord!
- https://hasura.io/newsletter/
- https://discord.com/invite/hasura
.. admonition:: Additional Resources
This Hands-on Demo walks you through Getting Started with Hasura on SQL Server & common use cases. - `View Recording here <https://hasura.io/events/webinar/hasura-sql-server/?pg=docs&plcmt=body&cta=view-recording&tech=>`__.

View File

@ -0,0 +1,162 @@
.. meta::
:description: Hasura with Docker for MS SQL Server
:keywords: hasura, docs, databases, ms sql, sql server, docker
.. _database_ms_sql_server_docker:
Get Started with Docker (Hasura & MS SQL Server)
================================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
Try it out
----------
Pre-requisites
^^^^^^^^^^^^^^
- `Docker <https://docs.docker.com/install/>`_
- `Docker Compose <https://docs.docker.com/compose/install/>`_
- An existing SQL Server database
Step 1: Get the docker-compose file
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Get the Hasura MS SQL Server docker compose file:
.. code-block:: bash
# in a new directory run
wget https://raw.githubusercontent.com/hasura/graphql-engine/master/install-manifests/docker-compose-ms-sql-server/docker-compose.yaml
# or run
curl https://raw.githubusercontent.com/hasura/graphql-engine/master/install-manifests/docker-compose-ms-sql-server/docker-compose.yaml -o docker-compose.yaml
Step 2: Run Hasura GraphQL engine
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The following command will run Hasura along with a Postgres database required
for its functioning.
.. code-block:: bash
$ docker-compose up -d
Check if the containers are running:
.. code-block:: bash
$ docker ps
CONTAINER ID IMAGE ... CREATED STATUS PORTS ...
097f58433a2b hasura/graphql-engine ... 1m ago Up 1m 8080->8080/tcp ...
b0b1aac0508d postgres ... 1m ago Up 1m 5432/tcp ...
Please do note that you will see a Postgres database running, which is used by Hasura to store its configuration (Hasura metadata).
Step 3: Open the Hasura console
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Head to ``http://localhost:8080/console`` to open the Hasura console.
Step 4: Add your SQL Server database as a source to Hasura
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Head to the ``Data > Manage databases`` section on the console to add
your MS SQL Server as a source to Hasura. You'll need your ODBC connection string. Make sure that
your ODBC driver is set to version 17.
Here are 2 examples of what your connection strings might look like:
.. raw:: html
<ul>
<li>Testing with SQL Server running locally on Mac:<br>
<code>
Driver={ODBC Driver 17 for SQL Server};Server=tcp:<b>host.docker.internal</b>,<b>1433</b>;Database=<b>tempdb</b>;Uid=<b>sa</b>;Pwd=<b>Password123</b>;
</code>
</li>
<li> A SQL Server instance on Azure SQL Serverless:<br>
<code>
Driver={ODBC Driver 17 for SQL Server};Server=tcp:<b>db.hostname.com</b>,<b>1433</b>;Database=<b>db-name</b>;Uid=<b>username</b>;Pwd=<b>password</b>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;
</code>
</li>
</ol>
If you're testing Hasura with SQL Server running locally, :ref:`read this guide<docker_networking>` on Docker networking in case you're not sure
how to make sure that your SQL Server database is reachable from the Hasura docker container on Linux, Mac or Windows.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/1-manage-databases.png
:alt: Manage databases
:width: 1000px
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/2-add-source.png
:alt: Add source
:width: 1000px
Once you add the database, you'll see your database pop up on the sidebar.
Step 5: Option 1: Track existing tables
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you have existing tables, head to the database page by clicking on the database name on the sidebar. You should see a list of tables.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/3-manage-mydb.png
:alt: Manage my-db
:width: 1000px
Track tables selectively or all of them so that Hasura can introspect the tables and create the corresponding GraphQL schema.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/4-track-tables.png
:alt: Track tables
:width: 1000px
If you have foreign keys, you'll also see suggested relationships. Again, you can choose to track them selectively or all at once.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/5-track-rels.png
:alt: Track relationships
:width: 1000px
Step 5: Option 2: Create new tables
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you don't have existing tables, head to the Run SQL window
to run SQL against your SQL Server database and create tables or hit the Create Table button
to create a table.
If you're running raw SQL queries to create your tables, Don't forget to check "track metadata"
at the bottom of the Run SQL window to make sure Hasura tracks your new database objects
in its GraphQL schema.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/7-run-sql.png
:alt: Run SQL to create table
:width: 1000px
Step 6: Try out a GraphQL query
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Head to the ``GraphiQL`` tab in the console and try running a GraphQL query! Use the explorer sidebar on GraphQL to get help in creating a GraphQL query.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/6-make-graphql-query.png
:alt: Make GraphQL query
:width: 1000px
Keep up to date
---------------
Hasura supports queries, subscriptions, relationships and permissions on MS SQL Server.
Please watch this space to get the latest docs on how you can try these features out via the console or by manipulating metadata in JSON/YAML directly.
If you'd like to stay informed about the status of SQL Server support, subscribe to our newsletter and join our discord!
- https://hasura.io/newsletter/
- https://discord.com/invite/hasura
.. admonition:: Additional Resources
This Hands-on Demo walks you through Getting Started with Hasura on SQL Server & common use cases. - `View Recording here <https://hasura.io/events/webinar/hasura-sql-server/?pg=docs&plcmt=body&cta=view-recording&tech=>`__.

View File

@ -0,0 +1,23 @@
.. meta::
:description: Getting Stated with Hasura & MS SQL Server
:keywords: hasura, docs, databases, ms sql, sql server,
Getting started with MS SQL Server
==================================
To try Hasura with SQL Server, you'll need your own new or existing SQL Server database.
Here are 2 ways you can get started with Hasura:
1. :ref:`Hasura Cloud <database_ms_sql_server_cloud>`: You'll need to be able to access your SQL Server database from Hasura Cloud.
2. :ref:`Docker <database_ms_sql_server_docker>`: Run Hasura with Docker and then connect your SQL Server database to Hasura.
.. toctree::
:hidden:
:maxdepth: 1
:titlesonly:
Hasura Cloud <cloud>
Docker <docker>

View File

@ -2,7 +2,7 @@
:description: Hasura MS SQL Server database support
:keywords: hasura, docs, databases, ms sql, sql server
.. _database_ms-sql-server:
.. _database_ms_sql_server:
MS SQL Server
=============
@ -17,126 +17,20 @@ Introduction
Hasura allows connecting to a SQL Server database and build an GraphQL API based on the database schema.
.. admonition:: Supported from
.. admonition:: Supported versions:
Hasura GraphQL engine ``v2.0.0-alpha.2`` onwards
1. Hasura GraphQL engine ``v2.0.0-alpha.2`` onwards
2. SQL Server 2016 and upwards
.. admonition:: Supported SQL Server versions
Get Started
-----------
Hasura GraphQL engine currently supports **SQL Server 2016 and above**.
To try Hasura with SQL Server, you'll need your own new or existing SQL Server database.
Try it out
----------
Here are 2 ways you can get started with Hasura:
You can run Hasura with SQL Server using ``docker-compose`` and an existing SQL Server database
as follows:
Prerequisites
^^^^^^^^^^^^^
- `Docker <https://docs.docker.com/install/>`_
- `Docker Compose <https://docs.docker.com/compose/install/>`_
- An existing SQL Server database
Step 1: Get the docker-compose file
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Get the Hasura MS SQL Server docker compose file:
.. code-block:: bash
# in a new directory run
wget https://raw.githubusercontent.com/hasura/graphql-engine/master/install-manifests/docker-compose-ms-sql-server/docker-compose.yaml
# or run
curl https://raw.githubusercontent.com/hasura/graphql-engine/master/install-manifests/docker-compose-ms-sql-server/docker-compose.yaml -o docker-compose.yaml
Step 2: Run Hasura GraphQL engine
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The following command will run Hasura along with a Postgres database required
for its functioning.
.. code-block:: bash
$ docker-compose up -d
Check if the containers are running:
.. code-block:: bash
$ docker ps
CONTAINER ID IMAGE ... CREATED STATUS PORTS ...
097f58433a2b hasura/graphql-engine ... 1m ago Up 1m 8080->8080/tcp ...
b0b1aac0508d postgres ... 1m ago Up 1m 5432/tcp ...
Please do note that you will see a Postgres database running, which is used by Hasura to store its configuration (Hasura metadata).
Step 3: Open the Hasura console
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Head to ``http://localhost:8080/console`` to open the Hasura console.
Step 4: Add your MS SQL Server as a source to Hasura
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Head to the ``Data > Manage databases`` section on the console to add
your MS SQL Server as a source to Hasura. You'll need your ODBC connection string. Make sure that
your ODBC driver is version 17.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/1-manage-databases.png
:alt: Manage databases
:width: 1000px
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/2-add-source.png
:alt: Add source
:width: 1000px
Once you add the database, you'll see your database pop up on the sidebar.
Step 5: Option 1: Track existing tables
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you have existing tables, head to the database page by clicking on the database name on the sidebar. You should see a list of tables.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/3-manage-mydb.png
:alt: Manage my-db
:width: 1000px
Track tables selectively or all of them so that Hasura can introspect the tables and create the corresponding GraphQL schema.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/4-track-tables.png
:alt: Track tables
:width: 1000px
If you have foreign keys, you'll also see suggested relationships. Again, you can choose to track them selectively or all at once.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/5-track-rels.png
:alt: Track relationships
:width: 1000px
Step 5: Option 2: Create new tables
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you don't have existing tables, head to the Run SQL window
to run SQL against your SQL Server database and create tables.
Don't forget to check "track metadata" at the bottom to make sure
Hasura tracks your new database objects in its GraphQL schema.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/7-run-sql.png
:alt: Run SQL to create table
:width: 1000px
Step 6: Try out a GraphQL query
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Head to the ``GraphiQL`` tab in the console and try running a GraphQL query! Use the explorer sidebar on GraphQL to get help in creating a GraphQL query.
.. thumbnail:: /img/graphql/core/databases/ms-sql-server/6-make-graphql-query.png
:alt: Make GraphQL query
:width: 1000px
1. :ref:`Hasura Cloud<database_ms_sql_server_cloud>`: You'll need to be able to access your SQL Server database from Hasura Cloud.
2. :ref:`Docker<database_ms_sql_server_docker>`: Run Hasura with Docker and then connect your SQL Server database to Hasura.
Keep up to date
---------------
@ -153,3 +47,25 @@ If you'd like to stay informed about the status of SQL Server support, subscribe
.. admonition:: Additional Resources
This Hands-on Demo walks you through Getting Started with Hasura on SQL Server & common use cases. - `View Recording here <https://hasura.io/events/webinar/hasura-sql-server/?pg=docs&plcmt=body&cta=view-recording&tech=>`__.
.. toctree::
:maxdepth: 1
:titlesonly:
Getting Started <getting-started/index>
Schema <schema/index>
Queries <queries/index>
Subscriptions <subscriptions/index>
.. TODO: DB-COMPATIBILITY
.. toctree::
:maxdepth: 1
:titlesonly:
Schema <schema/index>
Queries <queries/index>
Mutations <mutations/index>
Subscriptions <subscriptions/index>
Supported MS SQL Server types <mssql-types>

View File

@ -0,0 +1,339 @@
.. meta::
:description: Supported MS SQL Server types in the Hasura API
:keywords: hasura, docs, ms sql server types
.. _mssql_types:
MS SQL Server: Supported types
==============================
.. contents:: Table of contents
:backlinks: none
:depth: 1
:local:
.. _ms_sql_server_types_table:
Introduction
------------
List of MS SQL Server types supported by the Hasura GraphQL engine with their equivalent Hasura types:
.. csv-table::
:file: mssqltypes.csv
:widths: 13, 11, 25, 6
:header-rows: 1
.. _Int:
Int
---
GraphQL default scalar with name **Int**.
E.g.
.. code-block:: graphql
objects: [
{
int_col: 27
}
]
.. _Float:
Float
-----
GraphQL custom scalar type with name **float8**.
E.g.
.. code-block:: graphql
objects: [
{
float_col: 0.8
}
]
.. note::
To avoid loss of data when retrieving IEEE 754 style data from the database,
please refer to the :ref:`server_flag_reference` for instructions on setting
the ``extra_float_digits`` parameter, which has a bad default value in
PostgreSQL 11 and older.
.. _Numeric:
Numeric
-------
GraphQL custom scalar type with name **numeric**.
E.g.
.. code-block:: graphql
objects: [
{
numeric_col: 0.00000008
}
]
.. _Bool:
Bool
----
GraphQL default Scalar with name **Boolean**. The **Boolean** scalar type represents ``true`` or ``false``.
E.g.
.. code-block:: graphql
objects: [
{
is_published: true
}
]
.. _Char:
Char
----
GraphQL custom scalar with name **character**. It is a ``String`` with single character.
E.g.
.. code-block:: graphql
objects: [
{
char_column: "a"
}
]
.. _String:
String
------
GraphQL default scalar with name **String**. The **String** scalar type represents textual data, represented as UTF-8 character sequences.
The String type is most often used by GraphQL to represent free-form human-readable text.
E.g.
.. code-block:: graphql
objects: [
{
name: "Raven"
}
]
.. _Date:
Date
----
GraphQL custom scalar with name **date**. Date (no time of day). Allowed values are yyyy-mm-dd.
E.g.
.. code-block:: graphql
objects: [
{
date: "1996-03-15"
}
]
.. _Timetz:
Time with time zone
-------------------
GraphQL custom scalar type with name **timetz**. Time of day only, with time zone. Allowed values should be of ISO8601 format
(e.g. 17:30:15Z, 17:30:15+05:30, 17:30:15.234890+05:30).
E.g.
.. code-block:: graphql
objects: [
{
time: "17:30:15+05:30"
}
]
.. _Timestamptz:
Timestamp with time zone
------------------------
GraphQL custom scalar type with name **timestamptz**. Both date and time, with time zone. Allowed values should be of ISO8601 format
(e.g. 2016-07-20T17:30:15Z, 2016-07-20T17:30:15+05:30, 2016-07-20T17:30:15.234890+05:30).
E.g.
.. code-block:: graphql
objects: [
{
timestamptz_col: "2016-07-20T17:30:15+05:30"
}
]
.. _JSON:
JSON
----
GraphQL custom scalar type with name **json**. It is a stringified json value.
E.g.
.. code-block:: graphql
objects: [
{
json_col: "{ \"name\": \"raven\" }"
}
]
.. _JSONB:
JSONB
-----
GraphQL custom scalar type with name **jsonb**. Value should be given through a variable of type **jsonb**.
E.g.
.. code-block:: graphql
mutation insert_test($value : jsonb) {
insert_test(
objects: [
{
jsonb_col: $value
}
]
) {
affected_rows
returning{
jsonb_col
}
}
}
variables:
.. code-block:: json
{
"value": {
"name": "raven"
}
}
.. _Geometry:
Geometry
--------
GraphQL custom scalar type ``geometry`` is generated for a ``GEOMETRY`` column
on a PostGIS enabled MS SQL Server instance. Value should be given as GeoJSON.
E.g.
.. code-block:: graphql
mutation insertGeometry($point: geometry!) {
insert_test(
objects: [{
geometry_col: $point
}]
) {
affected_rows
returning {
geometry_col
}
}
}
variables:
.. code-block:: json
{
"point": {
"type": "Point",
"coordinates": [0, 0]
}
}
.. _Geography:
Geography
---------
GraphQL custom scalar type ``geography`` is generated for a ``GEOGRAPHY`` column
on a PostGIS enabled MS SQL Server instance. Value should be given as GeoJSON.
E.g.
.. code-block:: graphql
mutation insertGeography($point: geography!) {
insert_test(
objects: [{
geography_col: $point
}]
) {
affected_rows
returning {
geography_col
}
}
}
variables:
.. code-block:: json
{
"point": {
"type": "Point",
"coordinates": [0, 0]
}
}
.. _Implicit:
Implicitly Supported types
--------------------------
All ``Implicit`` types in the :ref:`above table <ms_sql_server_types_table>` are implicitly supported by the GraphQL engine. You have to
provide the value as a **String**.
E.g. For time without time zone type
In ISO 8601 format
.. code-block:: graphql
objects: [
{
time_col: "04:05:06.789"
}
]
E.g. For macaddr type
.. code-block:: graphql
objects: [
{
macaddr_col: "08:00:2b:01:02:03"
}
]
.. Note::
You can learn more about MS SQL Server data types `here <https://www.postgresql.org/docs/current/static/datatype.html>`__.

View File

@ -0,0 +1,46 @@
Name,Aliases,Description,Hasura Type
bigint,int8,signed eight-byte integer,String_
bigserial,serial8,autoincrementing eight-byte integer,String_
bit [ (n) ],,fixed-length bit string,Implicit_
bit varying [ (n) ],varbit [ (n) ],variable-length bit string,Implicit_
boolean,bool,logical Boolean (true/false),Bool_
box,,rectangular box on a plane,Implicit_
bytea,,binary data (“byte array”),Implicit_
character [ (n) ],char [ (n) ],fixed-length character string,Char_
character varying [ (n) ],varchar [ (n) ],variable-length character string,String_
cidr,,IPv4 or IPv6 network address, Implicit_
circle,,circle on a plane,Implicit_
date,,"calendar date (year, month, day)",Date_
double precision,float8,double precision floating-point number (8 bytes),Float_
inet,,IPv4 or IPv6 host address,Implicit_
integer,"int, int4",signed four-byte integer,Int_
interval [ fields ] [ (p) ],,time span,Implicit_
json,,textual JSON data,JSON_
jsonb,,"binary JSON data, decomposed",JSONB_
line,,infinite line on a plane,Implicit_
lseg,,line segment on a plane, Implicit_
ltree,,labels of data stored in a hierarchical tree-like structure,Implicit_
geometry,,PostGIS Geometry type, Geometry_
geography,,PostGIS Geography type, Geography_
macaddr,,MAC (Media Access Control) address, Implicit_
macaddr8,,MAC (Media Access Control) address (EUI-64 format), Implicit_
money,,currency amount,Implicit_
"numeric [ (p, s) ]","decimal [ (p, s) ]",exact numeric of selectable precision, Numeric_
path,,geometric path on a plane,Implicit_
pg_lsn,,PostgreSQL Log Sequence Number,Implicit_
point,,geometric point on a plane,Implicit_
polygon,,closed geometric path on a plane,Implicit_
real,float4,single precision floating-point number (4 bytes),Float_
smallint,int2,signed two-byte integer,Int_
smallserial,serial2,autoincrementing two-byte integer,Int_
serial,serial4,autoincrementing four-byte integer,Int_
text,,variable-length character string,String_
time [ (p) ] [ without time zone ],,time of day (no time zone),Implicit_
time [ (p) ] with time zone,timetz,"time of day, including time zone",Timetz_
timestamp [ (p) ] [ without time zone ],,date and time (no time zone),Implicit_
timestamp [ (p) ] with time zone,timestamptz,"date and time, including time zone",Timestamptz_
tsquery,,text search query,Implicit_
tsvector,,text search document,Implicit_
txid_snapshot,,user-level transaction ID snapshot,Implicit_
uuid,,universally unique identifier,Implicit_
xml,,XML data,Implicit_
1 Name Aliases Description Hasura Type
2 bigint int8 signed eight-byte integer String_
3 bigserial serial8 autoincrementing eight-byte integer String_
4 bit [ (n) ] fixed-length bit string Implicit_
5 bit varying [ (n) ] varbit [ (n) ] variable-length bit string Implicit_
6 boolean bool logical Boolean (true/false) Bool_
7 box rectangular box on a plane Implicit_
8 bytea binary data (“byte array”) Implicit_
9 character [ (n) ] char [ (n) ] fixed-length character string Char_
10 character varying [ (n) ] varchar [ (n) ] variable-length character string String_
11 cidr IPv4 or IPv6 network address Implicit_
12 circle circle on a plane Implicit_
13 date calendar date (year, month, day) Date_
14 double precision float8 double precision floating-point number (8 bytes) Float_
15 inet IPv4 or IPv6 host address Implicit_
16 integer int, int4 signed four-byte integer Int_
17 interval [ fields ] [ (p) ] time span Implicit_
18 json textual JSON data JSON_
19 jsonb binary JSON data, decomposed JSONB_
20 line infinite line on a plane Implicit_
21 lseg line segment on a plane Implicit_
22 ltree labels of data stored in a hierarchical tree-like structure Implicit_
23 geometry PostGIS Geometry type Geometry_
24 geography PostGIS Geography type Geography_
25 macaddr MAC (Media Access Control) address Implicit_
26 macaddr8 MAC (Media Access Control) address (EUI-64 format) Implicit_
27 money currency amount Implicit_
28 numeric [ (p, s) ] decimal [ (p, s) ] exact numeric of selectable precision Numeric_
29 path geometric path on a plane Implicit_
30 pg_lsn PostgreSQL Log Sequence Number Implicit_
31 point geometric point on a plane Implicit_
32 polygon closed geometric path on a plane Implicit_
33 real float4 single precision floating-point number (4 bytes) Float_
34 smallint int2 signed two-byte integer Int_
35 smallserial serial2 autoincrementing two-byte integer Int_
36 serial serial4 autoincrementing four-byte integer Int_
37 text variable-length character string String_
38 time [ (p) ] [ without time zone ] time of day (no time zone) Implicit_
39 time [ (p) ] with time zone timetz time of day, including time zone Timetz_
40 timestamp [ (p) ] [ without time zone ] date and time (no time zone) Implicit_
41 timestamp [ (p) ] with time zone timestamptz date and time, including time zone Timestamptz_
42 tsquery text search query Implicit_
43 tsvector text search document Implicit_
44 txid_snapshot user-level transaction ID snapshot Implicit_
45 uuid universally unique identifier Implicit_
46 xml XML data Implicit_

View File

@ -0,0 +1,204 @@
.. meta::
:description: Make aggregation queries on MS SQL Server with Hasura
:keywords: hasura, docs, ms sql server, query, aggregation query
.. _ms_sql_server_aggregation_queries:
MS SQL Server: Aggregation queries
==================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
**Aggregate** fields
--------------------
You can fetch aggregations on columns along with nodes using an aggregation query.
The **name of the aggregate field** is of the form ``<field-name> + _aggregate``.
Common aggregation functions are ``count``, ``sum``, ``avg``, ``max``, ``min``, etc. You can see the complete
specification of the aggregate field in the :ref:`API reference <AggregateObject>`.
.. note::
For more advanced use cases, you can use :ref:`views <ms_sql_server_custom_views>`.
Fetch aggregated data of an object
----------------------------------
**Example:** Fetch a list of articles with aggregated data of their rating:
.. graphiql::
:view_only:
:query:
query {
articles_aggregate {
aggregate {
count
sum {
rating
}
avg {
rating
}
max {
rating
}
}
}
}
:response:
{
"data": {
"articles_aggregate": {
"aggregate": {
"count": 10,
"sum": {
"rating": 26
},
"avg": {
"rating": 2.6
},
"max": {
"rating": 4
}
}
}
}
}
.. TODO: DBCOMPATIBILITY unsupported now
nodes {
id
title
rating
}
}
}
:response:
{
"data": {
"articles_aggregate": {
"aggregate": {
"count": 10,
"sum": {
"rating": 26
},
"avg": {
"rating": 2.6
},
"max": {
"rating": 4
}
},
"nodes": [
{
"id": 1,
"title": "sit amet",
"rating": 1
},
{
"id": 2,
"title": "a nibh",
"rating": 3
},
{
"id": 3,
"title": "amet justo morbi",
"rating": 4
},
{
"id": 4,
"title": "vestibulum ac est",
"rating": 2
},
{
"id": 5,
"title": "ut blandit",
"rating": 2
},
{
"id": 6,
"title": "sapien ut",
"rating": 1
},
{
"id": 7,
"title": "nisl duis ac",
"rating": 4
},
{
"id": 8,
"title": "donec semper sapien",
"rating": 3
},
{
"id": 9,
"title": "sit amet",
"rating": 3
},
{
"id": 10,
"title": "dui proin leo",
"rating": 3
}
]
}
}
}
.. _ms_sql_server_nested_aggregate:
Fetch aggregated data on nested objects
---------------------------------------
The following is an example of a nested object query with aggregations on the **array relationship** between an author
and articles.
**Example:** Fetch author with id "1" and a nested list of articles with aggregated data of their rating:
.. graphiql::
:view_only:
:query:
query {
authors (where: {id: {_eq: 1}}) {
id
name
articles_aggregate {
aggregate {
count
avg {
rating
}
max {
rating
}
}
}
}
}
:response:
{
"data": {
"authors": [
{
"id": 1,
"name": "Justin",
"articles_aggregate": {
"aggregate": {
"count": 2,
"avg": {
"rating": 2.5
},
"max": {
"rating": 4
}
},
}
}
]
}
}

View File

@ -0,0 +1,95 @@
.. meta::
:description: Manage queries on MS SQL Server with Hasura
:keywords: hasura, docs, ms sql server, query
.. _ms_sql_server_queries:
MS SQL Server: Queries
======================
.. contents:: Table of contents
:backlinks: none
:depth: 1
:local:
Introduction
------------
GraphQL queries are used to fetch data from the server.
Hasura GraphQL engine auto-generates queries as part of the GraphQL schema from your MS SQL Server schema model.
It generates a range of possible queries and operators that also work with relationships defined in your SQL
schema.
All tables of the database tracked by the GraphQL engine can be queried over the GraphQL endpoint.
If you have a tracked table in your database, its query field is added as a nested
field under the ``query_root`` root level type.
Auto-generated query field schema
---------------------------------
**For example**, the auto-generated schema for the query field for a table ``author`` looks like the following:
.. code-block:: graphql
author (
distinct_on: [author_select_column]
where: author_bool_exp
limit: Int
offset: Int
order_by: [author_order_by!]
): [author]
.. TODO: DBCOMPATIBILITY
# single object select
author_by_pk (
# all primary key columns args
id: Int!
): author
See the :ref:`Query API reference <graphql_api_query>` for the full specifications.
.. note::
If a table is not in the ``dbo`` MS SQL Server schema, the query field will be of the format
``<schema_name>_<table_name>``.
Exploring queries
-----------------
You can explore the entire schema and the available queries using the ``GraphiQL`` interface in the Hasura console.
Lets take a look at the different queries you can run using the Hasura GraphQL engine. Well use examples
based on a typical author/article schema for reference.
.. toctree::
:maxdepth: 1
Simple object queries <simple-object-queries>
Nested object queries <nested-object-queries>
Aggregation queries <aggregation-queries>
Filter query results / search queries <query-filters>
Sort query results <sorting>
Paginate query results <pagination>
Using multiple arguments <multiple-arguments>
multiple-queries
Using variables / aliases / fragments / directives <variables-aliases-fragments-directives>
Query performance <performance>
.. TODO: DBCOMPATIBILITY
.. toctree::
:maxdepth: 1
Simple object queries <simple-object-queries>
Nested object queries <nested-object-queries>
Aggregation queries <aggregation-queries>
Filter query results / search queries <query-filters>
Sort query results <sorting>
Distinct query results <distinct-queries>
Paginate query results <pagination>
Using multiple arguments <multiple-arguments>
multiple-queries
Using variables / aliases / fragments / directives <variables-aliases-fragments-directives>
Query performance <performance>

View File

@ -0,0 +1,120 @@
.. meta::
:description: Use multiple arguments in a query in Hasura
:keywords: hasura, docs, query, multiple arguments
.. _ms_sql_server_multiple_arguments_query:
Using multiple arguments in a query
===================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
Multiple arguments can be used together in the same query.
For example, you can use the ``where`` argument to filter the results and then use the ``order_by`` argument to
sort them.
**For example**, fetch a list of authors and only 2 of their published articles that are sorted by their date
of publication:
.. graphiql::
:view_only:
:query:
query {
authors {
id
name
articles(
where: {is_published: {_eq: true}},
order_by: {published_on: desc},
limit: 2
) {
id
title
is_published
published_on
}
}
}
:response:
{
"data": {
"authors": [
{
"id": 1,
"name": "Justin",
"articles": [
{
"is_published": true,
"id": 16,
"title": "sem duis aliquam",
"published_on": "2018-02-14"
},
{
"is_published": true,
"id": 15,
"title": "vel dapibus at",
"published_on": "2018-01-02"
}
]
},
{
"id": 2,
"name": "Beltran",
"articles": [
{
"is_published": true,
"id": 2,
"title": "a nibh",
"published_on": "2018-06-10"
},
{
"is_published": true,
"id": 9,
"title": "sit amet",
"published_on": "2017-05-16"
}
]
},
{
"id": 3,
"name": "Sidney",
"articles": [
{
"is_published": true,
"id": 6,
"title": "sapien ut",
"published_on": "2018-01-08"
},
{
"is_published": true,
"id": 11,
"title": "turpis eget",
"published_on": "2017-04-14"
}
]
},
{
"id": 4,
"name": "Anjela",
"articles": [
{
"is_published": true,
"id": 1,
"title": "sit amet",
"published_on": "2017-08-09"
},
{
"is_published": true,
"id": 3,
"title": "amet justo morbi",
"published_on": "2017-05-26"
}
]
}
]
}
}

View File

@ -0,0 +1,64 @@
.. meta::
:description: Run multiple queries in a request in Hasura
:keywords: hasura, docs, query, multiple queries, request
.. _ms_sql_server_multiple_queries:
Multiple queries in a request
=============================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
Execution
---------
If multiple queries are part of the same request, they are executed **sequentially**, the
individual responses are collated and returned together. You can fetch objects of different
unrelated types in the same query.
Run multiple top level queries in the same request
--------------------------------------------------
**For example**, fetch a list of ``authors`` and a list of ``articles``:
.. graphiql::
:view_only:
:query:
query {
authors(limit: 2) {
id
name
}
articles(limit: 2) {
id
title
}
}
:response:
{
"data": {
"authors": [
{
"id": 1,
"name": "Justin"
},
{
"id": 2,
"name": "Beltran"
}
],
"articles": [
{
"id": 1,
"title": "sit amet"
},
{
"id": 2,
"title": "a nibh"
}
]
}
}

View File

@ -0,0 +1,153 @@
.. meta::
:description: Make nested object queries on MS SQL Server in Hasura
:keywords: hasura, docs, ms sql server, query, nested object query
.. _ms_sql_server_nested_object_queries:
MS SQL Server: Nested object queries
====================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
Introduction
------------
You can use the object (one-to-one) or array (one-to-many) :ref:`relationships <ms_sql_server_table_relationships>` defined
in your schema to make a nested query i.e. fetch data for a type along with data from a nested or related type.
The **name of the nested object** is the same as the name of the object/array relationship configured in
the console.
You can also filter, sort, aggregate and paginate nested objects in case of array relationships. These are not exposed
for object relationships as they have only one nested object.
Fetch nested object using an object relationship
------------------------------------------------
The following is an example of a nested object query using the **object relationship** between an article and an
author.
**Example:** Fetch a list of articles and the name of each articles author:
.. graphiql::
:view_only:
:query:
query {
articles {
id
title
author {
name
}
}
}
:response:
{
"data": {
"articles": [
{
"id": 1,
"title": "sit amet",
"author": {
"name": "Anjela"
}
},
{
"id": 2,
"title": "a nibh",
"author": {
"name": "Beltran"
}
},
{
"id": 3,
"title": "amet justo morbi",
"author": {
"name": "Anjela"
}
}
]
}
}
Fetch nested objects using an array relationship
------------------------------------------------
The following is an example of a nested object query using the **array relationship** between an author and
articles.
**Example:** Fetch a list of authors and a nested list of each authors articles:
.. graphiql::
:view_only:
:query:
query {
authors {
id
name
articles {
id
title
}
}
}
:response:
{
"data": {
"authors": [
{
"id": 1,
"name": "Justin",
"articles": [
{
"id": 15,
"title": "vel dapibus at"
},
{
"id": 16,
"title": "sem duis aliquam"
}
]
},
{
"id": 2,
"name": "Beltran",
"articles": [
{
"id": 2,
"title": "a nibh"
},
{
"id": 9,
"title": "sit amet"
}
]
},
{
"id": 3,
"name": "Sidney",
"articles": [
{
"id": 6,
"title": "sapien ut"
},
{
"id": 11,
"title": "turpis eget"
},
{
"id": 14,
"title": "congue etiam justo"
}
]
}
]
}
}
.. note::
You can also :ref:`filter <ms_sql_server_nested_filter>`, :ref:`sort <ms_sql_server_nested_sort>`, :ref:`aggregate <ms_sql_server_nested_aggregate>`
and :ref:`paginate <ms_sql_server_nested_paginate>` nested objects in case of array relationships.

View File

@ -0,0 +1,328 @@
.. meta::
:description: Manage pagination on MS SQL Server in Hasura
:keywords: hasura, docs, ms sql server, query, pagination
.. _ms_sql_server_pagination:
MS SQL Server: Paginate query results
=====================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
The **limit** & **offset** arguments
------------------------------------
The operators ``limit`` and ``offset`` are used for pagination.
``limit`` specifies the number of rows to retain from the result set and ``offset`` determines which slice to
retain from the results.
You can see the complete specification of the ``limit`` and ``offset`` arguments in the
:ref:`API reference <PaginationExp>`.
The following are examples of different pagination scenarios:
Limit results
-------------
**Example:** Fetch the first 5 authors from the list of all authors:
.. graphiql::
:view_only:
:query:
query {
authors(
limit: 5
) {
id
name
}
}
:response:
{
"data": {
"authors": [
{
"id": 1,
"name": "Justin"
},
{
"id": 2,
"name": "Beltran"
},
{
"id": 3,
"name": "Sidney"
},
{
"id": 4,
"name": "Anjela"
},
{
"id": 5,
"name": "Amii"
}
]
}
}
Limit results from an offset
----------------------------
**Example:** Fetch 5 authors from the list of all authors, starting with the 6th one:
.. graphiql::
:view_only:
:query:
query {
authors(
limit: 5,
offset:5
) {
id
name
}
}
:response:
{
"data": {
"authors": [
{
"id": 6,
"name": "Corny"
},
{
"id": 7,
"name": "Berti"
},
{
"id": 8,
"name": "April"
},
{
"id": 9,
"name": "Ninnetta"
},
{
"id": 10,
"name": "Lyndsay"
}
]
}
}
.. _ms_sql_server_nested_paginate:
Limit results in a nested object
--------------------------------
**Example:** Fetch a list of authors and a list of their first 2 articles:
.. graphiql::
:view_only:
:query:
query {
authors {
id
name
articles (
limit: 2
offset: 0
) {
id
title
}
}
}
:response:
{
"data": {
"authors": [
{
"id": 1,
"name": "Justin",
"articles": [
{
"id": 15,
"title": "vel dapibus at"
},
{
"id": 16,
"title": "sem duis aliquam"
}
]
},
{
"id": 2,
"name": "Beltran",
"articles": [
{
"id": 2,
"title": "a nibh"
},
{
"id": 9,
"title": "sit amet"
}
]
},
{
"id": 3,
"name": "Sidney",
"articles": [
{
"id": 6,
"title": "sapien ut"
},
{
"id": 11,
"title": "turpis eget"
}
]
},
{
"id": 4,
"name": "Anjela",
"articles": [
{
"id": 1,
"title": "sit amet"
},
{
"id": 3,
"title": "amet justo morbi"
}
]
}
]
}
}
Keyset cursor based pagination
------------------------------
Cursors are used to traverse across rows of a dataset. They work by returning a pointer to a specific row which can
then be used to fetch the next batch of data.
Keyset cursors are a column (or a set of columns) of the data that are used as the cursor. The column(s) used as the
cursor must be unique and sequential. This ensures that data is read after a specific row rather than relying on the
position of the row in the dataset as done by ``offset``, and that duplicate records are not fetched again.
**For example**, consider the following query to fetch a list of authors with a ``where`` clause used in place of
``offset``:
.. graphiql::
:view_only:
:query:
query {
authors(
limit: 5,
where: { id: {_gt: 5} }
) {
id
name
}
}
:response:
{
"data": {
"authors": [
{
"id": 6,
"name": "Corny"
},
{
"id": 7,
"name": "Berti"
},
{
"id": 8,
"name": "April"
},
{
"id": 9,
"name": "Ninnetta"
},
{
"id": 10,
"name": "Lyndsay"
}
]
}
}
Here we are fetching authors where the value of ``id`` is greater than 5. This will always skip the previously fetched
results which would have been ids 1 to 5, ensuring no duplicate results. Column ``id`` is acting as the cursor here,
unique and sequential.
The choice of cursor columns depends on the order of the expected results i.e. if the query has an ``order_by``
clause, the column(s) used in the ``order_by`` need to be used as the cursor.
Columns such as ``id`` (auto-incrementing integer/big integer) or ``created_at`` (timestamp) are commonly used as
cursors when an order is not explicit, as they should be unique and sequential.
.. note::
Keyset cursor based pagination using ``where`` is more performant than using ``offset`` because we can leverage
database indexes on the columns that are being used as cursors.
Fetch limited results along with data aggregated over all results *(e.g. total count)* in the same query
--------------------------------------------------------------------------------------------------------
Sometimes, some aggregated information on all the data is required along with a subset of data.
E.g. the total count of results can be returned along with a page of results. The count can then be used to calculate
the number of pages based on the limit that is set.
**Example:** Fetch a list of articles where a certain condition is true and get their count. Then limit the number of
articles to return.
.. graphiql::
:view_only:
:query:
query articles ($where: articles_bool_exp!) {
articles_aggregate(where: $where) {
aggregate {
totalCount: count
}
}
articles (where: $where limit: 4) {
id
title
}
}
:response:
{
"data": {
"articles_aggregate": {
"aggregate": {
"totalCount": 8
}
},
"articles": [
{
"id": 33,
"title": "How to make fajitas"
},
{
"id": 31,
"title": "How to make fajitas"
},
{
"id": 32,
"title": "How to make fajitas"
},
{
"id": 2,
"title": "How to climb mount everest"
}
]
}
}
.. admonition:: Caveat
If this needs to be done over :ref:`subscriptions <ms_sql_server_subscriptions>`, two subscriptions will need to be run
as Hasura follows the `GraphQL spec <https://graphql.github.io/graphql-spec/June2018/#sec-Single-root-field>`__ which
allows for only one root field in a subscription.

View File

@ -0,0 +1,264 @@
.. meta::
:description: Performance of Hasura GraphQL queries on MS SQL Server
:keywords: hasura, docs, ms sql server, schema, queries, performance
.. _ms_sql_server_query_performance:
MS SQL Server: Query performance
================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
Introduction
------------
Sometimes queries can become slow due to large data volumes or levels of nesting.
This page explains how to identify the query performance, how the query plan caching in Hasura works, and how queries can be optimized.
.. _ms_sql_server_analysing_query_performance:
Analysing query performance
---------------------------
Let's say we want to analyse the following query:
.. code-block:: graphql
query {
authors(where: {name: {_eq: "Mario"}}) {
rating
}
}
In order to analyse the performance of a query, you can click on the ``Analyze`` button on the Hasura console:
.. thumbnail:: /img/graphql/core/queries/analyze-query.png
:class: no-shadow
:width: 75%
:alt: Query analyze button on Hasura console
The following query execution plan is generated:
.. thumbnail:: /img/graphql/core/queries/query-analysis-before-index.png
:class: no-shadow
:width: 75%
:alt: Execution plan for Hasura GraphQL query
We can see that a sequential scan is conducted on the ``authors`` table. This means that MS SQL Server goes through every row of the ``authors`` table in order to check if the author's name equals "Mario".
The ``cost`` of a query is an arbitrary number generated by MS SQL Server and is to be interpreted as a measure of comparison rather than an absolute measure of something.
Read more about query performance analysis in the `MS SQL Server explain statement docs <https://docs.microsoft.com/en-us/sql/t-sql/queries/explain-transact-sql?view=azure-sqldw-latest>`__.
.. _ms_sql_server_query_plan_caching:
Query plan caching
------------------
How it works
^^^^^^^^^^^^
Hasura executes GraphQL queries as follows:
1. The incoming GraphQL query is parsed into an `abstract syntax tree <https://en.wikipedia.org/wiki/Abstract_syntax_tree>`__ (AST) which is how GraphQL is represented.
2. The GraphQL AST is validated against the schema to generate an internal representation.
3. The internal representation is converted into an SQL statement (a `prepared statement <https://docs.microsoft.com/en-us/sql/relational-databases/native-client-odbc-queries/executing-statements/prepared-execution?view=sql-server-ver15>`__ whenever possible).
4. The (prepared) statement is executed on MS SQL Server to retrieve the result of the query.
For most use cases, Hasura constructs a "plan" for a query, so that a new instance of the same query can be executed without the overhead of steps 1 to 3.
For example, let's consider the following query:
.. code-block:: graphql
query getAuthor($id: Int!) {
authors(where: {id: {_eq: $id}}) {
name
rating
}
}
With the following variable:
.. code-block:: graphql
{
"id": 1
}
Hasura now tries to map a GraphQL query to a prepared statement where the parameters have a one-to-one correspondence to the variables defined in the GraphQL query.
The first time a query comes in, Hasura generates a plan for the query which consists of two things:
1. The prepared statement
2. Information necessary to convert variables into the prepared statement's arguments
For the above query, Hasura generates the following prepared statement (simplified):
.. code-block:: plpgsql
select name, rating from author where id = $1
With the following prepared variables:
.. code-block:: plpgsql
$1 = 1
This plan is then saved in a data structure called ``Query Plan Cache``. The next time the same query is executed,
Hasura uses the plan to convert the provided variables into the prepared statement's arguments and then executes the statement.
This will significantly cut down the execution time for a GraphQL query resulting in lower latencies and higher throughput.
Caveats
^^^^^^^
The above optimization is not possible for all types of queries. For example, consider this query:
.. code-block:: graphql
query getAuthorWithCondition($condition: author_bool_exp!) {
author(where: $condition)
name
rating
}
}
The statement generated for ``getAuthorWithCondition`` is now dependent on the variables.
With the following variables:
.. code-block:: json
{
"condition": {"id": {"_eq": 1}}
}
the generated statement will be:
.. code-block:: plpgsql
select name, rating from author where id = $1
However, with the following variables:
.. code-block:: json
{
"condition": {"name": {"_eq": "John"}}
}
the generated statement will be:
.. code-block:: plpgsql
select name, rating from author where name = 'John'
A plan cannot be generated for such queries because the variables defined in the GraphQL query don't have a one-to-one correspondence to the parameters in the prepared statement.
Query optimization
------------------
Using GraphQL variables
^^^^^^^^^^^^^^^^^^^^^^^
In order to leverage Hasura's query plan caching (as explained in the :ref:`previous section <ms_sql_server_query_plan_caching>`) to the full extent, GraphQL queries should be defined with
variables whose types are **non-nullable scalars** whenever possible.
To make variables non-nullable, add a ``!`` at the end of the type, like here:
.. code-block:: graphql
:emphasize-lines: 1
query getAuthor($id: Int!) {
authors(where: {id: {_eq: $id}}) {
name
rating
}
}
If the ``!`` is not added and the variable is nullable, the generated query will be different depending on whether an ``id`` is passed or whether the variable is ``null``
(for the latter, there is no ``where`` statement present). Therefore, it's not possible for Hasura to create a reusable plan for a query in this case.
.. note::
Hasura is fast even for queries which cannot have a reusable plan.
This should concern you only if you face a high volume of traffic (thousands of requests per second).
.. _ms_sql_server_data_validation_mssql_indexes:
Using MS SQL indexes
^^^^^^^^^^^^^^^^^^^^
`MS SQL Server indexes <https://docs.microsoft.com/en-us/sql/relational-databases/indexes/indexes?view=sql-server-ver15>`__ are special lookup tables that MS SQL Server can use to speed up data lookup.
An index acts as a pointer to data in a table, and it works very similar to an index in the back of a book.
If you look in the index first, you'll find the data much quicker than searching the whole book (or - in this case - database).
Let's say we know that ``authors`` table is frequently queried by ``name``:
.. code-block:: graphql
query {
authors(where: {name: {_eq: "Mario"}}) {
rating
}
}
We've seen in the :ref:`above example <ms_sql_server_analysing_query_performance>` that by default MS SQL Server conducts a sequential scan i.e. going through all the rows.
Whenever there is a sequential scan, it can be optimized by adding an index.
The following statement sets an index on ``name`` in the ``authors`` table.
.. code-block:: plpgsql
CREATE INDEX ON authors (name);
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
An index can be added in the ``Data -> SQL`` tab in the Hasura console.
.. tab:: CLI
:ref:`Create a migration manually <manual_migrations>` and add your create index statement to the ``up.sql`` file.
Also, add an SQL statement to revert that statement to the ``down.sql`` file in case you need to :ref:`roll back <roll_back_migrations>` the migration.
Apply the migration by running:
.. code-block:: bash
hasura migrate apply
.. tab:: API
You can add an index by making an API call to the :ref:`schema_run_sql metadata API <schema_run_sql>`:
.. code-block:: http
POST /v2/query HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "schema_run_sql",
"args": {
"sql": "<create index statement>"
}
}
Let's compare the performance analysis to :ref:`the one before adding the index <ms_sql_server_analysing_query_performance>`.
What was a ``sequential scan`` in the example earlier is now an ``index scan``. ``Index scans`` are usually more performant than ``sequential scans``.
We can also see that the ``cost`` of the query is now lower than the one before we added the index.
.. thumbnail:: /img/graphql/core/queries/query-analysis-after-index.png
:class: no-shadow
:width: 75%
:alt: Execution plan for Hasura GraphQL query
.. note::
In some cases sequential scans can still be faster than index scans, e.g. if the result returns a high percentage of the rows in the table.
MS SQL Server comes up with multiple query plans and takes the call on what kind of scan would be faster.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,115 @@
.. meta::
:description: Make simple object queries on MS SQL Server in Hasura
:keywords: hasura, docs, ms sql server, query, object query
.. _ms_sql_server_simple_object_queries:
MS SQL Server: Simple object queries
====================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
Introduction
------------
You can fetch a single node or multiple nodes of the same type using a simple object query.
Fetch list of objects
---------------------
**Example:** Fetch a list of authors:
.. graphiql::
:view_only:
:query:
query {
authors {
id
name
}
}
:response:
{
"data": {
"authors": [
{
"id": 1,
"name": "Justin"
},
{
"id": 2,
"name": "Beltran"
},
{
"id": 3,
"name": "Sidney"
},
{
"id": 4,
"name": "Anjela"
}
]
}
}
.. TODO: DBCOMPATIBILITY
Fetch an object using its primary key
-------------------------------------
**Example:** Fetch an author using their primary key:
.. graphiql::
:view_only:
:query:
query {
authors_by_pk(id: 1) {
id
name
}
}
:response:
{
"data": {
"authors_by_pk": {
"id": 1,
"name": "Justin"
}
}
}
Fetch value from JSON/JSONB column at particular path
-----------------------------------------------------
**Example:** Fetch the city and phone number of an author from their JSONB
address column:
.. graphiql::
:view_only:
:query:
query {
authors_by_pk(id: 1) {
id
name
address
city: address(path: "$.city")
phone: address(path: "$.phone_numbers.[0]")
}
}
:response:
{
"data": {
"authors_by_pk": {
"id": 1,
"name": "Justin",
"address": {
"city": "Bengaluru",
"phone_numbers": [9090909090, 8080808080]
},
"city": "Bengaluru",
"phone": 9090909090
}
}
}
See the :ref:`API reference <SimpleObject>` for more details.

View File

@ -0,0 +1,432 @@
.. meta::
:description: Sort query results on MS SQL Server in Hasura
:keywords: hasura, docs, ms sql server, query, sort
.. _ms_sql_server_sort_query_results:
MS SQL Server: Sort query results
=================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
The **order_by** argument
-------------------------
Results from your query can be sorted by using the ``order_by`` argument. The argument can be used to sort nested
objects too.
The sort order (ascending vs. descending) is set by specifying the ``asc`` or ``desc``
enum value for the column name in the ``order_by`` input object, e.g. ``{name: desc}``.
By default, for ascending ordering ``null`` values are returned at the end of the results and for descending
ordering ``null`` values are returned at the start of the results. ``null`` values can be fetched first on
ascending ordering by specifying ``asc_nulls_first`` and last on descending ordering by specifying
``desc_nulls_last`` enum value e.g. ``{name: desc_nulls_last}``.
The ``order_by`` argument takes an array of objects to allow sorting by multiple columns.
You can also use nested objects' fields to sort the results. Only **columns from object relationships** and
**aggregates from array relationships** can be used for sorting.
You can see the complete specification of the ``order_by`` argument in the :ref:`API reference <OrderByExp>`.
The following are example queries for different sorting use cases:
Sorting objects
---------------
**Example:** Fetch a list of authors sorted by their names in an ascending order:
.. graphiql::
:view_only:
:query:
query {
authors (
order_by: {name: asc}
) {
id
name
}
}
:response:
{
"data": {
"authors": [
{
"id": 5,
"name": "Amii"
},
{
"id": 4,
"name": "Anjela"
},
{
"id": 8,
"name": "April"
},
{
"id": 2,
"name": "Beltran"
},
{
"id": 7,
"name": "Berti"
},
{
"id": 6,
"name": "Corny"
}
]
}
}
.. _ms_sql_server_nested_sort:
Sorting nested objects
----------------------
**Example:** Fetch a list of authors sorted by their names with a list of their articles that is sorted by
their rating:
.. graphiql::
:view_only:
:query:
query {
authors (order_by: {name: asc}) {
id
name
articles(order_by: {rating: desc}) {
id
title
rating
}
}
}
:response:
{
"data": {
"authors": [
{
"id": 5,
"name": "Amii",
"articles": [
{
"rating": 5,
"id": 17,
"title": "montes nascetur ridiculus"
},
{
"rating": 3,
"id": 12,
"title": "volutpat quam pede"
},
{
"rating": 2,
"id": 4,
"title": "vestibulum ac est"
}
]
},
{
"id": 4,
"name": "Anjela",
"articles": [
{
"rating": 4,
"id": 3,
"title": "amet justo morbi"
},
{
"rating": 1,
"id": 1,
"title": "sit amet"
}
]
},
{
"id": 8,
"name": "April",
"articles": [
{
"rating": 4,
"id": 13,
"title": "vulputate elementum"
},
{
"rating": 2,
"id": 20,
"title": "eu nibh"
}
]
}
]
}
}
Sorting based on nested object's fields
---------------------------------------
Only **columns from object relationships** and **aggregates from array relationships** can be used for sorting.
For object relationships
^^^^^^^^^^^^^^^^^^^^^^^^
For object relationships only columns can be used for sorting.
**Example:** Fetch a list of articles that are sorted by their author's ids in descending order:
.. graphiql::
:view_only:
:query:
query {
articles (
order_by: {author: {id: desc}}
) {
id
rating
published_on
author {
id
name
}
}
}
:response:
{
"data": {
"articles": [
{
"id": 3,
"title": "Article 3",
"content": "Sample article content 3",
"author": {
"id": 2,
"name": "Author 2"
}
},
{
"id": 1,
"title": "Article 1",
"content": "Sample article content 1",
"author": {
"id": 1,
"name": "Author 1"
}
},
{
"id": 2,
"title": "Article 2",
"content": "Sample article content 2",
"author": {
"id": 1,
"name": "Author 1"
}
}
]
}
}
For array relationships
^^^^^^^^^^^^^^^^^^^^^^^
For array relationships only aggregates can be used for sorting.
**Example:** Fetch a list of authors sorted in descending order of their article count:
.. graphiql::
:view_only:
:query:
query {
authors (
order_by: {
articles_aggregate: {count: desc}
}
) {
id
name
articles_aggregate {
aggregate{
count
}
}
}
}
:response:
{
"data": {
"authors": [
{
"id": 5,
"name": "Amii",
"articles_aggregate":{
"aggregate": {
"count": 3
}
}
},
{
"id": 4,
"name": "Anjela",
"articles_aggregate":{
"aggregate": {
"count": 2
}
}
},
{
"id": 8,
"name": "April",
"articles_aggregate":{
"aggregate": {
"count": 2
}
}
}
]
}
}
**Example:** Fetch a list of authors sorted in increasing order of their highest article rating:
.. graphiql::
:view_only:
:query:
query {
authors(
order_by: {
articles_aggregate: {
max: {rating: asc_nulls_last}
}
}
) {
id
name
articles_aggregate {
aggregate{
max {rating}
}
}
}
}
:response:
{
"data": {
"authors": [
{
"id": 7,
"name": "Berti",
"articles_aggregate": {
"aggregate": {
"max": {
"rating": 2
}
}
}
},
{
"id": 2,
"name": "Beltran",
"articles_aggregate": {
"aggregate": {
"max": {
"rating": 3
}
}
}
},
{
"id": 8,
"name": "April",
"articles_aggregate": {
"aggregate": {
"max": {
"rating": 4
}
}
}
},
{
"id": 3,
"name": "Sidney",
"articles_aggregate": {
"aggregate": {
"max": {
"rating": 4
}
}
}
},
{
"id": 5,
"name": "Amii",
"articles_aggregate": {
"aggregate": {
"max": {
"rating": 5
}
}
}
},
{
"id": 9,
"name": "Ninnetta",
"articles_aggregate": {
"aggregate": {
"max": {
"rating": null
}
}
}
}
]
}
}
Sorting by multiple fields
--------------------------
**Example:** Fetch a list of articles that is sorted by their rating (descending) and then on their published
date (ascending with nulls first):
.. graphiql::
:view_only:
:query:
query {
articles (
order_by: [
{rating: desc},
{published_on: asc_nulls_first}
]
) {
id
rating
published_on
}
}
:response:
{
"data": {
"articles": [
{
"id": 17,
"rating": 5,
"published_on": null
},
{
"id": 14,
"rating": 4,
"published_on": null
},
{
"id": 7,
"rating": 4,
"published_on": "2016-07-09"
},
{
"id": 3,
"rating": 4,
"published_on": "2017-05-26"
}
]
}
}

View File

@ -0,0 +1,328 @@
.. meta::
:description: Use variables, aliases, fragments and directives in Hasura queries
:keywords: hasura, docs, query, variable, alias, fragment, directive
.. _ms_sql_server_variables_aliases_fragments_directives:
Using variables / aliases / fragments / directives in queries
=============================================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
Using variables
---------------
In order to make a query re-usable, it can be made dynamic by using variables.
**Example:** Fetch an author by their ``author_id``:
.. graphiql::
:view_only:
:query:
query getArticles($author_id: Int!) {
articles(
where: { author_id: { _eq: $author_id } }
) {
id
title
}
}
:response:
{
"data": {
"articles": [
{
"id": 15,
"title": "How to climb Mount Everest"
},
{
"id": 6,
"title": "How to be successful on broadway"
}
]
}
}
:variables:
{
"author_id": 1
}
.. admonition:: Variables and performance
Variables have an impact on query performance. Refer to :ref:`query performance <ms_sql_server_query_performance>` to learn more about Hasura's query plan caching and about optimizing when using variables.
Using aliases
-------------
Aliases can be used to return objects with a different name than their field name. This is especially useful while
fetching the same type of objects with different arguments in the same query.
**Example:** First, fetch all articles. Second, fetch the two top-rated articles. Third, fetch the worst-rated article:
.. graphiql::
:view_only:
:query:
query getArticles {
articles {
title
rating
}
topTwoArticles: articles(
order_by: {rating: desc},
limit: 2
) {
title
rating
}
worstArticle: articles(
order_by: {rating: asc},
limit: 1
) {
title
rating
}
}
:response:
{
"data": {
"articles": [
{
"title": "How to climb Mount Everest",
"rating": 4
},
{
"title": "How to be successful on broadway",
"rating": 20
},
{
"title": "How to make fajitas",
"rating": 6
}
],
"topTwoArticles": [
{
"title": "How to be successful on broadway",
"rating": 20
},
{
"title": "How to make fajitas",
"rating": 6
}
],
"worstArticle": [
{
"title": "How to climb Mount Everest",
"rating": 4
}
]
}
}
Using fragments
---------------
Sometimes, queries can get long and confusing. A fragment is a set of fields with any chosen name. This fragment
can then be used to represent the defined set.
**Example:** Creating a fragment for a set of ``article`` fields (``id`` and ``title``) and using it in a query:
.. graphiql::
:view_only:
:query:
fragment articleFields on articles {
id
title
}
query getArticles {
articles {
...articleFields
}
topTwoArticles: articles(
order_by: {rating: desc},
limit: 2
) {
...articleFields
}
}
:response:
{
"data": {
"articles": [
{
"id": 3,
"title": "How to make fajitas"
},
{
"id": 15,
"title": "How to climb Mount Everest"
},
{
"id": 6,
"title": "How to be successful on broadway"
}
],
"topTwoArticles": [
{
"id": 6,
"title": "How to be successful on broadway"
},
{
"id": 3,
"title": "How to make fajitas"
}
]
}
}
Using directives
----------------
Directives make it possible to include or skip a field based on a boolean expression passed as a query
variable.
@include(if: Boolean)
^^^^^^^^^^^^^^^^^^^^^
With ``@include(if: Boolean)``, it is possible to include a field in the query result based on a Boolean expression.
**Example:** The query result includes the field ``publisher``, as ``$with_publisher`` is set to ``true``:
.. graphiql::
:view_only:
:query:
query getArticles($with_publisher: Boolean!) {
articles {
title
publisher @include(if: $with_publisher)
}
}
:response:
{
"data": {
"articles": [
{
"title": "How to climb Mount Everest",
"publisher": "Mountain World"
},
{
"title": "How to be successful on broadway",
"publisher": "Broadway World"
},
{
"title": "How to make fajitas",
"publisher": "Fajita World"
}
]
}
}
:variables:
{
"with_publisher": true
}
**Example:** The query result doesn't include the field ``publisher``, as ``$with_publisher`` is set to ``false``:
.. graphiql::
:view_only:
:query:
query getArticles($with_publisher: Boolean!) {
articles {
title
publisher @include(if: $with_publisher)
}
}
:response:
{
"data": {
"articles": [
{
"title": "How to climb Mount Everest"
},
{
"title": "How to be successful on broadway"
},
{
"title": "How to make fajitas"
}
]
}
}
:variables:
{
"with_publisher": false
}
@skip(if: Boolean)
^^^^^^^^^^^^^^^^^^
With ``@skip(if: Boolean)``, it is possible to exclude (skip) a field in the query result based on a Boolean expression.
**Example:** The query result doesn't include the field ``publisher``, as ``$with_publisher`` is set to ``true``:
.. graphiql::
:view_only:
:query:
query getArticles($with_publisher: Boolean!) {
articles {
title
publisher @skip(if: $with_publisher)
}
}
:response:
{
"data": {
"articles": [
{
"title": "How to climb Mount Everest"
},
{
"title": "How to be successful on broadway"
},
{
"title": "How to make fajitas"
}
]
}
}
:variables:
{
"with_publisher": true
}
**Example:** The query result includes the field ``publisher``, as ``$with_publisher`` is set to ``false``:
.. graphiql::
:view_only:
:query:
query getArticles($with_publisher: Boolean!) {
articles {
title
publisher @skip(if: $with_publisher)
}
}
:response:
{
"data": {
"articles": [
{
"title": "How to climb Mount Everest",
"publisher": "Mountain World"
},
{
"title": "How to be successful on broadway",
"publisher": "Broadway World"
},
{
"title": "How to make fajitas",
"publisher": "Fajita World"
}
]
}
}
:variables:
{
"with_publisher": false
}

View File

@ -0,0 +1,161 @@
.. meta::
:description: Use custom field names for MS SQL Server in Hasura
:keywords: hasura, docs, ms sql server, schema, custom field name
.. _ms_sql_server_custom_field_names:
MS SQL Server: Customise auto-generated field names
===================================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
Introduction
------------
Hasura auto-generates GraphQL field names based on your database table and column names. If you'd like to change the defaults,
it is possible to override the auto-generated table and column field names exposed over the GraphQL API.
.. admonition:: Supported from
This feature is supported in versions ``v1.0.0-beta.8`` and later.
Expose columns with a different name in the GraphQL API
-------------------------------------------------------
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
Console support coming soon
..
Head to the ``Data -> [table-name] -> Modify``. On the relevant field, click ``Edit`` and change the GraphQL field name to a name of your choice.
.. thumbnail:: /img/graphql/core/schema/custom-field-name-column.png
:alt: Customise GraphQL field name
.. tab:: CLI
You can customize auto-generated field names in the ``tables.yaml`` file inside the ``metadata`` directory:
.. code-block:: yaml
:emphasize-lines: 4-6
- table:
schema: dbo
name: author
configuration:
custom_column_names:
addr: address
Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
A custom field name can be set for a column via the following 2 methods:
.. TODO: BROKEN_LINK
1. Passing a :ref:`table_config` with the :ref:`CustomColumnNames` to the :ref:`mssql_set_table_customization` API while tracking a table:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "mssql_set_table_customization",
"args": {
"table": "authors",
"configuration": {
"custom_column_names": {
"id": "AuthorId"
}
}
}
}
.. TODO: BROKEN_LINK
2. Customization can be done at the time of creation using :ref:`mssql_track_table` API also.
Expose table root fields with a different name in the GraphQL API
-----------------------------------------------------------------
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
Console support coming soon
..
Head to the ``Data -> [table-name] -> Modify``. Click the ``Edit`` button in the ``Custom GraphQL Root Fields`` section and define names over which you'd like to expose the table root fields.
.. thumbnail:: /img/graphql/core/schema/custom-field-name-root-fields.png
:alt: Customise GraphQL root field
.. tab:: CLI
You can expose table root fields with a different name in the GraphQL API in the ``tables.yaml`` file inside the ``metadata`` directory:
.. code-block:: yaml
:emphasize-lines: 3-6
- table:
schema: dbo
name: authors
configuration:
custom_root_fields:
select: authors_aggregate
After that, apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
A custom field name can be set for a table root field via the following 2 methods:
.. TODO: BROKEN_LINK
1. Passing a :ref:`table_config` with the :ref:`custom_root_fields` to the :ref:`mssql_set_table_customization` API while tracking a table:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "mssql_set_table_customization",
"args": {
"table": "authors",
"configuration": {
"custom_column_names": {
"id": "AuthorId"
}
"custom_root_fields": {
"select": "authors",
"select_aggregate": "authors_aggregate"
}
}
}
}
.. TODO: BROKEN_LINK
2. Customization can be done at the time of creation using :ref:`mssql_track_table` API also.

View File

@ -0,0 +1,52 @@
.. meta::
:description: Manage GraphQL schema over MS SQL Server with Hasura
:keywords: hasura, docs, ms sql server, schema
.. _ms_sql_server_schema:
MS SQL Server: Schema
=====================
.. contents:: Table of contents
:backlinks: none
:depth: 1
:local:
The Hasura GraphQL engine automatically generates your GraphQL schema and resolvers based on your tables/views
in MS SQL Server. **You don't need to write a GraphQL schema or resolvers.** See
:ref:`How Hasura GraphQL engine works <how_it_works>` for more details.
The Hasura console gives you UI tools that speed up your data-modelling process, or working with your existing database.
The console also automatically generates migrations or metadata files that you can edit directly and check into your
version control.
The Hasura GraphQL engine lets you do anything you would usually do with MS SQL Server by giving you GraphQL over native
MS SQL Server constructs.
**See:**
.. toctree::
:maxdepth: 1
Tables basics <tables>
Table relationships <table-relationships/index>
Extend with views <views>
Customise auto-generated fields <custom-field-names>
Using an existing database <using-existing-database>
.. TODO: DB-COMPATIBILITY
.. toctree::
:maxdepth: 1
Tables basics <tables>
Table relationships <table-relationships/index>
Remote relationships <remote-relationships/index>
Extend with views <views>
Extend with SQL functions <custom-functions>
Default field values <default-values/index>
Enum type fields <enums>
Computed fields <computed-fields>
Customise auto-generated fields <custom-field-names>
Data validations <data-validations>
Using an existing database <using-existing-database>
Relay schema <relay-schema>

View File

@ -0,0 +1,584 @@
.. meta::
:description: Create relationships between MS SQL Server tables/views in Hasura
:keywords: hasura, docs, ms sql server, schema, relationship, create
.. _ms_sql_server_create_relationships:
MS SQL Server: Creating relationships
=====================================
.. contents:: Table of contents
:backlinks: none
:depth: 1
:local:
Introduction
------------
A relationship from one table/view to another can be created by defining a link between a column of the table/view to a
column of the other table/view.
Typically, relationships are defined using foreign-key constraints. But in some cases, it might not be possible to
use foreign-key constraints to create the relation. For example, while trying to create a relationship involving a view
as foreign-keys can't be created on views.
.. _ms_sql_server_relationships-using-fkey:
Using foreign keys
------------------
Say we created two tables, ``authors(id, name)`` and ``articles(id, title, content, rating, author_id)``.
Let us now connect these tables to enable nested queries using a foreign-key:
Step 1: Add foreign-key constraint
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Let's add a foreign-key constraint to the ``author_id`` column in the ``articles`` table.
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
In the console, navigate to the ``Modify`` tab of the ``articles`` table. Click the ``Add`` button in
the Foreign Keys section and configure the ``author_id`` column as a foreign-key for the ``id`` column in
the ``authors`` table:
.. thumbnail:: /img/graphql/core/schema/add-foreign-key-mssql.png
:alt: Add foreign-key constraint
.. tab:: CLI
:ref:`Create a migration manually <manual_migrations>` and add the following SQL statement to the ``up.sql`` file:
.. code-block:: sql
ALTER TABLE articles
ADD FOREIGN KEY (author_id) REFERENCES authors(id);
Add the following statement to the ``down.sql`` file in case you need to :ref:`roll back <roll_back_migrations>` the above statement:
.. code-block:: sql
ALTER TABLE articles
DROP CONSTRAINT articles_author_id_fkey;
Apply the migration by running:
.. code-block:: bash
hasura migrate apply
.. tab:: API
You can add a foreign-key constraint using the :ref:`schema_run_sql metadata API <schema_run_sql>`:
.. code-block:: http
POST /v2/query HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "run_sql",
"args": {
"sql": "ALTER TABLE articles ADD FOREIGN KEY (author_id) REFERENCES authors(id);"
}
}
Step 2: Create an object relationship
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Each article has one author. This is an ``object relationship``.
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
The console infers potential relationships using the foreign-key created above and recommends these in the
``Relationships`` tab of the ``articles`` table.
Add an ``object relationship`` named ``author`` for the ``articles`` table as shown here:
.. thumbnail:: /img/graphql/core/schema/add-1-1-relationship.png
:alt: Create an object relationship
.. tab:: CLI
You can add an object relationship in the ``tables.yaml`` file inside the ``metadata`` directory:
.. code-block:: yaml
:emphasize-lines: 4-7
- table:
schema: public
name: articles
object_relationships:
- name: author
using:
foreign_key_constraint_on: author_id
- table:
schema: public
name: authors
Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
.. TODO: BROKEN_LINK
You can create an object relationship by using the :ref:`mssql_create_object_relationship metadata API <mssql_create_object_relationship>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "mssql_create_object_relationship",
"args": {
"table": "articles",
"name": "author",
"source": "default",
"using": {
"foreign_key_constraint_on" : ["author_id"]
}
}
}
We can now run a nested object query that is based on this ``object relationship``.
Fetch a list of articles and each article's author:
.. graphiql::
:view_only:
:query:
query {
articles {
id
title
author {
id
name
}
}
}
:response:
{
"data": {
"articles": [
{
"id": 1,
"title": "sit amet",
"author": {
"name": "Anjela",
"id": 4
}
},
{
"id": 2,
"title": "a nibh",
"author": {
"name": "Beltran",
"id": 2
}
},
{
"id": 3,
"title": "amet justo morbi",
"author": {
"name": "Anjela",
"id": 4
}
}
]
}
}
Step 3: Create an array relationship
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
An author can write multiple articles. This is an ``array relationship``.
You can add an ``array relationship`` in the same fashion as an ``object relationship`` as shown above.
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
On the console, add an ``array relationship`` named ``articles`` for the ``authors`` table as shown here:
.. thumbnail:: /img/graphql/core/schema/add-1-many-relationship.png
:alt: Create an array relationship
We can now run a nested object query that is based on this ``array relationship``.
.. tab:: CLI
You can add an array relationship in the ``tables.yaml`` file inside the ``metadata`` directory:
.. code-block:: yaml
:emphasize-lines: 11-18
- table:
schema: public
name: articles
object_relationships:
- name: author
using:
foreign_key_constraint_on: author_id
- table:
schema: public
name: authors
array_relationships:
- name: articles
using:
foreign_key_constraint_on:
column: author_id
table:
schema: public
name: articles
Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
.. TODO: BROKEN_LINK
You can create an array relationship by using the :ref:`mssql_create_array_relationship metadata API <mssql_create_array_relationship>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "mssql_create_array_relationship",
"args": {
"table": "author",
"name": "articles",
"source": "default",
"using": {
"foreign_key_constraint_on" : {
"table" : "articles",
"columns" : ["author_id"]
}
}
}
}
Fetch a list of authors and a nested list of each author's articles:
.. graphiql::
:view_only:
:query:
query {
authors {
id
name
articles {
id
title
}
}
}
:response:
{
"data": {
"authors": [
{
"id": 1,
"name": "Justin",
"articles": [
{
"id": 15,
"title": "vel dapibus at"
},
{
"id": 16,
"title": "sem duis aliquam"
}
]
},
{
"id": 2,
"name": "Beltran",
"articles": [
{
"id": 2,
"title": "a nibh"
},
{
"id": 9,
"title": "sit amet"
}
]
},
{
"id": 3,
"name": "Sidney",
"articles": [
{
"id": 6,
"title": "sapien ut"
},
{
"id": 11,
"title": "turpis eget"
},
{
"id": 14,
"title": "congue etiam justo"
}
]
}
]
}
}
.. _ms_sql_server_create_manual_relationships:
Using manual relationships
--------------------------
Let's say you have a table ``authors (id, name)`` and a :ref:`view <ms_sql_server_custom_views>` ``author_avg_rating (id, avg)`` which has the
average rating of articles for each author.
Let us now create an ``object relationship`` called ``avg_rating`` from the ``authors`` table to the
``author_avg_rating`` view using a manual relationship:
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
**Step 1: Open the manual relationship section**
- Open the console and navigate to the ``Data -> authors -> Relationships`` tab.
- Click on the ``Configure`` button:
.. thumbnail:: /img/graphql/core/schema/manual-relationship-btn.png
:alt: Open the manual relationship section
**Step 2: Define the relationship**
The above step will open up a section as shown below:
.. thumbnail:: /img/graphql/core/schema/manual-relationship-create.png
:alt: Define the relationship
In this case:
- **Relationship Type** will be: ``Object Relationship``
- **Relationship Name** can be: ``avg_rating``
- **Reference** will be: ``id -> author_avg_rating . id`` *(similar to defining a foreign-key)*
**Step 3: Create the relationship**
Now click on the ``Save`` button to create the relationship.
.. tab:: CLI
You can add a manual relationship in the ``tables.yaml`` file inside the ``metadata`` directory:
.. code-block:: yaml
:emphasize-lines: 7-15
- table:
schema: public
name: articles
- table:
schema: public
name: authors
object_relationships:
- name: avg_rating
using:
manual_configuration:
remote_table:
schema: public
name: author_average_rating
column_mapping:
id: author_id
- table:
schema: public
name: author_average_rating
Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
You can add a manual relationship by using the :ref:`mssql_create_object_relationship metadata API <mssql_create_object_relationship>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "mssql_create_object_relationship",
"args": {
"table": "authors",
"name": "avg_rating",
"source": "default",
"using": {
"manual_configuration": {
"remote_table": "author_average_rating",
"column_mapping": {
"id": "author_id"
}
}
}
}
}
We can now run a nested object query that is based on this ``object relationship``.
Fetch a list of authors with the average rating of their articles:
.. graphiql::
:view_only:
:query:
query {
authors {
id
name
avg_rating {
avg
}
}
}
:response:
{
"data": {
"authors": [
{
"id": 1,
"name": "Justin",
"avg_rating": {
"avg": 2.5
}
},
{
"id": 2,
"name": "Beltran",
"avg_rating": {
"avg": 3
}
},
{
"id": 3,
"name": "Sidney",
"avg_rating": {
"avg": 2.6666666666666665
}
}
]
}
}
Tracking existing relationships inferred via foreign-keys
---------------------------------------------------------
As mentioned in the Introduction section above, relationships can be inferred via foreign-keys that exist in your database:
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
The console infers potential relationships using existing foreign-keys and recommends these on the ``Data -> Schema`` page
.. thumbnail:: /img/graphql/core/schema/schema-track-relationships.png
:alt: Track all relationships
You can choose to track the relationships individually using the ``Track`` buttons or hit the ``Track all`` button to
track all the inferred relationships in one go.
.. tab:: CLI
You can add relationships in the ``tables.yaml`` file inside the ``metadata`` directory:
.. code-block:: yaml
:emphasize-lines: 4-7,11-18
- table:
schema: public
name: articles
object_relationships:
- name: author
using:
foreign_key_constraint_on: author_id
- table:
schema: public
name: authors
array_relationships:
- name: articles
using:
foreign_key_constraint_on:
column: author_id
table:
schema: public
name: articles
Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
.. TODO: BROKEN_LINK
You can create multiple relationships by using the :ref:`mssql_create_object_relationship metadata API <mssql_create_object_relationship>`
and the :ref:`mssql_create_array_relationship metadata API <mssql_create_array_relationship>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "bulk",
"args": [
{
"type": "mssql_create_object_relationship",
"args": {
"table": "articles",
"name": "author",
"using": {
"foreign_key_constraint_on": "author_id"
}
}
},
{
"type": "mssql_create_array_relationship",
"args": {
"table": "authors",
"name": "articles",
"using": {
"foreign_key_constraint_on" : {
"table" : "articles",
"column" : "author_id"
}
}
}
}
]
}

View File

@ -0,0 +1,19 @@
.. meta::
:description: Relationships modelling in Hasura
:keywords: hasura, docs, schema, database modelling
.. _ms_sql_server_relationship_database_modelling:
Database relationship modelling guides
======================================
.. contents:: Table of contents
:backlinks: none
:depth: 1
:local:
The following guides will help you model the different types of table relationships in the database:
- :ref:`one_to_one_modelling`
- :ref:`one_to_many_modelling`
- :ref:`many_to_many_modelling`

View File

@ -0,0 +1,86 @@
.. meta::
:description: Manage relationships between MS SQL Server tables/views in Hasura
:keywords: hasura, docs, ms sql server, schema, relationship
.. _ms_sql_server_table_relationships:
MS SQL Server: Relationships between tables/views
=================================================
.. contents:: Table of contents
:backlinks: none
:depth: 1
:local:
Introduction
------------
To make :ref:`nested object queries <ms_sql_server_nested_object_queries>`, the tables/views in your database need to
be connected via relationships.
Let's say we have the following tables in our database: ``authors``, ``passport_infos``, ``articles`` and ``tags``.
Table relationships
-------------------
The tables/views in any relational database are typically related to each other via one of the
following types of table relationships:
+------------------+-------------------------------------+------------------------------------------------+
| Type | Example | Meaning |
+==================+=====================================+================================================+
| ``one-to-one`` | ``authors`` and ``passport_infos`` | - an ``author`` can have one ``passport_info`` |
| | | - a ``passport_info`` can have one ``owner`` |
+------------------+-------------------------------------+------------------------------------------------+
| ``one-to-many`` | ``authors`` and ``articles`` | - an ``author`` can have many ``articles`` |
| | | - an ``article`` can have one ``author`` |
+------------------+-------------------------------------+------------------------------------------------+
| ``many-to-many`` | ``articles`` and ``tags`` | - an ``article`` can have many ``tags`` |
| | | - a ``tag`` can have many ``articles`` |
+------------------+-------------------------------------+------------------------------------------------+
.. _ms_sql_server_graphql_relationships:
GraphQL schema relationships
----------------------------
Each table relationship, as you can see from the above section, will have two component relationships
(one in either direction) in the GraphQL schema. These relationships can be one of the following types:
+-----------------------------------------+------------------------------------------+---------------------------------------------------------------------------------------+
| Type | Example | Meaning |
+=========================================+==========================================+=======================================================================================+
| ``object relationship`` (one-to-one) | an ``article`` can have one ``author`` | an ``article`` object will have a single nested author object called ``author`` |
+-----------------------------------------+------------------------------------------+---------------------------------------------------------------------------------------+
| ``array relationship`` (one-to-many) | an ``author`` can have many ``articles`` | an ``author`` object will have an array of nested article objects called ``articles`` |
+-----------------------------------------+------------------------------------------+---------------------------------------------------------------------------------------+
.. note::
The relationship name is used to refer to the nested objects in queries. For example, "``articles``" of an ``author``
and "``author``" of an ``article``.
Managing GraphQL relationships
------------------------------
See the following to manage the object/array relationships between tables/views for the GraphQL schema:
- :ref:`ms_sql_server_create_relationships`
- :ref:`ms_sql_server_rename_relationships`
Table relationships modelling guides
------------------------------------
The following guides will help you model the different types of table relationships in the database:
- :ref:`one_to_one_modelling`
- :ref:`one_to_many_modelling`
- :ref:`many_to_many_modelling`
.. toctree::
:maxdepth: 1
:hidden:
Creating relationships <create>
Renaming relationships <rename>
Database modelling <database-modelling>

View File

@ -0,0 +1,75 @@
.. meta::
:description: Rename MS SQL Server relationships in Hasura
:keywords: hasura, docs, ms sql server, schema, relationship, rename
.. _ms_sql_server_rename_relationships:
MS SQL Server: Renaming relationships
=====================================
.. contents:: Table of contents
:backlinks: none
:depth: 1
:local:
An existing relationship can be renamed as follows:
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
- Head to ``Data -> [table-name] -> Relationships`` in the console
- Drop the existing relationship
- Recreate the relationship with the new name
.. tab:: CLI
You can rename a relationship by changing the relationship name in the ``tables.yaml`` file inside the ``metadata`` directory:
.. code-block:: yaml
:emphasize-lines: 5
- table:
schema: public
name: articles
object_relationships:
- name: author
using:
foreign_key_constraint_on: author_id
- table:
schema: public
name: authors
Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
.. TODO: BROKEN_LINK
You can rename a relationship by using the :ref:`mssql_rename_relationship metadata API <mssql_rename_relationship>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "mssql_rename_relationship",
"args": {
"table": "articles",
"name": "article_details",
"source": "default",
"new_name": "article_detail"
}
}
.. note::
You might not be allowed to drop a relationship if it has been referenced elsewhere (e.g. in a permissions rule).
In this case you will have to delete the references first, rename the relationship, and then re-add the references.

View File

@ -0,0 +1,311 @@
.. meta::
:description: GraphQL over MS SQL Server tables in Hasura
:keywords: hasura, docs, ms sql server, schema, tables
.. _ms_sql_server_schema_tables:
MS SQL Server: Tables basics
============================
.. contents:: Table of contents
:backlinks: none
:depth: 1
:local:
Introduction
------------
Adding tables allows you to define the GraphQL types of your schema including their corresponding fields.
.. _ms_sql_server_create_tables:
Creating tables
---------------
Let's say we want to create two simple tables for ``articles`` and ``authors`` schema:
.. code-block:: sql
authors (
id int PRIMARY KEY,
name text
)
articles (
id int PRIMARY KEY,
title text,
content text,
rating int,
author_id int
)
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
Open the Hasura console and head to the ``Data`` tab and click on the button on the left side bar to open up an interface to
create tables.
For example, here is the schema for the ``articles`` table in this interface:
.. thumbnail:: /img/graphql/core/schema/create-table-graphql-mssql.png
:alt: Schema for an article table
.. tab:: CLI
1. :ref:`Create a migration manually <manual_migrations>` and add the following SQL statement to the ``up.sql`` file:
.. code-block:: sql
CREATE TABLE articles(id int NOT NULL, title text NOT NULL, content text NOT NULL, rating int NOT NULL, author_id int NOT NULL, PRIMARY KEY (id));
2. Add the following statement to the ``down.sql`` file in case you need to :ref:`roll back <roll_back_migrations>` the above statement:
.. code-block:: sql
DROP TABLE articles;
3. Apply the migration by running:
.. code-block:: bash
hasura migrate apply
.. tab:: API
You can create a table by making an API call to the :ref:`schema_run_sql metadata API <schema_run_sql>`:
.. code-block:: http
POST /v2/query HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "schema_run_sql",
"args": {
"sql": "CREATE TABLE articles(id int NOT NULL, title text NOT NULL, content text NOT NULL, rating int NOT NULL, author_id int NOT NULL, PRIMARY KEY (id));"
}
}
Tracking tables
---------------
Tables can be present in the underlying MS SQL Server database without being exposed over the GraphQL API.
In order to expose a table over the GraphQL API, it needs to be **tracked**.
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
When a table is created via the Hasura console, it gets tracked by default.
You can track any existing tables in your database from the ``Data -> Schema`` page:
.. thumbnail:: /img/graphql/core/schema/schema-track-tables-mssql.png
:alt: Track table
.. tab:: CLI
1. To track the table and expose it over the GraphQL API, edit the ``tables.yaml`` file in the ``metadata`` directory as follows:
.. code-block:: yaml
:emphasize-lines: 4-6
- table:
schema: public
name: authors
- table:
schema: public
name: articles
2. Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
.. TODO: BROKEN_LINK
To track the table and expose it over the GraphQL API, make the following API call to the :ref:`mssql_track_table metadata API <mssql_track_table>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "mssql_track_table",
"args": {
"table": "authors",
"configuration": {
"custom_name": "authors_table"
}
}
}
.. MSSQLUPDATE
.. code-block:: http
POST /v1/query HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "track_table",
"args": {
"schema": "public",
"name": "articles"
}
}
Generated GraphQL schema types
------------------------------
As soon as a table is created and tracked, the corresponding GraphQL schema types
and query fields will be automatically generated.
The following object type is generated for the ``articles``
table we just created and tracked:
.. code-block:: graphql
# Object type
type Articles {
id: Int
title: String
content: String
rating: Int
author_id: Int
}
Let's analyze the above type:
- ``Articles`` is the name of the type
- ``id``, ``title``, ``content``, ``rating`` and ``author_id`` are fields of the ``Articles`` type
- ``Int`` and ``String`` are types that fields can have
The following query fields are generated for the ``articles``
table we just created and tracked:
.. code-block:: graphql
# Query field
articles (
where: articles_bool_exp
limit: Int
offset: Int
order_by: [articles_order_by!]
): [articles!]!
..
# insert/upsert mutation field
insert_articles (
objects: [articles_insert_input!]!
on_conflict: articles_on_conflict
): articles_mutation_response
# update mutation field
update_articles (
where: articles_bool_exp!
_inc: articles_inc_input
_set: articles_set_input
): articles_mutation_response
# delete mutation field
delete_articles (
where: articles_bool_exp!
): articles_mutation_response
These auto-generated fields will allow you to query data
in our table.
See the :ref:`query <graphql_api_query>` API reference for the full specifications.
Try out basic GraphQL requests
------------------------------
At this point, you should be able to try out basic GraphQL queries on
the newly created tables from the GraphiQL tab in the console. *(You may want to add some
sample data into the tables first)*
- Query all rows in the ``articles`` table:
.. graphiql::
:view_only:
:query:
query {
articles {
id
title
author_id
}
}
:response:
{
"data": {
"articles": [
{
"id": 1,
"title": "sit amet",
"author_id": 4
},
{
"id": 2,
"title": "a nibh",
"author_id": 2
},
{
"id": 3,
"title": "amet justo morbi",
"author_id": 4
},
{
"id": 4,
"title": "vestibulum ac est",
"author_id": 5
}
]
}
}
..
Insert data in the ``author`` table:
.. graphiql::
:view_only:
:query:
mutation add_author {
insert_author(
objects: [
{ name: "Jane" }
]
) {
affected_rows
returning {
id
name
}
}
}
:response:
{
"data": {
"insert_author": {
"affected_rows": 1,
"returning": [
{
"id": 11,
"name": "Jane"
}
]
}
}
}
.. MSSQLUPDATE
.. note::
author's ``id`` does not need to be passed as an input as it is of type ``serial`` (auto incrementing integer).

View File

@ -0,0 +1,374 @@
.. meta::
:description: Set up a Hasura GraphQL schema with an existing database
:keywords: hasura, docs, schema, existing database
.. _ms_sql_server_schema_existing_db:
Setting up a GraphQL schema using an existing MS SQL Server database
====================================================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
Introduction
------------
When you have an existing database with a schema already present, you don't need to create tables or views or run
DDL queries through the Hasura console.
All you need to do is indicate to Hasura GraphQL engine which tables and views you want to expose over GraphQL and
how they are connected to each other so that you can query them as a "graph".
Step 1: Track tables/views
--------------------------
Tracking a table or a view means telling Hasura GraphQL engine that you want to expose that table/view over GraphQL.
To track a table or a view
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
#. Head to the ``Data -> Schema`` section of the console.
#. Under the heading ``Untracked Tables/Views``, click on the ``Track`` button next to the table/view name.
.. tab:: CLI
To track the table and expose it over the GraphQL API, add it to the ``tables.yaml`` file in the ``metadata`` directory as follows:
.. code-block:: yaml
:emphasize-lines: 1-3
- table:
schema: dbo
name: <table name>
Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
.. TODO: BROKEN_LINK
To track a table and expose it over the GraphQL API, use the :ref:`mssql_track_table metadata API <mssql_track_table>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "mssql_track_table",
"args": {
"schema": "dbo",
"name": "<table name>"
}
}
To track all tables and views present in the database
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
#. Head to the ``Data -> Schema`` section of the console.
#. Under the heading ``Untracked Tables/Views``, click the ``Track All`` button.
.. tab:: CLI
To track all tables and expose them over the GraphQL API, add them to the ``tables.yaml`` file in the ``metadata`` directory as follows:
.. code-block:: yaml
:emphasize-lines: 1-6
- table:
schema: dbo
name: <table-name-1>
- table:
schema: dbo
name: <table-name-2>
To automate this, you could add the tables in a loop through a script.
Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
.. TODO: BROKEN_LINK
To track all tables and expose them over the GraphQL API, use the :ref:`mssql_track_table metadata API <mssql_track_table>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "bulk",
"args": [
{
"type": "mssql_track_table",
"args": {
"schema": "public",
"name": "<table-name-1>"
}
},
{
"type": "mssql_track_table",
"args": {
"schema": "public",
"name": "<table-name-2>"
}
}
]
}
To automate this, you could add the ``mssql_track_table`` requests to the ``bulk`` request in a loop through a script.
Step 2: Track foreign-keys
--------------------------
Tracking a foreign-key means creating a :ref:`relationship <ms_sql_server_table_relationships>` between the tables involved in the
foreign-key.
To track a foreign-key between two tables in the database
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
#. Head to the ``Data -> Schema`` section of the console.
#. Click on a table involved in the foreign-key and head to the ``Relationships`` tab.
#. You should see a suggested relationship based on the foreign-key. Click ``Add``, give a name to your relationship
(this will be the name of the :ref:`nested object <ms_sql_server_nested_object_queries>` in the GraphQL query), and
hit ``Save`` to create the relationship.
#. Repeat with the other table involved in the foreign-key.
.. tab:: CLI
To track a relationship and expose it over the GraphQL API, add it to the ``tables.yaml`` file in the ``metadata`` directory as follows:
**Object relationship**
.. code-block:: yaml
:emphasize-lines: 4-7
- table:
schema: dbo
name: <table name>
object_relationships:
- name: <relationship name>
using:
foreign_key_constraint_on: <reference column>
**Array relationship**
.. code-block:: yaml
:emphasize-lines: 4-11
- table:
schema: dbo
name: <table name>
array_relationships:
- name: <relationship name>
using:
foreign_key_constraint_on:
column: <reference column>
table:
schema: dbo
name: <reference table name>
Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
**Object relationship**
.. TODO: BROKEN_LINK
You can create an object relationship by using the :ref:`mssql_create_object_relationship metadata API <mssql_create_object_relationship>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "mssql_create_object_relationship",
"args": {
"table": "<table name>",
"name": "<relationship name>",
"using": {
"foreign_key_constraint_on": "<reference column>"
}
}
}
**Array relationship**
.. TODO: BROKEN_LINK
You can create an array relationship by using the :ref:`mssql_create_array_relationship metadata API <mssql_create_array_relationship>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "mssql_create_array_relationship",
"args": {
"table": "<table name>",
"name": "<relationship name>",
"using": {
"foreign_key_constraint_on" : {
"table" : "<reference table name>",
"column" : "<reference column>"
}
}
}
}
To track all the foreign-keys of all tables in the database
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
#. Head to the ``Data -> Schema`` section of the console.
#. Under the heading ``Untracked foreign-key relations``, click the ``Track All`` button to automatically
create relationships based on the foreign-keys.
.. tab:: CLI
To track all relationships and expose them over the GraphQL API, add them to the ``tables.yaml`` file in the ``metadata`` directory as follows:
**Object relationship**
.. code-block:: yaml
:emphasize-lines: 4-7
- table:
schema: dbo
name: <table name>
object_relationships:
- name: <relationship name>
using:
foreign_key_constraint_on: <reference column>
**Array relationship**
.. code-block:: yaml
:emphasize-lines: 4-11
- table:
schema: dbo
name: <table name>
array_relationships:
- name: <relationship name>
using:
foreign_key_constraint_on:
column: <reference column>
table:
schema: dbo
name: <reference table name>
To automate this, you could add the relationships in a loop through a script.
Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
.. TODO: BROKEN_LINK
You can create multiple relationships by using the :ref:`mssql_create_object_relationship metadata API <mssql_create_object_relationship>`
and the :ref:`mssql_create_array_relationship metadata API <mssql_create_array_relationship>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "bulk",
"args": [
{
"type": "mssql_create_object_relationship",
"args": {
"table": "<table name>",
"name": "<relationship name>",
"using": {
"foreign_key_constraint_on": "<reference column>"
}
}
},
{
"type": "mssql_create_array_relationship",
"args": {
"table": "<table name>",
"name": "<relationship name>",
"using": {
"foreign_key_constraint_on" : {
"table" : "<reference table name>",
"column" : "<reference column>"
}
}
}
}
]
}
To automate this, you could add the create relationships requests to the ``bulk`` request in a loop through a script.
.. admonition:: Relationship nomenclature
In this case, Hasura GraphQL engine will **automatically generate relationship names** (the names of the
:ref:`nested objects <ms_sql_server_nested_object_queries>` in the GraphQL query) based on the table names and the
foreign-key names.
The name is generated in the following format:
- For object relationships: ``singular of foreignTableName``
- For array relationships: ``plural of foreignTableName``
For example, for the foreign-key ``article.author_id -> author.id``, the relationship names will be
``author`` for ``article`` table and ``articles`` for ``author`` table.
In case a field with the generated name already exists, a new name will be generated of the form:
``camel case of (singular/plural of foreignTableName + _by_ + foreignKeyColumnName)``
Note that, **this is just an arbitrary naming convention** chosen by Hasura to ensure the generation of unique
relationship names. You can choose to rename your relationships to anything you wish. You can **change the
relationship names** with a name of your choice as shown in :ref:`ms_sql_server_rename_relationships`.

View File

@ -0,0 +1,195 @@
.. meta::
:description: Customise the Hasura GraphQL schema with views
:keywords: hasura, docs, schema, view
.. _ms_sql_server_custom_views:
MS SQL Server: Extend schema with views
=======================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
What are views?
---------------
`Views <https://docs.microsoft.com/en-us/sql/relational-databases/views/create-views?view=sql-server-ver15>`__ can be used to expose the results of a custom
query as a virtual table. Views are not persisted physically i.e. the query defining a view is executed whenever
data is requested from the view.
Hasura GraphQL engine lets you expose views over the GraphQL API to allow querying them using both ``queries`` and
``subscriptions`` just like regular tables.
.. _ms_sql_server_create_views:
Creating views
--------------
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
Views can be created using SQL which can be run in the Hasura console:
- Head to the ``Data -> SQL`` section of the Hasura console
- Enter your `create view SQL statement <https://docs.microsoft.com/en-us/sql/relational-databases/views/create-views?view=sql-server-ver15>`__
- Hit the ``Run`` button
.. tab:: CLI
1. :ref:`Create a migration manually <manual_migrations>` and add your `create view SQL statement <https://docs.microsoft.com/en-us/sql/relational-databases/views/create-views?view=sql-server-ver15>`__ to the ``up.sql`` file. Also, add an SQL statement to the ``down.sql`` file that reverts the previous statement.
2. Apply the migration and metadata by running:
.. code-block:: bash
hasura migrate apply
.. tab:: API
.. TODO: BROKEN_LINK
You can add a view by using the :ref:`schema_run_sql metadata API <schema_run_sql>`:
.. code-block:: http
POST /v2/query HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "schema_run_sql",
"args": {
"sql": "<create view statement>"
}
}
Tracking views
--------------
Views can be present in the underlying MS SQL Server database without being exposed over the GraphQL API.
In order to expose a view over the GraphQL API, it needs to be **tracked**.
.. rst-class:: api_tabs
.. tabs::
.. tab:: Console
While creating views from the ``Data -> SQL`` page, selecting the ``Track this`` checkbox
will expose the new view over the GraphQL API right after creation.
You can track any existing views in your database from the ``Data -> Schema`` page:
.. thumbnail:: /img/graphql/core/schema/schema-track-views.png
:alt: Track views
.. tab:: CLI
1. To track the view and expose it over the GraphQL API, edit the ``tables.yaml`` file in the ``metadata`` directory as follows:
.. code-block:: yaml
:emphasize-lines: 7-9
- table:
schema: dbo
name: authors
- table:
schema: dbo
name: articles
- table:
schema: dbo
name: <name of view>
2. Apply the metadata by running:
.. code-block:: bash
hasura metadata apply
.. tab:: API
.. TODO: BROKEN_LINK
To track the view and expose it over the GraphQL API, make the following API call to the :ref:`mssql_track_table metadata API <mssql_track_table>`:
.. code-block:: http
POST /v1/metadata HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "mssql_track_table",
"args": {
"table": "authors",
"source": "default",
"schema": "dbo",
"name": "<name of view>"
}
}
.. CODEBACKUP
.. code-block:: http
POST /v1/query HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
{
"type": "track_table",
"args": {
"schema": "public",
"name": "<name of view>"
}
}
Use cases
---------
Views are ideal solutions for retrieving some derived data based on some custom business logic.
Let's look at a few example use cases for views:
Example: Group by and then aggregate
************************************
Sometimes we might want to fetch some data derived by aggregating (avg, min, max, etc.) over a group of rows in a table.
Lets say we want to fetch the average article rating for each author in the following schema:
.. code-block:: plpgsql
author(id integer, name text, city text, email text, phone integer, address text)
article(id integer, title text, content text, rating integer, author_id integer)
A view that averages the rating of articles for each author can be created using the following SQL query:
.. code-block:: SQL
CREATE VIEW author_average_rating AS
SELECT author_id, avg(rating)
FROM article
GROUP BY author_id
Example: Hide certain fields of a table
***************************************
Sometimes we might have some sensitive information in a table which we wouldn't want to expose.
Let's say, we want to expose the following ``author`` table without the fields ``email``, ``phone`` and ``address``:
.. code-block:: plpgsql
author(id integer, name text, city text, email text, phone integer, address text)
A view that only exposes the non-sensitive fields of the ``author`` table can be created using the following SQL query:
.. code-block:: SQL
CREATE VIEW author_public AS
SELECT id, name, city
FROM author

View File

@ -0,0 +1,109 @@
.. meta::
:description: Tuning Hasura for High-performance Subscriptions
:keywords: hasura, docs, subscriptions, performance, tuning
.. _ms_sql_server_subscriptions_execution_and_performance:
Subscriptions execution and performance
=======================================
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:
Introduction
------------
Hasura Graphql Subscriptions are **live queries** executing over the Websocket protocol to fetch near real-time data from the database.
Execution
---------
The Hasura GraphQL engine subscriptions are actually **live queries**, i.e. a subscription will return the
latest result of the query being made and not the individual events leading up to the result.
Subscriptions, on start, will emit the result of the underlying query. Subsequently, results will be emitted only if the result of the query changes underneath (via insert/update/delete on the subscribed resource).
Subscription multiplexing
^^^^^^^^^^^^^^^^^^^^^^^^^
Hasura optimizes subscriptions by combining multiple similar subscriptions into one SQL query and getting a single response from the database instead of
making separate SQL queries for each subscription. Each row in the response contains the result for a different subscription. Once Hasura gets the response
from the database, it diff-checks the individual responses and returns the result to the clients only if there is any difference in their data.
Multiplexed live queries are further split into batches which can be configured via ``HASURA_GRAPHQL_LIVE_QUERIES_MULTIPLEXED_BATCH_SIZE`` environment
variable or the ``--live-queries-multiplexed-batch-size`` flag. By default this value is set to ``100``.
For example, with the default value, if there are 1000 subscription clients with similar queries, Hasura multiplexes 100 subscriptions into
1 batch and make a single SQL query to the DB for that batch. So, in total there will be only 10 SQL queries to the DB for the 1000 subscriptions.
Example
^^^^^^^
A practical use of subscriptions can be for tracking the live locations of delivery agents carrying food orders in a food-ordering system.
The setup is operating with the default Hasura params of subscription refetch interval as 1 second and multiplexed batch size as 100.
The below figure shows multiplexing in action, where the 3 similar subscriptions differing only in the variables are batched into one SQL:
.. thumbnail:: /img/graphql/core/databases/postgres/subscriptions/subscription-multiplexing.png
:class: no-shadow
:width: 900px
:alt: Hasura subscription multiplexing AST
In this case, all 3 subscriptions are multiplexed into 1 batch resulting in 1 SQL query which is run every 1 second. If there is an
update in the location, the appropriate client gets sent the updated data.
Tuning subscription performance
-------------------------------
Analyze
^^^^^^^
Subscriptions can be 'Analyzed' (from the Analyze button in GraphiQl window of Hasura console) to see the generated multiplexed SQL and its query plan. The query plan can reveal the bottlenecks in query execution and appropriate indexes can be added to improve performance.
In addition to these, simplifying the subscription to avoid unnecessary joins or avoiding fetching fields which are not going to change can also help improve performance.
Parameters
^^^^^^^^^^
The parameters governing the performance of subscriptions in terms of throughput, latency and resource utilization are:
* ``HASURA_GRAPHQL_LIVE_QUERIES_MULTIPLEXED_REFETCH_INTERVAL``
* Time interval between Hasura multiplexed queries to the DB for fetching changes in subscriptions data, default = 1 sec
* Increasing this reduces frequency of queries to the DB thereby reducing the load on it and improving throughput while increasing the
latency of updates to the clients.
* ``HASURA_GRAPHQL_LIVE_QUERIES_MULTIPLEXED_BATCH_SIZE``
* Number of similar subscriptions batched into a single SQL query to the DB, default = 100
* Increasing this reduces the number of SQL statements fired to the DB thereby reducing the load on it and improving throughput while
increasing individual SQL execution times and hence latency.
* This value should be reduced in case the execution time of the SQL generated by Hasura after multiplexing is more than the
refetch interval.
* ``HASURA_GRAPHQL_PG_CONNECTIONS``
* Max number of connection Hasura opens with the DB, default = 50
* Increasing this increases the number of connections that can be opened with the DB to execute queries thereby improving concurrency but adding load to
the database. Very high number of concurrent connections can result in poor DB performance.
.. note::
* Tuning these parameters have no impact on the resource utilization of Hasura. Hasura's CPU and memory utilization depends on the number of
requests being served.
* For most use cases, the default values offer reasonable trade-off between resource utilization and performance. For scenarios with heavy queries
and high number of active subscriptions, the setup needs to be benchmarked and these parameters need to be iterated upon to achieve optimal
performance.
Further reading
---------------
You can read more details about the implementation of subscriptions in our `architecture and benchmarking doc <https://github.com/hasura/graphql-engine/blob/master/architecture/live-queries.md>`__.

View File

@ -0,0 +1,116 @@
.. meta::
:description: Manage subscriptions on MS SQL Server with Hasura
:keywords: hasura, docs, ms sql server, subscription
.. _ms_sql_server_subscriptions:
MS SQL Server: Subscriptions
============================
.. contents:: Table of contents
:backlinks: none
:depth: 1
:local:
Introduction
------------
A GraphQL subscription is essentially a query where the client receives an update whenever the value of any field
changes upstream.
Subscriptions are supported for all kinds of queries. All the concepts of
:ref:`queries <ms_sql_server_queries>` hold true for subscriptions as well.
Implementation
--------------
The Hasura GraphQL engine subscriptions are actually **live queries**, i.e. a subscription will return the
latest result of the query being made and not necessarily all the individual events leading up to the result.
By default, updates are delivered to clients every **1 sec**.
.. TODO: DB COMPATIBILITY
See more details on :ref:`subscriptions execution and performance <ms_sql_server_subscriptions_execution_and_performance>`.
Convert a query to a subscription
---------------------------------
You can turn any query into a subscription by simply replacing ``query`` with ``subscription`` as the operation type.
.. admonition:: Caveat
Hasura follows the `GraphQL spec <https://graphql.github.io/graphql-spec/June2018/#sec-Single-root-field>`__ which
allows for only one root field in a subscription.
Use cases
---------
- :ref:`ms_sql_server_subscribe_field`
- :ref:`ms_sql_server_subscribe_table`
- :ref:`ms_sql_server_subscribe_derived`
Communication protocol
----------------------
Hasura GraphQL engine uses the `GraphQL over WebSocket Protocol
<https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md>`__ by the
`apollographql/subscriptions-transport-ws <https://github.com/apollographql/subscriptions-transport-ws>`__ library
for sending and receiving events.
.. admonition:: Setting headers for subscriptions with Apollo client
If you are using Apollo Client, headers can be passed to a subscription by setting ``connectionParams`` while
`creating the wsLink <https://www.apollographql.com/docs/react/data/subscriptions/#client-setup>`_:
.. code-block:: js
:emphasize-lines: 6-8
// Create a WebSocket link:
const wsLink = new WebSocketLink({
uri: `<graphql-endpoint>`,
options: {
reconnect: true,
connectionParams: {
headers: {headers-object}
}
}
});
See `this <https://www.apollographql.com/docs/react/data/subscriptions/#authentication-over-websocket>`__ for more
info on using ``connectionParams``.
Cookies and WebSockets
----------------------
The Hasura GraphQL engine will read cookies sent by the browser when initiating a
WebSocket connection. The browser will send the cookie only if it is a secure cookie
(``secure`` flag in the cookie) and if the cookie has a ``HttpOnly`` flag.
Hasura will read this cookie and use it as headers when resolving authorization
(i.e. when resolving the auth webhook).
Cookies, WebSockets and CORS
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
As browsers don't enforce Same Origin Policy (SOP) for websockets, the Hasura server
enforces the CORS rules when accepting the websocket connection.
It uses the provided CORS configuration (as per :ref:`configure-cors`).
1. When it is ``*``, the cookie is read and the CORS check is not enforced.
2. When there are explicit domains, the cookie will only be read if the request originates from one of
the listed domains.
3. If CORS is disabled, the default behaviour is that the cookie won't be read
(because of potential security issues). To override the behaviour, you can
use the flag ``--ws-read-cookie`` or the environment variable
``HASURA_GRAPHQL_WS_READ_COOKIE``. See
:ref:`server_flag_reference` for the setting.
.. toctree::
:maxdepth: 1
:hidden:
Sample use cases <use-cases>
.. Execution and performance <execution-and-performance>

View File

@ -0,0 +1,294 @@
.. meta::
:description: Use cases for Hasura subscriptions
:keywords: hasura, docs, subscription, use case
.. _ms_sql_server_subscription_use_cases:
Subscriptions sample use cases
==============================
.. contents:: Table of contents
:backlinks: none
:depth: 1
:local:
Introduction
------------
The following are a few use cases for using subscriptions:
.. _ms_sql_server_subscribe_field:
Subscribe to the latest value of a particular field
---------------------------------------------------
In case you are interested only in the latest value of a particular field, you can use subscriptions to fetch the
field and get updated with its latest value whenever it changes.
Example: Live location tracking
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Use subscriptions to show the current location of a vehicle on a map.
Let's say we have the following database schema:
.. code-block:: sql
vehicle (
id INT PRIMARY KEY,
vehicle_number TEXT
)
vehicle_location (
id INT PRIMARY KEY,
location TEXT,
timestamp TIMESTAMP,
/* used to create relationship 'locations' for vehicle */
vehicle_id INT FOREIGN KEY REFERENCES vehicle(id)
)
Now we can use the following subscription to fetch the latest location of a vehicle to display it on a map:
.. graphiql::
:view_only:
:query:
# $vehicleId = 3
subscription getLocation($vehicleId: Int!) {
vehicle(where: {id: {_eq: $vehicleId}}) {
id
vehicle_number
locations(order_by: {timestamp: desc}, limit: 1) {
location
timestamp
}
}
}
:response:
{
"data": {
"vehicle": [
{
"id": 3,
"vehicle_number": "KA04AD4583",
"locations": [
{
"location": "(12.93623,77.61701)",
"timestamp": "2018-09-05T06:52:44.383588+00:00"
}
]
}
]
}
}
Check this `sample app <https://realtime-location-tracking.demo.hasura.app/>`__ for a working demo
(`source code <https://github.com/hasura/graphql-engine/tree/master/community/sample-apps/realtime-location-tracking>`__).
.. _ms_sql_server_subscribe_table:
Subscribe to changes to a table's entries
-----------------------------------------
In case you are interested in all the additions/changes to a table's entries, you can use subscriptions to fetch the
table rows and get updates whenever there are any additions/changes to the table.
Example: Chat app
^^^^^^^^^^^^^^^^^
Use subscriptions to show new messages in a chatroom.
Let's say we have the following database schema:
.. code-block:: sql
user (
id INT PRIMARY KEY,
username TEXT UNIQUE
)
message (
id INT PRIMARY KEY,
text TEXT,
timestamp TIMESTAMP,
/* used to create relationship 'author' for message */
user_id INT FOREIGN KEY REFERENCES user(id)
)
Now we can use the following subscription to display the latest messages in a chatroom:
.. graphiql::
:view_only:
:query:
subscription getMessages {
message(order_by: {timestamp: desc}) {
text
timestamp
author {
username
}
}
}
:response:
{
"data": {
"message": [
{
"text": "I am fine.",
"timestamp": "2018-09-05T10:52:23.522223+00:00",
"author": {
"username": "Jane"
}
},
{
"text": "Hi! How are you?",
"timestamp": "2018-09-05T10:52:04.75283+00:00",
"author": {
"username": "Jose"
},
},
{
"text": "Hi!",
"timestamp": "2018-09-05T10:51:43.622839+00:00",
"author": {
"username": "Jane"
}
}
]
}
}
Check this `sample app <https://realtime-chat.demo.hasura.app/>`__ for a working demo
(`source code <https://github.com/hasura/graphql-engine/tree/master/community/sample-apps/realtime-chat>`__).
.. _ms_sql_server_subscribe_derived:
Subscribe to the latest value of some derived data
--------------------------------------------------
In case you are interested in the latest value of some derived data, you can :ref:`create a view to query the derived
data <ms_sql_server_custom_views>` and then use subscriptions to fetch the derived value and get its latest value
whenever it updates.
Example: A poll dashboard
^^^^^^^^^^^^^^^^^^^^^^^^^
Use subscriptions to show the result of a poll.
Let's say we have the following database schema:
.. code-block:: sql
poll (
id INT PRIMARY KEY,
question TEXT
)
option (
id INT PRIMARY KEY
poll_id INT FOREIGN KEY REFERENCES poll(id)
text TEXT
)
user (
id INT PRIMARY KEY
name TEXT
)
vote (
id INT PRIMARY KEY,
option_id INT FOREIGN KEY REFERENCES option(id),
user_id INT FOREIGN KEY REFERENCES user(id),
timestamp TIMESTAMP
)
First, create a view ``poll_results`` to give the result of the poll:
.. code-block:: sql
CREATE OR REPLACE VIEW public."poll_results" AS
SELECT poll.id AS poll_id,
o.option_id,
count(*) AS votes
FROM (
(
SELECT vote.option_id,
option.poll_id,
option.text
FROM (
vote
LEFT JOIN option ON ((option.id = vote.option_id))
)
) o
LEFT JOIN poll ON ((poll.id = o.poll_id))
)
GROUP BY poll.question, o.option_id, poll.id;
This view will have the following fields: ``poll_id``, ``option_id`` and ``votes``, i.e. it gives the number of votes
received by each option for a poll.
Next, :ref:`set up relationships <ms_sql_server_table_relationships>` ``poll`` and ``option`` between the ``poll_results`` view
and the ``poll`` and ``option`` tables using the ``poll_id`` and ``option_id`` fields respectively.
Now we can use the following subscription to display the latest poll result:
.. graphiql::
:view_only:
:query:
# $pollId = 1
subscription getResult($pollId: Int!) {
poll_results (
where: { poll_id: {_eq: $pollId} }
) {
poll_id
option {
text
}
votes
}
}
:response:
{
"data": {
"poll_results": [
{
"poll_id": 1,
"votes": 1,
"option": {
"text": "Pizza"
}
},
{
"poll_id": 1,
"votes": 1,
"option": {
"text": "Salad"
}
},
{
"poll_id": 1,
"votes": 2,
"option": {
"text": "Sandwich"
}
},
{
"poll_id": 1,
"votes": 3,
"option": {
"text": "Burger"
}
},
{
"poll_id": 1,
"votes": 1,
"option": {
"text": "Lasagna"
}
}
]
}
}
Check this `sample app <https://realtime-poll.demo.hasura.app/>`__ for a working demo
(`source code <https://github.com/hasura/graphql-engine/tree/master/community/sample-apps/realtime-poll>`__).

View File

@ -36,7 +36,7 @@ Postgres constructs.
Default field values <default-values/index>
Enum type fields <enums>
Computed fields <computed-fields>
Customise auto-generated field <custom-field-names>
Customise auto-generated fields <custom-field-names>
Data validations <data-validations>
Using an existing database <using-existing-database>
Relay schema <relay-schema>

View File

@ -44,7 +44,7 @@ Get started using an existing database
.. admonition:: MS SQL Server support (alpha)
Hasura GraphQL engine supports **SQL server 2016 and above**. Head to :ref:`this guide <database_ms-sql-server>`
Hasura GraphQL engine supports **SQL server 2016 and above**. Head to :ref:`this guide <database_ms_sql_server>`
to get started with SQL Server.
.. admonition:: MySQL support (alpha)

Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB