-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy pathPostgresql.hs
1780 lines (1621 loc) · 69.4 KB
/
Postgresql.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-deprecations #-} -- Pattern match 'PersistDbSpecific'
-- | A postgresql backend for persistent.
module Database.Persist.Postgresql
( withPostgresqlPool
, withPostgresqlPoolWithVersion
, withPostgresqlConn
, withPostgresqlConnWithVersion
, withPostgresqlPoolWithConf
, createPostgresqlPool
, createPostgresqlPoolModified
, createPostgresqlPoolModifiedWithVersion
, createPostgresqlPoolWithConf
, module Database.Persist.Sql
, ConnectionString
, PostgresConf (..)
, PgInterval (..)
, openSimpleConn
, openSimpleConnWithVersion
, tableName
, fieldName
, mockMigration
, migrateEnableExtension
, PostgresConfHooks(..)
, defaultPostgresConfHooks
) where
import qualified Database.PostgreSQL.LibPQ as LibPQ
import qualified Database.PostgreSQL.Simple as PG
import qualified Database.PostgreSQL.Simple.Internal as PG
import qualified Database.PostgreSQL.Simple.FromField as PGFF
import qualified Database.PostgreSQL.Simple.ToField as PGTF
import qualified Database.PostgreSQL.Simple.Transaction as PG
import qualified Database.PostgreSQL.Simple.Types as PG
import qualified Database.PostgreSQL.Simple.TypeInfo.Static as PS
import Database.PostgreSQL.Simple.Ok (Ok (..))
import Control.Arrow
import Control.Exception (Exception, throw, throwIO)
import Control.Monad
import Control.Monad.Except
import Control.Monad.IO.Unlift (MonadIO (..), MonadUnliftIO)
import Control.Monad.Logger (MonadLoggerIO, runNoLoggingT)
import Control.Monad.Trans.Reader (runReaderT)
import Control.Monad.Trans.Writer (WriterT(..), runWriterT)
import qualified Blaze.ByteString.Builder.Char8 as BBB
import Data.Acquire (Acquire, mkAcquire, with)
import Data.Aeson
import Data.Aeson.Types (modifyFailure)
import qualified Data.Attoparsec.Text as AT
import qualified Data.Attoparsec.ByteString.Char8 as P
import Data.Bits ((.&.))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Char8 as B8
import Data.Char (ord)
import Data.Conduit
import qualified Data.Conduit.List as CL
import Data.Data
import Data.Either (partitionEithers)
import Data.Fixed (Fixed(..), Pico)
import Data.Function (on)
import Data.Int (Int64)
import qualified Data.IntMap as I
import Data.IORef
import Data.List (find, sort, groupBy, foldl')
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List as List
import qualified Data.List.NonEmpty as NEL
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid ((<>))
import Data.Pool (Pool)
import Data.String.Conversions.Monomorphic (toStrictByteString)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import Data.Text.Read (rational)
import Data.Time (utc, NominalDiffTime, localTimeToUTC)
import System.Environment (getEnvironment)
import Database.Persist.Sql
import qualified Database.Persist.Sql.Util as Util
-- | A @libpq@ connection string. A simple example of connection
-- string would be @\"host=localhost port=5432 user=test
-- dbname=test password=test\"@. Please read libpq's
-- documentation at
-- <https://www.postgresql.org/docs/current/static/libpq-connect.html>
-- for more details on how to create such strings.
type ConnectionString = ByteString
-- | PostgresServerVersionError exception. This is thrown when persistent
-- is unable to find the version of the postgreSQL server.
data PostgresServerVersionError = PostgresServerVersionError String
instance Show PostgresServerVersionError where
show (PostgresServerVersionError uniqueMsg) =
"Unexpected PostgreSQL server version, got " <> uniqueMsg
instance Exception PostgresServerVersionError
-- | Create a PostgreSQL connection pool and run the given action. The pool is
-- properly released after the action finishes using it. Note that you should
-- not use the given 'ConnectionPool' outside the action since it may already
-- have been released.
-- The provided action should use 'runSqlConn' and *not* 'runReaderT' because
-- the former brackets the database action with transaction begin/commit.
withPostgresqlPool :: (MonadLoggerIO m, MonadUnliftIO m)
=> ConnectionString
-- ^ Connection string to the database.
-> Int
-- ^ Number of connections to be kept open in
-- the pool.
-> (Pool SqlBackend -> m a)
-- ^ Action to be executed that uses the
-- connection pool.
-> m a
withPostgresqlPool ci = withPostgresqlPoolWithVersion getServerVersion ci
-- | Same as 'withPostgresPool', but takes a callback for obtaining
-- the server version (to work around an Amazon Redshift bug).
--
-- @since 2.6.2
withPostgresqlPoolWithVersion :: (MonadUnliftIO m, MonadLoggerIO m)
=> (PG.Connection -> IO (Maybe Double))
-- ^ Action to perform to get the server version.
-> ConnectionString
-- ^ Connection string to the database.
-> Int
-- ^ Number of connections to be kept open in
-- the pool.
-> (Pool SqlBackend -> m a)
-- ^ Action to be executed that uses the
-- connection pool.
-> m a
withPostgresqlPoolWithVersion getVerDouble ci = do
let getVer = oldGetVersionToNew getVerDouble
withSqlPool $ open' (const $ return ()) getVer ci
-- | Same as 'withPostgresqlPool', but can be configured with 'PostgresConf' and 'PostgresConfHooks'.
--
-- @since 2.11.0.0
withPostgresqlPoolWithConf :: (MonadUnliftIO m, MonadLoggerIO m)
=> PostgresConf -- ^ Configuration for connecting to Postgres
-> PostgresConfHooks -- ^ Record of callback functions
-> (Pool SqlBackend -> m a)
-- ^ Action to be executed that uses the
-- connection pool.
-> m a
withPostgresqlPoolWithConf conf hooks = do
let getVer = pgConfHooksGetServerVersion hooks
modConn = pgConfHooksAfterCreate hooks
let logFuncToBackend = open' modConn getVer (pgConnStr conf)
withSqlPoolWithConfig logFuncToBackend (postgresConfToConnectionPoolConfig conf)
-- | Create a PostgreSQL connection pool. Note that it's your
-- responsibility to properly close the connection pool when
-- unneeded. Use 'withPostgresqlPool' for an automatic resource
-- control.
createPostgresqlPool :: (MonadUnliftIO m, MonadLoggerIO m)
=> ConnectionString
-- ^ Connection string to the database.
-> Int
-- ^ Number of connections to be kept open
-- in the pool.
-> m (Pool SqlBackend)
createPostgresqlPool = createPostgresqlPoolModified (const $ return ())
-- | Same as 'createPostgresqlPool', but additionally takes a callback function
-- for some connection-specific tweaking to be performed after connection
-- creation. This could be used, for example, to change the schema. For more
-- information, see:
--
-- <https://groups.google.com/d/msg/yesodweb/qUXrEN_swEo/O0pFwqwQIdcJ>
--
-- @since 2.1.3
createPostgresqlPoolModified
:: (MonadUnliftIO m, MonadLoggerIO m)
=> (PG.Connection -> IO ()) -- ^ Action to perform after connection is created.
-> ConnectionString -- ^ Connection string to the database.
-> Int -- ^ Number of connections to be kept open in the pool.
-> m (Pool SqlBackend)
createPostgresqlPoolModified = createPostgresqlPoolModifiedWithVersion getServerVersion
-- | Same as other similarly-named functions in this module, but takes callbacks for obtaining
-- the server version (to work around an Amazon Redshift bug) and connection-specific tweaking
-- (to change the schema).
--
-- @since 2.6.2
createPostgresqlPoolModifiedWithVersion
:: (MonadUnliftIO m, MonadLoggerIO m)
=> (PG.Connection -> IO (Maybe Double)) -- ^ Action to perform to get the server version.
-> (PG.Connection -> IO ()) -- ^ Action to perform after connection is created.
-> ConnectionString -- ^ Connection string to the database.
-> Int -- ^ Number of connections to be kept open in the pool.
-> m (Pool SqlBackend)
createPostgresqlPoolModifiedWithVersion getVerDouble modConn ci = do
let getVer = oldGetVersionToNew getVerDouble
createSqlPool $ open' modConn getVer ci
-- | Same as 'createPostgresqlPool', but can be configured with 'PostgresConf' and 'PostgresConfHooks'.
--
-- @since 2.11.0.0
createPostgresqlPoolWithConf
:: (MonadUnliftIO m, MonadLoggerIO m)
=> PostgresConf -- ^ Configuration for connecting to Postgres
-> PostgresConfHooks -- ^ Record of callback functions
-> m (Pool SqlBackend)
createPostgresqlPoolWithConf conf hooks = do
let getVer = pgConfHooksGetServerVersion hooks
modConn = pgConfHooksAfterCreate hooks
createSqlPoolWithConfig (open' modConn getVer (pgConnStr conf)) (postgresConfToConnectionPoolConfig conf)
postgresConfToConnectionPoolConfig :: PostgresConf -> ConnectionPoolConfig
postgresConfToConnectionPoolConfig conf =
ConnectionPoolConfig
{ connectionPoolConfigStripes = pgPoolStripes conf
, connectionPoolConfigIdleTimeout = fromInteger $ pgPoolIdleTimeout conf
, connectionPoolConfigSize = pgPoolSize conf
}
-- | Same as 'withPostgresqlPool', but instead of opening a pool
-- of connections, only one connection is opened.
-- The provided action should use 'runSqlConn' and *not* 'runReaderT' because
-- the former brackets the database action with transaction begin/commit.
withPostgresqlConn :: (MonadUnliftIO m, MonadLoggerIO m)
=> ConnectionString -> (SqlBackend -> m a) -> m a
withPostgresqlConn = withPostgresqlConnWithVersion getServerVersion
-- | Same as 'withPostgresqlConn', but takes a callback for obtaining
-- the server version (to work around an Amazon Redshift bug).
--
-- @since 2.6.2
withPostgresqlConnWithVersion :: (MonadUnliftIO m, MonadLoggerIO m)
=> (PG.Connection -> IO (Maybe Double))
-> ConnectionString
-> (SqlBackend -> m a)
-> m a
withPostgresqlConnWithVersion getVerDouble = do
let getVer = oldGetVersionToNew getVerDouble
withSqlConn . open' (const $ return ()) getVer
open'
:: (PG.Connection -> IO ())
-> (PG.Connection -> IO (NonEmpty Word))
-> ConnectionString -> LogFunc -> IO SqlBackend
open' modConn getVer cstr logFunc = do
conn <- PG.connectPostgreSQL cstr
modConn conn
ver <- getVer conn
smap <- newIORef $ Map.empty
return $ createBackend logFunc ver smap conn
-- | Gets the PostgreSQL server version
getServerVersion :: PG.Connection -> IO (Maybe Double)
getServerVersion conn = do
[PG.Only version] <- PG.query_ conn "show server_version";
let version' = rational version
--- λ> rational "9.8.3"
--- Right (9.8,".3")
--- λ> rational "9.8.3.5"
--- Right (9.8,".3.5")
case version' of
Right (a,_) -> return $ Just a
Left err -> throwIO $ PostgresServerVersionError err
getServerVersionNonEmpty :: PG.Connection -> IO (NonEmpty Word)
getServerVersionNonEmpty conn = do
[PG.Only version] <- PG.query_ conn "show server_version";
case AT.parseOnly parseVersion (T.pack version) of
Left err -> throwIO $ PostgresServerVersionError $ "Parse failure on: " <> version <> ". Error: " <> err
Right versionComponents -> case NEL.nonEmpty versionComponents of
Nothing -> throwIO $ PostgresServerVersionError $ "Empty Postgres version string: " <> version
Just neVersion -> pure neVersion
where
-- Partially copied from the `versions` package
-- Typically server_version gives e.g. 12.3
-- In Persistent's CI, we get "12.4 (Debian 12.4-1.pgdg100+1)", so we ignore the trailing data.
parseVersion = AT.decimal `AT.sepBy` AT.char '.'
-- | Choose upsert sql generation function based on postgresql version.
-- PostgreSQL version >= 9.5 supports native upsert feature,
-- so depending upon that we have to choose how the sql query is generated.
-- upsertFunction :: Double -> Maybe (EntityDef -> Text -> Text)
upsertFunction :: a -> NonEmpty Word -> Maybe a
upsertFunction f version = if (version >= postgres9dot5)
then Just f
else Nothing
where
postgres9dot5 :: NonEmpty Word
postgres9dot5 = 9 NEL.:| [5]
-- | If the user doesn't supply a Postgres version, we assume this version.
--
-- This is currently below any version-specific features Persistent uses.
minimumPostgresVersion :: NonEmpty Word
minimumPostgresVersion = 9 NEL.:| [4]
oldGetVersionToNew :: (PG.Connection -> IO (Maybe Double)) -> (PG.Connection -> IO (NonEmpty Word))
oldGetVersionToNew oldFn = \conn -> do
mDouble <- oldFn conn
case mDouble of
Nothing -> pure minimumPostgresVersion
Just double -> do
let (major, minor) = properFraction double
pure $ major NEL.:| [floor minor]
-- | Generate a 'SqlBackend' from a 'PG.Connection'.
openSimpleConn :: LogFunc -> PG.Connection -> IO SqlBackend
openSimpleConn = openSimpleConnWithVersion getServerVersion
-- | Generate a 'SqlBackend' from a 'PG.Connection', but takes a callback for
-- obtaining the server version.
--
-- @since 2.9.1
openSimpleConnWithVersion :: (PG.Connection -> IO (Maybe Double)) -> LogFunc -> PG.Connection -> IO SqlBackend
openSimpleConnWithVersion getVerDouble logFunc conn = do
smap <- newIORef $ Map.empty
serverVersion <- oldGetVersionToNew getVerDouble conn
return $ createBackend logFunc serverVersion smap conn
-- | Create the backend given a logging function, server version, mutable statement cell,
-- and connection.
createBackend :: LogFunc -> NonEmpty Word
-> IORef (Map.Map Text Statement) -> PG.Connection -> SqlBackend
createBackend logFunc serverVersion smap conn = do
SqlBackend
{ connPrepare = prepare' conn
, connStmtMap = smap
, connInsertSql = insertSql'
, connInsertManySql = Just insertManySql'
, connUpsertSql = upsertFunction upsertSql' serverVersion
, connPutManySql = upsertFunction putManySql serverVersion
, connClose = PG.close conn
, connMigrateSql = migrate'
, connBegin = \_ mIsolation -> case mIsolation of
Nothing -> PG.begin conn
Just iso -> PG.beginLevel (case iso of
ReadUncommitted -> PG.ReadCommitted -- PG Upgrades uncommitted reads to committed anyways
ReadCommitted -> PG.ReadCommitted
RepeatableRead -> PG.RepeatableRead
Serializable -> PG.Serializable) conn
, connCommit = const $ PG.commit conn
, connRollback = const $ PG.rollback conn
, connEscapeFieldName = escapeF
, connEscapeTableName = escapeE . entityDB
, connEscapeRawName = escape
, connNoLimit = "LIMIT ALL"
, connRDBMS = "postgresql"
, connLimitOffset = decorateSQLWithLimitOffset "LIMIT ALL"
, connLogFunc = logFunc
, connMaxParams = Nothing
, connRepsertManySql = upsertFunction repsertManySql serverVersion
}
prepare' :: PG.Connection -> Text -> IO Statement
prepare' conn sql = do
let query = PG.Query (T.encodeUtf8 sql)
return Statement
{ stmtFinalize = return ()
, stmtReset = return ()
, stmtExecute = execute' conn query
, stmtQuery = withStmt' conn query
}
insertSql' :: EntityDef -> [PersistValue] -> InsertSqlResult
insertSql' ent vals =
case entityPrimary ent of
Just _pdef -> ISRManyKeys sql vals
Nothing -> ISRSingle (sql <> " RETURNING " <> escapeF (fieldDB (entityId ent)))
where
(fieldNames, placeholders) = unzip (Util.mkInsertPlaceholders ent escapeF)
sql = T.concat
[ "INSERT INTO "
, escapeE $ entityDB ent
, if null (entityFields ent)
then " DEFAULT VALUES"
else T.concat
[ "("
, T.intercalate "," fieldNames
, ") VALUES("
, T.intercalate "," placeholders
, ")"
]
]
upsertSql' :: EntityDef -> NonEmpty (FieldNameHS, FieldNameDB) -> Text -> Text
upsertSql' ent uniqs updateVal =
T.concat
[ "INSERT INTO "
, escapeE (entityDB ent)
, "("
, T.intercalate "," fieldNames
, ") VALUES ("
, T.intercalate "," placeholders
, ") ON CONFLICT ("
, T.intercalate "," $ map (escapeF . snd) (NEL.toList uniqs)
, ") DO UPDATE SET "
, updateVal
, " WHERE "
, wher
, " RETURNING ??"
]
where
(fieldNames, placeholders) = unzip (Util.mkInsertPlaceholders ent escapeF)
wher = T.intercalate " AND " $ map (singleClause . snd) $ NEL.toList uniqs
singleClause :: FieldNameDB -> Text
singleClause field = escapeE (entityDB ent) <> "." <> (escapeF field) <> " =?"
-- | SQL for inserting multiple rows at once and returning their primary keys.
insertManySql' :: EntityDef -> [[PersistValue]] -> InsertSqlResult
insertManySql' ent valss =
ISRSingle sql
where
(fieldNames, placeholders)= unzip (Util.mkInsertPlaceholders ent escapeF)
sql = T.concat
[ "INSERT INTO "
, escapeE (entityDB ent)
, "("
, T.intercalate "," fieldNames
, ") VALUES ("
, T.intercalate "),(" $ replicate (length valss) $ T.intercalate "," placeholders
, ") RETURNING "
, Util.commaSeparated $ Util.dbIdColumnsEsc escapeF ent
]
execute' :: PG.Connection -> PG.Query -> [PersistValue] -> IO Int64
execute' conn query vals = PG.execute conn query (map P vals)
withStmt' :: MonadIO m
=> PG.Connection
-> PG.Query
-> [PersistValue]
-> Acquire (ConduitM () [PersistValue] m ())
withStmt' conn query vals =
pull `fmap` mkAcquire openS closeS
where
openS = do
-- Construct raw query
rawquery <- PG.formatQuery conn query (map P vals)
-- Take raw connection
(rt, rr, rc, ids) <- PG.withConnection conn $ \rawconn -> do
-- Execute query
mret <- LibPQ.exec rawconn rawquery
case mret of
Nothing -> do
merr <- LibPQ.errorMessage rawconn
fail $ case merr of
Nothing -> "Postgresql.withStmt': unknown error"
Just e -> "Postgresql.withStmt': " ++ B8.unpack e
Just ret -> do
-- Check result status
status <- LibPQ.resultStatus ret
case status of
LibPQ.TuplesOk -> return ()
_ -> PG.throwResultError "Postgresql.withStmt': bad result status " ret status
-- Get number and type of columns
cols <- LibPQ.nfields ret
oids <- forM [0..cols-1] $ \col -> fmap ((,) col) (LibPQ.ftype ret col)
-- Ready to go!
rowRef <- newIORef (LibPQ.Row 0)
rowCount <- LibPQ.ntuples ret
return (ret, rowRef, rowCount, oids)
let getters
= map (\(col, oid) -> getGetter conn oid $ PG.Field rt col oid) ids
return (rt, rr, rc, getters)
closeS (ret, _, _, _) = LibPQ.unsafeFreeResult ret
pull x = do
y <- liftIO $ pullS x
case y of
Nothing -> return ()
Just z -> yield z >> pull x
pullS (ret, rowRef, rowCount, getters) = do
row <- atomicModifyIORef rowRef (\r -> (r+1, r))
if row == rowCount
then return Nothing
else fmap Just $ forM (zip getters [0..]) $ \(getter, col) -> do
mbs <- LibPQ.getvalue' ret row col
case mbs of
Nothing ->
-- getvalue' verified that the value is NULL.
-- However, that does not mean that there are
-- no NULL values inside the value (e.g., if
-- we're dealing with an array of optional values).
return PersistNull
Just bs -> do
ok <- PGFF.runConversion (getter mbs) conn
bs `seq` case ok of
Errors (exc:_) -> throw exc
Errors [] -> error "Got an Errors, but no exceptions"
Ok v -> return v
-- | Avoid orphan instances.
newtype P = P PersistValue
instance PGTF.ToField P where
toField (P (PersistText t)) = PGTF.toField t
toField (P (PersistByteString bs)) = PGTF.toField (PG.Binary bs)
toField (P (PersistInt64 i)) = PGTF.toField i
toField (P (PersistDouble d)) = PGTF.toField d
toField (P (PersistRational r)) = PGTF.Plain $
BBB.fromString $
show (fromRational r :: Pico) -- FIXME: Too Ambigous, can not select precision without information about field
toField (P (PersistBool b)) = PGTF.toField b
toField (P (PersistDay d)) = PGTF.toField d
toField (P (PersistTimeOfDay t)) = PGTF.toField t
toField (P (PersistUTCTime t)) = PGTF.toField t
toField (P PersistNull) = PGTF.toField PG.Null
toField (P (PersistList l)) = PGTF.toField $ listToJSON l
toField (P (PersistMap m)) = PGTF.toField $ mapToJSON m
toField (P (PersistDbSpecific s)) = PGTF.toField (Unknown s)
toField (P (PersistLiteral l)) = PGTF.toField (UnknownLiteral l)
toField (P (PersistLiteralEscaped e)) = PGTF.toField (Unknown e)
toField (P (PersistArray a)) = PGTF.toField $ PG.PGArray $ P <$> a
toField (P (PersistObjectId _)) =
error "Refusing to serialize a PersistObjectId to a PostgreSQL value"
-- | Represent Postgres interval using NominalDiffTime
--
-- @since 2.11.0.0
newtype PgInterval = PgInterval { getPgInterval :: NominalDiffTime }
deriving (Eq, Show)
pgIntervalToBs :: PgInterval -> ByteString
pgIntervalToBs = toStrictByteString . show . getPgInterval
instance PGTF.ToField PgInterval where
toField (PgInterval t) = PGTF.toField t
instance PGFF.FromField PgInterval where
fromField f mdata =
if PGFF.typeOid f /= PS.typoid PS.interval
then PGFF.returnError PGFF.Incompatible f ""
else case mdata of
Nothing -> PGFF.returnError PGFF.UnexpectedNull f ""
Just dat -> case P.parseOnly (nominalDiffTime <* P.endOfInput) dat of
Left msg -> PGFF.returnError PGFF.ConversionFailed f msg
Right t -> return $ PgInterval t
where
toPico :: Integer -> Pico
toPico = MkFixed
-- Taken from Database.PostgreSQL.Simple.Time.Internal.Parser
twoDigits :: P.Parser Int
twoDigits = do
a <- P.digit
b <- P.digit
let c2d c = ord c .&. 15
return $! c2d a * 10 + c2d b
-- Taken from Database.PostgreSQL.Simple.Time.Internal.Parser
seconds :: P.Parser Pico
seconds = do
real <- twoDigits
mc <- P.peekChar
case mc of
Just '.' -> do
t <- P.anyChar *> P.takeWhile1 P.isDigit
return $! parsePicos (fromIntegral real) t
_ -> return $! fromIntegral real
where
parsePicos :: Int64 -> B8.ByteString -> Pico
parsePicos a0 t = toPico (fromIntegral (t' * 10^n))
where n = max 0 (12 - B8.length t)
t' = B8.foldl' (\a c -> 10 * a + fromIntegral (ord c .&. 15)) a0
(B8.take 12 t)
parseSign :: P.Parser Bool
parseSign = P.choice [P.char '-' >> return True, return False]
-- Db stores it in [-]HHH:MM:SS.[SSSS]
-- For example, nominalDay is stored as 24:00:00
interval :: P.Parser (Bool, Int, Int, Pico)
interval = do
s <- parseSign
h <- P.decimal <* P.char ':'
m <- twoDigits <* P.char ':'
ss <- seconds
if m < 60 && ss <= 60
then return (s, h, m, ss)
else fail "Invalid interval"
nominalDiffTime :: P.Parser NominalDiffTime
nominalDiffTime = do
(s, h, m, ss) <- interval
let pico = ss + 60 * (fromIntegral m) + 60 * 60 * (fromIntegral (abs h))
return . fromRational . toRational $ if s then (-pico) else pico
fromPersistValueError :: Text -- ^ Haskell type, should match Haskell name exactly, e.g. "Int64"
-> Text -- ^ Database type(s), should appear different from Haskell name, e.g. "integer" or "INT", not "Int".
-> PersistValue -- ^ Incorrect value
-> Text -- ^ Error message
fromPersistValueError haskellType databaseType received = T.concat
[ "Failed to parse Haskell type `"
, haskellType
, "`; expected "
, databaseType
, " from database, but received: "
, T.pack (show received)
, ". Potential solution: Check that your database schema matches your Persistent model definitions."
]
instance PersistField PgInterval where
toPersistValue = PersistLiteralEscaped . pgIntervalToBs
fromPersistValue (PersistDbSpecific bs) = fromPersistValue (PersistLiteralEscaped bs)
fromPersistValue x@(PersistLiteralEscaped bs) =
case P.parseOnly (P.signed P.rational <* P.char 's' <* P.endOfInput) bs of
Left _ -> Left $ fromPersistValueError "PgInterval" "Interval" x
Right i -> Right $ PgInterval i
fromPersistValue x = Left $ fromPersistValueError "PgInterval" "Interval" x
instance PersistFieldSql PgInterval where
sqlType _ = SqlOther "interval"
newtype Unknown = Unknown { unUnknown :: ByteString }
deriving (Eq, Show, Read, Ord)
instance PGFF.FromField Unknown where
fromField f mdata =
case mdata of
Nothing -> PGFF.returnError PGFF.UnexpectedNull f "Database.Persist.Postgresql/PGFF.FromField Unknown"
Just dat -> return (Unknown dat)
instance PGTF.ToField Unknown where
toField (Unknown a) = PGTF.Escape a
newtype UnknownLiteral = UnknownLiteral { unUnknownLiteral :: ByteString }
deriving (Eq, Show, Read, Ord, Typeable)
instance PGFF.FromField UnknownLiteral where
fromField f mdata =
case mdata of
Nothing -> PGFF.returnError PGFF.UnexpectedNull f "Database.Persist.Postgresql/PGFF.FromField UnknownLiteral"
Just dat -> return (UnknownLiteral dat)
instance PGTF.ToField UnknownLiteral where
toField (UnknownLiteral a) = PGTF.Plain $ BB.byteString a
type Getter a = PGFF.FieldParser a
convertPV :: PGFF.FromField a => (a -> b) -> Getter b
convertPV f = (fmap f .) . PGFF.fromField
builtinGetters :: I.IntMap (Getter PersistValue)
builtinGetters = I.fromList
[ (k PS.bool, convertPV PersistBool)
, (k PS.bytea, convertPV (PersistByteString . unBinary))
, (k PS.char, convertPV PersistText)
, (k PS.name, convertPV PersistText)
, (k PS.int8, convertPV PersistInt64)
, (k PS.int2, convertPV PersistInt64)
, (k PS.int4, convertPV PersistInt64)
, (k PS.text, convertPV PersistText)
, (k PS.xml, convertPV (PersistByteString . unUnknown))
, (k PS.float4, convertPV PersistDouble)
, (k PS.float8, convertPV PersistDouble)
, (k PS.money, convertPV PersistRational)
, (k PS.bpchar, convertPV PersistText)
, (k PS.varchar, convertPV PersistText)
, (k PS.date, convertPV PersistDay)
, (k PS.time, convertPV PersistTimeOfDay)
, (k PS.timestamp, convertPV (PersistUTCTime. localTimeToUTC utc))
, (k PS.timestamptz, convertPV PersistUTCTime)
, (k PS.interval, convertPV (PersistLiteralEscaped . pgIntervalToBs))
, (k PS.bit, convertPV PersistInt64)
, (k PS.varbit, convertPV PersistInt64)
, (k PS.numeric, convertPV PersistRational)
, (k PS.void, \_ _ -> return PersistNull)
, (k PS.json, convertPV (PersistByteString . unUnknown))
, (k PS.jsonb, convertPV (PersistByteString . unUnknown))
, (k PS.unknown, convertPV (PersistByteString . unUnknown))
-- Array types: same order as above.
-- The OIDs were taken from pg_type.
, (1000, listOf PersistBool)
, (1001, listOf (PersistByteString . unBinary))
, (1002, listOf PersistText)
, (1003, listOf PersistText)
, (1016, listOf PersistInt64)
, (1005, listOf PersistInt64)
, (1007, listOf PersistInt64)
, (1009, listOf PersistText)
, (143, listOf (PersistByteString . unUnknown))
, (1021, listOf PersistDouble)
, (1022, listOf PersistDouble)
, (1023, listOf PersistUTCTime)
, (1024, listOf PersistUTCTime)
, (791, listOf PersistRational)
, (1014, listOf PersistText)
, (1015, listOf PersistText)
, (1182, listOf PersistDay)
, (1183, listOf PersistTimeOfDay)
, (1115, listOf PersistUTCTime)
, (1185, listOf PersistUTCTime)
, (1187, listOf (PersistLiteralEscaped . pgIntervalToBs))
, (1561, listOf PersistInt64)
, (1563, listOf PersistInt64)
, (1231, listOf PersistRational)
-- no array(void) type
, (2951, listOf (PersistLiteralEscaped . unUnknown))
, (199, listOf (PersistByteString . unUnknown))
, (3807, listOf (PersistByteString . unUnknown))
-- no array(unknown) either
]
where
k (PGFF.typoid -> i) = PG.oid2int i
-- A @listOf f@ will use a @PGArray (Maybe T)@ to convert
-- the values to Haskell-land. The @Maybe@ is important
-- because the usual way of checking NULLs
-- (c.f. withStmt') won't check for NULL inside
-- arrays---or any other compound structure for that matter.
listOf f = convertPV (PersistList . map (nullable f) . PG.fromPGArray)
where nullable = maybe PersistNull
getGetter :: PG.Connection -> PG.Oid -> Getter PersistValue
getGetter _conn oid
= fromMaybe defaultGetter $ I.lookup (PG.oid2int oid) builtinGetters
where defaultGetter = convertPV (PersistLiteralEscaped . unUnknown)
unBinary :: PG.Binary a -> a
unBinary (PG.Binary x) = x
doesTableExist :: (Text -> IO Statement)
-> EntityNameDB
-> IO Bool
doesTableExist getter (EntityNameDB name) = do
stmt <- getter sql
with (stmtQuery stmt vals) (\src -> runConduit $ src .| start)
where
sql = "SELECT COUNT(*) FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog'"
<> " AND schemaname != 'information_schema' AND tablename=?"
vals = [PersistText name]
start = await >>= maybe (error "No results when checking doesTableExist") start'
start' [PersistInt64 0] = finish False
start' [PersistInt64 1] = finish True
start' res = error $ "doesTableExist returned unexpected result: " ++ show res
finish x = await >>= maybe (return x) (error "Too many rows returned in doesTableExist")
migrate' :: [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO (Either [Text] [(Bool, Text)])
migrate' allDefs getter entity = fmap (fmap $ map showAlterDb) $ do
old <- getColumns getter entity newcols'
case partitionEithers old of
([], old'') -> do
exists' <-
if null old
then doesTableExist getter name
else return True
return $ Right $ migrationText exists' old''
(errs, _) -> return $ Left errs
where
name = entityDB entity
(newcols', udefs, fdefs) = postgresMkColumns allDefs entity
migrationText exists' old''
| not exists' =
createText newcols fdefs udspair
| otherwise =
let (acs, ats) =
getAlters allDefs entity (newcols, udspair) old'
acs' = map (AlterColumn name) acs
ats' = map (AlterTable name) ats
in
acs' ++ ats'
where
old' = partitionEithers old''
newcols = filter (not . safeToRemove entity . cName) newcols'
udspair = map udToPair udefs
-- Check for table existence if there are no columns, workaround
-- for https://github.com/yesodweb/persistent/issues/152
createText newcols fdefs_ udspair =
(addTable newcols entity) : uniques ++ references ++ foreignsAlt
where
uniques = flip concatMap udspair $ \(uname, ucols) ->
[AlterTable name $ AddUniqueConstraint uname ucols]
references =
mapMaybe
(\Column { cName, cReference } ->
getAddReference allDefs entity cName =<< cReference
)
newcols
foreignsAlt = mapMaybe (mkForeignAlt entity) fdefs_
mkForeignAlt
:: EntityDef
-> ForeignDef
-> Maybe AlterDB
mkForeignAlt entity fdef = pure $ AlterColumn tableName_ addReference
where
tableName_ = entityDB entity
addReference =
AddReference
(foreignRefTableDBName fdef)
constraintName
childfields
escapedParentFields
(foreignFieldCascade fdef)
constraintName =
foreignConstraintNameDBName fdef
(childfields, parentfields) =
unzip (map (\((_,b),(_,d)) -> (b,d)) (foreignFields fdef))
escapedParentFields =
map escapeF parentfields
addTable :: [Column] -> EntityDef -> AlterDB
addTable cols entity =
AddTable $ T.concat
-- Lower case e: see Database.Persist.Sql.Migration
[ "CREATe TABLE " -- DO NOT FIX THE CAPITALIZATION!
, escapeE name
, "("
, idtxt
, if null nonIdCols then "" else ","
, T.intercalate "," $ map showColumn nonIdCols
, ")"
]
where
nonIdCols =
case entityPrimary entity of
Just _ ->
cols
_ ->
filter (\c -> cName c /= fieldDB (entityId entity) ) cols
name =
entityDB entity
idtxt =
case entityPrimary entity of
Just pdef ->
T.concat
[ " PRIMARY KEY ("
, T.intercalate "," $ map (escapeF . fieldDB) $ compositeFields pdef
, ")"
]
Nothing ->
let defText = defaultAttribute $ fieldAttrs $ entityId entity
sType = fieldSqlType $ entityId entity
in T.concat
[ escapeF $ fieldDB (entityId entity)
, maySerial sType defText
, " PRIMARY KEY UNIQUE"
, mayDefault defText
]
maySerial :: SqlType -> Maybe Text -> Text
maySerial SqlInt64 Nothing = " SERIAL8 "
maySerial sType _ = " " <> showSqlType sType
mayDefault :: Maybe Text -> Text
mayDefault def = case def of
Nothing -> ""
Just d -> " DEFAULT " <> d
type SafeToRemove = Bool
data AlterColumn
= ChangeType Column SqlType Text
| IsNull Column
| NotNull Column
| Add' Column
| Drop Column SafeToRemove
| Default Column Text
| NoDefault Column
| Update' Column Text
| AddReference EntityNameDB ConstraintNameDB [FieldNameDB] [Text] FieldCascade
| DropReference ConstraintNameDB
deriving Show
data AlterTable
= AddUniqueConstraint ConstraintNameDB [FieldNameDB]
| DropConstraint ConstraintNameDB
deriving Show
data AlterDB = AddTable Text
| AlterColumn EntityNameDB AlterColumn
| AlterTable EntityNameDB AlterTable
deriving Show
-- | Returns all of the columns in the given table currently in the database.
getColumns :: (Text -> IO Statement)
-> EntityDef -> [Column]
-> IO [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
getColumns getter def cols = do
let sqlv = T.concat
[ "SELECT "
, "column_name "
, ",is_nullable "
, ",COALESCE(domain_name, udt_name)" -- See DOMAINS below
, ",column_default "
, ",generation_expression "
, ",numeric_precision "
, ",numeric_scale "
, ",character_maximum_length "
, "FROM information_schema.columns "
, "WHERE table_catalog=current_database() "
, "AND table_schema=current_schema() "
, "AND table_name=? "
]
-- DOMAINS Postgres supports the concept of domains, which are data types
-- with optional constraints. An app might make an "email" domain over the
-- varchar type, with a CHECK that the emails are valid In this case the
-- generated SQL should use the domain name: ALTER TABLE users ALTER COLUMN
-- foo TYPE email This code exists to use the domain name (email), instead
-- of the underlying type (varchar). This is tested in
-- EquivalentTypeTest.hs
stmt <- getter sqlv
let vals =
[ PersistText $ unEntityNameDB $ entityDB def
]
columns <- with (stmtQuery stmt vals) (\src -> runConduit $ src .| processColumns .| CL.consume)
let sqlc = T.concat
[ "SELECT "
, "c.constraint_name, "
, "c.column_name "
, "FROM information_schema.key_column_usage AS c, "
, "information_schema.table_constraints AS k "
, "WHERE c.table_catalog=current_database() "
, "AND c.table_catalog=k.table_catalog "
, "AND c.table_schema=current_schema() "
, "AND c.table_schema=k.table_schema "
, "AND c.table_name=? "
, "AND c.table_name=k.table_name "
, "AND c.constraint_name=k.constraint_name "
, "AND NOT k.constraint_type IN ('PRIMARY KEY', 'FOREIGN KEY') "
, "ORDER BY c.constraint_name, c.column_name"
]
stmt' <- getter sqlc
us <- with (stmtQuery stmt' vals) (\src -> runConduit $ src .| helperU)
return $ columns ++ us
where
refMap =
fmap (\cr -> (crTableName cr, crConstraintName cr))
$ Map.fromList
$ foldl' ref [] cols
where
ref rs c =
maybe rs (\r -> (unFieldNameDB $ cName c, r) : rs) (cReference c)
getAll =
CL.mapM $ \x ->
pure $ case x of
[PersistText con, PersistText col] ->
(con, col)
[PersistByteString con, PersistByteString col] ->
(T.decodeUtf8 con, T.decodeUtf8 col)
o ->
error $ "unexpected datatype returned for postgres o="++show o
helperU = do
rows <- getAll .| CL.consume
return $ map (Right . Right . (ConstraintNameDB . fst . head &&& map (FieldNameDB . snd)))
$ groupBy ((==) `on` fst) rows
processColumns =
CL.mapM $ \x'@((PersistText cname) : _) -> do
col <- liftIO $ getColumn getter (entityDB def) x' (Map.lookup cname refMap)
pure $ case col of
Left e -> Left e
Right c -> Right $ Left c
-- | Check if a column name is listed as the "safe to remove" in the entity
-- list.
safeToRemove :: EntityDef -> FieldNameDB -> Bool
safeToRemove def (FieldNameDB colName)
= any (elem FieldAttrSafeToRemove . fieldAttrs)
$ filter ((== FieldNameDB colName) . fieldDB)
$ keyAndEntityFields def
getAlters :: [EntityDef]
-> EntityDef
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])