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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
module Database.Persist.QuasiSpec where
import Prelude hiding (lines)
import Control.Exception
import Control.Monad
import Data.List hiding (lines)
import Data.List.NonEmpty (NonEmpty(..), (<|))
import qualified Data.List.NonEmpty as NEL
import qualified Data.Map as Map
import qualified Data.Text as T
import Database.Persist.EntityDef.Internal
import Database.Persist.Quasi
import Database.Persist.Quasi.Internal
import Database.Persist.Types
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Text.Shakespeare.Text (st)
spec :: Spec
spec = describe "Quasi" $ do
describe "parseEntityFields" $ do
let helloWorldTokens = Token "hello" :| [Token "world"]
foobarbazTokens = Token "foo" :| [Token "bar", Token "baz"]
it "works" $ do
parseEntityFields []
`shouldBe`
mempty
it "works2" $ do
parseEntityFields
[ Line 0 helloWorldTokens
]
`shouldBe`
( [NEL.toList helloWorldTokens], mempty )
it "works3" $ do
parseEntityFields
[ Line 0 helloWorldTokens
, Line 2 foobarbazTokens
]
`shouldBe`
( [NEL.toList helloWorldTokens, NEL.toList foobarbazTokens], mempty )
it "works4" $ do
parseEntityFields
[ Line 0 [Token "Product"]
, Line 2 (Token <$> ["name", "Text"])
, Line 2 (Token <$> ["added", "UTCTime", "default=CURRENT_TIMESTAMP"])
]
`shouldBe`
( []
, Map.fromList
[ ("Product",
[ ["name", "Text"]
, ["added", "UTCTime", "default=CURRENT_TIMESTAMP"]
]
) ]
)
it "works5" $ do
parseEntityFields
[ Line 0 [Token "Product"]
, Line 2 (Token <$> ["name", "Text"])
, Line 4 [Token "ExtraBlock"]
, Line 4 (Token <$> ["added", "UTCTime", "default=CURRENT_TIMESTAMP"])
]
`shouldBe`
( []
, Map.fromList
[ ("Product",
[ ["name", "Text"]
, ["ExtraBlock"]
, ["added", "UTCTime", "default=CURRENT_TIMESTAMP"]
]
)]
)
describe "takeColsEx" $ do
let subject = takeColsEx upperCaseSettings
it "fails on a single word" $ do
subject ["asdf"]
`shouldBe`
Nothing
it "errors on invalid input" $ do
evaluate (subject ["name", "int"])
`shouldErrorWithMessage` "Invalid field type \"int\" PSFail \"int\""
it "works if it has a name and a type" $ do
subject ["asdf", "Int"]
`shouldBe`
Just UnboundFieldDef
{ unboundFieldNameHS = FieldNameHS "asdf"
, unboundFieldNameDB = FieldNameDB "asdf"
, unboundFieldType = FTTypeCon Nothing "Int"
, unboundFieldAttrs = []
, unboundFieldStrict = True
, unboundFieldCascade = noCascade
, unboundFieldComments = Nothing
, unboundFieldGenerated = Nothing
}
it "works if it has a name, type, and cascade" $ do
subject ["asdf", "Int", "OnDeleteCascade", "OnUpdateCascade"]
`shouldBe`
Just UnboundFieldDef
{ unboundFieldNameHS = FieldNameHS "asdf"
, unboundFieldNameDB = FieldNameDB "asdf"
, unboundFieldType = FTTypeCon Nothing "Int"
, unboundFieldAttrs = []
, unboundFieldStrict = True
, unboundFieldCascade = FieldCascade (Just Cascade) (Just Cascade)
, unboundFieldComments = Nothing
, unboundFieldGenerated = Nothing
}
it "never tries to make a refernece" $ do
subject ["asdf", "UserId", "OnDeleteCascade"]
`shouldBe`
Just UnboundFieldDef
{ unboundFieldNameHS = FieldNameHS "asdf"
, unboundFieldNameDB = FieldNameDB "asdf"
, unboundFieldType = FTTypeCon Nothing "UserId"
, unboundFieldAttrs = []
, unboundFieldStrict = True
, unboundFieldCascade = FieldCascade Nothing (Just Cascade)
, unboundFieldComments = Nothing
, unboundFieldGenerated = Nothing
}
describe "parseLine" $ do
it "returns nothing when line is just whitespace" $
parseLine " " `shouldBe` Nothing
it "handles normal words" $
parseLine " foo bar baz" `shouldBe`
Just
( Line 1
[ Token "foo"
, Token "bar"
, Token "baz"
]
)
it "handles numbers" $
parseLine " one (Finite 1)" `shouldBe`
Just
( Line 2
[ Token "one"
, Token "Finite 1"
]
)
it "handles quotes" $
parseLine " \"foo bar\" \"baz\"" `shouldBe`
Just
( Line 2
[ Token "foo bar"
, Token "baz"
]
)
it "should error if quotes are unterminated" $ do
evaluate (parseLine " \"foo bar")
`shouldErrorWithMessage`
"Unterminated quoted string starting with foo bar"
it "handles quotes mid-token" $
parseLine " x=\"foo bar\" \"baz\"" `shouldBe`
Just
( Line 2
[ Token "x=foo bar"
, Token "baz"
]
)
it "handles escaped quote mid-token" $
parseLine " x=\\\"foo bar\" \"baz\"" `shouldBe`
Just
( Line 2
[ Token "x=\\\"foo"
, Token "bar\""
, Token "baz"
]
)
it "handles unnested parantheses" $
parseLine " (foo bar) (baz)" `shouldBe`
Just
( Line 2
[ Token "foo bar"
, Token "baz"
]
)
it "handles unnested parantheses mid-token" $
parseLine " x=(foo bar) (baz)" `shouldBe`
Just
( Line 2
[ Token "x=foo bar"
, Token "baz"
]
)
it "handles nested parantheses" $
parseLine " (foo (bar)) (baz)" `shouldBe`
Just
( Line 2
[ Token "foo (bar)"
, Token "baz"
]
)
it "escaping" $
parseLine " (foo \\(bar) y=\"baz\\\"\"" `shouldBe`
Just
( Line 2
[ Token "foo (bar"
, Token "y=baz\""
]
)
it "mid-token quote in later token" $
parseLine "foo bar baz=(bin\")" `shouldBe`
Just
( Line 0
[ Token "foo"
, Token "bar"
, Token "baz=bin\""
]
)
describe "comments" $ do
it "recognizes one line" $ do
parseLine "-- | this is a comment" `shouldBe`
Just
( Line 0
[ DocComment "this is a comment"
]
)
it "recognizes empty line" $ do
parseLine "-- |" `shouldBe`
Just
( Line 0
[ DocComment ""
]
)
it "works if comment is indented" $ do
parseLine " -- | comment" `shouldBe`
Just (Line 2 [DocComment "comment"])
describe "parse" $ do
let subject =
[st|
Bicycle -- | this is a bike
brand String -- | the brand of the bike
ExtraBike
foo bar -- | this is a foo bar
baz
deriving Eq
-- | This is a Car
Car
-- | the make of the Car
make String
-- | the model of the Car
model String
UniqueModel model
deriving Eq Show
+Vehicle
bicycle BicycleId -- | the bike reference
car CarId -- | the car reference
|]
let [bicycle, car, vehicle] = parse lowerCaseSettings subject
it "should parse the `entityHaskell` field" $ do
getUnboundEntityNameHS bicycle `shouldBe` EntityNameHS "Bicycle"
getUnboundEntityNameHS car `shouldBe` EntityNameHS "Car"
getUnboundEntityNameHS vehicle `shouldBe` EntityNameHS "Vehicle"
it "should parse the `entityDB` field" $ do
entityDB (unboundEntityDef bicycle) `shouldBe` EntityNameDB "bicycle"
entityDB (unboundEntityDef car) `shouldBe` EntityNameDB "car"
entityDB (unboundEntityDef vehicle) `shouldBe` EntityNameDB "vehicle"
it "should parse the `entityAttrs` field" $ do
entityAttrs (unboundEntityDef bicycle) `shouldBe` ["-- | this is a bike"]
entityAttrs (unboundEntityDef car) `shouldBe` []
entityAttrs (unboundEntityDef vehicle) `shouldBe` []
it "should parse the `unboundEntityFields` field" $ do
let simplifyField field =
(unboundFieldNameHS field, unboundFieldNameDB field, unboundFieldComments field)
(simplifyField <$> unboundEntityFields bicycle) `shouldBe`
[ (FieldNameHS "brand", FieldNameDB "brand", Nothing)
]
(simplifyField <$> unboundEntityFields car) `shouldBe`
[ (FieldNameHS "make", FieldNameDB "make", Just "the make of the Car\n")
, (FieldNameHS "model", FieldNameDB "model", Just "the model of the Car\n")
]
(simplifyField <$> unboundEntityFields vehicle) `shouldBe`
[ (FieldNameHS "bicycle", FieldNameDB "bicycle", Nothing)
, (FieldNameHS "car", FieldNameDB "car", Nothing)
]
it "should parse the `entityUniques` field" $ do
let simplifyUnique unique =
(uniqueHaskell unique, uniqueFields unique)
(simplifyUnique <$> entityUniques (unboundEntityDef bicycle)) `shouldBe` []
(simplifyUnique <$> entityUniques (unboundEntityDef car)) `shouldBe`
[ (ConstraintNameHS "UniqueModel", [(FieldNameHS "model", FieldNameDB "model")])
]
(simplifyUnique <$> entityUniques (unboundEntityDef vehicle)) `shouldBe` []
it "should parse the `entityForeigns` field" $ do
let [user, notification] = parse lowerCaseSettings [st|
User
name Text
emailFirst Text
emailSecond Text
UniqueEmail emailFirst emailSecond
Notification
content Text
sentToFirst Text
sentToSecond Text
Foreign User fk_noti_user sentToFirst sentToSecond References emailFirst emailSecond
|]
unboundForeignDefs user `shouldBe` []
map unboundForeignDef (unboundForeignDefs notification) `shouldBe`
[ ForeignDef
{ foreignRefTableHaskell = EntityNameHS "User"
, foreignRefTableDBName = EntityNameDB "user"
, foreignConstraintNameHaskell = ConstraintNameHS "fk_noti_user"
, foreignConstraintNameDBName = ConstraintNameDB "notificationfk_noti_user"
, foreignFieldCascade = FieldCascade Nothing Nothing
, foreignFields =
[]
-- the foreign fields are not set yet in an unbound
-- entity def
, foreignAttrs = []
, foreignNullable = False
, foreignToPrimary = False
}
]
it "should parse the `entityDerives` field" $ do
entityDerives (unboundEntityDef bicycle) `shouldBe` ["Eq"]
entityDerives (unboundEntityDef car) `shouldBe` ["Eq", "Show"]
entityDerives (unboundEntityDef vehicle) `shouldBe` []
it "should parse the `entityEntities` field" $ do
entityExtra (unboundEntityDef bicycle) `shouldBe` Map.singleton "ExtraBike" [["foo", "bar", "-- | this is a foo bar"], ["baz"]]
entityExtra (unboundEntityDef car) `shouldBe` mempty
entityExtra (unboundEntityDef vehicle) `shouldBe` mempty
it "should parse the `entitySum` field" $ do
entitySum (unboundEntityDef bicycle) `shouldBe` False
entitySum (unboundEntityDef car) `shouldBe` False
entitySum (unboundEntityDef vehicle) `shouldBe` True
it "should parse the `entityComments` field" $ do
entityComments (unboundEntityDef bicycle) `shouldBe` Nothing
entityComments (unboundEntityDef car) `shouldBe` Just "This is a Car\n"
entityComments (unboundEntityDef vehicle) `shouldBe` Nothing
it "should error on malformed input, unterminated parens" $ do
let definitions = [st|
User
name Text
age (Maybe Int
|]
let [user] = parse lowerCaseSettings definitions
evaluate (unboundEntityDef user)
`shouldErrorWithMessage`
"Unterminated parens string starting with Maybe Int"
it "errors on duplicate cascade update declarations" $ do
let definitions = [st|
User
age Int OnUpdateCascade OnUpdateCascade
|]
let [user] = parse lowerCaseSettings definitions
mapM (evaluate . unboundFieldCascade) (unboundEntityFields user)
`shouldErrorWithMessage`
"found more than one OnUpdate action, tokens: [\"OnUpdateCascade\",\"OnUpdateCascade\"]"
it "errors on duplicate cascade delete declarations" $ do
let definitions = [st|
User
age Int OnDeleteCascade OnDeleteCascade
|]
let [user] = parse lowerCaseSettings definitions
mapM (evaluate . unboundFieldCascade) (unboundEntityFields user)
`shouldErrorWithMessage`
"found more than one OnDelete action, tokens: [\"OnDeleteCascade\",\"OnDeleteCascade\"]"
describe "custom Id column" $ do
it "parses custom Id column" $ do
let definitions = [st|
User
Id Text
name Text
age Int
|]
let [user] = parse lowerCaseSettings definitions
getUnboundEntityNameHS user `shouldBe` EntityNameHS "User"
entityDB (unboundEntityDef user) `shouldBe` EntityNameDB "user"
let idFields = NEL.toList (entitiesPrimary (unboundEntityDef user))
(fieldHaskell <$> idFields) `shouldBe` [FieldNameHS "Id"]
(fieldDB <$> idFields) `shouldBe` [FieldNameDB "id"]
(fieldType <$> idFields) `shouldBe` [FTTypeCon Nothing "Text"]
(unboundFieldNameHS <$> unboundEntityFields user) `shouldBe`
[ FieldNameHS "name"
, FieldNameHS "age"
]
it "errors on duplicate custom Id column" $ do
let definitions = [st|
User
Id Text
Id Text
name Text
age Int
|]
let [user] = parse lowerCaseSettings definitions
errMsg = [st|expected only one Id declaration per entity|]
evaluate (unboundEntityDef user) `shouldErrorWithMessage`
(T.unpack errMsg)
describe "primary declaration" $ do
it "parses Primary declaration" $ do
let definitions = [st|
User
ref Text
name Text
age Int
Primary ref
|]
let [user] = parse lowerCaseSettings definitions
getUnboundEntityNameHS user `shouldBe` EntityNameHS "User"
entityDB (unboundEntityDef user) `shouldBe` EntityNameDB "user"
let idFields = NEL.toList (entitiesPrimary (unboundEntityDef user))
(fieldHaskell <$> idFields) `shouldBe` [FieldNameHS "Id"]
(fieldDB <$> idFields) `shouldBe` [FieldNameDB "id"]
(fieldType <$> idFields) `shouldBe` [FTTypeCon Nothing "UserId"]
(unboundFieldNameHS <$> unboundEntityFields user) `shouldBe`
[ FieldNameHS "ref"
, FieldNameHS "name"
, FieldNameHS "age"
]
entityUniques (unboundEntityDef user) `shouldBe`
[ UniqueDef
{ uniqueHaskell =
ConstraintNameHS "UserPrimaryKey"
, uniqueDBName =
ConstraintNameDB "primary_key"
, uniqueFields =
pure (FieldNameHS "ref", FieldNameDB "ref")
, uniqueAttrs =
[]
}
]
it "errors on duplicate custom Primary declaration" $ do
let definitions = [st|
User
ref Text
name Text
age Int
Primary ref
Primary name
|]
let [user] = parse lowerCaseSettings definitions
errMsg = "expected only one Primary declaration per entity"
evaluate (unboundEntityDef user) `shouldErrorWithMessage`
errMsg
it "errors on conflicting Primary/Id declarations" $ do
let definitions = [st|
User
Id Text
ref Text
name Text
age Int
Primary ref
|]
let [user] = parse lowerCaseSettings definitions
errMsg = [st|Specified both an ID field and a Primary field|]
evaluate (unboundEntityDef user) `shouldErrorWithMessage`
(T.unpack errMsg)
it "triggers error on invalid declaration" $ do
let definitions = [st|
User
age Text
Primary ref
|]
let [user] = parse lowerCaseSettings definitions
case unboundPrimarySpec user of
NaturalKey ucd -> do
evaluate (NEL.head $ unboundCompositeCols ucd) `shouldErrorWithMessage`
"Unknown column in primary key constraint: \"ref\""
_ ->
error "Expected NaturalKey, failing"
describe "entity unique constraints" $ do
it "triggers error if declared field does not exist" $ do
let definitions = [st|
User
name Text
emailFirst Text
UniqueEmail emailFirst emailSecond
|]
let [user] = parse lowerCaseSettings definitions
uniques = entityUniques (unboundEntityDef user)
[dbNames] = fmap snd . uniqueFields <$> uniques
errMsg = unwords
[ "Unknown column in \"UniqueEmail\" constraint: \"emailSecond\""
, "possible fields: [\"name\",\"emailFirst\"]"
]
evaluate (head (NEL.tail dbNames)) `shouldErrorWithMessage`
errMsg
it "triggers error if no valid constraint name provided" $ do
let definitions = [st|
User
age Text
Unique some
|]
let [user] = parse lowerCaseSettings definitions
evaluate (unboundPrimarySpec user) `shouldErrorWithMessage`
"invalid unique constraint on table[\"User\"] expecting an uppercase constraint name xs=[\"some\"]"
describe "foreign keys" $ do
let validDefinitions = [st|
User
name Text
emailFirst Text
emailSecond Text
UniqueEmail emailFirst emailSecond
Notification
content Text
sentToFirst Text
sentToSecond Text
Foreign User fk_noti_user sentToFirst sentToSecond References emailFirst emailSecond
|]
it "should allow you to modify the FK name via provided function" $ do
let
flippedFK (EntityNameHS entName) (ConstraintNameHS conName) =
conName <> entName
[_user, notification] =
parse (setPsToFKName flippedFK lowerCaseSettings) validDefinitions
[notificationForeignDef] =
unboundForeignDef <$> unboundForeignDefs notification
foreignConstraintNameDBName notificationForeignDef
`shouldBe`
ConstraintNameDB "fk_noti_user_notification"
it "should error when insufficient params provided" $ do
let definitions = [st|
User
name Text
emailFirst Text
emailSecond Text
UniqueEmail emailFirst emailSecond
Notification
content Text
sentToFirst Text
sentToSecond Text
Foreign User
|]
let [_user, notification] = parse (setPsUseSnakeCaseForiegnKeys lowerCaseSettings) definitions
mapM (evaluate . unboundForeignFields) (unboundForeignDefs notification)
`shouldErrorWithMessage`
"invalid foreign key constraint on table[\"Notification\"] expecting a lower case constraint name or a cascading action xs=[]"
it "should error when foreign fields not provided" $ do
let definitions = [st|
User
name Text
emailFirst Text
emailSecond Text
UniqueEmail emailFirst emailSecond
Notification
content Text
sentToFirst Text
sentToSecond Text
Foreign User fk_noti_user
|]
let [_user, notification] = parse (setPsUseSnakeCaseForiegnKeys lowerCaseSettings) definitions
mapM (evaluate . unboundForeignFields) (unboundForeignDefs notification)
`shouldErrorWithMessage`
"No fields on foreign reference."
it "should error when number of parent and foreign fields differ" $ do
let definitions = [st|
User
name Text
emailFirst Text
emailSecond Text
UniqueEmail emailFirst emailSecond
Notification
content Text
sentToFirst Text
sentToSecond Text
Foreign User fk_noti_user sentToFirst sentToSecond References emailFirst
|]
let [_user, notification] = parse (setPsUseSnakeCaseForiegnKeys lowerCaseSettings) definitions
mapM (evaluate . unboundForeignFields) (unboundForeignDefs notification)
`shouldErrorWithMessage`
"invalid foreign key constraint on table[\"Notification\"] Found 2 foreign fields but 1 parent fields"
it "should throw error when there is more than one delete cascade on the declaration" $ do
let definitions = [st|
User
name Text
emailFirst Text
emailSecond Text
UniqueEmail emailFirst emailSecond
Notification
content Text
sentToFirst Text
sentToSecond Text
Foreign User OnDeleteCascade OnDeleteCascade
|]
let [_user, notification] = parse (setPsUseSnakeCaseForiegnKeys lowerCaseSettings) definitions
mapM (evaluate . unboundForeignFields) (unboundForeignDefs notification)
`shouldErrorWithMessage`
"invalid foreign key constraint on table[\"Notification\"] found more than one OnDelete actions"
it "should throw error when there is more than one update cascade on the declaration" $ do
let definitions = [st|
User
name Text
emailFirst Text
emailSecond Text
UniqueEmail emailFirst emailSecond
Notification
content Text
sentToFirst Text
sentToSecond Text
Foreign User OnUpdateCascade OnUpdateCascade
|]
let [_user, notification] = parse (setPsUseSnakeCaseForiegnKeys lowerCaseSettings) definitions
mapM (evaluate . unboundForeignFields) (unboundForeignDefs notification)
`shouldErrorWithMessage`
"invalid foreign key constraint on table[\"Notification\"] found more than one OnUpdate actions"
it "should allow you to enable snake cased foriegn keys via a preset configuration function" $ do
let [_user, notification] =
parse (setPsUseSnakeCaseForiegnKeys lowerCaseSettings) validDefinitions
[notificationForeignDef] =
unboundForeignDef <$> unboundForeignDefs notification
foreignConstraintNameDBName notificationForeignDef
`shouldBe`
ConstraintNameDB "notification_fk_noti_user"
describe "ticked types" $ do
it "should be able to parse ticked types" $ do
let simplifyField field =
(unboundFieldNameHS field, unboundFieldType field)
let tickedDefinition = [st|
CustomerTransfer
customerId CustomerId
moneyAmount (MoneyAmount 'Customer 'Debit)
currencyCode CurrencyCode
uuid TransferUuid
|]
let [customerTransfer] = parse lowerCaseSettings tickedDefinition
let expectedType =
FTTypeCon Nothing "MoneyAmount" `FTApp` FTTypePromoted "Customer" `FTApp` FTTypePromoted "Debit"
(simplifyField <$> unboundEntityFields customerTransfer) `shouldBe`
[ (FieldNameHS "customerId", FTTypeCon Nothing "CustomerId")
, (FieldNameHS "moneyAmount", expectedType)
, (FieldNameHS "currencyCode", FTTypeCon Nothing "CurrencyCode")
, (FieldNameHS "uuid", FTTypeCon Nothing "TransferUuid")
]
describe "type literals" $ do
it "should be able to parse type literals" $ do
let simplifyField field =
(unboundFieldNameHS field, unboundFieldType field)
let tickedDefinition = [st|
WithFinite
one (Finite 1)
twenty (Labelled "twenty")
|]
let [withFinite] = parse lowerCaseSettings tickedDefinition
(simplifyField <$> unboundEntityFields withFinite) `shouldBe`
[ (FieldNameHS "one", FTApp (FTTypeCon Nothing "Finite") (FTLit (IntTypeLit 1)))
, (FieldNameHS "twenty", FTApp (FTTypeCon Nothing "Labelled") (FTLit (TextTypeLit "twenty")))
]
describe "parseFieldType" $ do
it "simple types" $
parseFieldType "FooBar" `shouldBe` Right (FTTypeCon Nothing "FooBar")
it "module types" $
parseFieldType "Data.Map.FooBar" `shouldBe` Right (FTTypeCon (Just "Data.Map") "FooBar")
it "application" $
parseFieldType "Foo Bar" `shouldBe` Right (
FTTypeCon Nothing "Foo" `FTApp` FTTypeCon Nothing "Bar")
it "application multiple" $
parseFieldType "Foo Bar Baz" `shouldBe` Right (
(FTTypeCon Nothing "Foo" `FTApp` FTTypeCon Nothing "Bar")
`FTApp` FTTypeCon Nothing "Baz"
)
it "parens" $ do
let foo = FTTypeCon Nothing "Foo"
bar = FTTypeCon Nothing "Bar"
baz = FTTypeCon Nothing "Baz"
parseFieldType "Foo (Bar Baz)" `shouldBe` Right (
foo `FTApp` (bar `FTApp` baz))
it "lists" $ do
let foo = FTTypeCon Nothing "Foo"
bar = FTTypeCon Nothing "Bar"
bars = FTList bar
baz = FTTypeCon Nothing "Baz"
parseFieldType "Foo [Bar] Baz" `shouldBe` Right (
foo `FTApp` bars `FTApp` baz)
it "numeric type literals" $ do
let expected = FTApp (FTTypeCon Nothing "Finite") (FTLit (IntTypeLit 1))
parseFieldType "Finite 1" `shouldBe` Right expected
it "string type literals" $ do
let expected = FTApp (FTTypeCon Nothing "Labelled") (FTLit (TextTypeLit "twenty"))
parseFieldType "Labelled \"twenty\"" `shouldBe` Right expected
it "nested list / parens (list inside parens)" $ do
let maybeCon = FTTypeCon Nothing "Maybe"
int = FTTypeCon Nothing "Int"
parseFieldType "Maybe (Maybe [Int])" `shouldBe` Right
(maybeCon `FTApp` (maybeCon `FTApp` FTList int))
it "nested list / parens (parens inside list)" $ do
let maybeCon = FTTypeCon Nothing "Maybe"
int = FTTypeCon Nothing "Int"
parseFieldType "[Maybe (Maybe Int)]" `shouldBe` Right
(FTList (maybeCon `FTApp` (maybeCon `FTApp` int)))
it "fails on lowercase starts" $ do
parseFieldType "nothanks" `shouldBe` Left "PSFail \"nothanks\""
describe "#1175 empty entity" $ do
let subject =
[st|
Foo
name String
age Int
EmptyEntity
Bar
name String
Baz
a Int
b String
c FooId
|]
let preparsed =
preparse subject
it "preparse works" $ do
(length <$> preparsed) `shouldBe` Just 10
let fooLines =
[ Line
{ lineIndent = 0
, tokens = Token "Foo" :| []
}
, Line
{ lineIndent = 4
, tokens = Token "name" :| [Token "String"]
}
, Line
{ lineIndent = 4
, tokens = Token "age" :| [Token "Int"]
}
]
emptyLines =
[ Line
{ lineIndent = 0
, tokens = Token "EmptyEntity" :| []
}
]
barLines =
[ Line
{ lineIndent = 0
, tokens = Token "Bar" :| []
}
, Line
{ lineIndent = 4
, tokens = Token "name" :| [Token "String"]
}
]
bazLines =
[ Line
{ lineIndent = 0
, tokens = Token "Baz" :| []
}
, Line
{ lineIndent = 4
, tokens = Token "a" :| [Token "Int"]
}
, Line
{ lineIndent = 4
, tokens = Token "b" :| [Token "String"]
}
, Line
{ lineIndent = 4
, tokens = Token "c" :| [Token "FooId"]
}
]
let
linesAssociated =
case preparsed of
Nothing -> error "preparsed failed"
Just lines -> associateLines lines
it "associateLines works" $ do
linesAssociated `shouldMatchList`
[ LinesWithComments
{ lwcLines = NEL.fromList fooLines
, lwcComments = []
}
, LinesWithComments (NEL.fromList emptyLines) []
, LinesWithComments (NEL.fromList barLines) []
, LinesWithComments (NEL.fromList bazLines) []
]
it "parse works" $ do
let test name'fieldCount parsedList = do
case (name'fieldCount, parsedList) of
([], []) ->
pure ()
((name, fieldCount) : _, []) ->
expectationFailure
$ "Expected an entity with name "
<> name
<> " and " <> show fieldCount <> " fields"
<> ", but the list was empty..."
((name, fieldCount) : ys, (x : xs)) -> do
let
UnboundEntityDef {..} =
x
(unEntityNameHS (getUnboundEntityNameHS x), length unboundEntityFields)
`shouldBe`
(T.pack name, fieldCount)
test ys xs
([], _:_) ->
expectationFailure
"more entities parsed than expected"
result =
parse lowerCaseSettings subject
length result `shouldBe` 4
test
[ ("Foo", 2)
, ("EmptyEntity", 0)
, ("Bar", 1)
, ("Baz", 3)
]
result
describe "preparse" $ do
prop "omits lines that are only whitespace" $ \len -> do
ws <- vectorOf len arbitraryWhiteSpaceChar
pure $ preparse (T.pack ws) === Nothing
it "recognizes entity" $ do
let expected =
Line { lineIndent = 0, tokens = pure (Token "Person") } :|
[ Line { lineIndent = 2, tokens = Token "name" :| [Token "String"] }
, Line { lineIndent = 2, tokens = Token "age" :| [Token "Int"] }
]
preparse "Person\n name String\n age Int" `shouldBe` Just expected
it "recognizes comments" $ do
let text = "Foo\n x X\n-- | Hello\nBar\n name String"
let expected =
Line { lineIndent = 0, tokens = pure (Token "Foo") } :|
[ Line { lineIndent = 2, tokens = Token "x" :| [Token "X"] }
, Line { lineIndent = 0, tokens = pure (DocComment "Hello") }
, Line { lineIndent = 0, tokens = pure (Token "Bar") }
, Line { lineIndent = 1, tokens = Token "name" :| [Token "String"] }
]
preparse text `shouldBe` Just expected
it "preparse indented" $ do
let t = T.unlines
[ " Foo"
, " x X"
, " -- | Comment"
, " -- hidden comment"
, " Bar"
, " name String"
]
expected =
Line { lineIndent = 2, tokens = pure (Token "Foo") } :|
[ Line { lineIndent = 4, tokens = Token "x" :| [Token "X"] }
, Line { lineIndent = 2, tokens = pure (DocComment "Comment") }
, Line { lineIndent = 2, tokens = pure (Token "Bar") }
, Line { lineIndent = 4, tokens = Token "name" :| [Token "String"] }
]
preparse t `shouldBe` Just expected
it "preparse extra blocks" $ do
let t = T.unlines
[ "LowerCaseTable"
, " name String"
, " ExtraBlock"
, " foo bar"
, " baz"
, " ExtraBlock2"
, " something"
]
expected =
Line { lineIndent = 0, tokens = pure (Token "LowerCaseTable") } :|
[ Line { lineIndent = 2, tokens = Token "name" :| [Token "String"] }
, Line { lineIndent = 2, tokens = pure (Token "ExtraBlock") }
, Line { lineIndent = 4, tokens = Token "foo" :| [Token "bar"] }
, Line { lineIndent = 4, tokens = pure (Token "baz") }
, Line { lineIndent = 2, tokens = pure (Token "ExtraBlock2") }
, Line { lineIndent = 4, tokens = pure (Token "something") }
]
preparse t `shouldBe` Just expected
it "field comments" $ do
let text = T.unlines
[ "-- | Model"
, "Foo"
, " -- | Field"
, " name String"
]
expected =
Line { lineIndent = 0, tokens = [DocComment "Model"] } :|
[ Line { lineIndent = 0, tokens = [Token "Foo"] }
, Line { lineIndent = 2, tokens = [DocComment "Field"] }
, Line { lineIndent = 2, tokens = (Token <$> ["name", "String"]) }
]
preparse text `shouldBe` Just expected
describe "associateLines" $ do
let foo =
Line
{ lineIndent = 0
, tokens = pure (Token "Foo")
}
name'String =
Line
{ lineIndent = 2
, tokens = Token "name" :| [Token "String"]
}
comment =
Line
{ lineIndent = 0
, tokens = pure (DocComment "comment")
}
it "works" $ do
associateLines
( comment :|
[ foo
, name'String
])
`shouldBe`
[ LinesWithComments
{ lwcComments = ["comment"]
, lwcLines = foo :| [name'String]
}
]
let bar =
Line
{ lineIndent = 0
, tokens = Token "Bar" :| [Token "sql", Token "=", Token "bars"]
}
age'Int =
Line
{ lineIndent = 1
, tokens = Token "age" :| [Token "Int"]
}
it "works when used consecutively" $ do
associateLines
( bar :|
[ age'Int
, comment
, foo
, name'String
])
`shouldBe`
[ LinesWithComments
{ lwcComments = []
, lwcLines = bar :| [age'Int]
}
, LinesWithComments
{ lwcComments = ["comment"]
, lwcLines = foo :| [name'String]
}
]
it "works with textual input" $ do
let text = preparse "Foo\n x X\n-- | Hello\nBar\n name String"
associateLines <$> text
`shouldBe` Just
[ LinesWithComments
{ lwcLines =
Line {lineIndent = 0, tokens = Token "Foo" :| []}
:| [ Line {lineIndent = 2, tokens = Token "x" :| [Token "X"]} ]
, lwcComments =
[]
}
, LinesWithComments
{ lwcLines =
Line {lineIndent = 0, tokens = Token "Bar" :| []}
:| [ Line {lineIndent = 1, tokens = Token "name" :| [Token "String"]}]
, lwcComments =
["Hello"]
}
]
it "works with extra blocks" $ do
let text = preparse . T.unlines $
[ "LowerCaseTable"
, " Id sql=my_id"
, " fullName Text"
, " ExtraBlock"
, " foo bar"
, " baz"
, " bin"
, " ExtraBlock2"
, " something"
]
associateLines <$> text `shouldBe` Just
[ LinesWithComments
{ lwcLines =
Line { lineIndent = 0, tokens = pure (Token "LowerCaseTable") } :|
[ Line { lineIndent = 4, tokens = Token "Id" :| [Token "sql=my_id"] }
, Line { lineIndent = 4, tokens = Token "fullName" :| [Token "Text"] }
, Line { lineIndent = 4, tokens = pure (Token "ExtraBlock") }
, Line { lineIndent = 8, tokens = Token "foo" :| [Token "bar"] }
, Line { lineIndent = 8, tokens = pure (Token "baz") }
, Line { lineIndent = 8, tokens = pure (Token "bin") }
, Line { lineIndent = 4, tokens = pure (Token "ExtraBlock2") }
, Line { lineIndent = 8, tokens = pure (Token "something") }
]
, lwcComments = []
}
]
it "works with extra blocks twice" $ do
let text = preparse . T.unlines $
[ "IdTable"
, " Id Day default=CURRENT_DATE"
, " name Text"
, ""
, "LowerCaseTable"
, " Id sql=my_id"
, " fullName Text"
, " ExtraBlock"
, " foo bar"
, " baz"
, " bin"
, " ExtraBlock2"
, " something"
]
associateLines <$> text `shouldBe` Just
[ LinesWithComments
{ lwcLines = Line 0 (pure (Token "IdTable")) :|
[ Line 4 (Token "Id" <| Token "Day" :| [Token "default=CURRENT_DATE"])
, Line 4 (Token "name" :| [Token "Text"])
]
, lwcComments = []
}
, LinesWithComments
{ lwcLines =
Line { lineIndent = 0, tokens = pure (Token "LowerCaseTable") } :|
[ Line { lineIndent = 4, tokens = Token "Id" :| [Token "sql=my_id"] }
, Line { lineIndent = 4, tokens = Token "fullName" :| [Token "Text"] }
, Line { lineIndent = 4, tokens = pure (Token "ExtraBlock") }
, Line { lineIndent = 8, tokens = Token "foo" :| [Token "bar"] }
, Line { lineIndent = 8, tokens = pure (Token "baz") }
, Line { lineIndent = 8, tokens = pure (Token "bin") }
, Line { lineIndent = 4, tokens = pure (Token "ExtraBlock2") }
, Line { lineIndent = 8, tokens = pure (Token "something") }
]
, lwcComments = []
}
]
it "works with field comments" $ do
let text = preparse . T.unlines $
[ "-- | Model"
, "Foo"
, " -- | Field"
, " name String"
]
associateLines <$> text `shouldBe` Just
[ LinesWithComments
{ lwcLines =
Line { lineIndent = 0, tokens = (Token "Foo") :| [] } :|
[ Line { lineIndent = 2, tokens = pure (DocComment "Field") }
, Line { lineIndent = 2, tokens = Token "name" :| [Token "String"] }
]
, lwcComments =
["Model"]
}
]
describe "parseLines" $ do
let lines =
T.unlines
[ "-- | Comment"
, "Foo"
, " -- | Field"
, " name String"
, " age Int"
, " Extra"
, " foo bar"
, " baz"
, " Extra2"
, " something"
]
let [subject] = parse lowerCaseSettings lines
it "produces the right name" $ do
getUnboundEntityNameHS subject `shouldBe` EntityNameHS "Foo"
describe "unboundEntityFields" $ do
let fields = unboundEntityFields subject
it "has the right field names" $ do
map unboundFieldNameHS fields `shouldMatchList`
[ FieldNameHS "name"
, FieldNameHS "age"
]
it "has comments" $ do
map unboundFieldComments fields `shouldBe`
[ Just "Field\n"
, Nothing
]
it "has the comments" $ do
entityComments (unboundEntityDef subject) `shouldBe`
Just "Comment\n"
it "combines extrablocks" $ do
entityExtra (unboundEntityDef subject) `shouldBe` Map.fromList
[ ("Extra", [["foo", "bar"], ["baz"]])
, ("Extra2", [["something"]])
]
describe "works with extra blocks" $ do
let [_, lowerCaseTable, idTable] =
case parse lowerCaseSettings $ T.unlines
[ ""
, "IdTable"
, " Id Day default=CURRENT_DATE"
, " name Text"
, ""
, "LowerCaseTable"
, " Id sql=my_id"
, " fullName Text"
, " ExtraBlock"
, " foo bar"
, " baz"
, " bin"
, " ExtraBlock2"
, " something"
, ""
, "IdTable"
, " Id Day default=CURRENT_DATE"
, " name Text"
, ""
] of
[a, b, c] ->
[a, b, c] :: [UnboundEntityDef]
xs ->
error
$ "Expected 3 elements in list, got: "
<> show (length xs)
<> ", list contents: \n\n" <> intercalate "\n" (map show xs)
describe "idTable" $ do
let UnboundEntityDef { unboundEntityDef = EntityDef {..}, .. } = idTable
it "has no extra blocks" $ do
entityExtra `shouldBe` mempty
it "has the right name" $ do
entityHaskell `shouldBe` EntityNameHS "IdTable"
it "has the right fields" $ do
map unboundFieldNameHS unboundEntityFields `shouldMatchList`
[ FieldNameHS "name"
]
describe "lowerCaseTable" $ do
let UnboundEntityDef { unboundEntityDef = EntityDef {..}, ..} = lowerCaseTable
it "has the right name" $ do
entityHaskell `shouldBe` EntityNameHS "LowerCaseTable"
it "has the right fields" $ do
map unboundFieldNameHS unboundEntityFields `shouldMatchList`
[ FieldNameHS "fullName"
]
it "has ExtraBlock" $ do
Map.lookup "ExtraBlock" entityExtra
`shouldBe` Just
[ ["foo", "bar"]
, ["baz"]
, ["bin"]
]
it "has ExtraBlock2" $ do
Map.lookup "ExtraBlock2" entityExtra
`shouldBe` Just
[ ["something"]
]
arbitraryWhiteSpaceChar :: Gen Char
arbitraryWhiteSpaceChar =
oneof $ pure <$> [' ', '\t', '\n', '\r']
shouldErrorWithMessage :: IO a -> String -> Expectation
shouldErrorWithMessage action expectedMsg = do
res <- try action
case res of
Left (ErrorCall msg) ->
msg `shouldBe` expectedMsg
_ ->
expectationFailure "Expected `error` to have been called"
|