forked from yesodweb/persistent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInternal.hs
More file actions
1220 lines (1142 loc) · 43.5 KB
/
Internal.hs
File metadata and controls
1220 lines (1142 loc) · 43.5 KB
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 FlexibleContexts #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
module Database.Persist.Postgresql.Internal
( P (..)
, PgInterval (..)
, getGetter
, AlterDB (..)
, AlterTable (..)
, AlterColumn (..)
, SafeToRemove
, migrateStructured
, mockMigrateStructured
, addTable
, findAlters
, maySerial
, mayDefault
, showSqlType
, showColumn
, showAlter
, showAlterDb
, showAlterTable
, getAddReference
, udToPair
, safeToRemove
, postgresMkColumns
, getAlters
, escapeE
, escapeF
, escape
) where
import qualified Database.PostgreSQL.Simple as PG
import qualified Database.PostgreSQL.Simple.FromField as PGFF
import qualified Database.PostgreSQL.Simple.Internal as PG
import qualified Database.PostgreSQL.Simple.Interval as Interval
import qualified Database.PostgreSQL.Simple.ToField as PGTF
import qualified Database.PostgreSQL.Simple.TypeInfo.Static as PS
import qualified Database.PostgreSQL.Simple.Types as PG
import qualified Blaze.ByteString.Builder.Char8 as BBB
import Control.Arrow
import Control.Monad
import Control.Monad.Except
import Control.Monad.IO.Unlift (MonadIO (..))
import Control.Monad.Trans.Class (lift)
import Data.Acquire (with)
import Data.Bits (toIntegralSized)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Builder as BB
import Data.Conduit
import qualified Data.Conduit.List as CL
import Data.Data (Typeable)
import Data.Either (partitionEithers)
import Data.Fixed (Fixed (..), Micro, Pico)
import Data.Function (on)
import qualified Data.IntMap as I
import Data.List as List (find, foldl', groupBy, sort)
import qualified Data.List.NonEmpty as NEL
import qualified Data.Map as Map
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time
( NominalDiffTime
, localTimeToUTC
, nominalDiffTimeToSeconds
, secondsToNominalDiffTime
, utc
)
import Database.Persist.Sql
import qualified Database.Persist.Sql.Util as Util
-- | Newtype used to avoid orphan instances for @postgresql-simple@ classes.
--
-- @since 2.13.2.0
newtype P = P {unP :: 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 (PersistLiteral_ DbSpecific s)) = PGTF.toField (Unknown s)
toField (P (PersistLiteral_ Unescaped l)) = PGTF.toField (UnknownLiteral l)
toField (P (PersistLiteral_ Escaped 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"
instance PGFF.FromField P where
fromField field mdata = fmap P $ case mdata of
-- If we try to simply decode based on oid, we will hit unexpected null
-- errors.
Nothing -> pure PersistNull
data' -> getGetter (PGFF.typeOid field) field data'
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 $ toPersistValue @Interval.Interval)
, (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 $ toPersistValue @Interval.Interval)
, (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
-- | Get the field parser corresponding to the given 'PG.Oid'.
--
-- For example, pass in the 'PG.Oid' of 'PS.bool', and you will get back a
-- field parser which parses boolean values in the table into 'PersistBool's.
--
-- @since 2.13.2.0
getGetter :: PG.Oid -> Getter PersistValue
getGetter oid =
fromMaybe defaultGetter $ I.lookup (PG.oid2int oid) builtinGetters
where
defaultGetter = convertPV (PersistLiteralEscaped . unUnknown)
unBinary :: PG.Binary a -> a
unBinary (PG.Binary x) = x
-- | Represent Postgres interval using NominalDiffTime
--
-- @since 2.11.0.0
--
-- Note that this type cannot be losslessly round tripped through PostgreSQL.
-- For example the value @'PgInterval' 0.0000009@ will truncate extra
-- precision. And the value @'PgInterval' 9223372036854.775808@ will overflow.
-- Use the 'Interval.Interval' type if that is a problem for you.
newtype PgInterval = PgInterval {getPgInterval :: NominalDiffTime}
deriving (Eq, Show)
instance PGTF.ToField PgInterval where
toField = PGTF.toField . pgIntervalToInterval
instance PGFF.FromField PgInterval where
fromField f =
maybe (PGFF.returnError PGFF.ConversionFailed f "invalid interval") pure
. intervalToPgInterval
<=< PGFF.fromField f
instance PersistField PgInterval where
toPersistValue =
toPersistValue
. pgIntervalToInterval
fromPersistValue =
maybe (Left "invalid interval") pure
. intervalToPgInterval
<=< fromPersistValue
instance PersistFieldSql PgInterval where
sqlType _ = SqlOther "interval"
pgIntervalToInterval :: PgInterval -> Interval.Interval
pgIntervalToInterval =
Interval.fromTimeSaturating mempty
. getPgInterval
intervalToPgInterval :: Interval.Interval -> Maybe PgInterval
intervalToPgInterval interval =
let
(calendarDiffDays, nominalDiffTime) = Interval.intoTime interval
in
if calendarDiffDays == mempty
then Just $ PgInterval nominalDiffTime
else Nothing
-- | Indicates whether a Postgres Column is safe to drop.
--
-- @since 2.17.1.0
newtype SafeToRemove = SafeToRemove Bool
deriving (Show, Eq)
-- | Represents a change to a Postgres column in a DB statement.
--
-- @since 2.17.1.0
data AlterColumn
= ChangeType Column SqlType Text
| IsNull Column
| NotNull Column
| AddColumn Column
| Drop Column SafeToRemove
| Default Column Text
| NoDefault Column
| UpdateNullToValue Column Text
| AddReference
EntityNameDB
ConstraintNameDB
(NEL.NonEmpty FieldNameDB)
[Text]
FieldCascade
| DropReference ConstraintNameDB
deriving (Show, Eq)
-- | Represents a change to a Postgres table in a DB statement.
--
-- @since 2.17.1.0
data AlterTable
= AddUniqueConstraint ConstraintNameDB [FieldNameDB]
| DropConstraint ConstraintNameDB
deriving (Show, Eq)
-- | Represents a change to a Postgres DB in a statement.
--
-- @since 2.17.1.0
data AlterDB
= AddTable EntityNameDB EntityIdDef [Column]
| AlterColumn EntityNameDB AlterColumn
| AlterTable EntityNameDB AlterTable
deriving (Show, Eq)
-- | Returns a structured representation of all of the
-- DB changes required to migrate the Entity from its
-- current state in the database to the state described in
-- Haskell.
--
-- @since 2.17.1.0
migrateStructured
:: [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO (Either [Text] [AlterDB])
migrateStructured allDefs getter entity = 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 = getEntityDBName 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_
-- | Returns a structured representation of all of the
-- DB changes required to migrate the Entity to the state
-- described in Haskell, assuming it currently does not
-- exist in the database.
--
-- @since 2.17.1.0
mockMigrateStructured
:: [EntityDef]
-> EntityDef
-> [AlterDB]
mockMigrateStructured allDefs entity = migrationText
where
name = getEntityDBName entity
migrationText = createText newcols fdefs udspair
where
(newcols', udefs, fdefs) = postgresMkColumns allDefs entity
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
-- | Returns a structured representation of all of the
-- DB changes required to migrate the Entity from its current state
-- in the database to the state described in Haskell.
--
-- @since 2.17.1.0
addTable :: [Column] -> EntityDef -> AlterDB
addTable cols entity =
AddTable name entityId nonIdCols
where
nonIdCols =
case entityPrimary entity of
Just _ ->
cols
_ ->
filter keepField cols
where
keepField c =
Just (cName c) /= fmap fieldDB (getEntityIdField entity)
&& not (safeToRemove entity (cName c))
entityId = getEntityId entity
name = getEntityDBName entity
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
getAlters
:: [EntityDef]
-> EntityDef
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
-> ([AlterColumn], [AlterTable])
getAlters defs def (c1, u1) (c2, u2) =
(getAltersC c1 c2, getAltersU u1 u2)
where
getAltersC [] old =
map (\x -> Drop x $ SafeToRemove $ safeToRemove def $ cName x) old
getAltersC (new : news) old =
let
(alters, old') = findAlters defs def new old
in
alters ++ getAltersC news old'
getAltersU
:: [(ConstraintNameDB, [FieldNameDB])]
-> [(ConstraintNameDB, [FieldNameDB])]
-> [AlterTable]
getAltersU [] old =
map DropConstraint $ filter (not . isManual) $ map fst old
getAltersU ((name, cols) : news) old =
case lookup name old of
Nothing ->
AddUniqueConstraint name cols : getAltersU news old
Just ocols ->
let
old' = filter (\(x, _) -> x /= name) old
in
if sort cols == sort ocols
then getAltersU news old'
else
DropConstraint name
: AddUniqueConstraint name cols
: getAltersU news old'
-- Don't drop constraints which were manually added.
isManual (ConstraintNameDB x) = "__manual_" `T.isPrefixOf` x
-- | Postgres' default maximum identifier length in bytes
-- (You can re-compile Postgres with a new limit, but I'm assuming that virtually noone does this).
-- See https://www.postgresql.org/docs/11/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
maximumIdentifierLength :: Int
maximumIdentifierLength = 63
-- | Intelligent comparison of SQL types, to account for SqlInt32 vs SqlOther integer
sqlTypeEq :: SqlType -> SqlType -> Bool
sqlTypeEq x y =
let
-- Non exhaustive helper to map postgres aliases to the same name. Based on
-- https://www.postgresql.org/docs/9.5/datatype.html.
-- This prevents needless `ALTER TYPE`s when the type is the same.
normalize "int8" = "bigint"
normalize "serial8" = "bigserial"
normalize v = v
in
normalize (T.toCaseFold (showSqlType x))
== normalize (T.toCaseFold (showSqlType y))
-- We check if we should alter a foreign key. This is almost an equality check,
-- except we consider 'Nothing' and 'Just Restrict' equivalent.
equivalentRef :: Maybe ColumnReference -> Maybe ColumnReference -> Bool
equivalentRef Nothing Nothing = True
equivalentRef (Just cr1) (Just cr2) =
crTableName cr1 == crTableName cr2
&& crConstraintName cr1 == crConstraintName cr2
&& eqCascade (fcOnUpdate $ crFieldCascade cr1) (fcOnUpdate $ crFieldCascade cr2)
&& eqCascade (fcOnDelete $ crFieldCascade cr1) (fcOnDelete $ crFieldCascade cr2)
where
eqCascade :: Maybe CascadeAction -> Maybe CascadeAction -> Bool
eqCascade Nothing Nothing = True
eqCascade Nothing (Just Restrict) = True
eqCascade (Just Restrict) Nothing = True
eqCascade (Just cs1) (Just cs2) = cs1 == cs2
eqCascade _ _ = False
equivalentRef _ _ = False
refName :: EntityNameDB -> FieldNameDB -> ConstraintNameDB
refName (EntityNameDB table) (FieldNameDB column) =
let
overhead = T.length $ T.concat ["_", "_fkey"]
(fromTable, fromColumn) = shortenNames overhead (T.length table, T.length column)
in
ConstraintNameDB $
T.concat [T.take fromTable table, "_", T.take fromColumn column, "_fkey"]
where
-- Postgres automatically truncates too long foreign keys to a combination of
-- truncatedTableName + "_" + truncatedColumnName + "_fkey"
-- This works fine for normal use cases, but it creates an issue for Persistent
-- Because after running the migrations, Persistent sees the truncated foreign key constraint
-- doesn't have the expected name, and suggests that you migrate again
-- To workaround this, we copy the Postgres truncation approach before sending foreign key constraints to it.
--
-- I believe this will also be an issue for extremely long table names,
-- but it's just much more likely to exist with foreign key constraints because they're usually tablename * 2 in length
-- Approximation of the algorithm Postgres uses to truncate identifiers
-- See makeObjectName https://github.com/postgres/postgres/blob/5406513e997f5ee9de79d4076ae91c04af0c52f6/src/backend/commands/indexcmds.c#L2074-L2080
shortenNames :: Int -> (Int, Int) -> (Int, Int)
shortenNames overhead (x, y)
| x + y + overhead <= maximumIdentifierLength = (x, y)
| x > y = shortenNames overhead (x - 1, y)
| otherwise = shortenNames overhead (x, y - 1)
postgresMkColumns
:: [EntityDef] -> EntityDef -> ([Column], [UniqueDef], [ForeignDef])
postgresMkColumns allDefs t =
mkColumns allDefs t $
setBackendSpecificForeignKeyName refName emptyBackendSpecificOverrides
-- | 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) $
allEntityFields
where
allEntityFields =
getEntityFieldsDatabase def <> case getEntityId def of
EntityIdField fdef ->
[fdef]
_ ->
[]
udToPair :: UniqueDef -> (ConstraintNameDB, [FieldNameDB])
udToPair ud = (uniqueDBName ud, map snd $ NEL.toList $ uniqueFields ud)
-- | Get the references to be added to a table for the given column.
getAddReference
:: [EntityDef]
-> EntityDef
-> FieldNameDB
-> ColumnReference
-> Maybe AlterDB
getAddReference allDefs entity cname cr@ColumnReference{crTableName = s, crConstraintName = constraintName} = do
guard $ Just cname /= fmap fieldDB (getEntityIdField entity)
pure $
AlterColumn
table
(AddReference s constraintName (cname NEL.:| []) id_ (crFieldCascade cr))
where
table = getEntityDBName entity
id_ =
fromMaybe
(error $ "Could not find ID of entity " ++ show s)
$ do
entDef <- find ((== s) . getEntityDBName) allDefs
return $ NEL.toList $ Util.dbIdColumnsEsc escapeF entDef
mkForeignAlt
:: EntityDef
-> ForeignDef
-> Maybe AlterDB
mkForeignAlt entity fdef = case NEL.nonEmpty childfields of
Nothing -> Nothing
Just childfields' -> Just $ AlterColumn tableName_ addReference
where
addReference =
AddReference
(foreignRefTableDBName fdef)
constraintName
childfields'
escapedParentFields
(foreignFieldCascade fdef)
where
tableName_ = getEntityDBName entity
constraintName =
foreignConstraintNameDBName fdef
(childfields, parentfields) =
unzip (map (\((_, b), (_, d)) -> (b, d)) (foreignFields fdef))
escapedParentFields =
map escapeF parentfields
escapeC :: ConstraintNameDB -> Text
escapeC = escapeWith escape
escapeE :: EntityNameDB -> Text
escapeE = escapeWith escape
escapeF :: FieldNameDB -> Text
escapeF = escapeWith escape
escape :: Text -> Text
escape s =
T.pack $ '"' : go (T.unpack s) ++ "\""
where
go "" = ""
go ('"' : xs) = "\"\"" ++ go xs
go (x : xs) = x : go xs
showAlterDb :: AlterDB -> (Bool, Text)
showAlterDb (AddTable name entityId nonIdCols) = (False, rawText)
where
idtxt =
case entityId of
EntityIdNaturalKey pdef ->
T.concat
[ " PRIMARY KEY ("
, T.intercalate "," $ map (escapeF . fieldDB) $ NEL.toList $ compositeFields pdef
, ")"
]
EntityIdField field ->
let
defText = defaultAttribute $ fieldAttrs field
sType = fieldSqlType field
in
T.concat
[ escapeF $ fieldDB field
, maySerial sType defText
, " PRIMARY KEY UNIQUE"
, mayDefault defText
]
rawText =
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
, ")"
]
showAlterDb (AlterColumn t ac) =
(isUnsafe ac, showAlter t ac)
where
isUnsafe (Drop _ (SafeToRemove safeRemove)) = not safeRemove
isUnsafe _ = False
showAlterDb (AlterTable t at) = (False, showAlterTable t at)
showAlterTable :: EntityNameDB -> AlterTable -> Text
showAlterTable table (AddUniqueConstraint cname cols) =
T.concat
[ "ALTER TABLE "
, escapeE table
, " ADD CONSTRAINT "
, escapeC cname
, " UNIQUE("
, T.intercalate "," $ map escapeF cols
, ")"
]
showAlterTable table (DropConstraint cname) =
T.concat
[ "ALTER TABLE "
, escapeE table
, " DROP CONSTRAINT "
, escapeC cname
]
showAlter :: EntityNameDB -> AlterColumn -> Text
showAlter table (ChangeType c t extra) =
T.concat
[ "ALTER TABLE "
, escapeE table
, " ALTER COLUMN "
, escapeF (cName c)
, " TYPE "
, showSqlType t
, extra
]
showAlter table (IsNull c) =
T.concat
[ "ALTER TABLE "
, escapeE table
, " ALTER COLUMN "
, escapeF (cName c)
, " DROP NOT NULL"
]
showAlter table (NotNull c) =
T.concat
[ "ALTER TABLE "
, escapeE table
, " ALTER COLUMN "
, escapeF (cName c)
, " SET NOT NULL"
]
showAlter table (AddColumn col) =
T.concat
[ "ALTER TABLE "
, escapeE table
, " ADD COLUMN "
, showColumn col
]
showAlter table (Drop c _) =
T.concat
[ "ALTER TABLE "
, escapeE table
, " DROP COLUMN "
, escapeF (cName c)
]
showAlter table (Default c s) =
T.concat
[ "ALTER TABLE "
, escapeE table
, " ALTER COLUMN "
, escapeF (cName c)
, " SET DEFAULT "
, s
]
showAlter table (NoDefault c) =
T.concat
[ "ALTER TABLE "
, escapeE table
, " ALTER COLUMN "
, escapeF (cName c)
, " DROP DEFAULT"
]
showAlter table (UpdateNullToValue c s) =
T.concat
[ "UPDATE "
, escapeE table
, " SET "
, escapeF (cName c)
, "="
, s
, " WHERE "
, escapeF (cName c)
, " IS NULL"
]
showAlter table (AddReference reftable fkeyname t2 id2 cascade) =
T.concat
[ "ALTER TABLE "
, escapeE table
, " ADD CONSTRAINT "
, escapeC fkeyname
, " FOREIGN KEY("
, T.intercalate "," $ map escapeF $ NEL.toList t2
, ") REFERENCES "
, escapeE reftable
, "("
, T.intercalate "," id2
, ")"
]
<> renderFieldCascade cascade
showAlter table (DropReference cname) =
T.concat
[ "ALTER TABLE "
, escapeE table
, " DROP CONSTRAINT "
, escapeC cname
]
showColumn :: Column -> Text
showColumn (Column n nu sqlType' def gen _defConstraintName _maxLen _ref) =
T.concat
[ escapeF n
, " "
, showSqlType sqlType'
, " "
, if nu then "NULL" else "NOT NULL"
, case def of
Nothing -> ""
Just s -> " DEFAULT " <> s
, case gen of
Nothing -> ""
Just s -> " GENERATED ALWAYS AS (" <> s <> ") STORED"
]
showSqlType :: SqlType -> Text
showSqlType SqlString = "VARCHAR"
showSqlType SqlInt32 = "INT4"
showSqlType SqlInt64 = "INT8"
showSqlType SqlReal = "DOUBLE PRECISION"
showSqlType (SqlNumeric s prec) = T.concat ["NUMERIC(", T.pack (show s), ",", T.pack (show prec), ")"]
showSqlType SqlDay = "DATE"
showSqlType SqlTime = "TIME"
showSqlType SqlDayTime = "TIMESTAMP WITH TIME ZONE"
showSqlType SqlBlob = "BYTEA"
showSqlType SqlBool = "BOOLEAN"
-- Added for aliasing issues re: https://github.com/yesodweb/yesod/issues/682
showSqlType (SqlOther (T.toLower -> "integer")) = "INT4"
showSqlType (SqlOther t) = t
findAlters
:: [EntityDef]
-- ^ The list of all entity definitions that persistent is aware of.
-> EntityDef
-- ^ The entity definition for the entity that we're working on.
-> Column
-- ^ The column that we're searching for potential alterations for.
-> [Column]
-> ([AlterColumn], [Column])
findAlters defs edef col@(Column name isNull sqltype def _gen _defConstraintName _maxLen ref) cols =
case List.find (\c -> cName c == name) cols of
Nothing ->
([AddColumn col], cols)
Just
(Column _oldName isNull' sqltype' def' _gen' _defConstraintName' _maxLen' ref') ->
let
refDrop Nothing = []
refDrop (Just ColumnReference{crConstraintName = cname}) =
[DropReference cname]
refAdd Nothing = []
refAdd (Just colRef) =
case find ((== crTableName colRef) . getEntityDBName) defs of
Just refdef
| Just _oldName /= fmap fieldDB (getEntityIdField edef) ->
[ AddReference
(crTableName colRef)
(crConstraintName colRef)
(name NEL.:| [])
(NEL.toList $ Util.dbIdColumnsEsc escapeF refdef)
(crFieldCascade colRef)
]
Just _ -> []
Nothing ->
error $
"could not find the entityDef for reftable["
++ show (crTableName colRef)
++ "]"
modRef =
if equivalentRef ref ref'
then []
else refDrop ref' ++ refAdd ref
modNull = case (isNull, isNull') of
(True, False) -> do
guard $ Just name /= fmap fieldDB (getEntityIdField edef)
pure (IsNull col)
(False, True) ->
let
up = case def of
Nothing -> id
Just s -> (:) (UpdateNullToValue col s)
in
up [NotNull col]
_ -> []
modType
| sqlTypeEq sqltype sqltype' = []
-- When converting from Persistent pre-2.0 databases, we
-- need to make sure that TIMESTAMP WITHOUT TIME ZONE is
-- treated as UTC.
| sqltype == SqlDayTime && sqltype' == SqlOther "timestamp" =
[ ChangeType col sqltype $
T.concat
[ " USING "
, escapeF name
, " AT TIME ZONE 'UTC'"
]
]
| otherwise = [ChangeType col sqltype ""]
modDef =
if def == def'
|| isJust (T.stripPrefix "nextval" =<< def')
then []
else case def of
Nothing -> [NoDefault col]
Just s -> [Default col s]
dropSafe =
if safeToRemove edef name
then error "wtf" [Drop col (SafeToRemove True)]
else []
in
( modRef ++ modDef ++ modNull ++ modType ++ dropSafe
, filter (\c -> cName c /= name) cols
)
-- | 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 $ getEntityDBName 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 $
List.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 (getEntityDBName def) x' (Map.lookup cname refMap)
pure $ case col of
Left e -> Left e