2022-03-16 03:39:21 +03:00
|
|
|
{-# LANGUAGE TemplateHaskell #-}
|
|
|
|
|
2021-08-04 14:42:24 +03:00
|
|
|
module Hasura.Backends.MySQL.SQL
|
2021-09-24 01:56:37 +03:00
|
|
|
( runSQL,
|
|
|
|
RunSQL (..),
|
2021-08-04 14:42:24 +03:00
|
|
|
)
|
|
|
|
where
|
2021-07-21 13:22:03 +03:00
|
|
|
|
2021-09-24 01:56:37 +03:00
|
|
|
import Data.Aeson qualified as J
|
|
|
|
import Data.Aeson.TH
|
|
|
|
import Data.ByteString hiding (null, reverse)
|
|
|
|
import Data.Pool (withResource)
|
|
|
|
import Data.String (fromString)
|
|
|
|
import Data.Text qualified as T
|
|
|
|
import Data.Text.Encoding (decodeUtf8With)
|
|
|
|
import Data.Text.Encoding.Error (lenientDecode)
|
|
|
|
import Database.MySQL.Base (fetchFields, query, storeResult)
|
|
|
|
import Database.MySQL.Base.Types (Field (fieldName))
|
|
|
|
import Hasura.Backends.MySQL.Connection (fetchAllRows)
|
|
|
|
import Hasura.Backends.MySQL.Types (SourceConfig (..))
|
|
|
|
import Hasura.Base.Error
|
|
|
|
import Hasura.EncJSON
|
|
|
|
import Hasura.Prelude
|
|
|
|
import Hasura.RQL.DDL.Schema (RunSQLRes (..))
|
2022-04-27 16:57:28 +03:00
|
|
|
import Hasura.RQL.Types.Common
|
|
|
|
import Hasura.RQL.Types.Metadata
|
|
|
|
import Hasura.RQL.Types.SchemaCache
|
|
|
|
import Hasura.RQL.Types.SchemaCache.Build
|
|
|
|
import Hasura.SQL.Backend
|
2021-09-24 01:56:37 +03:00
|
|
|
|
|
|
|
data RunSQL = RunSQL
|
2022-07-29 17:05:03 +03:00
|
|
|
{ _Sql :: Text,
|
|
|
|
_Source :: SourceName
|
2021-09-24 01:56:37 +03:00
|
|
|
}
|
|
|
|
deriving (Show, Eq)
|
2021-08-04 14:42:24 +03:00
|
|
|
|
2021-07-21 13:22:03 +03:00
|
|
|
$(deriveJSON hasuraJSON ''RunSQL)
|
|
|
|
|
|
|
|
runSQL :: (MonadIO m, CacheRWM m, MonadError QErr m, MetadataM m) => RunSQL -> m EncJSON
|
|
|
|
runSQL (RunSQL sql source) = do
|
|
|
|
pool <- scConnectionPool <$> askSourceConfig @'MySQL source
|
2021-09-24 01:56:37 +03:00
|
|
|
result :: [[Maybe ByteString]] <- liftIO $
|
|
|
|
withResource pool $ \conn -> do
|
|
|
|
query conn (fromString . T.unpack $ sql)
|
|
|
|
r <- storeResult conn
|
|
|
|
fieldNames <- fmap (Just . fieldName) <$> fetchFields r -- fieldNames as Maybes for convenience
|
|
|
|
rows <- fetchAllRows r
|
|
|
|
pure (fieldNames : rows)
|
2021-07-21 13:22:03 +03:00
|
|
|
pure . encJFromJValue $
|
|
|
|
if null result
|
|
|
|
then RunSQLRes "CommandOK" J.Null
|
|
|
|
else RunSQLRes "TuplesOk" . J.toJSON . (fmap . fmap . fmap) (decodeUtf8With lenientDecode) $ result
|