2023-02-03 19:27:44 +03:00
|
|
|
-- | Validate native queries against postgres-like flavors.
|
|
|
|
module Hasura.Backends.Postgres.Instances.NativeQueries
|
|
|
|
( validateNativeQuery,
|
|
|
|
)
|
|
|
|
where
|
|
|
|
|
|
|
|
import Data.Aeson (toJSON)
|
2023-02-14 15:14:33 +03:00
|
|
|
import Data.Environment qualified as Env
|
2023-02-08 18:46:09 +03:00
|
|
|
import Data.Text.Extended (toTxt)
|
2023-02-03 19:27:44 +03:00
|
|
|
import Database.PG.Query qualified as PG
|
|
|
|
import Hasura.Backends.Postgres.Connection qualified as PG
|
|
|
|
import Hasura.Backends.Postgres.Connection.Connect (withPostgresDB)
|
|
|
|
import Hasura.Base.Error
|
|
|
|
import Hasura.NativeQuery.Metadata
|
|
|
|
import Hasura.Prelude
|
|
|
|
import Hasura.SQL.Backend
|
|
|
|
|
|
|
|
-- | Prepare a native query against a postgres-like database to validate it.
|
2023-02-15 19:26:16 +03:00
|
|
|
validateNativeQuery :: (MonadIO m, MonadError QErr m) => Env.Environment -> PG.PostgresConnConfiguration -> NativeQueryInfo ('Postgres pgKind) -> m ()
|
2023-02-14 15:14:33 +03:00
|
|
|
validateNativeQuery env connConf nativeQuery = do
|
2023-02-15 19:26:16 +03:00
|
|
|
let name = getNativeQueryName $ nqiRootFieldName nativeQuery
|
2023-02-03 19:27:44 +03:00
|
|
|
let code :: Text
|
|
|
|
code = fold $ flip evalState (1 :: Int) do
|
2023-02-15 19:26:16 +03:00
|
|
|
for (getInterpolatedQuery $ nqiCode nativeQuery) \case
|
2023-02-03 19:27:44 +03:00
|
|
|
IIText t -> pure t
|
|
|
|
IIVariable _v -> do
|
|
|
|
i <- get
|
|
|
|
modify (+ 1)
|
|
|
|
pure $ "$" <> tshow i
|
|
|
|
result <-
|
|
|
|
liftIO $
|
2023-02-14 15:14:33 +03:00
|
|
|
withPostgresDB env connConf $
|
2023-02-03 19:27:44 +03:00
|
|
|
PG.rawQE
|
|
|
|
( \e ->
|
|
|
|
(err400 ValidationFailed "Failed to validate query")
|
|
|
|
{ qeInternal = Just $ ExtraInternal $ toJSON e
|
|
|
|
}
|
|
|
|
)
|
2023-02-08 18:46:09 +03:00
|
|
|
(PG.fromText $ "PREPARE _naqi_vali_" <> toTxt name <> " AS " <> code)
|
2023-02-03 19:27:44 +03:00
|
|
|
[]
|
|
|
|
False
|
|
|
|
case result of
|
|
|
|
-- running the query failed
|
|
|
|
Left err ->
|
2023-02-15 19:26:16 +03:00
|
|
|
throwError err
|
2023-02-03 19:27:44 +03:00
|
|
|
-- running the query succeeded
|
|
|
|
Right () ->
|
|
|
|
pure ()
|