{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DefaultSignatures #-}

-- |
-- Module      : Database.Record.ToSql
-- Copyright   : 2013-2017 Kei Hibino
-- License     : BSD3
--
-- Maintainer  : ex8k.hibino@gmail.com
-- Stability   : experimental
-- Portability : unknown
--
-- This module defines interfaces
-- from Haskell type into list of database value type.
module Database.Record.ToSql (
  -- * Conversion from record type into list of database value type
  ToSqlM, execToSqlM, RecordToSql, runFromRecord, wrapToSql,
  createRecordToSql,

  (<&>),

  -- * Derivation rules of 'RecordToSql' conversion
  ToSql (recordToSql),
  putRecord, putEmpty, fromRecord,

  valueRecordToSql,

  -- * Make parameter list for updating with key
  updateValuesByUnique,
  updateValuesByPrimary,

  untypedUpdateValuesIndex,
  unsafeUpdateValuesWithIndexes,
  ) where

import GHC.Generics (Generic, Rep, U1 (..), K1 (..), M1 (..), (:*:)(..), from)
import Data.Array (listArray, (!))
import Data.Set (toList, fromList, (\\))
import Control.Monad.Trans.Writer (Writer, execWriter, tell)
import Data.DList (DList)
import qualified Data.DList as DList

import Database.Record.Persistable
  (PersistableSqlType, runPersistableNullValue, PersistableType (persistableType),
   PersistableRecordWidth, runPersistableRecordWidth, PersistableWidth(persistableWidth))
import Database.Record.KeyConstraint
  (Primary, Unique, KeyConstraint, HasKeyConstraint(keyConstraint), unique, indexes)


-- | Context type to convert into database value list.
type ToSqlM q a = Writer (DList q) a

-- | extract appended print result of record.
execToSqlM :: ToSqlM q a -> [q]
execToSqlM :: forall q a. ToSqlM q a -> [q]
execToSqlM =  forall a. DList a -> [a]
DList.toList forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall w a. Writer w a -> w
execWriter

{- |
'RecordToSql' 'q' 'a' is data-type wrapping function
to convert from Haskell type 'a' into list of database value type (to send to database) ['q'].

This structure is similar to printer.
While running 'RecordToSql' behavior is the same as list printer.
which appends list of database value type ['q'] stream.
-}
newtype RecordToSql q a = RecordToSql (a -> ToSqlM q ())

runRecordToSql :: RecordToSql q a -> a -> ToSqlM q ()
runRecordToSql :: forall q a. RecordToSql q a -> a -> ToSqlM q ()
runRecordToSql (RecordToSql a -> ToSqlM q ()
f) = a -> ToSqlM q ()
f

-- | Finalize 'RecordToSql' record printer.
wrapToSql :: (a -> ToSqlM q ()) -> RecordToSql q a
wrapToSql :: forall a q. (a -> ToSqlM q ()) -> RecordToSql q a
wrapToSql =  forall q a. (a -> ToSqlM q ()) -> RecordToSql q a
RecordToSql

-- | Run 'RecordToSql' printer function object. Convert from Haskell type 'a' into list of database value type ['q'].
runFromRecord :: RecordToSql q a -- ^ printer function object which has capability to convert
              -> a               -- ^ Haskell type
              -> [q]             -- ^ list of database value
runFromRecord :: forall q a. RecordToSql q a -> a -> [q]
runFromRecord RecordToSql q a
r = forall q a. ToSqlM q a -> [q]
execToSqlM forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall q a. RecordToSql q a -> a -> ToSqlM q ()
runRecordToSql RecordToSql q a
r

-- | Axiom of 'RecordToSql' for database value type 'q' and Haksell type 'a'.
createRecordToSql :: (a -> [q])      -- ^ Convert function body
                  -> RecordToSql q a -- ^ Result printer function object
createRecordToSql :: forall a q. (a -> [q]) -> RecordToSql q a
createRecordToSql a -> [q]
f =  forall a q. (a -> ToSqlM q ()) -> RecordToSql q a
wrapToSql forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
tell forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. [a] -> DList a
DList.fromList forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> [q]
f

-- unsafely map record
mapToSql :: (a -> b) -> RecordToSql q b -> RecordToSql q a
mapToSql :: forall a b q. (a -> b) -> RecordToSql q b -> RecordToSql q a
mapToSql a -> b
f RecordToSql q b
x = forall a q. (a -> ToSqlM q ()) -> RecordToSql q a
wrapToSql forall a b. (a -> b) -> a -> b
$ forall q a. RecordToSql q a -> a -> ToSqlM q ()
runRecordToSql RecordToSql q b
x forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> b
f

-- unsafely put product record
productToSql :: (c -> (a -> b -> ToSqlM q ()) -> ToSqlM q ())
             -> RecordToSql q a -> RecordToSql q b -> RecordToSql q c
productToSql :: forall c a b q.
(c -> (a -> b -> ToSqlM q ()) -> ToSqlM q ())
-> RecordToSql q a -> RecordToSql q b -> RecordToSql q c
productToSql c -> (a -> b -> ToSqlM q ()) -> ToSqlM q ()
run RecordToSql q a
ra RecordToSql q b
rb = forall a q. (a -> ToSqlM q ()) -> RecordToSql q a
wrapToSql forall a b. (a -> b) -> a -> b
$ \c
c -> c -> (a -> b -> ToSqlM q ()) -> ToSqlM q ()
run c
c forall a b. (a -> b) -> a -> b
$ \a
a b
b -> do
  forall q a. RecordToSql q a -> a -> ToSqlM q ()
runRecordToSql RecordToSql q a
ra a
a
  forall q a. RecordToSql q a -> a -> ToSqlM q ()
runRecordToSql RecordToSql q b
rb b
b

-- | Derivation rule of 'RecordToSql' printer function object for Haskell tuple (,) type.
(<&>) :: RecordToSql q a -> RecordToSql q b -> RecordToSql q (a, b)
<&> :: forall q a b.
RecordToSql q a -> RecordToSql q b -> RecordToSql q (a, b)
(<&>) = forall c a b q.
(c -> (a -> b -> ToSqlM q ()) -> ToSqlM q ())
-> RecordToSql q a -> RecordToSql q b -> RecordToSql q c
productToSql forall a b. (a -> b) -> a -> b
$ forall a b c. (a -> b -> c) -> b -> a -> c
flip forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry

-- | Derivation rule of 'RecordToSql' printer function object for Haskell 'Maybe' type.
maybeRecord :: PersistableSqlType q -> PersistableRecordWidth a -> RecordToSql q a -> RecordToSql q (Maybe a)
maybeRecord :: forall q a.
PersistableSqlType q
-> PersistableRecordWidth a
-> RecordToSql q a
-> RecordToSql q (Maybe a)
maybeRecord PersistableSqlType q
qt PersistableRecordWidth a
w RecordToSql q a
ra =  forall a q. (a -> ToSqlM q ()) -> RecordToSql q a
wrapToSql Maybe a -> ToSqlM q ()
d  where
  d :: Maybe a -> ToSqlM q ()
d (Just a
r) = forall q a. RecordToSql q a -> a -> ToSqlM q ()
runRecordToSql RecordToSql q a
ra a
r
  d Maybe a
Nothing  = forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
tell forall a b. (a -> b) -> a -> b
$ forall a. Int -> a -> DList a
DList.replicate (forall a. PersistableRecordWidth a -> Int
runPersistableRecordWidth PersistableRecordWidth a
w) (forall q. PersistableSqlType q -> q
runPersistableNullValue PersistableSqlType q
qt)

infixl 4 <&>

{- |
'ToSql' 'q' 'a' is implicit rule to derive 'RecordToSql' 'q' 'a' record printer function for type 'a'.

Generic programming (<https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#generic-programming>)
with default signature is available for 'ToSql' class,
so you can make instance like below:

@
  \{\-\# LANGUAGE DeriveGeneric \#\-\}
  import GHC.Generics (Generic)
  import Database.HDBC (SqlValue)
  --
  data Foo = Foo { ... } deriving Generic
  instance ToSql SqlValue Foo
@

To make instances of 'ToSql' manually,
'ToSql' 'q' 'a' and 'RecordToSql' 'q 'a' are composable with monadic context.
When, you have data constructor and objects like below.

@
  data MyRecord = MyRecord Foo Bar Baz
@

@
  instance ToSql SqlValue Foo where
    ...
  instance ToSql SqlValue Bar where
    ...
  instance ToSql SqlValue Baz where
    ...
@

You can get composed 'ToSql' implicit rule like below.

@
  instance ToSql SqlValue MyRecord where
    recordToSql =
    recordToSql = wrapToSql $ \\ (MyRecord x y z) -> do
      putRecord x
      putRecord y
      putRecord z
@

-}
class PersistableWidth a => ToSql q a where
  -- | Derived 'RecordToSql' printer function object.
  recordToSql :: RecordToSql q a

  default recordToSql :: (Generic a, GToSql q (Rep a)) => RecordToSql q a
  recordToSql = forall a x. Generic a => a -> Rep a x
from forall a b q. (a -> b) -> RecordToSql q b -> RecordToSql q a
`mapToSql` forall q (f :: * -> *) a. GToSql q f => RecordToSql q (f a)
gToSql

class GToSql q f where
  gToSql :: RecordToSql q (f a)

instance GToSql q U1 where
  gToSql :: forall a. RecordToSql q (U1 a)
gToSql = forall a q. (a -> ToSqlM q ()) -> RecordToSql q a
wrapToSql forall a b. (a -> b) -> a -> b
$ \U1 a
U1 -> forall (m :: * -> *) w. Monad m => w -> WriterT w m ()
tell forall a. DList a
DList.empty

instance (GToSql q a, GToSql q b) => GToSql q (a :*: b) where
  gToSql :: forall a. RecordToSql q ((:*:) a b a)
gToSql = forall c a b q.
(c -> (a -> b -> ToSqlM q ()) -> ToSqlM q ())
-> RecordToSql q a -> RecordToSql q b -> RecordToSql q c
productToSql (\ (a a
a:*:b a
b) a a -> b a -> ToSqlM q ()
f -> a a -> b a -> ToSqlM q ()
f a a
a b a
b) forall q (f :: * -> *) a. GToSql q f => RecordToSql q (f a)
gToSql forall q (f :: * -> *) a. GToSql q f => RecordToSql q (f a)
gToSql

instance GToSql q a => GToSql q (M1 i c a) where
  gToSql :: forall a. RecordToSql q (M1 i c a a)
gToSql = (\(M1 a a
a) -> a a
a) forall a b q. (a -> b) -> RecordToSql q b -> RecordToSql q a
`mapToSql` forall q (f :: * -> *) a. GToSql q f => RecordToSql q (f a)
gToSql

instance ToSql q a => GToSql q (K1 i a) where
  gToSql :: forall a. RecordToSql q (K1 i a a)
gToSql = (\(K1 a
a) -> a
a) forall a b q. (a -> b) -> RecordToSql q b -> RecordToSql q a
`mapToSql` forall q a. ToSql q a => RecordToSql q a
recordToSql


-- | Implicit derivation rule of 'RecordToSql' printer function object which can convert
--   from Haskell 'Maybe' type into list of database value type ['q'].
instance (PersistableType q, ToSql q a) => ToSql q (Maybe a)  where
  recordToSql :: RecordToSql q (Maybe a)
recordToSql = forall q a.
PersistableSqlType q
-> PersistableRecordWidth a
-> RecordToSql q a
-> RecordToSql q (Maybe a)
maybeRecord forall q. PersistableType q => PersistableSqlType q
persistableType forall a. PersistableWidth a => PersistableRecordWidth a
persistableWidth forall q a. ToSql q a => RecordToSql q a
recordToSql

-- | Implicit derivation rule of 'RecordToSql' printer function object which can convert
--   from Haskell unit () type into /empty/ list of database value type ['q'].
instance ToSql q ()  -- default generic instance

-- | Run implicit 'RecordToSql' printer function object.
--   Context to convert haskell record type 'a' into lib of database value type ['q'].
putRecord :: ToSql q a => a -> ToSqlM q ()
putRecord :: forall q a. ToSql q a => a -> ToSqlM q ()
putRecord =  forall q a. RecordToSql q a -> a -> ToSqlM q ()
runRecordToSql forall q a. ToSql q a => RecordToSql q a
recordToSql

-- | Run 'RecordToSql' empty printer.
putEmpty :: () -> ToSqlM q ()
putEmpty :: forall q. () -> ToSqlM q ()
putEmpty =  forall q a. ToSql q a => a -> ToSqlM q ()
putRecord

-- | Run implicit 'RecordToSql' printer function object.
--   Convert from haskell type 'a' into list of database value type ['q'].
fromRecord :: ToSql q a => a -> [q]
fromRecord :: forall q a. ToSql q a => a -> [q]
fromRecord =  forall q a. ToSqlM q a -> [q]
execToSqlM forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall q a. ToSql q a => a -> ToSqlM q ()
putRecord

-- | Derivation rule of 'RecordToSql' printer function object for value convert function.
valueRecordToSql :: (a -> q) -> RecordToSql q a
valueRecordToSql :: forall a q. (a -> q) -> RecordToSql q a
valueRecordToSql = forall a q. (a -> [q]) -> RecordToSql q a
createRecordToSql forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((forall a. a -> [a] -> [a]
:[]) forall b c a. (b -> c) -> (a -> b) -> a -> c
.)

-- | Make untyped indexes to update column from key indexes and record width.
--   Expected by update form like
--
--  @
--   UPDATE /table/ SET /c0/ = ?, /c1/ = ?, /c2/ = ? ... WHERE /key0/ = ? AND /key1/ = ? AND key2 = ? ...
--  @
untypedUpdateValuesIndex :: [Int] -- ^ Key indexes
                         -> Int   -- ^ Record width
                         -> [Int] -- ^ Indexes to update other than key
untypedUpdateValuesIndex :: [Int] -> Int -> [Int]
untypedUpdateValuesIndex [Int]
key Int
width = [Int]
otherThanKey  where
    maxIx :: Int
maxIx = Int
width forall a. Num a => a -> a -> a
- Int
1
    otherThanKey :: [Int]
otherThanKey = forall a. Set a -> [a]
toList forall a b. (a -> b) -> a -> b
$ forall a. Ord a => [a] -> Set a
fromList [Int
0 .. Int
maxIx] forall a. Ord a => Set a -> Set a -> Set a
\\ forall a. Ord a => [a] -> Set a
fromList [Int]
key

-- | Unsafely specify key indexes to convert from Haskell type `ra`
--   into database value `q` list expected by update form like
--
-- @
--   UPDATE /table/ SET /c0/ = ?, /c1/ = ?, /c2/ = ? ... WHERE /key0/ = ? AND /key1/ = ? AND /key2/ = ? ...
-- @
--
--   using 'RecordToSql' printer function object.
unsafeUpdateValuesWithIndexes :: ToSql q ra
                              => [Int]
                              -> ra
                              -> [q]
unsafeUpdateValuesWithIndexes :: forall q ra. ToSql q ra => [Int] -> ra -> [q]
unsafeUpdateValuesWithIndexes [Int]
key ra
a =
  [ Array Int q
valsA forall i e. Ix i => Array i e -> i -> e
! Int
i | Int
i <- [Int]
otherThanKey forall a. [a] -> [a] -> [a]
++ [Int]
key ]  where
    vals :: [q]
vals = forall q a. ToSqlM q a -> [q]
execToSqlM forall a b. (a -> b) -> a -> b
$ forall q a. ToSql q a => a -> ToSqlM q ()
putRecord ra
a
    width :: Int
width = forall (t :: * -> *) a. Foldable t => t a -> Int
length [q]
vals
    valsA :: Array Int q
valsA = forall i e. Ix i => (i, i) -> [e] -> Array i e
listArray (Int
0, Int
width forall a. Num a => a -> a -> a
- Int
1) [q]
vals
    otherThanKey :: [Int]
otherThanKey = [Int] -> Int -> [Int]
untypedUpdateValuesIndex [Int]
key Int
width

-- | Convert from Haskell type `ra` into database value `q` list expected by update form like
--
-- @
--   UPDATE /table/ SET /c0/ = ?, /c1/ = ?, /c2/ = ? ... WHERE /key0/ = ? AND /key1/ = ? AND /key2/ = ? ...
-- @
--
--   using printer function object inferred by ToSql ra q.
updateValuesByUnique :: ToSql q ra
                     => KeyConstraint Unique ra -- ^ Unique key table constraint printer function object.
                     -> ra
                     -> [q]
updateValuesByUnique :: forall q ra. ToSql q ra => KeyConstraint Unique ra -> ra -> [q]
updateValuesByUnique KeyConstraint Unique ra
uk = forall q ra. ToSql q ra => [Int] -> ra -> [q]
unsafeUpdateValuesWithIndexes (forall c r. KeyConstraint c r -> [Int]
indexes KeyConstraint Unique ra
uk)

-- | Convert like 'updateValuesByUnique'' using implicit 'RecordToSql' and 'ColumnConstraint'.
updateValuesByPrimary :: (HasKeyConstraint Primary ra, ToSql q ra)
                      => ra -> [q]
updateValuesByPrimary :: forall ra q. (HasKeyConstraint Primary ra, ToSql q ra) => ra -> [q]
updateValuesByPrimary =  forall q ra. ToSql q ra => KeyConstraint Unique ra -> ra -> [q]
updateValuesByUnique (forall r. PrimaryConstraint r -> UniqueConstraint r
unique forall c a. HasKeyConstraint c a => KeyConstraint c a
keyConstraint)