forked from yesodweb/persistent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTH.hs
More file actions
3428 lines (3142 loc) · 118 KB
/
TH.hs
File metadata and controls
3428 lines (3142 loc) · 118 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 AllowAmbiguousTypes #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveLift #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
-- | This module provides the tools for defining your database schema and using
-- it to generate Haskell data types and migrations.
--
-- For documentation on the domain specific language used for defining database
-- models, see "Database.Persist.Quasi".
--
--
module Database.Persist.TH
( -- * Parse entity defs
persistWith
, persistUpperCase
, persistLowerCase
, persistFileWith
, persistManyFileWith
-- * Turn @EntityDef@s into types
, mkPersist
, mkPersistWith
-- ** Configuring Entity Definition
, MkPersistSettings
, mkPersistSettings
, sqlSettings
-- *** Record Fields (for update/viewing settings)
, mpsBackend
, mpsGeneric
, mpsPrefixFields
, mpsFieldLabelModifier
, mpsAvoidHsKeyword
, mpsConstraintLabelModifier
, mpsEntityHaddocks
, mpsEntityJSON
, mpsGenerateLenses
, mpsDeriveInstances
, mpsCamelCaseCompositeKeySelector
, EntityJSON(..)
-- ** Implicit ID Columns
, ImplicitIdDef
, setImplicitIdDef
-- * Various other TH functions
, mkMigrate
, migrateModels
, discoverEntities
, mkEntityDefList
, share
, derivePersistField
, derivePersistFieldJSON
, persistFieldFromEntity
-- * Internal
, lensPTH
, parseReferences
, embedEntityDefs
, fieldError
, AtLeastOneUniqueKey(..)
, OnlyOneUniqueKey(..)
, pkNewtype
) where
-- Development Tip: See persistent-template/README.md for advice on seeing generated Template Haskell code
-- It's highly recommended to check the diff between master and your PR's generated code.
import Prelude hiding (concat, exp, splitAt, take, (++))
import Control.Monad
import Data.Aeson
( FromJSON(..)
, ToJSON(..)
, eitherDecodeStrict'
, object
, withObject
, (.:)
, (.:?)
, (.=)
)
#if MIN_VERSION_aeson(2,0,0)
import qualified Data.Aeson.Key as Key
#endif
import qualified Data.ByteString as BS
import Data.Char (toLower, toUpper)
import Data.Coerce
import Data.Data (Data)
import Data.Either
import qualified Data.HashMap.Strict as HM
import Data.Int (Int64)
import Data.Ix (Ix)
import Data.List (foldl')
import qualified Data.List as List
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NEL
import qualified Data.Map as M
import Data.Maybe (fromMaybe, isJust, listToMaybe, mapMaybe)
import Data.Proxy (Proxy(Proxy))
import Data.Text (Text, concat, cons, pack, stripSuffix, uncons, unpack)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import qualified Data.Text.Encoding as TE
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import GHC.Stack (HasCallStack)
import GHC.TypeLits
import Instances.TH.Lift ()
-- Bring `Lift (fmap k v)` instance into scope, as well as `Lift Text`
-- instance on pre-1.2.4 versions of `text`
import Data.Foldable (asum, toList)
import qualified Data.Set as Set
import Language.Haskell.TH.Lib
(appT, conE, conK, conT, litT, strTyLit, varE, varP, varT)
#if MIN_VERSION_template_haskell(2,21,0)
import Language.Haskell.TH.Lib (defaultBndrFlag)
#endif
import Language.Haskell.TH.Quote
import Language.Haskell.TH.Syntax
import Web.HttpApiData (FromHttpApiData(..), ToHttpApiData(..))
import Web.PathPieces (PathPiece(..))
import Database.Persist
import Database.Persist.Class.PersistEntity
import Database.Persist.Quasi
import Database.Persist.Quasi.Internal
import Database.Persist.Sql
(Migration, PersistFieldSql, SqlBackend, migrate, sqlType)
import Database.Persist.EntityDef.Internal (EntityDef(..))
import Database.Persist.ImplicitIdDef (autoIncrementingInteger)
import Database.Persist.ImplicitIdDef.Internal
#if MIN_VERSION_template_haskell(2,18,0)
conp :: Name -> [Pat] -> Pat
conp name pats = ConP name [] pats
#else
conp :: Name -> [Pat] -> Pat
conp = ConP
#endif
-- | Converts a quasi-quoted syntax into a list of entity definitions, to be
-- used as input to the template haskell generation code (mkPersist).
persistWith :: PersistSettings -> QuasiQuoter
persistWith ps = QuasiQuoter
{ quoteExp =
parseReferences ps . pack
, quotePat =
error "persistWith can't be used as pattern"
, quoteType =
error "persistWith can't be used as type"
, quoteDec =
error "persistWith can't be used as declaration"
}
-- | Apply 'persistWith' to 'upperCaseSettings'.
persistUpperCase :: QuasiQuoter
persistUpperCase = persistWith upperCaseSettings
-- | Apply 'persistWith' to 'lowerCaseSettings'.
persistLowerCase :: QuasiQuoter
persistLowerCase = persistWith lowerCaseSettings
-- | Same as 'persistWith', but uses an external file instead of a
-- quasiquotation. The recommended file extension is @.persistentmodels@.
persistFileWith :: PersistSettings -> FilePath -> Q Exp
persistFileWith ps fp = persistManyFileWith ps [fp]
-- | Same as 'persistFileWith', but uses several external files instead of
-- one. Splitting your Persistent definitions into multiple modules can
-- potentially dramatically speed up compile times.
--
-- The recommended file extension is @.persistentmodels@.
--
-- ==== __Examples__
--
-- Split your Persistent definitions into multiple files (@models1@, @models2@),
-- then create a new module for each new file and run 'mkPersist' there:
--
-- @
-- -- Model1.hs
-- 'share'
-- ['mkPersist' 'sqlSettings']
-- $('persistFileWith' 'lowerCaseSettings' "models1")
-- @
-- @
-- -- Model2.hs
-- 'share'
-- ['mkPersist' 'sqlSettings']
-- $('persistFileWith' 'lowerCaseSettings' "models2")
-- @
--
-- Use 'persistManyFileWith' to create your migrations:
--
-- @
-- -- Migrate.hs
-- 'mkMigrate' "migrateAll"
-- $('persistManyFileWith' 'lowerCaseSettings' ["models1.persistentmodels","models2.persistentmodels"])
-- @
--
-- Tip: To get the same import behavior as if you were declaring all your models in
-- one file, import your new files @as Name@ into another file, then export @module Name@.
--
-- This approach may be used in the future to reduce memory usage during compilation,
-- but so far we've only seen mild reductions.
--
-- See <https://github.com/yesodweb/persistent/issues/778 persistent#778> and
-- <https://github.com/yesodweb/persistent/pull/791 persistent#791> for more details.
--
-- @since 2.5.4
persistManyFileWith :: PersistSettings -> [FilePath] -> Q Exp
persistManyFileWith ps fps = do
mapM_ qAddDependentFile fps
ss <- mapM (qRunIO . getFileContents) fps
let s = T.intercalate "\n" ss -- be tolerant of the user forgetting to put a line-break at EOF.
parseReferences ps s
getFileContents :: FilePath -> IO Text
getFileContents = fmap decodeUtf8 . BS.readFile
-- | Takes a list of (potentially) independently defined entities and properly
-- links all foreign keys to reference the right 'EntityDef', tying the knot
-- between entities.
--
-- Allows users to define entities indepedently or in separate modules and then
-- fix the cross-references between them at runtime to create a 'Migration'.
--
-- @since 2.7.2
embedEntityDefs
:: [EntityDef]
-- ^ A list of 'EntityDef' that have been defined in a previous 'mkPersist'
-- call.
--
-- @since 2.13.0.0
-> [UnboundEntityDef]
-> [UnboundEntityDef]
embedEntityDefs eds = snd . embedEntityDefsMap eds
embedEntityDefsMap
:: [EntityDef]
-- ^ A list of 'EntityDef' that have been defined in a previous 'mkPersist'
-- call.
--
-- @since 2.13.0.0
-> [UnboundEntityDef]
-> (EmbedEntityMap, [UnboundEntityDef])
embedEntityDefsMap existingEnts rawEnts =
(embedEntityMap, noCycleEnts)
where
noCycleEnts = entsWithEmbeds
embedEntityMap = constructEmbedEntityMap entsWithEmbeds
entsWithEmbeds = fmap setEmbedEntity (rawEnts <> map unbindEntityDef existingEnts)
setEmbedEntity ubEnt =
let
ent = unboundEntityDef ubEnt
in
ubEnt
{ unboundEntityDef =
overEntityFields
(fmap (setEmbedField (entityHaskell ent) embedEntityMap))
ent
}
-- | Calls 'parse' to Quasi.parse individual entities in isolation
-- afterwards, sets references to other entities
--
-- In 2.13.0.0, this was changed to splice in @['UnboundEntityDef']@
-- instead of @['EntityDef']@.
--
-- @since 2.5.3
parseReferences :: PersistSettings -> Text -> Q Exp
parseReferences ps s = lift $ parse ps s
preprocessUnboundDefs
:: [EntityDef]
-> [UnboundEntityDef]
-> (M.Map EntityNameHS (), [UnboundEntityDef])
preprocessUnboundDefs preexistingEntities unboundDefs =
(embedEntityMap, noCycleEnts)
where
(embedEntityMap, noCycleEnts) =
embedEntityDefsMap preexistingEntities unboundDefs
liftAndFixKeys
:: MkPersistSettings
-> M.Map EntityNameHS a
-> EntityMap
-> UnboundEntityDef
-> Q Exp
liftAndFixKeys mps emEntities entityMap unboundEnt =
let
ent =
unboundEntityDef unboundEnt
fields =
getUnboundFieldDefs unboundEnt
in
[|
ent
{ entityFields =
$(ListE <$> traverse combinedFixFieldDef fields)
, entityId =
$(fixPrimarySpec mps unboundEnt)
, entityForeigns =
$(fixUnboundForeignDefs (unboundForeignDefs unboundEnt))
}
|]
where
fixUnboundForeignDefs
:: [UnboundForeignDef]
-> Q Exp
fixUnboundForeignDefs fdefs =
fmap ListE $ forM fdefs fixUnboundForeignDef
where
fixUnboundForeignDef UnboundForeignDef{..} =
[|
unboundForeignDef
{ foreignFields =
$(lift fixForeignFields)
, foreignNullable =
$(lift fixForeignNullable)
, foreignRefTableDBName =
$(lift fixForeignRefTableDBName)
}
|]
where
fixForeignRefTableDBName =
entityDB (unboundEntityDef parentDef)
foreignFieldNames =
case unboundForeignFields of
FieldListImpliedId ffns ->
ffns
FieldListHasReferences references ->
fmap ffrSourceField references
parentDef =
case M.lookup parentTableName entityMap of
Nothing ->
error $ mconcat
[ "Foreign table not defined: "
, show parentTableName
]
Just a ->
a
parentTableName =
foreignRefTableHaskell unboundForeignDef
fixForeignFields :: [(ForeignFieldDef, ForeignFieldDef)]
fixForeignFields =
case unboundForeignFields of
FieldListImpliedId ffns ->
mkReferences $ toList ffns
FieldListHasReferences references ->
toList $ fmap convReferences references
where
-- in this case, we're up against the implied ID of the parent
-- dodgy assumption: columns are listed in the right order. we
-- can't check this any more clearly right now.
mkReferences fieldNames
| length fieldNames /= length parentKeyFieldNames =
error $ mconcat
[ "Foreign reference needs to have the same number "
, "of fields as the target table."
, "\n Table : "
, show (getUnboundEntityNameHS unboundEnt)
, "\n Foreign Table: "
, show parentTableName
, "\n Fields : "
, show fieldNames
, "\n Parent fields: "
, show (fmap fst parentKeyFieldNames)
, "\n\nYou can use the References keyword to fix this."
]
| otherwise =
zip (fmap (withDbName fieldStore) fieldNames) (toList parentKeyFieldNames)
where
parentKeyFieldNames
:: NonEmpty (FieldNameHS, FieldNameDB)
parentKeyFieldNames =
case unboundPrimarySpec parentDef of
NaturalKey ucd ->
fmap (withDbName parentFieldStore) (unboundCompositeCols ucd)
SurrogateKey uid ->
pure (FieldNameHS "Id", unboundIdDBName uid)
DefaultKey dbName ->
pure (FieldNameHS "Id", dbName)
withDbName store fieldNameHS =
( fieldNameHS
, findDBName store fieldNameHS
)
convReferences
:: ForeignFieldReference
-> (ForeignFieldDef, ForeignFieldDef)
convReferences ForeignFieldReference {..} =
( withDbName fieldStore ffrSourceField
, withDbName parentFieldStore ffrTargetField
)
fixForeignNullable =
all ((NotNullable /=) . isForeignNullable) foreignFieldNames
where
isForeignNullable fieldNameHS =
case getFieldDef fieldNameHS fieldStore of
Nothing ->
error "Field name not present in map"
Just a ->
isUnboundFieldNullable a
fieldStore =
mkFieldStore unboundEnt
parentFieldStore =
mkFieldStore parentDef
findDBName store fieldNameHS =
case getFieldDBName fieldNameHS store of
Nothing ->
error $ mconcat
[ "findDBName: failed to fix dbname for: "
, show fieldNameHS
]
Just a->
a
combinedFixFieldDef :: UnboundFieldDef -> Q Exp
combinedFixFieldDef ufd@UnboundFieldDef{..} =
[|
FieldDef
{ fieldHaskell =
unboundFieldNameHS
, fieldDB =
unboundFieldNameDB
, fieldType =
unboundFieldType
, fieldSqlType =
$(sqlTyp')
, fieldAttrs =
unboundFieldAttrs
, fieldStrict =
unboundFieldStrict
, fieldReference =
$(fieldRef')
, fieldCascade =
unboundFieldCascade
, fieldComments =
unboundFieldComments
, fieldGenerated =
unboundFieldGenerated
, fieldIsImplicitIdColumn =
False
}
|]
where
sqlTypeExp =
getSqlType emEntities entityMap ufd
FieldDef _x _ _ _ _ _ _ _ _ _ _ =
error "need to update this record wildcard match"
(fieldRef', sqlTyp') =
case extractForeignRef entityMap ufd of
Just targetTable ->
let targetTableQualified =
fromMaybe targetTable (guessFieldReferenceQualified ufd)
in (lift (ForeignRef targetTable), liftSqlTypeExp (SqlTypeReference targetTableQualified))
Nothing ->
(lift NoReference, liftSqlTypeExp sqlTypeExp)
data FieldStore
= FieldStore
{ fieldStoreMap :: M.Map FieldNameHS UnboundFieldDef
, fieldStoreId :: Maybe FieldNameDB
, fieldStoreEntity :: UnboundEntityDef
}
mkFieldStore :: UnboundEntityDef -> FieldStore
mkFieldStore ued =
FieldStore
{ fieldStoreEntity = ued
, fieldStoreMap =
M.fromList
$ fmap (\ufd ->
( unboundFieldNameHS ufd
, ufd
)
)
$ getUnboundFieldDefs
$ ued
, fieldStoreId =
case unboundPrimarySpec ued of
NaturalKey _ ->
Nothing
SurrogateKey fd ->
Just $ unboundIdDBName fd
DefaultKey n ->
Just n
}
getFieldDBName :: FieldNameHS -> FieldStore -> Maybe FieldNameDB
getFieldDBName name fs
| FieldNameHS "Id" == name =
fieldStoreId fs
| otherwise =
unboundFieldNameDB <$> getFieldDef name fs
getFieldDef :: FieldNameHS -> FieldStore -> Maybe UnboundFieldDef
getFieldDef fieldNameHS fs =
M.lookup fieldNameHS (fieldStoreMap fs)
extractForeignRef :: EntityMap -> UnboundFieldDef -> Maybe EntityNameHS
extractForeignRef entityMap fieldDef = do
refName <- guessFieldReference fieldDef
ent <- M.lookup refName entityMap
pure $ entityHaskell $ unboundEntityDef ent
guessFieldReference :: UnboundFieldDef -> Maybe EntityNameHS
guessFieldReference = guessReference . unboundFieldType
guessReference :: FieldType -> Maybe EntityNameHS
guessReference ft =
EntityNameHS <$> guessReferenceText (Just ft)
where
checkIdSuffix =
T.stripSuffix "Id"
guessReferenceText mft =
asum
[ do
FTTypeCon _ (checkIdSuffix -> Just tableName) <- mft
pure tableName
, do
FTApp (FTTypeCon _ "Key") (FTTypeCon _ tableName) <- mft
pure tableName
, do
FTApp (FTTypeCon _ "Maybe") next <- mft
guessReferenceText (Just next)
]
guessFieldReferenceQualified :: UnboundFieldDef -> Maybe EntityNameHS
guessFieldReferenceQualified = guessReferenceQualified . unboundFieldType
guessReferenceQualified :: FieldType -> Maybe EntityNameHS
guessReferenceQualified ft =
EntityNameHS <$> guessReferenceText (Just ft)
where
checkIdSuffix =
T.stripSuffix "Id"
guessReferenceText mft =
asum
[ do
FTTypeCon mmod (checkIdSuffix -> Just tableName) <- mft
-- handle qualified name.
pure $ maybe tableName (\qualName -> qualName <> "." <> tableName) mmod
, do
FTApp (FTTypeCon _ "Key") (FTTypeCon mmod tableName) <- mft
-- handle qualified name.
pure $ maybe tableName (\qualName -> qualName <> "." <> tableName) mmod
, do
FTApp (FTTypeCon _ "Maybe") next <- mft
guessReferenceText (Just next)
]
mkDefaultKey
:: MkPersistSettings
-> FieldNameDB
-> EntityNameHS
-> FieldDef
mkDefaultKey mps pk unboundHaskellName =
let
iid =
mpsImplicitIdDef mps
in
maybe id addFieldAttr (FieldAttrDefault <$> iidDefault iid) $
maybe id addFieldAttr (FieldAttrMaxlen <$> iidMaxLen iid) $
mkAutoIdField' pk unboundHaskellName (iidFieldSqlType iid)
fixPrimarySpec
:: MkPersistSettings
-> UnboundEntityDef
-> Q Exp
fixPrimarySpec mps unboundEnt= do
case unboundPrimarySpec unboundEnt of
DefaultKey pk ->
lift $ EntityIdField $
mkDefaultKey mps pk unboundHaskellName
SurrogateKey uid -> do
let
entNameHS =
getUnboundEntityNameHS unboundEnt
fieldTyp =
fromMaybe (mkKeyConType entNameHS) (unboundIdType uid)
[|
EntityIdField
FieldDef
{ fieldHaskell =
FieldNameHS "Id"
, fieldDB =
$(lift $ getSqlNameOr (unboundIdDBName uid) (unboundIdAttrs uid))
, fieldType =
$(lift fieldTyp)
, fieldSqlType =
$( liftSqlTypeExp (SqlTypeExp fieldTyp) )
, fieldStrict =
False
, fieldReference =
ForeignRef entNameHS
, fieldAttrs =
unboundIdAttrs uid
, fieldComments =
Nothing
, fieldCascade = unboundIdCascade uid
, fieldGenerated = Nothing
, fieldIsImplicitIdColumn = True
}
|]
NaturalKey ucd ->
[| EntityIdNaturalKey $(bindCompositeDef unboundEnt ucd) |]
where
unboundHaskellName =
getUnboundEntityNameHS unboundEnt
bindCompositeDef :: UnboundEntityDef -> UnboundCompositeDef -> Q Exp
bindCompositeDef ued ucd = do
fieldDefs <-
fmap ListE $ forM (toList $ unboundCompositeCols ucd) $ \col ->
mkLookupEntityField ued col
[|
CompositeDef
{ compositeFields =
NEL.fromList $(pure fieldDefs)
, compositeAttrs =
$(lift $ unboundCompositeAttrs ucd)
}
|]
getSqlType :: M.Map EntityNameHS a -> EntityMap -> UnboundFieldDef -> SqlTypeExp
getSqlType emEntities entityMap field =
maybe
(defaultSqlTypeExp emEntities entityMap field)
(SqlType' . SqlOther)
(listToMaybe $ mapMaybe attrSqlType $ unboundFieldAttrs field)
-- In the case of embedding, there won't be any datatype created yet.
-- We just use SqlString, as the data will be serialized to JSON.
defaultSqlTypeExp :: M.Map EntityNameHS a -> EntityMap -> UnboundFieldDef -> SqlTypeExp
defaultSqlTypeExp emEntities entityMap field =
case mEmbedded emEntities ftype of
Right _ ->
SqlType' SqlString
Left (Just (FTKeyCon ty)) ->
SqlTypeExp (FTTypeCon Nothing ty)
Left Nothing ->
case extractForeignRef entityMap field of
Just refName ->
case M.lookup refName entityMap of
Nothing ->
-- error $ mconcat
-- [ "Failed to find model: "
-- , show refName
-- , " in entity list: \n"
-- ]
-- <> (unlines $ map show $ M.keys $ entityMap)
-- going to assume that it's fine, will reify it out
-- right later anyway)
SqlTypeExp ftype
-- A ForeignRef is blindly set to an Int64 in setEmbedField
-- correct that now
Just _ ->
SqlTypeReference refName
_ ->
case ftype of
-- In the case of lists, we always serialize to a string
-- value (via JSON).
--
-- Normally, this would be determined automatically by
-- SqlTypeExp. However, there's one corner case: if there's
-- a list of entity IDs, the datatype for the ID has not
-- yet been created, so the compiler will fail. This extra
-- clause works around this limitation.
FTList _ ->
SqlType' SqlString
_ ->
SqlTypeExp ftype
where
ftype = unboundFieldType field
attrSqlType :: FieldAttr -> Maybe Text
attrSqlType = \case
FieldAttrSqltype x -> Just x
_ -> Nothing
data SqlTypeExp
= SqlTypeExp FieldType
| SqlType' SqlType
| SqlTypeReference EntityNameHS
deriving Show
liftSqlTypeExp :: SqlTypeExp -> Q Exp
liftSqlTypeExp ste =
case ste of
SqlType' t ->
lift t
SqlTypeExp ftype -> do
let
typ = ftToType ftype
mtyp = ConT ''Proxy `AppT` typ
typedNothing = SigE (ConE 'Proxy) mtyp
pure $ VarE 'sqlType `AppE` typedNothing
SqlTypeReference entNameHs -> do
let
entNameId :: Name
entNameId =
mkName $ T.unpack (unEntityNameHS entNameHs) <> "Id"
[| sqlType (Proxy :: Proxy $(conT entNameId)) |]
type EmbedEntityMap = M.Map EntityNameHS ()
constructEmbedEntityMap :: [UnboundEntityDef] -> EmbedEntityMap
constructEmbedEntityMap =
M.fromList . fmap
(\ent ->
( entityHaskell (unboundEntityDef ent)
-- , toEmbedEntityDef (unboundEntityDef ent)
, ()
)
)
lookupEmbedEntity :: M.Map EntityNameHS a -> FieldDef -> Maybe EntityNameHS
lookupEmbedEntity allEntities field = do
let mfieldTy = Just $ fieldType field
entName <- EntityNameHS <$> asum
[ do
FTTypeCon _ t <- mfieldTy
stripSuffix "Id" t
, do
FTApp (FTTypeCon _ "Key") (FTTypeCon _ entName) <- mfieldTy
pure entName
, do
FTApp (FTTypeCon _ "Maybe") (FTTypeCon _ t) <- mfieldTy
stripSuffix "Id" t
]
guard (M.member entName allEntities) -- check entity name exists in embed fmap
pure entName
type EntityMap = M.Map EntityNameHS UnboundEntityDef
constructEntityMap :: [UnboundEntityDef] -> EntityMap
constructEntityMap =
M.fromList . fmap (\ent -> (entityHaskell (unboundEntityDef ent), ent))
data FTTypeConDescr = FTKeyCon Text
deriving Show
-- | Recurses through the 'FieldType'. Returns a 'Right' with the
-- 'EmbedEntityDef' if the 'FieldType' corresponds to an unqualified use of
-- a name and that name is present in the 'EmbedEntityMap' provided as
-- a first argument.
--
-- If the 'FieldType' represents a @Key something@, this returns a @'Left
-- ('Just' 'FTKeyCon')@.
--
-- If the 'FieldType' has a module qualified value, then it returns @'Left'
-- 'Nothing'@.
mEmbedded
:: M.Map EntityNameHS a
-> FieldType
-> Either (Maybe FTTypeConDescr) EntityNameHS
mEmbedded _ (FTTypeCon Just{} _) =
Left Nothing
mEmbedded ents (FTTypeCon Nothing (EntityNameHS -> name)) =
maybe (Left Nothing) (\_ -> Right name) $ M.lookup name ents
mEmbedded _ (FTTypePromoted _) =
Left Nothing
mEmbedded ents (FTList x) =
mEmbedded ents x
mEmbedded _ (FTApp (FTTypeCon Nothing "Key") (FTTypeCon _ a)) =
Left $ Just $ FTKeyCon $ a <> "Id"
mEmbedded _ (FTApp _ _) =
Left Nothing
mEmbedded _ (FTLit _) =
Left Nothing
setEmbedField :: EntityNameHS -> M.Map EntityNameHS a -> FieldDef -> FieldDef
setEmbedField entName allEntities field =
case fieldReference field of
NoReference ->
setFieldReference ref field
_ ->
field
where
ref =
case mEmbedded allEntities (fieldType field) of
Left _ -> fromMaybe NoReference $ do
refEntName <- lookupEmbedEntity allEntities field
pure $ ForeignRef refEntName
Right em ->
if em /= entName
then EmbedRef em
else if maybeNullable (unbindFieldDef field)
then SelfReference
else case fieldType field of
FTList _ -> SelfReference
_ -> error $ unpack $ unEntityNameHS entName <> ": a self reference must be a Maybe or List"
setFieldReference :: ReferenceDef -> FieldDef -> FieldDef
setFieldReference ref field = field { fieldReference = ref }
-- | Create data types and appropriate 'PersistEntity' instances for the given
-- 'UnboundEntityDef's.
--
-- This function should be used if you are only defining a single block of
-- Persistent models for the entire application. If you intend on defining
-- multiple blocks in different fiels, see 'mkPersistWith' which allows you
-- to provide existing entity definitions so foreign key references work.
--
-- Example:
--
-- @
-- mkPersist 'sqlSettings' ['persistLowerCase'|
-- User
-- name Text
-- age Int
--
-- Dog
-- name Text
-- owner UserId
--
-- |]
-- @
--
-- Example from a file:
--
-- @
-- mkPersist 'sqlSettings' $('persistFileWith' 'lowerCaseSettings' "models.persistentmodels")
-- @
--
-- For full information on the 'QuasiQuoter' syntax, see
-- "Database.Persist.Quasi" documentation.
mkPersist
:: MkPersistSettings
-> [UnboundEntityDef]
-> Q [Dec]
mkPersist mps = mkPersistWith mps []
-- | Like 'mkPersist', but allows you to provide a @['EntityDef']@
-- representing the predefined entities. This function will include those
-- 'EntityDef' when looking for foreign key references.
--
-- You should use this if you intend on defining Persistent models in
-- multiple files.
--
-- Suppose we define a table @Foo@ which has no dependencies.
--
-- @
-- module DB.Foo where
--
-- 'mkPersistWith' 'sqlSettings' [] ['persistLowerCase'|
-- Foo
-- name Text
-- |]
-- @
--
-- Then, we define a table @Bar@ which depends on @Foo@:
--
-- @
-- module DB.Bar where
--
-- import DB.Foo
--
-- 'mkPersistWith' 'sqlSettings' [entityDef (Proxy :: Proxy Foo)] ['persistLowerCase'|
-- Bar
-- fooId FooId
-- |]
-- @
--
-- Writing out the list of 'EntityDef' can be annoying. The
-- @$('discoverEntities')@ shortcut will work to reduce this boilerplate.
--
-- @
-- module DB.Quux where
--
-- import DB.Foo
-- import DB.Bar
--
-- 'mkPersistWith' 'sqlSettings' $('discoverEntities') ['persistLowerCase'|
-- Quux
-- name Text
-- fooId FooId
-- barId BarId
-- |]
-- @
--
-- @since 2.13.0.0
mkPersistWith
:: MkPersistSettings
-> [EntityDef]
-> [UnboundEntityDef]
-> Q [Dec]
mkPersistWith mps preexistingEntities ents' = do
let
(embedEntityMap, predefs) =
preprocessUnboundDefs preexistingEntities ents'
allEnts =
embedEntityDefs preexistingEntities
$ fmap (setDefaultIdFields mps)
$ predefs
entityMap =
constructEntityMap allEnts
preexistingSet =
Set.fromList $ map getEntityHaskellName preexistingEntities
newEnts =
filter
(\e -> getUnboundEntityNameHS e `Set.notMember` preexistingSet)
allEnts
ents <- filterM shouldGenerateCode newEnts
requireExtensions
[ [TypeFamilies], [GADTs, ExistentialQuantification]
, [DerivingStrategies], [GeneralizedNewtypeDeriving], [StandaloneDeriving]
, [UndecidableInstances], [DataKinds], [FlexibleInstances]
]
persistFieldDecs <- fmap mconcat $ mapM (persistFieldFromEntity mps) ents
entityDecs <- fmap mconcat $ mapM (mkEntity embedEntityMap entityMap mps) ents
jsonDecs <- fmap mconcat $ mapM (mkJSON mps) ents
uniqueKeyInstances <- fmap mconcat $ mapM (mkUniqueKeyInstances mps) ents
safeToInsertInstances <- mconcat <$> mapM (mkSafeToInsertInstance mps) ents
symbolToFieldInstances <- fmap mconcat $ mapM (mkSymbolToFieldInstances mps entityMap) ents
return $ mconcat
[ persistFieldDecs
, entityDecs
, jsonDecs
, uniqueKeyInstances
, symbolToFieldInstances
, safeToInsertInstances
]
mkSafeToInsertInstance :: MkPersistSettings -> UnboundEntityDef -> Q [Dec]
mkSafeToInsertInstance mps ued =
case unboundPrimarySpec ued of
NaturalKey _ ->
instanceOkay
SurrogateKey uidDef -> do
let attrs =
unboundIdAttrs uidDef
isDefaultFieldAttr = \case
FieldAttrDefault _ ->
True
_ ->
False
case unboundIdType uidDef of
Nothing ->
instanceOkay
Just _ ->
case List.find isDefaultFieldAttr attrs of
Nothing ->
badInstance
Just _ -> do
instanceOkay
DefaultKey _ ->
instanceOkay
where
typ :: Type
typ = genericDataType mps (getUnboundEntityNameHS ued) backendT
mkInstance merr =
InstanceD Nothing (maybe id (:) merr withPersistStoreWriteCxt) (ConT ''SafeToInsert `AppT` typ) []
instanceOkay =
pure
[ mkInstance Nothing
]
badInstance = do
err <- [t| TypeError (SafeToInsertErrorMessage $(pure typ)) |]
pure
[ mkInstance (Just err)
]
withPersistStoreWriteCxt =
if mpsGeneric mps
then
[ConT ''PersistStoreWrite `AppT` backendT]
else
[]
-- we can't just use 'isInstance' because TH throws an error
shouldGenerateCode :: UnboundEntityDef -> Q Bool
shouldGenerateCode ed = do
mtyp <- lookupTypeName entityName
case mtyp of
Nothing -> do
pure True
Just typeName -> do
instanceExists <- isInstance ''PersistEntity [ConT typeName]