{-# LANGUAGE OverloadedStrings #-}

module Arbiter.Core.Array
  ( -- * Array Formatting
    fmtArray
  , fmtNullableArray
  ) where

import Data.ByteString (ByteString)
import Database.PostgreSQL.Simple.Arrays qualified as PSA

-- | Format a list of values as a PostgreSQL array literal.
fmtArray :: [ByteString] -> ByteString
fmtArray :: [ByteString] -> ByteString
fmtArray = Char -> ArrayFormat -> ByteString
PSA.fmt Char
',' (ArrayFormat -> ByteString)
-> ([ByteString] -> ArrayFormat) -> [ByteString] -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [ArrayFormat] -> ArrayFormat
PSA.Array ([ArrayFormat] -> ArrayFormat)
-> ([ByteString] -> [ArrayFormat]) -> [ByteString] -> ArrayFormat
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ByteString -> ArrayFormat) -> [ByteString] -> [ArrayFormat]
forall a b. (a -> b) -> [a] -> [b]
map ByteString -> ArrayFormat
PSA.Quoted

-- | Format a nullable list as a PostgreSQL array literal (Nothing becomes NULL).
fmtNullableArray :: [Maybe ByteString] -> ByteString
fmtNullableArray :: [Maybe ByteString] -> ByteString
fmtNullableArray = Char -> ArrayFormat -> ByteString
PSA.fmt Char
',' (ArrayFormat -> ByteString)
-> ([Maybe ByteString] -> ArrayFormat)
-> [Maybe ByteString]
-> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [ArrayFormat] -> ArrayFormat
PSA.Array ([ArrayFormat] -> ArrayFormat)
-> ([Maybe ByteString] -> [ArrayFormat])
-> [Maybe ByteString]
-> ArrayFormat
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Maybe ByteString -> ArrayFormat)
-> [Maybe ByteString] -> [ArrayFormat]
forall a b. (a -> b) -> [a] -> [b]
map Maybe ByteString -> ArrayFormat
toElement
  where
    toElement :: Maybe ByteString -> ArrayFormat
toElement Maybe ByteString
Nothing = ByteString -> ArrayFormat
PSA.Plain ByteString
"NULL"
    toElement (Just ByteString
bs) = ByteString -> ArrayFormat
PSA.Quoted ByteString
bs