-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathClickHaskell.hs
2238 lines (1789 loc) · 75.3 KB
/
ClickHaskell.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE
BangPatterns
, ConstraintKinds
, DuplicateRecordFields
, GeneralizedNewtypeDeriving
, LambdaCase
, NoFieldSelectors
, NumericUnderscores
, OverloadedStrings
, RecordWildCards
, TupleSections
#-}
{-# OPTIONS_GHC
-Wno-orphans
#-}
module ClickHaskell
(
-- * Connection
ChCredential(..), defaultCredentials
, Connection(..), openNativeConnection
-- * Reading and writing
, Table
, Columns, Column, KnownColumn(..), DeserializableColumn(..)
-- ** Reading
, ReadableFrom(..)
-- *** Simple
, select
, selectFrom
, selectFromView, View, parameter, Parameter, Parameters, viewParameters
-- *** Streaming
, streamSelect
, streamSelectFrom
, streamSelectFromView
-- *** Internal
, handleSelect
-- * Errors
, ClientError(..)
, ConnectionError(..)
, UserError(..)
, InternalError(..)
-- ** Writing
, WritableInto(..)
, insertInto
-- * Ping database connection
, ping
-- * ClickHouse types
, IsChType(ToChTypeName, chTypeName, defaultValueOfTypeName)
, ToChType(toChType)
, FromChType(fromChType)
, ToQueryPart(toQueryPart)
, ChDateTime(..)
, ChDate(..)
, ChInt8(..), ChInt16(..), ChInt32(..), ChInt64(..), ChInt128(..)
, ChUInt8(..), ChUInt16(..), ChUInt32(..), ChUInt64(..), ChUInt128(..)
, ChString(..)
, ChUUID(..)
, ChArray(..)
, Nullable
, LowCardinality, IsLowCardinalitySupported
, UVarInt(..)
, module Data.WideWord
) where
-- Internal
import Paths_ClickHaskell (version)
-- GHC included
import Control.Concurrent (MVar, newMVar, withMVar)
import Control.DeepSeq (NFData, (<$!!>))
import Control.Exception (Exception, bracketOnError, catch, finally, throwIO, SomeException)
import Control.Monad (forM, replicateM, (<$!>))
import Data.Binary.Get
import Data.Binary.Get.Internal (readN)
import Data.Binary.Put
import Data.Bits
import Data.ByteString as BS (StrictByteString, length, take, toStrict)
import Data.ByteString.Builder (Builder, byteString, stringUtf8, toLazyByteString, word8)
import Data.ByteString.Builder as BS (Builder, byteString, word16HexFixed)
import Data.ByteString.Char8 as BS8 (concatMap, length, pack, replicate, singleton)
import Data.Coerce (coerce)
import Data.Functor (($>))
import Data.IORef (IORef, atomicWriteIORef, newIORef, readIORef)
import Data.Int (Int16, Int32, Int64, Int8)
import Data.Kind (Constraint, Type)
import Data.List (uncons)
import Data.Maybe (listToMaybe)
import Data.String (IsString (..))
import Data.Text (Text)
import Data.Text.Encoding as Text (encodeUtf8)
import Data.Time (UTCTime, ZonedTime, zonedTimeToUTC)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds)
import Data.Typeable (Proxy (..))
import Data.Vector.Primitive.Mutable (Prim)
import Data.Version (Version (..))
import Data.Word (Word16, Word32, Word8)
import Debug.Trace (traceShowId)
import GHC.Generics
import GHC.Stack (HasCallStack, callStack, prettyCallStack)
import GHC.TypeLits (AppendSymbol, ErrorMessage (..), KnownNat, KnownSymbol, Nat, Symbol, TypeError, natVal, symbolVal)
import GHC.Word (Word64)
import System.Timeout (timeout)
import Data.Type.Equality (type(==))
import Data.Type.Bool (If)
-- External
import Data.WideWord (Int128 (..), Word128(..))
import Network.Socket as Sock
import Network.Socket.ByteString (recv)
import Network.Socket.ByteString.Lazy (sendAll)
-- * Connection
data ChCredential = MkChCredential
{ chLogin :: Text
, chPass :: Text
, chDatabase :: Text
, chHost :: HostName
, chPort :: ServiceName
}
defaultCredentials :: ChCredential
defaultCredentials = MkChCredential
{ chLogin = "default"
, chPass = ""
, chHost = "localhost"
, chDatabase = "default"
, chPort = "9000"
}
data Connection where MkConnection :: (MVar ConnectionState) -> Connection
withConnection :: Connection -> (ConnectionState -> IO a) -> IO a
withConnection (MkConnection connStateMVar) f =
withMVar connStateMVar $ \connState ->
catch
@ClientError
(f connState)
(\err -> throwIO err)
data ConnectionState = MkConnectionState
{ sock :: Socket
, user :: ChString
, buffer :: Buffer
, revision :: ProtocolRevision
}
data ConnectionError = NoAdressResolved | EstablishTimeout
deriving (Show, Exception)
openNativeConnection :: HasCallStack => ChCredential -> IO Connection
openNativeConnection MkChCredential{chHost, chPort, chLogin, chPass, chDatabase} = do
AddrInfo{addrFamily, addrSocketType, addrProtocol, addrAddress}
<- maybe (throwIO NoAdressResolved) pure . listToMaybe
=<< getAddrInfo
(Just defaultHints{addrFlags = [AI_ADDRCONFIG], addrSocketType = Stream})
(Just chHost)
(Just chPort)
sock <- maybe (throwIO EstablishTimeout) pure
=<< timeout 3_000_000 (
bracketOnError
(socket addrFamily addrSocketType addrProtocol)
(\sock ->
catch @SomeException
(finally
(shutdown sock ShutdownBoth)
(close sock)
)
(const $ pure ())
)
(\sock -> do
setSocketOption sock NoDelay 1
setSocketOption sock Sock.KeepAlive 1
connect sock addrAddress
pure sock
)
)
(sendAll sock . toLazyByteString . serialize latestSupportedRevision)
(mkHelloPacket MkHelloParameters{..})
buffer <- initBuffer 4096 sock
serverPacketType <- rawBufferizedRead buffer (deserialize latestSupportedRevision)
case serverPacketType of
HelloResponse MkHelloResponse{server_revision} -> do
let revision = min server_revision latestSupportedRevision
(sendAll sock . toLazyByteString) (serialize revision mkAddendum)
a <- newMVar MkConnectionState
{ user = toChType chLogin
, revision
, sock
, buffer
}
pure (MkConnection a)
Exception exception -> throwIO (UserError $ DatabaseException exception)
otherPacket -> throwIO (InternalError $ UnexpectedPacketType otherPacket)
-- * Ping
ping :: HasCallStack => Connection -> IO ()
ping conn = do
withConnection conn $ \MkConnectionState{sock, revision, buffer} -> do
(sendAll sock . toLazyByteString)
(serialize revision mkPingPacket)
responsePacket <- rawBufferizedRead buffer (deserialize revision)
case responsePacket of
Pong -> pure ()
Exception exception -> throwIO (UserError $ DatabaseException exception)
otherPacket -> throwIO (InternalError $ UnexpectedPacketType otherPacket)
-- * Querying
data Table (name :: Symbol) (columns :: [Type])
instance HasColumns (Table name columns) where
type GetColumns (Table _ columns) = columns
-- ** Selecting
-- *** Simple
selectFrom ::
forall table record name columns
.
( table ~ Table name columns
, KnownSymbol name
, ReadableFrom table record
)
=>
Connection -> IO [record]
selectFrom conn = do
withConnection conn $ \connState@MkConnectionState{sock, revision, user} -> do
let query
= "SELECT " <> readingColumns @table @record
<> " FROM " <> (byteString . BS8.pack) (symbolVal $ Proxy @name)
(sendAll sock . toLazyByteString)
( serialize revision (mkQueryPacket revision user (toChType query))
<> serialize revision (mkDataPacket "" 0 0)
)
handleSelect @table connState pure
select ::
forall columns record
.
ReadableFrom (Columns columns) record
=>
Connection -> ChString -> IO [record]
select conn query = do
withConnection conn $ \connState@MkConnectionState{sock, revision, user} -> do
(sendAll sock . toLazyByteString)
( serialize revision (mkQueryPacket revision user query)
<> serialize revision (mkDataPacket "" 0 0)
)
handleSelect @(Columns columns) connState pure
instance HasColumns (View name columns parameters) where
type GetColumns (View _ columns _) = columns
data View (name :: Symbol) (columns :: [Type]) (parameters :: [Type])
selectFromView ::
forall view record name columns parameters passedParameters
.
( ReadableFrom view record
, KnownSymbol name
, view ~ View name columns parameters
, CheckParameters parameters passedParameters
)
=> Connection -> (Parameters '[] -> Parameters passedParameters) -> IO [record]
selectFromView conn interpreter = do
withConnection conn $ \connState@MkConnectionState{sock, revision, user} -> do
let query =
"SELECT " <> readingColumns @view @record <>
" FROM " <> (byteString . BS8.pack . symbolVal @name) Proxy <> viewParameters interpreter
(sendAll sock . toLazyByteString)
( serialize revision (mkQueryPacket revision user (toChType query))
<> serialize revision (mkDataPacket "" 0 0)
)
handleSelect @view connState pure
-- *** Streaming
streamSelectFrom ::
forall table record name columns a
.
( table ~ Table name columns
, KnownSymbol name
, ReadableFrom table record
, NFData a
)
=>
Connection -> ([record] -> IO [a]) -> IO [a]
streamSelectFrom conn f = do
withConnection conn $ \connState@MkConnectionState{sock, revision, user} -> do
let query
= "SELECT " <> readingColumns @table @record
<> " FROM " <> (byteString . BS8.pack) (symbolVal $ Proxy @name)
(sendAll sock . toLazyByteString)
( serialize revision (mkQueryPacket revision user (toChType query))
<> serialize revision (mkDataPacket "" 0 0)
)
let f' x = id <$!!> f x
handleSelect @table connState f'
streamSelect ::
forall columns record a
.
(ReadableFrom (Columns columns) record, NFData a)
=>
Connection -> ChString -> ([record] -> IO [a]) -> IO [a]
streamSelect conn query f = do
withConnection conn $ \connState@MkConnectionState{sock, revision, user} -> do
(sendAll sock . toLazyByteString)
( serialize revision (mkQueryPacket revision user query)
<> serialize revision (mkDataPacket "" 0 0)
)
let f' x = id <$!!> f x
handleSelect @(Columns columns) connState f'
streamSelectFromView ::
forall view record name columns parameters passedParameters a
.
( ReadableFrom view record
, KnownSymbol name
, view ~ View name columns parameters
, NFData a
, CheckParameters parameters passedParameters
)
=> Connection -> (Parameters '[] -> Parameters passedParameters) -> ([record] -> IO [a]) -> IO [a]
streamSelectFromView conn interpreter f = do
withConnection conn $ \connState@MkConnectionState{sock, revision, user} -> do
let query =
"SELECT " <> readingColumns @view @record <>
" FROM " <> (byteString . BS8.pack . symbolVal @name) Proxy <> viewParameters interpreter
(sendAll sock . toLazyByteString)
( serialize revision (mkQueryPacket revision user (toChType query))
<> serialize revision (mkDataPacket "" 0 0)
)
let f' x = id <$!!> f x
handleSelect @view connState f'
-- *** Internal
handleSelect ::
forall hasColumns record a
.
ReadableFrom hasColumns record
=>
ConnectionState -> ([record] -> IO [a]) -> IO [a]
handleSelect conn@MkConnectionState{..} f = do
packet <- rawBufferizedRead buffer (deserialize revision)
case packet of
DataResponse MkDataPacket{columns_count, rows_count} -> do
case (columns_count, rows_count) of
(0, 0) -> handleSelect @hasColumns conn f
(_, rows) -> do
columns <- rawBufferizedRead buffer (deserializeColumns @hasColumns revision rows)
processedColumns <- f columns
(processedColumns ++) <$> handleSelect @hasColumns conn f
Progress _ -> handleSelect @hasColumns conn f
ProfileInfo _ -> handleSelect @hasColumns conn f
EndOfStream -> pure []
Exception exception -> throwIO (UserError $ DatabaseException exception)
otherPacket -> throwIO (InternalError $ UnexpectedPacketType otherPacket)
-- ** Inserting
insertInto ::
forall table record name columns
.
( table ~ Table name columns
, WritableInto table record
, KnownSymbol name
)
=> Connection -> [record] -> IO ()
insertInto conn columnsData = do
withConnection conn $ \connState@MkConnectionState{sock, user, revision} -> do
let query =
"INSERT INTO " <> (byteString . BS8.pack) (symbolVal $ Proxy @name)
<> " (" <> writingColumns @table @record <> ") VALUES"
(sendAll sock . toLazyByteString)
( serialize revision (mkQueryPacket revision user (toChType query))
<> serialize revision (mkDataPacket "" 0 0)
)
handleInsertResult @table connState columnsData
handleInsertResult :: forall columns record . WritableInto columns record => ConnectionState -> [record] -> IO ()
handleInsertResult conn@MkConnectionState{..} records = do
firstPacket <- rawBufferizedRead buffer (deserialize revision)
case firstPacket of
TableColumns _ -> handleInsertResult @columns conn records
DataResponse MkDataPacket{} -> do
_emptyDataPacket <- rawBufferizedRead buffer (deserializeInsertHeader @columns @record revision)
(sendAll sock . toLazyByteString)
( serialize revision (mkDataPacket "" (columnsCount @columns @record) (fromIntegral $ Prelude.length records))
<> serializeRecords @columns revision records
<> serialize revision (mkDataPacket "" 0 0)
)
handleInsertResult @columns @record conn []
EndOfStream -> pure ()
Exception exception -> throwIO (UserError $ DatabaseException exception)
otherPacket -> throwIO (InternalError $ UnexpectedPacketType otherPacket)
-- * Bufferization
data Buffer = MkBuffer
{ bufferSize :: Int
, bufferSocket :: Socket
, buff :: IORef StrictByteString
}
initBuffer :: Int -> Socket -> IO Buffer
initBuffer size sock = MkBuffer size sock <$> newIORef ""
flushBuffer :: Buffer -> IO ()
flushBuffer MkBuffer{buff} = atomicWriteIORef buff ""
rawBufferizedRead :: Buffer -> Get packet -> IO packet
rawBufferizedRead buffer parser = runBufferReader buffer (runGetIncremental parser)
runBufferReader :: Buffer -> Decoder packet -> IO packet
runBufferReader buffer@MkBuffer{bufferSocket, bufferSize, buff} = \case
(Partial decoder) -> do
currentBuffer <- readIORef buff
chosenBuffer <- case BS.length currentBuffer of
0 -> recv bufferSocket bufferSize
_ -> flushBuffer buffer $> currentBuffer
case BS.length chosenBuffer of
0 -> throwIO (DeserializationError "Expected more bytes while reading packet")
_ -> runBufferReader buffer (decoder $ Just $! chosenBuffer)
(Done leftover _consumed packet) -> atomicWriteIORef buff leftover $> packet
(Fail _leftover _consumed msg) -> throwIO (DeserializationError msg)
-- * Errors handling
data ClientError where
UserError :: HasCallStack => UserError -> ClientError
InternalError :: HasCallStack => InternalError -> ClientError
instance Show ClientError where
show (UserError err) = "UserError " <> show err <> "\n" <> prettyCallStack callStack
show (InternalError err) = "InternalError " <> show err <> "\n" <> prettyCallStack callStack
deriving anyclass instance Exception ClientError
{- |
You shouldn't see this exceptions. Please report a bug if it appears
-}
data InternalError
= UnexpectedPacketType ServerPacketType
| DeserializationError String
deriving (Show, Exception)
data UserError
= UnmatchedType String
| UnmatchedColumn String
| DatabaseException ExceptionPacket
deriving (Show, Exception)
-- * Compatibility
latestSupportedRevision :: ProtocolRevision
latestSupportedRevision = mostRecentRevision
-- * Client packets
data ClientPacketType
= Hello
| Query
| Data
| Cancel
| Ping
| TablesStatusRequest
| KeepAlive
| Scalar
| IgnoredPartUUIDs
| ReadTaskResponse
| MergeTreeReadTaskResponse
| SSHChallengeRequest
| SSHChallengeResponse
deriving (Enum, Show)
type family PacketTypeNumber (packetType :: ClientPacketType)
where
PacketTypeNumber Hello = 0
PacketTypeNumber Query = 1
PacketTypeNumber Data = 2
PacketTypeNumber Cancel = 3
PacketTypeNumber Ping = 4
PacketTypeNumber TablesStatusRequest = 5
PacketTypeNumber ClickHaskell.KeepAlive = 6
PacketTypeNumber Scalar = 7
PacketTypeNumber IgnoredPartUUIDs = 8
PacketTypeNumber ReadTaskResponse = 9
PacketTypeNumber MergeTreeReadTaskResponse = 10
PacketTypeNumber SSHChallengeRequest = 11
PacketTypeNumber SSHChallengeResponse = 12
data Packet (packetType :: ClientPacketType) = MkPacket
instance KnownNat (PacketTypeNumber packetType) => Show (Packet (packetType :: ClientPacketType)) where
show _ = show . toEnum @ClientPacketType . fromIntegral $ packetNumVal @packetType
packetNumVal :: forall packetType . KnownNat (PacketTypeNumber packetType) => UVarInt
packetNumVal = fromIntegral . natVal $ Proxy @(PacketTypeNumber packetType)
instance
KnownNat (PacketTypeNumber packetType)
=>
Serializable (Packet (packetType :: ClientPacketType)) where
serialize rev _ = serialize @UVarInt rev (packetNumVal @packetType)
instance Deserializable (Packet (packetType :: ClientPacketType)) where
deserialize _rev = pure (MkPacket @packetType)
-- ** Hello
data HelloParameters = MkHelloParameters
{ chDatabase :: Text
, chLogin :: Text
, chPass :: Text
}
mkHelloPacket :: HelloParameters -> HelloPacket
mkHelloPacket MkHelloParameters{chDatabase, chLogin, chPass} =
MkHelloPacket
{ packet_type = MkPacket
, client_name, client_version_major, client_version_minor
, tcp_protocol_version = latestSupportedRevision
, default_database = toChType chDatabase
, user = toChType chLogin
, password = toChType chPass
}
data HelloPacket = MkHelloPacket
{ packet_type :: Packet Hello
, client_name :: ChString
, client_version_major :: UVarInt
, client_version_minor :: UVarInt
, tcp_protocol_version :: ProtocolRevision
, default_database :: ChString
, user :: ChString
, password :: ChString
}
deriving (Generic, Serializable)
mkAddendum :: Addendum
mkAddendum = MkAddendum
{ quota_key = MkSinceRevision ""
}
data Addendum = MkAddendum
{ quota_key :: ChString `SinceRevision` DBMS_MIN_PROTOCOL_VERSION_WITH_QUOTA_KEY
}
deriving (Generic, Serializable)
-- ** Ping
mkPingPacket :: PingPacket
mkPingPacket = MkPingPacket{packet_type = MkPacket}
data PingPacket = MkPingPacket{packet_type :: Packet Ping}
deriving (Generic, Serializable)
-- ** Query
mkQueryPacket :: ProtocolRevision -> ChString -> ChString -> QueryPacket
mkQueryPacket chosenRev user query = MkQueryPacket
{ query_packet = MkPacket
, query_id = ""
, client_info = MkSinceRevision MkClientInfo
{ query_kind = InitialQuery
, initial_user = user
, initial_query_id = ""
, initial_adress = "0.0.0.0:0"
, initial_time = MkSinceRevision 0
, interface_type = 1 -- [tcp - 1, http - 2]
, os_user = "dmitry"
, hostname = "desktop"
, client_name, client_version_major, client_version_minor
, client_revision = chosenRev
, quota_key = MkSinceRevision ""
, distrubuted_depth = MkSinceRevision 0
, client_version_patch
, open_telemetry = MkSinceRevision 0
, collaborate_with_initiator = MkSinceRevision 0
, count_participating_replicas = MkSinceRevision 0
, number_of_current_replica = MkSinceRevision 0
}
, settings = MkDbSettings
, interserver_secret = MkSinceRevision ""
, query_stage = Complete
, compression = 0
, query = query
, parameters = MkSinceRevision MkQueryParameters
}
data QueryPacket = MkQueryPacket
{ query_packet :: Packet Query
, query_id :: ChString
, client_info :: ClientInfo `SinceRevision` DBMS_MIN_REVISION_WITH_CLIENT_INFO
, settings :: DbSettings
, interserver_secret :: ChString `SinceRevision` DBMS_MIN_REVISION_WITH_INTERSERVER_SECRET
, query_stage :: QueryStage
, compression :: UVarInt
, query :: ChString
, parameters :: QueryParameters `SinceRevision` DBMS_MIN_PROTOCOL_VERSION_WITH_PARAMETERS
}
deriving (Generic, Serializable)
data DbSettings = MkDbSettings
instance Serializable DbSettings where serialize rev _ = serialize @ChString rev ""
data QueryParameters = MkQueryParameters
instance Serializable QueryParameters where serialize rev _ = serialize @ChString rev ""
data QueryStage
= FetchColumns
| WithMergeableState
| Complete
| WithMergeableStateAfterAggregation
| WithMergeableStateAfterAggregationAndLimit
deriving (Enum)
instance Serializable QueryStage where
serialize rev = serialize @UVarInt rev . queryStageCode
queryStageCode :: QueryStage -> UVarInt
queryStageCode = \case
FetchColumns -> 0
WithMergeableState -> 1
Complete -> 2
WithMergeableStateAfterAggregation -> 3
WithMergeableStateAfterAggregationAndLimit -> 4
data Flags = IMPORTANT | CUSTOM | OBSOLETE
_flagCode :: Flags -> ChUInt64
_flagCode IMPORTANT = 0x01
_flagCode CUSTOM = 0x02
_flagCode OBSOLETE = 0x04
data ClientInfo = MkClientInfo
{ query_kind :: QueryKind
, initial_user :: ChString
, initial_query_id :: ChString
, initial_adress :: ChString
, initial_time :: ChInt64 `SinceRevision` DBMS_MIN_PROTOCOL_VERSION_WITH_INITIAL_QUERY_START_TIME
, interface_type :: ChUInt8
, os_user :: ChString
, hostname :: ChString
, client_name :: ChString
, client_version_major :: UVarInt
, client_version_minor :: UVarInt
, client_revision :: ProtocolRevision
, quota_key :: ChString `SinceRevision` DBMS_MIN_REVISION_WITH_QUOTA_KEY_IN_CLIENT_INFO
, distrubuted_depth :: UVarInt `SinceRevision` DBMS_MIN_PROTOCOL_VERSION_WITH_DISTRIBUTED_DEPTH
, client_version_patch :: UVarInt `SinceRevision` DBMS_MIN_REVISION_WITH_VERSION_PATCH
, open_telemetry :: ChUInt8 `SinceRevision` DBMS_MIN_REVISION_WITH_OPENTELEMETRY
, collaborate_with_initiator :: UVarInt `SinceRevision` DBMS_MIN_REVISION_WITH_PARALLEL_REPLICAS
, count_participating_replicas :: UVarInt `SinceRevision` DBMS_MIN_REVISION_WITH_PARALLEL_REPLICAS
, number_of_current_replica :: UVarInt `SinceRevision` DBMS_MIN_REVISION_WITH_PARALLEL_REPLICAS
}
deriving (Generic, Serializable)
data QueryKind = NoQuery | InitialQuery | SecondaryQuery
deriving (Enum)
instance Serializable QueryKind where
serialize rev = serialize @ChUInt8 rev . queryKindToEnum
queryKindToEnum :: QueryKind -> ChUInt8
queryKindToEnum = \case NoQuery -> 1; InitialQuery -> 2; SecondaryQuery -> 3
-- ** Data
mkDataPacket :: ChString -> UVarInt -> UVarInt -> DataPacket
mkDataPacket table_name columns_count rows_count =
MkDataPacket
{ packet_type = MkPacket
, table_name
, block_info = MkBlockInfo
{ field_num1 = 1, is_overflows = 0
, field_num2 = 2, bucket_num = -1
, eof = 0
}
, columns_count
, rows_count
}
data DataPacket = MkDataPacket
{ packet_type :: Packet Data
, table_name :: ChString
, block_info :: BlockInfo
, columns_count :: UVarInt
, rows_count :: UVarInt
}
deriving (Generic, Serializable, Deserializable, Show)
data BlockInfo = MkBlockInfo
{ field_num1 :: UVarInt, is_overflows :: ChUInt8
, field_num2 :: UVarInt, bucket_num :: ChInt32
, eof :: UVarInt
}
deriving (Generic, Serializable, Deserializable, Show)
-- * Server packets
data ServerPacketType where
HelloResponse :: HelloResponse -> ServerPacketType
DataResponse :: DataPacket -> ServerPacketType
Exception :: ExceptionPacket -> ServerPacketType
Progress :: ProgressPacket -> ServerPacketType
Pong :: ServerPacketType
EndOfStream :: ServerPacketType
ProfileInfo :: ProfileInfo -> ServerPacketType
Totals :: ServerPacketType
Extremes :: ServerPacketType
TablesStatusResponse :: ServerPacketType
Log :: ServerPacketType
TableColumns :: TableColumns -> ServerPacketType
UUIDs :: ServerPacketType
ReadTaskRequest :: ServerPacketType
ProfileEvents :: ServerPacketType
UnknownPacket :: UVarInt -> ServerPacketType
instance Deserializable ServerPacketType where
deserialize rev = do
packetNum <- deserialize @UVarInt rev
case packetNum of
0 -> HelloResponse <$> deserialize rev
1 -> DataResponse <$> deserialize rev
2 -> Exception <$> deserialize rev
3 -> Progress <$> deserialize rev
4 -> pure Pong
5 -> pure EndOfStream
6 -> ProfileInfo <$> deserialize rev
7 -> pure Totals
8 -> pure Extremes
9 -> pure TablesStatusResponse
10 -> pure Log
11 -> TableColumns <$> deserialize rev
12 -> pure UUIDs
13 -> pure ReadTaskRequest
14 -> pure ProfileEvents
_ -> pure $ UnknownPacket packetNum
instance Show ServerPacketType where
show (HelloResponse hello) = "HelloResponse " <> show hello
show (DataResponse dataPacket) = "DataResponse " <> show dataPacket
show (Exception exception) = "Exception " <> show exception
show (Progress progress) = "Progress " <> show progress
show Pong = "Pong"
show EndOfStream = "EndOfStream"
show (ProfileInfo profileInfo) = "ProfileInfo " <> show profileInfo
show Totals = "Totals"
show Extremes = "Extremes"
show TablesStatusResponse = "TablesStatusResponse"
show Log = "Log"
show (TableColumns tabelColumnsPacket) = "TableColumns " <> show tabelColumnsPacket
show UUIDs = "UUIDs"
show ReadTaskRequest = "ReadTaskRequest"
show ProfileEvents = "ProfileEvents"
show (UnknownPacket packetNum) = "UnknownPacket: " <> show packetNum
-- ** HelloResponse
{-
https://github.com/ClickHouse/ClickHouse/blob/eb4a74d7412a1fcf52727cd8b00b365d6b9ed86c/src/Client/Connection.cpp#L520
-}
data HelloResponse = MkHelloResponse
{ server_name :: ChString
, server_version_major :: UVarInt
, server_version_minor :: UVarInt
, server_revision :: ProtocolRevision
, server_parallel_replicas_proto :: UVarInt `SinceRevision` DBMS_MIN_REVISION_WITH_VERSIONED_PARALLEL_REPLICAS_PROTOCOL
, server_timezone :: ChString `SinceRevision` DBMS_MIN_REVISION_WITH_SERVER_TIMEZONE
, server_display_name :: ChString `SinceRevision` DBMS_MIN_REVISION_WITH_SERVER_DISPLAY_NAME
, server_version_patch :: UVarInt `SinceRevision` DBMS_MIN_REVISION_WITH_VERSION_PATCH
, proto_send_chunked_srv :: ChString `SinceRevision` DBMS_MIN_PROTOCOL_VERSION_WITH_CHUNKED_PACKETS
, proto_recv_chunked_srv :: ChString `SinceRevision` DBMS_MIN_PROTOCOL_VERSION_WITH_CHUNKED_PACKETS
, password_complexity_rules :: [PasswordComplexityRules] `SinceRevision` DBMS_MIN_PROTOCOL_VERSION_WITH_PASSWORD_COMPLEXITY_RULES
, read_nonce :: ChUInt64 `SinceRevision` DBMS_MIN_REVISION_WITH_INTERSERVER_SECRET_V2
}
deriving (Generic, Show)
instance Deserializable HelloResponse where
deserialize revision = do
server_name <- deserialize revision
server_version_major <- deserialize revision
server_version_minor <- deserialize revision
server_revision <- deserialize revision
-- Override current protocol revision for backward compatibility
let chosenRevision = min server_revision revision
server_parallel_replicas_proto <- deserialize chosenRevision
server_timezone <- deserialize chosenRevision
server_display_name <- deserialize chosenRevision
server_version_patch <- deserialize chosenRevision
proto_send_chunked_srv <- deserialize chosenRevision
proto_recv_chunked_srv <- deserialize chosenRevision
password_complexity_rules <- deserialize chosenRevision
read_nonce <- deserialize chosenRevision
pure MkHelloResponse{..}
data PasswordComplexityRules = MkPasswordComplexityRules
{ original_pattern :: ChString
, exception_message :: ChString
}
deriving (Generic, Deserializable, Show)
instance Deserializable [PasswordComplexityRules] where
deserialize rev = do
len <- deserialize @UVarInt rev
replicateM (fromIntegral len) (deserialize @PasswordComplexityRules rev)
-- ** Exception
data ExceptionPacket = MkExceptionPacket
{ code :: ChInt32
, name :: ChString
, message :: ChString
, stack_trace :: ChString
, nested :: ChUInt8
}
deriving (Generic, Deserializable, Show)
-- ** Progress
data ProgressPacket = MkProgressPacket
{ rows :: UVarInt
, bytes :: UVarInt
, total_rows :: UVarInt
, total_bytes :: UVarInt `SinceRevision` DBMS_MIN_PROTOCOL_VERSION_WITH_TOTAL_BYTES_IN_PROGRESS
, wrote_rows :: UVarInt `SinceRevision` DBMS_MIN_PROTOCOL_VERSION_WITH_TOTAL_BYTES_IN_PROGRESS
, wrote_bytes :: UVarInt `SinceRevision` DBMS_MIN_REVISION_WITH_CLIENT_WRITE_INFO
, elapsed_ns :: UVarInt `SinceRevision` DBMS_MIN_REVISION_WITH_CLIENT_WRITE_INFO
}
deriving (Generic, Deserializable, Show)
-- ** ProfileInfo
data ProfileInfo = MkProfileInfo
{ rows :: UVarInt
, blocks :: UVarInt
, bytes :: UVarInt
, applied_limit :: ChUInt8
, rows_before_limit :: UVarInt
, calculated_rows_before_limit :: ChUInt8
, applied_aggregation :: ChUInt8 `SinceRevision` DBMS_MIN_REVISION_WITH_ROWS_BEFORE_AGGREGATION
, rows_before_aggregation :: UVarInt `SinceRevision` DBMS_MIN_REVISION_WITH_ROWS_BEFORE_AGGREGATION
}
deriving (Generic, Deserializable, Show)
-- ** TableColumns
data TableColumns = MkTableColumns
{ table_name :: ChString
, table_columns :: ChString
}
deriving (Generic, Deserializable, Show)
-- * Deserialization
-- ** Generic API
type GenericReadable record hasColumns =
( Generic record
, GReadable (GetColumns hasColumns) (Rep record)
)
class HasColumns hasColumns => ReadableFrom hasColumns record
where
default deserializeColumns :: GenericReadable record hasColumns => ProtocolRevision -> UVarInt -> Get [record]
deserializeColumns :: ProtocolRevision -> UVarInt -> Get [record]
deserializeColumns rev size = do
list <- gFromColumns @(GetColumns hasColumns) rev size
pure $ do
element <- list
case to element of res -> pure $! res
default readingColumns :: GenericReadable record hasColumns => Builder
readingColumns :: Builder
readingColumns = gReadingColumns @(GetColumns hasColumns) @(Rep record)
class GReadable (columns :: [Type]) f
where
gFromColumns :: ProtocolRevision -> UVarInt -> Get [f p]
gReadingColumns :: Builder
instance
GReadable columns f
=>
GReadable columns (D1 c (C1 c2 f))
where
{-# INLINE gFromColumns #-}
gFromColumns rev size = map (M1 . M1) <$> gFromColumns @columns rev size
gReadingColumns = gReadingColumns @columns @f
instance
GReadable columns (left :*: (right1 :*: right2))
=>
GReadable columns ((left :*: right1) :*: right2)
where
{-# INLINE gFromColumns #-}
gFromColumns rev size = do
list <- gFromColumns @columns rev size
pure [(l :*: r1) :*: r2 | (l :*: (r1 :*: r2)) <- list]
gReadingColumns = gReadingColumns @columns @(left :*: (right1 :*: right2))
instance
( KnownColumn (Column name chType)
, GReadable '[Column name chType] (S1 (MetaSel (Just name) a b f) rec)
, GReadable restColumns right
, '(Column name chType, restColumns) ~ TakeColumn name columns
)
=>
GReadable columns (S1 (MetaSel (Just name) a b f) rec :*: right)
where
{-# INLINE gFromColumns #-}
gFromColumns rev size = do
zipWith (:*:)
<$> gFromColumns @'[Column name chType] rev size
<*> gFromColumns @restColumns rev size
gReadingColumns =
renderColumnName @(Column name chType)
<> ", " <> gReadingColumns @restColumns @right
instance
( KnownColumn (Column name chType)
, DeserializableColumn (Column name chType)
, FromChType chType inputType
, '(Column name chType, restColumns) ~ TakeColumn name columns
) => GReadable columns ((S1 (MetaSel (Just name) a b f)) (Rec0 inputType))
where
{-# INLINE gFromColumns #-}
gFromColumns rev size = map (M1 . K1 . fromChType @chType) . columnValues <$> deserializeColumn @(Column name chType) rev size
gReadingColumns = renderColumnName @(Column name chType)
-- ** Column deserialization
{-# SPECIALIZE replicateM :: Int -> Get chType -> Get [chType] #-}
class DeserializableColumn column where
deserializeColumn :: ProtocolRevision -> UVarInt -> Get column
instance
( KnownColumn (Column name chType)
, Deserializable chType
) =>
DeserializableColumn (Column name chType) where
deserializeColumn rev rows = do
_columnName <- deserialize @ChString rev
_columnType <- deserialize @ChString rev
_isCustom <- deserialize @(ChUInt8 `SinceRevision` DBMS_MIN_REVISION_WITH_CUSTOM_SERIALIZATION) rev
column <- replicateM (fromIntegral rows) (deserialize @chType rev)
pure $ mkColumn @(Column name chType) column