graphql-engine/server/src-lib/Hasura/RQL/DML/Update.hs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

233 lines
7.0 KiB
Haskell
Raw Normal View History

module Hasura.RQL.DML.Update
( runUpdate,
)
where
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.Aeson.Types
import Data.HashMap.Strict qualified as M
import Data.HashMap.Strict qualified as Map
import Data.Sequence qualified as DS
import Data.Text.Extended
import Database.PG.Query qualified as Q
import Hasura.Backends.Postgres.Connection
import Hasura.Backends.Postgres.Execute.Mutation
import Hasura.Backends.Postgres.SQL.DML qualified as S
import Hasura.Backends.Postgres.SQL.Types
import Hasura.Backends.Postgres.Translate.Returning
import Hasura.Backends.Postgres.Types.Table
import Hasura.Backends.Postgres.Types.Update
import Hasura.Base.Error
import Hasura.EncJSON
import Hasura.Prelude
import Hasura.QueryTags
import Hasura.RQL.DML.Internal
import Hasura.RQL.DML.Types
import Hasura.RQL.IR.BoolExp
import Hasura.RQL.IR.Update
import Hasura.RQL.Types.Column
import Hasura.RQL.Types.Common
import Hasura.RQL.Types.Metadata
import Hasura.RQL.Types.Permission
import Hasura.RQL.Types.SchemaCache
import Hasura.RQL.Types.Table
import Hasura.SQL.Backend
import Hasura.SQL.Types
import Hasura.Server.Types
import Hasura.Session
import Hasura.Tracing qualified as Tracing
convInc ::
(QErrM m) =>
ValueParser ('Postgres 'Vanilla) m S.SQLExp ->
PGCol ->
ColumnType ('Postgres 'Vanilla) ->
Value ->
m (PGCol, S.SQLExp)
2018-06-27 16:11:32 +03:00
convInc f col colType val = do
prepExp <- f (CollectableTypeScalar colType) val
return (col, S.SEOpApp S.incOp [S.mkSIdenExp col, prepExp])
2018-06-27 16:11:32 +03:00
convMul ::
(QErrM m) =>
ValueParser ('Postgres 'Vanilla) m S.SQLExp ->
PGCol ->
ColumnType ('Postgres 'Vanilla) ->
Value ->
m (PGCol, S.SQLExp)
2018-06-27 16:11:32 +03:00
convMul f col colType val = do
prepExp <- f (CollectableTypeScalar colType) val
return (col, S.SEOpApp S.mulOp [S.mkSIdenExp col, prepExp])
2018-06-27 16:11:32 +03:00
convSet ::
(QErrM m) =>
ValueParser ('Postgres 'Vanilla) m S.SQLExp ->
PGCol ->
ColumnType ('Postgres 'Vanilla) ->
Value ->
m (PGCol, S.SQLExp)
2018-06-27 16:11:32 +03:00
convSet f col colType val = do
prepExp <- f (CollectableTypeScalar colType) val
2018-06-27 16:11:32 +03:00
return (col, prepExp)
convDefault :: (Monad m) => PGCol -> ColumnType ('Postgres 'Vanilla) -> () -> m (PGCol, S.SQLExp)
2018-06-27 16:11:32 +03:00
convDefault col _ _ = return (col, S.SEUnsafe "DEFAULT")
convOp ::
(UserInfoM m, QErrM m) =>
FieldInfoMap (FieldInfo ('Postgres 'Vanilla)) ->
[PGCol] ->
UpdPermInfo ('Postgres 'Vanilla) ->
[(PGCol, a)] ->
(PGCol -> ColumnType ('Postgres 'Vanilla) -> a -> m (PGCol, S.SQLExp)) ->
m [(PGCol, S.SQLExp)]
convOp fieldInfoMap preSetCols updPerm objs conv =
2018-06-27 16:11:32 +03:00
forM objs $ \(pgCol, a) -> do
-- if column has predefined value then throw error
when (pgCol `elem` preSetCols) $ throwNotUpdErr pgCol
checkPermOnCol PTUpdate allowedCols pgCol
colType <- askColumnType fieldInfoMap pgCol relWhenPgErr
2018-06-27 16:11:32 +03:00
res <- conv pgCol colType a
-- build a set expression's entry
withPathK (getPGColTxt pgCol) $ return res
where
allowedCols = upiCols updPerm
2018-06-27 16:11:32 +03:00
relWhenPgErr = "relationships can't be updated"
throwNotUpdErr c = do
backend only insert permissions (rfc #4120) (#4224) * move user info related code to Hasura.User module * the RFC #4120 implementation; insert permissions with admin secret * revert back to old RoleName based schema maps An attempt made to avoid duplication of schema contexts in types if any role doesn't possess any admin secret specific schema * fix compile errors in haskell test * keep 'user_vars' for session variables in http-logs * no-op refacto * tests for admin only inserts * update docs for admin only inserts * updated CHANGELOG.md * default behaviour when admin secret is not set * fix x-hasura-role to X-Hasura-Role in pytests * introduce effective timeout in actions async tests * update docs for admin-secret not configured case * Update docs/graphql/manual/api-reference/schema-metadata-api/permission.rst Co-Authored-By: Marion Schleifer <marion@hasura.io> * Apply suggestions from code review Co-Authored-By: Marion Schleifer <marion@hasura.io> * a complete iteration backend insert permissions accessable via 'x-hasura-backend-privilege' session variable * console changes for backend-only permissions * provide tooltip id; update labels and tooltips; * requested changes * requested changes - remove className from Toggle component - use appropriate function name (capitalizeFirstChar -> capitalize) * use toggle props from definitelyTyped * fix accidental commit * Revert "introduce effective timeout in actions async tests" This reverts commit b7a59c19d643520cfde6af579889e1038038438a. * generate complete schema for both 'default' and 'backend' sessions * Apply suggestions from code review Co-Authored-By: Marion Schleifer <marion@hasura.io> * remove unnecessary import, export Toggle as is * update session variable in tooltip * 'x-hasura-use-backend-only-permissions' variable to switch * update help texts * update docs * update docs * update console help text * regenerate package-lock * serve no backend schema when backend_only: false and header set to true - Few type name refactor as suggested by @0x777 * update CHANGELOG.md * Update CHANGELOG.md * Update CHANGELOG.md * fix a merge bug where a certain entity didn't get removed Co-authored-by: Marion Schleifer <marion@hasura.io> Co-authored-by: Rishichandra Wawhal <rishi@hasura.io> Co-authored-by: rikinsk <rikin.kachhia@gmail.com> Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
2020-04-24 12:10:53 +03:00
roleName <- _uiRole <$> askUserInfo
throw400 NotSupported $
"column " <> c <<> " is not updatable"
<> " for role "
<> roleName <<> "; its value is predefined in permission"
validateUpdateQueryWith ::
(UserInfoM m, QErrM m, TableInfoRM ('Postgres 'Vanilla) m) =>
SessionVariableBuilder m ->
ValueParser ('Postgres 'Vanilla) m S.SQLExp ->
UpdateQuery ->
m (AnnotatedUpdate ('Postgres 'Vanilla))
2019-04-17 12:48:41 +03:00
validateUpdateQueryWith sessVarBldr prepValBldr uq = do
2018-06-27 16:11:32 +03:00
let tableName = uqTable uq
tableInfo <- withPathK "table" $ askTableInfoSource tableName
let coreInfo = _tiCoreInfo tableInfo
2018-06-27 16:11:32 +03:00
-- If it is view then check if it is updatable
mutableView
tableName
viIsUpdatable
(_tciViewInfo coreInfo)
"updatable"
2018-06-27 16:11:32 +03:00
-- Check if the role has update permissions
updPerm <- askUpdPermInfo tableInfo
-- Check if all dependent headers are present
validateHeaders $ upiRequiredHeaders updPerm
-- Check if select is allowed
selPerm <-
modifyErr (<> selNecessaryMsg) $
askSelPermInfo tableInfo
2018-06-27 16:11:32 +03:00
let fieldInfoMap = _tciFieldInfoMap coreInfo
allCols = getCols fieldInfoMap
preSetObj = upiSet updPerm
preSetCols = M.keys preSetObj
2018-06-27 16:11:32 +03:00
-- convert the object to SQL set expression
setItems <-
withPathK "$set" $
convOp fieldInfoMap preSetCols updPerm (M.toList $ uqSet uq) $ convSet prepValBldr
2018-06-27 16:11:32 +03:00
incItems <-
withPathK "$inc" $
convOp fieldInfoMap preSetCols updPerm (M.toList $ uqInc uq) $ convInc prepValBldr
2018-06-27 16:11:32 +03:00
mulItems <-
withPathK "$mul" $
convOp fieldInfoMap preSetCols updPerm (M.toList $ uqMul uq) $ convMul prepValBldr
2018-06-27 16:11:32 +03:00
defItems <-
withPathK "$default" $
convOp fieldInfoMap preSetCols updPerm ((,()) <$> uqDefault uq) convDefault
2018-06-27 16:11:32 +03:00
-- convert the returning cols into sql returing exp
mAnnRetCols <- forM mRetCols $ \retCols ->
withPathK "returning" $ checkRetCols fieldInfoMap selPerm retCols
2018-06-27 16:11:32 +03:00
resolvedPreSetItems <-
M.toList
<$> mapM (convPartialSQLExp sessVarBldr) preSetObj
2019-04-17 12:48:41 +03:00
let setExpItems =
resolvedPreSetItems
++ setItems
++ incItems
++ mulItems
++ defItems
2018-06-27 16:11:32 +03:00
when (null setExpItems) $
throw400 UnexpectedPayload "atleast one of $set, $inc, $mul has to be present"
-- convert the where clause
annSQLBoolExp <-
withPathK "where" $
convBoolExp fieldInfoMap selPerm (uqWhere uq) sessVarBldr tableName prepValBldr
resolvedUpdFltr <-
convAnnBoolExpPartialSQL sessVarBldr $
upiFilter updPerm
resolvedUpdCheck <-
fromMaybe gBoolExpTrue
<$> traverse
(convAnnBoolExpPartialSQL sessVarBldr)
(upiCheck updPerm)
return $
AnnotatedUpdateG
tableName
(resolvedUpdFltr, annSQLBoolExp)
resolvedUpdCheck
(BackendUpdate $ Map.fromList $ fmap UpdateSet <$> setExpItems)
(mkDefaultMutFlds mAnnRetCols)
allCols
2018-06-27 16:11:32 +03:00
where
mRetCols = uqReturning uq
selNecessaryMsg =
"; \"update\" is only allowed if the role "
<> "has \"select\" permission as \"where\" can't be used "
<> "without \"select\" permission on the table"
2018-06-27 16:11:32 +03:00
validateUpdateQuery ::
(QErrM m, UserInfoM m, CacheRM m) =>
UpdateQuery ->
m (AnnotatedUpdate ('Postgres 'Vanilla), DS.Seq Q.PrepArg)
validateUpdateQuery query = do
let source = uqSource query
tableCache :: TableCache ('Postgres 'Vanilla) <- fold <$> askTableCache source
flip runTableCacheRT (source, tableCache) $
runDMLP1T $
validateUpdateQueryWith sessVarFromCurrentSetting (valueParserWithCollectableType binRHSBuilder) query
runUpdate ::
forall m.
( QErrM m,
UserInfoM m,
CacheRM m,
HasServerConfigCtx m,
MonadBaseControl IO m,
MonadIO m,
Tracing.MonadTrace m,
MetadataM m
) =>
UpdateQuery ->
m EncJSON
server: support remote relationships on SQL Server and BigQuery (#1497) Remote relationships are now supported on SQL Server and BigQuery. The major change though is the re-architecture of remote join execution logic. Prior to this PR, each backend is responsible for processing the remote relationships that are part of their AST. This is not ideal as there is nothing specific about a remote join's execution that ties it to a backend. The only backend specific part is whether or not the specification of the remote relationship is valid (i.e, we'll need to validate whether the scalars are compatible). The approach now changes to this: 1. Before delegating the AST to the backend, we traverse the AST, collect all the remote joins while modifying the AST to add necessary join fields where needed. 1. Once the remote joins are collected from the AST, the database call is made to fetch the response. The necessary data for the remote join(s) is collected from the database's response and one or more remote schema calls are constructed as necessary. 1. The remote schema calls are then executed and the data from the database and from the remote schemas is joined to produce the final response. ### Known issues 1. Ideally the traversal of the IR to collect remote joins should return an AST which does not include remote join fields. This operation can be type safe but isn't taken up as part of the PR. 1. There is a lot of code duplication between `Transport/HTTP.hs` and `Transport/Websocket.hs` which needs to be fixed ASAP. This too hasn't been taken up by this PR. 1. The type which represents the execution plan is only modified to handle our current remote joins and as such it will have to be changed to accommodate general remote joins. 1. Use of lenses would have reduced the boilerplate code to collect remote joins from the base AST. 1. The current remote join logic assumes that the join columns of a remote relationship appear with their names in the database response. This however is incorrect as they could be aliased. This can be taken up by anyone, I've left a comment in the code. ### Notes to the reviewers I think it is best reviewed commit by commit. 1. The first one is very straight forward. 1. The second one refactors the remote join execution logic but other than moving things around, it doesn't change the user facing functionality. This moves Postgres specific parts to `Backends/Postgres` module from `Execute`. Some IR related code to `Hasura.RQL.IR` module. Simplifies various type class function signatures as a backend doesn't have to handle remote joins anymore 1. The third one fixes partial case matches that for some weird reason weren't shown as warnings before this refactor 1. The fourth one generalizes the validation logic of remote relationships and implements `scalarTypeGraphQLName` function on SQL Server and BigQuery which is used by the validation logic. This enables remote relationships on BigQuery and SQL Server. https://github.com/hasura/graphql-engine-mono/pull/1497 GitOrigin-RevId: 77dd8eed326602b16e9a8496f52f46d22b795598
2021-06-11 06:26:50 +03:00
runUpdate q = do
sourceConfig <- askSourceConfig @('Postgres 'Vanilla) (uqSource q)
server: support remote relationships on SQL Server and BigQuery (#1497) Remote relationships are now supported on SQL Server and BigQuery. The major change though is the re-architecture of remote join execution logic. Prior to this PR, each backend is responsible for processing the remote relationships that are part of their AST. This is not ideal as there is nothing specific about a remote join's execution that ties it to a backend. The only backend specific part is whether or not the specification of the remote relationship is valid (i.e, we'll need to validate whether the scalars are compatible). The approach now changes to this: 1. Before delegating the AST to the backend, we traverse the AST, collect all the remote joins while modifying the AST to add necessary join fields where needed. 1. Once the remote joins are collected from the AST, the database call is made to fetch the response. The necessary data for the remote join(s) is collected from the database's response and one or more remote schema calls are constructed as necessary. 1. The remote schema calls are then executed and the data from the database and from the remote schemas is joined to produce the final response. ### Known issues 1. Ideally the traversal of the IR to collect remote joins should return an AST which does not include remote join fields. This operation can be type safe but isn't taken up as part of the PR. 1. There is a lot of code duplication between `Transport/HTTP.hs` and `Transport/Websocket.hs` which needs to be fixed ASAP. This too hasn't been taken up by this PR. 1. The type which represents the execution plan is only modified to handle our current remote joins and as such it will have to be changed to accommodate general remote joins. 1. Use of lenses would have reduced the boilerplate code to collect remote joins from the base AST. 1. The current remote join logic assumes that the join columns of a remote relationship appear with their names in the database response. This however is incorrect as they could be aliased. This can be taken up by anyone, I've left a comment in the code. ### Notes to the reviewers I think it is best reviewed commit by commit. 1. The first one is very straight forward. 1. The second one refactors the remote join execution logic but other than moving things around, it doesn't change the user facing functionality. This moves Postgres specific parts to `Backends/Postgres` module from `Execute`. Some IR related code to `Hasura.RQL.IR` module. Simplifies various type class function signatures as a backend doesn't have to handle remote joins anymore 1. The third one fixes partial case matches that for some weird reason weren't shown as warnings before this refactor 1. The fourth one generalizes the validation logic of remote relationships and implements `scalarTypeGraphQLName` function on SQL Server and BigQuery which is used by the validation logic. This enables remote relationships on BigQuery and SQL Server. https://github.com/hasura/graphql-engine-mono/pull/1497 GitOrigin-RevId: 77dd8eed326602b16e9a8496f52f46d22b795598
2021-06-11 06:26:50 +03:00
userInfo <- askUserInfo
strfyNum <- stringifyNum . _sccSQLGenCtx <$> askServerConfigCtx
validateUpdateQuery q
>>= runTxWithCtx (_pscExecCtx sourceConfig) Q.ReadWrite
. flip runReaderT emptyQueryTagsComment
. execUpdateQuery strfyNum userInfo