-
Notifications
You must be signed in to change notification settings - Fork 301
Expand file tree
/
Copy pathMySQL.hs
More file actions
1653 lines (1517 loc) · 62.5 KB
/
MySQL.hs
File metadata and controls
1653 lines (1517 loc) · 62.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 BangPatterns #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-deprecations #-} -- Pattern match 'PersistDbSpecific'
-- | A MySQL backend for @persistent@.
module Database.Persist.MySQL
( withMySQLPool
, withMySQLConn
, createMySQLPool
, module Database.Persist.Sql
, MySQL.ConnectInfo(..)
, MySQLBase.SSLInfo(..)
, MySQL.defaultConnectInfo
, MySQLBase.defaultSSLInfo
, MySQLConf(..)
, mockMigration
-- * @ON DUPLICATE KEY UPDATE@ Functionality
, insertOnDuplicateKeyUpdate
, insertManyOnDuplicateKeyUpdate
, HandleUpdateCollision
, copyField
, copyUnlessNull
, copyUnlessEmpty
, copyUnlessEq
, openMySQLConn
) where
import qualified Blaze.ByteString.Builder.ByteString as BBS
import qualified Blaze.ByteString.Builder.Char8 as BBB
import Control.Arrow
import Control.Monad
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.IO.Unlift (MonadUnliftIO)
import Control.Monad.Logger (MonadLoggerIO, runNoLoggingT)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Except (ExceptT, runExceptT)
import Control.Monad.Trans.Reader (ReaderT, runReaderT)
import Control.Monad.Trans.Writer (runWriterT)
import Data.IORef (newIORef)
import Data.Proxy (Proxy(..))
import Data.Acquire (Acquire, mkAcquire, with)
import Data.Aeson
import Data.Aeson.Types (modifyFailure)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BSL
import Data.Conduit
import qualified Data.Conduit.List as CL
import Data.Either (partitionEithers)
import Data.Fixed (Pico)
import Data.Function (on)
import Data.Int (Int64)
import Data.List (find, groupBy, intercalate, sort)
import qualified Data.List.NonEmpty as NEL
import qualified Data.Map as Map
import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)
import Data.Monoid ((<>))
import qualified Data.Monoid as Monoid
import Data.Pool (Pool)
import Data.Text (Text, pack)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import GHC.Stack
import System.Environment (getEnvironment)
import Database.Persist.Sql
import Database.Persist.Sql.Types.Internal (makeIsolationLevelStatement)
import qualified Database.Persist.Sql.Util as Util
import Database.Persist.SqlBackend
import Database.Persist.SqlBackend.StatementCache
import qualified Database.MySQL.Base as MySQLBase
import qualified Database.MySQL.Base.Types as MySQLBase
import qualified Database.MySQL.Simple as MySQL
import qualified Database.MySQL.Simple.Param as MySQL
import qualified Database.MySQL.Simple.Result as MySQL
import qualified Database.MySQL.Simple.Types as MySQL
-- | Create a MySQL connection pool and run the given action.
-- The pool is properly released after the action finishes using
-- it. Note that you should not use the given 'ConnectionPool'
-- outside the action since it may be already been released.
withMySQLPool
:: (MonadLoggerIO m, MonadUnliftIO m)
=> MySQL.ConnectInfo
-- ^ Connection information.
-> Int
-- ^ Number of connections to be kept open in the pool.
-> (Pool SqlBackend -> m a)
-- ^ Action to be executed that uses the connection pool.
-> m a
withMySQLPool ci = withSqlPool $ open' ci
-- | Create a MySQL connection pool. Note that it's your
-- responsibility to properly close the connection pool when
-- unneeded. Use 'withMySQLPool' for automatic resource control.
createMySQLPool
:: (MonadUnliftIO m, MonadLoggerIO m)
=> MySQL.ConnectInfo
-- ^ Connection information.
-> Int
-- ^ Number of connections to be kept open in the pool.
-> m (Pool SqlBackend)
createMySQLPool ci = createSqlPool $ open' ci
-- | Same as 'withMySQLPool', but instead of opening a pool
-- of connections, only one connection is opened.
withMySQLConn
:: (MonadUnliftIO m, MonadLoggerIO m)
=> MySQL.ConnectInfo
-- ^ Connection information.
-> (SqlBackend -> m a)
-- ^ Action to be executed that uses the connection.
-> m a
withMySQLConn = withSqlConn . open'
-- | Open a connection to MySQL server, initialize the 'SqlBackend' and return
-- their tuple
--
-- @since 2.12.1.0
openMySQLConn :: MySQL.ConnectInfo -> LogFunc -> IO (MySQL.Connection, SqlBackend)
openMySQLConn ci logFunc = do
conn <- MySQL.connect ci
MySQLBase.autocommit conn False -- disable autocommit!
smap <- newIORef mempty
let
backend =
setConnPutManySql putManySql $
setConnRepsertManySql repsertManySql $
mkSqlBackend MkSqlBackendArgs
{ connPrepare = prepare' conn
, connStmtMap = smap
, connInsertSql = insertSql'
, connClose = MySQL.close conn
, connMigrateSql = migrate' ci
, connBegin = \_ mIsolation -> do
forM_ mIsolation $ \iso -> MySQL.execute_ conn (makeIsolationLevelStatement iso)
MySQL.execute_ conn "start transaction" >> return ()
, connCommit = const $ MySQL.commit conn
, connRollback = const $ MySQL.rollback conn
, connEscapeFieldName = T.pack . escapeF
, connEscapeTableName = \ent -> escapeET (getEntityDBName ent) (getEntitySchema ent)
, connEscapeRawName = T.pack . escapeDBName . T.unpack
, connNoLimit = "LIMIT 18446744073709551615"
-- This noLimit is suggested by MySQL's own docs, see
-- <http://dev.mysql.com/doc/refman/5.5/en/select.html>
, connRDBMS = "mysql"
, connLimitOffset = decorateSQLWithLimitOffset "LIMIT 18446744073709551615"
, connLogFunc = logFunc
}
pure (conn, backend)
-- | Internal function that opens a connection to the MySQL server.
open' :: MySQL.ConnectInfo -> LogFunc -> IO SqlBackend
open' ci logFunc = snd <$> openMySQLConn ci logFunc
-- | Prepare a query. We don't support prepared statements, but
-- we'll do some client-side preprocessing here.
prepare' :: MySQL.Connection -> Text -> IO Statement
prepare' conn sql = do
let query = MySQL.Query (T.encodeUtf8 sql)
return Statement
{ stmtFinalize = return ()
, stmtReset = return ()
, stmtExecute = execute' conn query
, stmtQuery = withStmt' conn query
}
-- | SQL code to be executed when inserting an entity.
insertSql' :: EntityDef -> [PersistValue] -> InsertSqlResult
insertSql' ent vals =
case getEntityId ent of
EntityIdNaturalKey _ ->
ISRManyKeys sql vals
EntityIdField _ ->
ISRInsertGet sql "SELECT LAST_INSERT_ID()"
where
(fieldNames, placeholders) = unzip (Util.mkInsertPlaceholders ent escapeFT)
sql = T.concat
[ "INSERT INTO "
, escapeET (getEntityDBName ent) (getEntitySchema ent)
, "("
, T.intercalate "," fieldNames
, ") VALUES("
, T.intercalate "," placeholders
, ")"
]
-- | Execute an statement that doesn't return any results.
execute' :: MySQL.Connection -> MySQL.Query -> [PersistValue] -> IO Int64
execute' conn query vals = MySQL.execute conn query (map P vals)
-- | Execute an statement that does return results. The results
-- are fetched all at once and stored into memory.
withStmt' :: MonadIO m
=> MySQL.Connection
-> MySQL.Query
-> [PersistValue]
-> Acquire (ConduitM () [PersistValue] m ())
withStmt' conn query vals = do
result <- mkAcquire createResult MySQLBase.freeResult
return $ fetchRows result >>= CL.sourceList
where
createResult = do
-- Execute the query
formatted <- MySQL.formatQuery conn query (map P vals)
MySQLBase.query conn formatted
MySQLBase.storeResult conn
fetchRows result = liftIO $ do
-- Find out the type of the columns
fields <- MySQLBase.fetchFields result
let getters = [ maybe PersistNull (getGetter f f . Just) | f <- fields]
convert = use getters
where use (g:gs) (col:cols) =
let !v = g col
!vs = use gs cols
in (v:vs)
use _ _ = []
-- Ready to go!
let go acc = do
row <- MySQLBase.fetchRow result
case row of
[] -> return (acc [])
_ -> let !converted = convert row
in go (acc . (converted:))
go id
-- | @newtype@ around 'PersistValue' that supports the
-- 'MySQL.Param' type class.
newtype P = P PersistValue
instance MySQL.Param P where
render (P (PersistText t)) = MySQL.render t
render (P (PersistByteString bs)) = MySQL.render bs
render (P (PersistInt64 i)) = MySQL.render i
render (P (PersistDouble d)) = MySQL.render d
render (P (PersistBool b)) = MySQL.render b
render (P (PersistDay d)) = MySQL.render d
render (P (PersistTimeOfDay t)) = MySQL.render t
render (P (PersistUTCTime t)) = MySQL.render t
render (P PersistNull) = MySQL.render MySQL.Null
render (P (PersistList l)) = MySQL.render $ listToJSON l
render (P (PersistMap m)) = MySQL.render $ mapToJSON m
render (P (PersistRational r)) =
MySQL.Plain $ BBB.fromString $ show (fromRational r :: Pico)
-- FIXME: Too Ambiguous, can not select precision without information about field
render (P (PersistLiteral_ DbSpecific s)) = MySQL.Plain $ BBS.fromByteString s
render (P (PersistLiteral_ Unescaped l)) = MySQL.Plain $ BBS.fromByteString l
render (P (PersistLiteral_ Escaped e)) = MySQL.Escape e
render (P (PersistArray a)) = MySQL.render (P (PersistList a))
render (P (PersistObjectId _)) =
error "Refusing to serialize a PersistObjectId to a MySQL value"
-- | @Getter a@ is a function that converts an incoming value
-- into a data type @a@.
type Getter a = MySQLBase.Field -> Maybe ByteString -> a
-- | Helper to construct 'Getter'@s@ using 'MySQL.Result'.
convertPV :: MySQL.Result a => (a -> b) -> Getter b
convertPV f = (f .) . MySQL.convert
-- | Get the corresponding @'Getter' 'PersistValue'@ depending on
-- the type of the column.
getGetter :: MySQLBase.Field -> Getter PersistValue
getGetter field = go (MySQLBase.fieldType field)
(MySQLBase.fieldLength field)
(MySQLBase.fieldCharSet field)
where
-- Bool
go MySQLBase.Tiny 1 _ = convertPV PersistBool
go MySQLBase.Tiny _ _ = convertPV PersistInt64
-- Int64
go MySQLBase.Int24 _ _ = convertPV PersistInt64
go MySQLBase.Short _ _ = convertPV PersistInt64
go MySQLBase.Long _ _ = convertPV PersistInt64
go MySQLBase.LongLong _ _ = convertPV PersistInt64
-- Double
go MySQLBase.Float _ _ = convertPV PersistDouble
go MySQLBase.Double _ _ = convertPV PersistDouble
go MySQLBase.Decimal _ _ = convertPV PersistDouble
go MySQLBase.NewDecimal _ _ = convertPV PersistDouble
-- ByteString and Text
-- The MySQL C client (and by extension the Haskell mysql package) doesn't distinguish between binary and non-binary string data at the type level.
-- (e.g. both BLOB and TEXT have the MySQLBase.Blob type).
-- Instead, the character set distinguishes them. Binary data uses character set number 63.
-- See https://dev.mysql.com/doc/refman/5.6/en/c-api-data-structures.html (Search for "63")
go MySQLBase.VarChar _ 63 = convertPV PersistByteString
go MySQLBase.VarString _ 63 = convertPV PersistByteString
go MySQLBase.String _ 63 = convertPV PersistByteString
go MySQLBase.VarChar _ _ = convertPV PersistText
go MySQLBase.VarString _ _ = convertPV PersistText
go MySQLBase.String _ _ = convertPV PersistText
go MySQLBase.Blob _ 63 = convertPV PersistByteString
go MySQLBase.TinyBlob _ 63 = convertPV PersistByteString
go MySQLBase.MediumBlob _ 63 = convertPV PersistByteString
go MySQLBase.LongBlob _ 63 = convertPV PersistByteString
go MySQLBase.Blob _ _ = convertPV PersistText
go MySQLBase.TinyBlob _ _ = convertPV PersistText
go MySQLBase.MediumBlob _ _ = convertPV PersistText
go MySQLBase.LongBlob _ _ = convertPV PersistText
-- Time-related
go MySQLBase.Time _ _ = convertPV PersistTimeOfDay
go MySQLBase.DateTime _ _ = convertPV PersistUTCTime
go MySQLBase.Timestamp _ _ = convertPV PersistUTCTime
go MySQLBase.Date _ _ = convertPV PersistDay
go MySQLBase.NewDate _ _ = convertPV PersistDay
go MySQLBase.Year _ _ = convertPV PersistDay
-- Null
go MySQLBase.Null _ _ = \_ _ -> PersistNull
-- Controversial conversions
go MySQLBase.Set _ _ = convertPV PersistText
go MySQLBase.Enum _ _ = convertPV PersistText
-- Conversion using PersistLiteral
go MySQLBase.Geometry _ _ = \_ m ->
case m of
Just g -> PersistLiteral g
Nothing -> error "Unexpected null in database specific value"
go MySQLBase.Json _ _ = convertPV PersistByteString
-- Unsupported
go other _ _ = error $ "MySQL.getGetter: type " ++
show other ++ " not supported."
----------------------------------------------------------------------
-- | Create the migration plan for the given 'PersistEntity'
-- @val@.
migrate' :: MySQL.ConnectInfo
-> [EntityDef]
-> (Text -> IO Statement)
-> EntityDef
-> IO (Either [Text] CautiousMigration)
migrate' connectInfo allDefs getter val = do
let name = getEntityDBName val
let schema = getEntitySchema val
let (newcols, udefs, fdefs) = mysqlMkColumns allDefs val
old <- getColumns connectInfo getter val newcols
let udspair = map udToPair udefs
case ([], old, partitionEithers old) of
-- Nothing found, create everything
([], [], _) -> do
let uniques = do
(uname, ucols) <- udspair
pure
$ AlterTable name schema
$ AddUniqueConstraint uname
$ map (findTypeAndMaxLen name) ucols
let foreigns = do
Column { cName=cname, cReference=Just cRef } <- newcols
let refConstraintName = crConstraintName cRef
let refTblName = crTableName cRef
let refSchmName = crSchemaName cRef
let refTarget =
addReference allDefs refConstraintName refTblName refSchmName cname (crFieldCascade cRef)
guard $ Just cname /= fmap fieldDB (getEntityIdField val)
return $ AlterColumn name schema refTarget
let foreignsAlt =
map
(\fdef ->
let (childfields, parentfields) =
unzip
$ map (\((_,b),(_,d)) -> (b,d))
$ foreignFields fdef
in
AlterColumn
name
schema
(AddReference
(foreignRefTableDBName fdef)
(foreignRefSchemaDBName fdef)
(foreignConstraintNameDBName fdef)
childfields
parentfields
(foreignFieldCascade fdef)
)
)
fdefs
return
$ Right
$ map showAlterDb
$ (addTable newcols val) : uniques ++ foreigns ++ foreignsAlt
-- No errors and something found, migrate
(_, _, ([], old')) -> do
let excludeForeignKeys (xs,ys) =
( map
(\c ->
case cReference c of
Just ColumnReference {crConstraintName=fk} ->
case find (\f -> fk == foreignConstraintNameDBName f) fdefs of
Just _ -> c { cReference = Nothing }
Nothing -> c
Nothing -> c
)
xs
, ys
)
(acs, ats) =
getAlters
allDefs
val
(newcols, udspair)
$ excludeForeignKeys
$ partitionEithers
$ old'
acs' =
map (AlterColumn name schema) acs
ats' =
map (AlterTable name schema) ats
return
$ Right
$ map showAlterDb
$ acs' ++ ats'
-- Errors
(_, _, (errs, _)) ->
return $ Left errs
where
findTypeAndMaxLen tblName col =
let (col', ty) = findTypeOfColumn allDefs tblName col
(_, ml) = findMaxLenOfColumn allDefs tblName col
in
(col', ty, ml)
addTable :: [Column] -> EntityDef -> AlterDB
addTable cols entity = AddTable $ concat
-- Lower case e: see Database.Persist.Sql.Migration
[ "CREATe TABLE "
, escapeE name schema
, "("
, idtxt
, if null nonIdCols then [] else ","
, intercalate "," $ map showCreateColumn nonIdCols
, ")"
]
where
nonIdCols =
filter (\c -> Just (cName c) /= fmap fieldDB (getEntityIdField entity) ) cols
name =
getEntityDBName entity
schema =
getEntitySchema entity
idtxt =
case getEntityId entity of
EntityIdNaturalKey pdef ->
concat
[ " PRIMARY KEY ("
, intercalate ","
$ map (escapeF . fieldDB)
$ NEL.toList
$ compositeFields pdef
, ")"
]
EntityIdField idField ->
let
defText =
defaultAttribute $ fieldAttrs idField
sType =
fieldSqlType idField
autoIncrementText =
case (sType, defText) of
(SqlInt64, Nothing) -> " AUTO_INCREMENT"
_ -> ""
maxlen =
findMaxLenOfField idField
in
concat
[ escapeF $ fieldDB idField
, " " <> showSqlType sType maxlen False
, " NOT NULL"
, autoIncrementText
, " PRIMARY KEY"
, case defText of
Nothing ->
""
Just def ->
concat
[ " DEFAULT ("
, T.unpack def
, ")"
]
]
-- | Find out the type of a column.
findTypeOfColumn :: [EntityDef] -> EntityNameDB -> FieldNameDB -> (FieldNameDB, FieldType)
findTypeOfColumn allDefs name col =
maybe
(error $ "Could not find type of column " ++
show col ++ " on table " ++ show name ++
" (allDefs = " ++ show allDefs ++ ")"
)
((,) col)
$ do
entDef <- find ((== name) . getEntityDBName) allDefs
fieldDef <- find ((== col) . fieldDB) (getEntityFieldsDatabase entDef)
return (fieldType fieldDef)
-- | Find out the maxlen of a column (default to 200)
findMaxLenOfColumn :: [EntityDef] -> EntityNameDB -> FieldNameDB -> (FieldNameDB, Integer)
findMaxLenOfColumn allDefs name col =
maybe (col, 200)
((,) col) $ do
entDef <- find ((== name) . getEntityDBName) allDefs
fieldDef <- find ((== col) . fieldDB) (getEntityFieldsDatabase entDef)
findMaxLenOfField fieldDef
-- | Find out the maxlen of a field
findMaxLenOfField :: FieldDef -> Maybe Integer
findMaxLenOfField fieldDef =
listToMaybe
. mapMaybe (\case
FieldAttrMaxlen x -> Just x
_ -> Nothing)
. fieldAttrs
$ fieldDef
-- | Helper for 'AddReference' that finds out the which primary key columns to reference.
addReference
:: [EntityDef]
-- ^ List of all known 'EntityDef's.
-> ConstraintNameDB
-- ^ Foreign key name
-> EntityNameDB
-- ^ Referenced table name
-> (Maybe SchemaNameDB)
-- ^ Referenced schema name
--
-- @since 2.13.1.6
-> FieldNameDB
-- ^ Column name
-> FieldCascade
-> AlterColumn
addReference allDefs fkeyname reftable refschema cname fc =
AddReference reftable refschema fkeyname [cname] referencedColumns fc
where
errorMessage =
error
$ "Could not find ID of entity " ++ show reftable
++ " (allDefs = " ++ show allDefs ++ ")"
referencedColumns =
fromMaybe errorMessage $ do
entDef <- find (\e -> getEntityDBName e == reftable && getEntitySchema e == refschema) allDefs
return $ map fieldDB $ NEL.toList $ getEntityKeyFields entDef
data AlterColumn = Change Column
| Add' Column
| Drop Column
| Default Column String
| NoDefault Column
| Gen Column SqlType (Maybe Integer) String
| NoGen Column SqlType (Maybe Integer)
| Update' Column String
-- | See the definition of the 'showAlter' function to see how these fields are used.
| AddReference
EntityNameDB -- Referenced table
(Maybe SchemaNameDB) -- Referenced table schema
ConstraintNameDB -- Foreign key name
[FieldNameDB] -- Referencing columns
[FieldNameDB] -- Referenced columns
FieldCascade
| DropReference ConstraintNameDB
deriving Show
data AlterTable = AddUniqueConstraint ConstraintNameDB [(FieldNameDB, FieldType, Integer)]
| DropUniqueConstraint ConstraintNameDB
deriving Show
data AlterDB = AddTable String
| AlterColumn EntityNameDB (Maybe SchemaNameDB) AlterColumn
| AlterTable EntityNameDB (Maybe SchemaNameDB) AlterTable
deriving Show
udToPair :: UniqueDef -> (ConstraintNameDB, [FieldNameDB])
udToPair ud = (uniqueDBName ud, map snd $ NEL.toList $ uniqueFields ud)
----------------------------------------------------------------------
-- | Returns all of the 'Column'@s@ in the given table currently
-- in the database.
getColumns
:: HasCallStack
=> MySQL.ConnectInfo
-> (Text -> IO Statement)
-> EntityDef -> [Column]
-> IO [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
getColumns connectInfo getter def cols = do
-- Find out all columns.
stmtClmns <- getter $ T.concat
[ "SELECT COLUMN_NAME, "
, "IS_NULLABLE, "
, "DATA_TYPE, "
, "COLUMN_TYPE, "
, "CHARACTER_MAXIMUM_LENGTH, "
, "NUMERIC_PRECISION, "
, "NUMERIC_SCALE, "
, "COLUMN_DEFAULT, "
, "GENERATION_EXPRESSION "
, "FROM INFORMATION_SCHEMA.COLUMNS "
, "WHERE TABLE_SCHEMA = ? "
, "AND TABLE_NAME = ? "
-- , "AND COLUMN_NAME <> ?"
]
inter2 <- with (stmtQuery stmtClmns vals) (\src -> runConduitRes $ src .| CL.consume)
cs <- runConduitRes $ CL.sourceList inter2 .| helperClmns -- avoid nested queries
-- Find out the constraints.
stmtCntrs <- getter $ T.concat
[ "SELECT CONSTRAINT_NAME, "
, "COLUMN_NAME "
, "FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE "
, "WHERE TABLE_SCHEMA = ? "
, "AND TABLE_NAME = ? "
-- , "AND COLUMN_NAME <> ? "
, "AND CONSTRAINT_NAME <> 'PRIMARY' "
, "AND REFERENCED_TABLE_SCHEMA IS NULL "
, "ORDER BY CONSTRAINT_NAME, "
, "COLUMN_NAME"
]
us <- with (stmtQuery stmtCntrs vals) (\src -> runConduitRes $ src .| helperCntrs)
-- Return both
return (cs ++ us)
where
refMap = Map.fromList $ foldl ref [] cols
where ref rs c = case cReference c of
Nothing -> rs
(Just r) -> (unFieldNameDB $ cName c, r) : rs
vals = [ PersistText $ fromMaybe (pack $ MySQL.connectDatabase connectInfo) $ fmap unSchemaNameDB $ getEntitySchema def
, PersistText $ unEntityNameDB $ getEntityDBName def
-- , PersistText $ unDBName $ fieldDB $ getEntityId def
]
helperClmns = CL.mapM getIt .| CL.consume
where
getIt row = fmap (either Left (Right . Left)) .
liftIO .
getColumn connectInfo getter (getEntityDBName def) (getEntitySchema def) row $ ref
where ref = case row of
(PersistText cname : _) -> (Map.lookup cname refMap)
_ -> Nothing
helperCntrs = do
let check [ PersistText cntrName
, PersistText clmnName] = return ( cntrName, clmnName )
check other = fail $ "helperCntrs: unexpected " ++ show other
rows <- mapM check =<< CL.consume
return $ map (Right . Right . (ConstraintNameDB . fst . head &&& map (FieldNameDB . snd)))
$ groupBy ((==) `on` fst) rows
-- | Get the information about a column in a table.
getColumn
:: HasCallStack
=> MySQL.ConnectInfo
-> (Text -> IO Statement)
-> EntityNameDB
-> Maybe SchemaNameDB
-- ^ @since 2.13.1.6
-> [PersistValue]
-> Maybe ColumnReference
-> IO (Either Text Column)
getColumn connectInfo getter tname tschema [ PersistText cname
, PersistText null_
, PersistText dataType
, PersistText colType
, colMaxLen
, colPrecision
, colScale
, default'
, generated
] cRef =
fmap (either (Left . pack) Right) $
runExceptT $ do
-- Default value
default_ <-
case default' of
PersistNull -> return Nothing
PersistText t -> return (Just t)
PersistByteString bs ->
case T.decodeUtf8' bs of
Left exc ->
fail
$ "Invalid default column: "
++ show default'
++ " (error: " ++ show exc ++ ")"
Right t ->
return (Just t)
_ ->
fail $ "Invalid default column: " ++ show default'
generated_ <-
case generated of
PersistNull -> return Nothing
PersistText "" -> return Nothing
PersistByteString "" -> return Nothing
PersistText t -> return (Just t)
PersistByteString bs ->
case T.decodeUtf8' bs of
Left exc ->
fail
$ "Invalid generated column: "
++ show generated
++ " (error: " ++ show exc ++ ")"
Right t ->
return (Just t)
_ ->
fail $ "Invalid generated column: " ++ show generated
ref <- getRef (crConstraintName <$> cRef)
let colMaxLen' =
case colMaxLen of
PersistInt64 l -> Just (fromIntegral l)
_ -> Nothing
ci = ColumnInfo
{ ciColumnType = colType
, ciMaxLength = colMaxLen'
, ciNumericPrecision = colPrecision
, ciNumericScale = colScale
}
(typ, maxLen) <- parseColumnType dataType ci
-- Okay!
return Column
{ cName = FieldNameDB cname
, cNull = null_ == "YES"
, cSqlType = typ
, cDefault = default_
, cGenerated = generated_
, cDefaultConstraintName = Nothing
, cMaxLen = maxLen
, cReference = ref
}
where
getRef Nothing = return Nothing
getRef (Just refName') = do
-- Foreign key (if any)
stmt <- lift . getter $ T.concat
[ "SELECT KCU.REFERENCED_TABLE_NAME, "
, "KCU.TABLE_SCHEMA, "
, "KCU.CONSTRAINT_NAME, "
, "KCU.ORDINAL_POSITION, "
, "DELETE_RULE, "
, "UPDATE_RULE "
, "FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU "
, "INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC "
, " USING (CONSTRAINT_SCHEMA, CONSTRAINT_NAME) "
, "WHERE KCU.TABLE_SCHEMA = ? "
, "AND KCU.TABLE_NAME = ? "
, "AND KCU.COLUMN_NAME = ? "
, "AND KCU.REFERENCED_TABLE_SCHEMA = ? "
, "AND KCU.CONSTRAINT_NAME = ? "
, "ORDER BY KCU.CONSTRAINT_NAME, "
, "KCU.COLUMN_NAME"
]
let vars =
[ PersistText $ fromMaybe (pack $ MySQL.connectDatabase connectInfo) $ fmap unSchemaNameDB tschema
, PersistText $ unEntityNameDB tname
, PersistText cname
, PersistText $ pack $ MySQL.connectDatabase connectInfo
, PersistText $ unConstraintNameDB refName'
]
parseCascadeAction txt =
case txt of
"RESTRICT" -> Just Restrict
"CASCADE" -> Just Cascade
"SET NULL" -> Just SetNull
"SET DEFAULT" -> Just SetDefault
"NO ACTION" -> Nothing
_ ->
error $ "Unexpected value in parseCascadeAction: " <> show txt
cntrs <- liftIO $ with (stmtQuery stmt vars) (\src -> runConduit $ src .| CL.consume)
pure $ case cntrs of
[] -> Nothing
[[PersistText tab, schema, PersistText ref, PersistInt64 pos, PersistText onDel, PersistText onUpd]] ->
if pos == 1
then Just $
let colSchema =
case schema of
PersistNull -> Nothing
PersistText schemaName -> do
guard $ not (T.null schemaName)
guard $ schemaName /= (pack $ MySQL.connectDatabase connectInfo)
pure $ SchemaNameDB schemaName
_ -> Nothing -- this should never happen
in ColumnReference
(EntityNameDB tab)
colSchema
(ConstraintNameDB ref)
FieldCascade
{ fcOnUpdate = parseCascadeAction onUpd
, fcOnDelete = parseCascadeAction onDel
}
else Nothing
xs -> error $ mconcat
[ "MySQL.getColumn/getRef: error fetching constraints. Expected a single result for foreign key query for table: "
, T.unpack (unEntityNameDB tname)
, " and column: "
, T.unpack cname
, " but got: "
, show xs
]
getColumn _ _ _ _ x _ =
return $ Left $ pack $ "Invalid result from INFORMATION_SCHEMA: " ++ show x
-- | Extra column information from MySQL schema
data ColumnInfo = ColumnInfo
{ ciColumnType :: Text
, ciMaxLength :: Maybe Integer
, ciNumericPrecision :: PersistValue
, ciNumericScale :: PersistValue
}
-- | Parse the type of column as returned by MySQL's
-- @INFORMATION_SCHEMA@ tables.
parseColumnType :: Text -> ColumnInfo -> ExceptT String IO (SqlType, Maybe Integer)
-- Ints
-- The display width is deprecated and being removed in MySQL 8.X
-- with [an exception of tinyint(1) which is used for boolean values](https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-19.html#mysqld-8-0-19-deprecation-removal).
-- To be consistent with earlier versions, which do report it, accept either
-- the bare type in `ciColumnType ci`, or the type adorned with the expected
-- value for the display width (ie the defaults for int and bigint, or the
-- value explicitly set in `showSqlType` for SqlBool).
--
parseColumnType "tinyint" ci
| ciColumnType ci == "tinyint(1)" = return (SqlBool, Nothing)
| otherwise = return (SqlOther "tinyint", Nothing)
parseColumnType "int" ci
| ciColumnType ci == "int" || ciColumnType ci == "int(11)" = return (SqlInt32, Nothing)
parseColumnType "bigint" ci
| ciColumnType ci == "bigint" || ciColumnType ci == "bigint(20)" = return (SqlInt64, Nothing)
-- Double
parseColumnType x@("double") ci | ciColumnType ci == x = return (SqlReal, Nothing)
parseColumnType "decimal" ci =
case (ciNumericPrecision ci, ciNumericScale ci) of
(PersistInt64 p, PersistInt64 s) ->
return (SqlNumeric (fromIntegral p) (fromIntegral s), Nothing)
_ ->
fail "missing DECIMAL precision in DB schema"
-- Text
parseColumnType "varchar" ci = return (SqlString, ciMaxLength ci)
parseColumnType "text" _ = return (SqlString, Nothing)
-- ByteString
parseColumnType "varbinary" ci = return (SqlBlob, ciMaxLength ci)
parseColumnType "blob" _ = return (SqlBlob, Nothing)
-- Time-related
parseColumnType "time" _ = return (SqlTime, Nothing)
parseColumnType "datetime" _ = return (SqlDayTime, Nothing)
parseColumnType "date" _ = return (SqlDay, Nothing)
parseColumnType _ ci = return (SqlOther (ciColumnType ci), Nothing)
----------------------------------------------------------------------
-- | @getAlters allDefs tblName new old@ finds out what needs to
-- be changed from @old@ to become @new@.
getAlters
:: [EntityDef]
-> EntityDef
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
-> ([Column], [(ConstraintNameDB, [FieldNameDB])])
-> ([AlterColumn], [AlterTable])
getAlters allDefs edef (c1, u1) (c2, u2) =
(getAltersC c1 c2, getAltersU u1 u2)
where
tblName = getEntityDBName edef
getAltersC [] old = concatMap dropColumn old
getAltersC (new:news) old =
let (alters, old') = findAlters edef allDefs new old
in alters ++ getAltersC news old'
dropColumn col =
[DropReference (crConstraintName cr) | Just cr <- [cReference col]] ++
[Drop col]
getAltersU [] old = map (DropUniqueConstraint . fst) old
getAltersU ((name, cols):news) old =
case lookup name old of
Nothing ->
AddUniqueConstraint name (map findTypeAndMaxLen cols)
: getAltersU news old
Just ocols ->
let old' = filter (\(x, _) -> x /= name) old
in if sort cols == ocols
then getAltersU news old'
else DropUniqueConstraint name
: AddUniqueConstraint name (map findTypeAndMaxLen cols)
: getAltersU news old'
where
findTypeAndMaxLen col =
let (col', ty) = findTypeOfColumn allDefs tblName col
(_, ml) = findMaxLenOfColumn allDefs tblName col
in
(col', ty, ml)
-- | @findAlters x y newColumn oldColumns@ finds out what needs to be
-- changed in the columns @oldColumns@ for @newColumn@ to be
-- supported.
findAlters
:: EntityDef
-> [EntityDef]
-> Column
-> [Column]
-> ([AlterColumn], [Column])
findAlters edef allDefs col@(Column name isNull type_ def gen _defConstraintName maxLen ref) cols =
case filter ((name ==) . cName) cols of
-- new fkey that didn't exist before
[] ->
case ref of
Nothing -> ([Add' col],cols)
Just cr ->
let tname = crTableName cr
cname = crConstraintName cr
sname = crSchemaName cr
cnstr = [addReference allDefs cname tname sname name (crFieldCascade cr)]
in
(Add' col : cnstr, cols)
Column _ isNull' type_' def' gen' _defConstraintName' maxLen' ref' : _ ->
let -- Foreign key
refDrop =
case (ref == ref', ref') of
(False, Just ColumnReference {crConstraintName=cname}) ->
[DropReference cname]
_ ->
[]
refAdd =
case (ref == ref', ref) of
(False, Just ColumnReference {crTableName=tname, crSchemaName=sname, crConstraintName=cname, crFieldCascade = cfc })
| tname /= getEntityDBName edef
, Just idField <- getEntityIdField edef
, unConstraintNameDB cname /= unFieldNameDB (fieldDB idField)
->
[addReference allDefs cname tname sname name cfc]
_ -> []
-- Type and nullability
modType | showSqlType type_ maxLen False `ciEquals` showSqlType type_' maxLen' False && isNull == isNull' = []
| otherwise = [Change col]
-- Default value
-- Avoid DEFAULT NULL, since it is always unnecessary, and is an error for text/blob fields
modDef =
if def == def' then []
else case def of
Nothing -> [NoDefault col]
Just s ->
if T.toUpper s == "NULL" then []
else [Default col $ T.unpack s]
-- Does the generated value need to change?
modGen =
if gen == gen' then []
else case gen of
Nothing -> [NoGen col type_ maxLen]
Just genExpr -> [Gen col type_ maxLen $ T.unpack genExpr]
in ( refDrop ++ modType ++ modDef ++ modGen ++ refAdd
, filter ((name /=) . cName) cols
)