-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasyncmysql.nim
1604 lines (1427 loc) · 54.8 KB
/
asyncmysql.nim
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
## This module implements (a subset of) the MySQL/MariaDB client
## protocol based on asyncnet and asyncdispatch.
##
## No attempt is made to make this look like the C-language
## libmysql API.
##
## This is currently somewhat experimental.
##
## Copyright (c) 2015,2020 William Lewis
##
{.experimental: "notnil".}
import asyncnet, asyncdispatch
import strutils
import std/sha1 as sha1
from endians import nil
from math import fcNormal, fcZero, fcNegZero, fcSubnormal, fcNan, fcInf, fcNegInf
when defined(ssl):
import net # needed for the SslContext type
when isMainModule:
import unittest
proc hexstr(s: string): string
# These are protocol constants; see
# https://dev.mysql.com/doc/internals/en/overview.html
const
ResponseCode_OK : uint8 = 0
ResponseCode_EOF : uint8 = 254 # Deprecated in mysql 5.7.5
ResponseCode_ERR : uint8 = 255
NullColumn = char(0xFB)
LenEnc_16 = 0xFC
LenEnc_24 = 0xFD
LenEnc_64 = 0xFE
HandshakeV10 : uint8 = 0x0A # Initial handshake packet since MySQL 3.21
Charset_swedish_ci : uint8 = 0x08
Charset_utf8_ci : uint8 = 0x21
Charset_binary : uint8 = 0x3f
type
# These correspond to the bits in the capability words,
# and the CLIENT_FOO_BAR definitions in mysql. We rely on
# Nim's set representation being compatible with the
# C bit-masking convention.
Cap {.pure.} = enum
longPassword = 0 # new more secure passwords
foundRows = 1 # Found instead of affected rows
longFlag = 2 # Get all column flags
connectWithDb = 3 # One can specify db on connect
noSchema = 4 # Don't allow database.table.column
compress = 5 # Can use compression protocol
odbc = 6 # Odbc client
localFiles = 7 # Can use LOAD DATA LOCAL
ignoreSpace = 8 # Ignore spaces before '('
protocol41 = 9 # New 4.1 protocol
interactive = 10 # This is an interactive client
ssl = 11 # Switch to SSL after handshake
ignoreSigpipe = 12 # IGNORE sigpipes
transactions = 13 # Client knows about transactions
reserved = 14 # Old flag for 4.1 protocol
secureConnection = 15 # Old flag for 4.1 authentication
multiStatements = 16 # Enable/disable multi-stmt support
multiResults = 17 # Enable/disable multi-results
psMultiResults = 18 # Multi-results in PS-protocol
pluginAuth = 19 # Client supports plugin authentication
connectAttrs = 20 # Client supports connection attributes
pluginAuthLenencClientData = 21 # Enable authentication response packet to be larger than 255 bytes.
canHandleExpiredPasswords = 22 # Don't close the connection for a connection with expired password.
sessionTrack = 23
deprecateEof = 24 # Client no longer needs EOF packet
sslVerifyServerCert = 30
rememberOptions = 31
Status {.pure.} = enum
inTransaction = 0 # a transaction is active
autoCommit = 1 # auto-commit is enabled
moreResultsExist = 3
noGoodIndexUsed = 4
noIndexUsed = 5
cursorExists = 6 # Used by Binary Protocol Resultset
lastRowSent = 7
dbDropped = 8
noBackslashEscapes = 9
metadataChanged = 10
queryWasSlow = 11
psOutParams = 12
inTransactionReadOnly = 13 # in a read-only transaction
sessionStateChanged = 14 # connection state information has changed
# These correspond to the CMD_FOO definitions in mysql.
# Commands marked "internal to the server", and commands
# only used by the replication protocol, are commented out
Command {.pure.} = enum
# sleep = 0
quiT = 1
initDb = 2
query = 3
fieldList = 4
createDb = 5
dropDb = 6
refresh = 7
shutdown = 8
statistics = 9
processInfo = 10
# connect = 11
processKill = 12
debug = 13
ping = 14
# time = 15
# delayedInsert = 16
changeUser = 17
# Replication commands
# binlogDump = 18
# tableDump = 19
# connectOut = 20
# registerSlave = 21
# binlogDumpGtid = 30
# Prepared statements
statementPrepare = 22
statementExecute = 23
statementSendLongData = 24
statementClose = 25
statementReset = 26
# Stored procedures
setOption = 27
statementFetch = 28
# daemon = 29
resetConnection = 31
FieldFlag* {.pure.} = enum
notNull = 0 # Field can't be NULL
primaryKey = 1 # Field is part of a primary key
uniqueKey = 2 # Field is part of a unique key
multipleKey = 3 # Field is part of a key
blob = 4 # Field is a blob
unsigned = 5 # Field is unsigned
zeroFill = 6 # Field is zerofill
binary = 7 # Field is binary
# The following are only sent to new clients (what is "new"? 4.1+?)
enumeration = 8 # field is an enum
autoIncrement = 9 # field is a autoincrement field
timeStamp = 10 # Field is a timestamp
isSet = 11 # Field is a set
noDefaultValue = 12 # Field doesn't have default value
onUpdateNow = 13 # Field is set to NOW on UPDATE
isNum = 15 # Field is num (for clients)
FieldType* = enum
fieldTypeDecimal = uint8(0)
fieldTypeTiny = uint8(1)
fieldTypeShort = uint8(2)
fieldTypeLong = uint8(3)
fieldTypeFloat = uint8(4)
fieldTypeDouble = uint8(5)
fieldTypeNull = uint8(6)
fieldTypeTimestamp = uint8(7)
fieldTypeLongLong = uint8(8)
fieldTypeInt24 = uint8(9)
fieldTypeDate = uint8(10)
fieldTypeTime = uint8(11)
fieldTypeDateTime = uint8(12)
fieldTypeYear = uint8(13)
fieldTypeVarchar = uint8(15)
fieldTypeBit = uint8(16)
fieldTypeNewDecimal = uint8(246)
fieldTypeEnum = uint8(247)
fieldTypeSet = uint8(248)
fieldTypeTinyBlob = uint8(249)
fieldTypeMediumBlob = uint8(250)
fieldTypeLongBlob = uint8(251)
fieldTypeBlob = uint8(252)
fieldTypeVarString = uint8(253)
fieldTypeString = uint8(254)
fieldTypeGeometry = uint8(255)
CursorType* {.pure.} = enum
noCursor = 0
readOnly = 1
forUpdate = 2
scrollable = 3
# This represents a value returned from the server when using
# the prepared statement / binary protocol. For convenience's sake
# we combine multiple wire types into the nearest Nim type.
ResultValueType = enum
rvtNull,
rvtInteger,
rvtLong,
rvtULong,
rvtFloat32,
rvtFloat64,
rvtDate,
rvtTime,
rvtDateTime,
rvtString,
rvtBlob
ResultValue* = object
## A value returned from the server when using the prepared statement
## (binary) protocol. This might contain a numeric or string type
## or NULL. To check for NULL, use `isNil`; attempts to read a value
## from a NULL result will result in a `ValueError`.
case typ: ResultValueType
of rvtInteger:
intVal: int
of rvtLong:
longVal: int64
of rvtULong:
uLongVal: uint64
of rvtString, rvtBlob:
strVal: string
of rvtNull:
discard
of rvtFloat32:
floatVal: float32
of rvtFloat64:
doubleVal: float64
of rvtDate, rvtTime, rvtDateTime:
discard # TODO
ResultString* = object
## A value returned from the server when using the text protocol.
## This contains either a string or an SQL NULL.
case isNull: bool
of false:
value: string
of true:
discard
ParamBindingType = enum
paramNull,
paramString,
paramBlob,
paramInt,
paramUInt,
paramFloat,
paramDouble,
# paramLazyString, paramLazyBlob,
ParameterBinding* = object
## This represents a value we're sending to the server as a parameter.
## Since parameters' types are always sent along with their values,
## we choose the wire type of integers based on the particular value
## we're sending each time.
case typ: ParamBindingType
of paramNull:
discard
of paramString, paramBlob:
strVal: string
of paramInt:
intVal: int64
of paramUInt:
uintVal: uint64
of paramFloat:
floatVal: float32
of paramDouble:
doubleVal: float64
type
nat24 = range[0 .. 16777215]
Connection* = ref ConnectionObj ## A database connection handle.
ConnectionObj* = object of RootObj
socket: AsyncSocket not nil # Bytestream connection
packet_number: uint8 # Next expected seq number (mod-256)
# Information from the connection setup
server_version*: string
thread_id*: uint32
server_caps: set[Cap]
# Other connection parameters
client_caps: set[Cap]
ProtocolError* = object of IOError
## ProtocolError is thrown if we get something we don't understand
## or expect. This is generally a fatal error as far as this connection
## is concerned, since we might have lost framing, packet sequencing,
## etc.. Unexpected connection closure will also result in this exception.
# Server response packets: OK and EOF
ResponseOK* {.final.} = object
## Status information returned from the server after each successful
## command.
eof : bool # True if EOF packet, false if OK packet
affected_rows* : Natural
last_insert_id* : Natural
status_flags* : set[Status]
warning_count* : Natural
info* : string
# session_state_changes: seq[ ... ]
# Server response packet: ERR (which can be thrown as an exception)
ResponseERR* = object of CatchableError
## This exception is thrown when a command fails.
error_code*: uint16 ## A MySQL-specific error number
sqlstate*: string ## An ANSI SQL state code
ColumnDefinition* {.final.} = object
catalog* : string
schema* : string
table* : string
orig_table* : string
name* : string
orig_name* : string
charset : int16
length* : uint32
column_type* : FieldType
flags* : set[FieldFlag]
decimals* : int
ResultSet*[T] {.final.} = object
status* : ResponseOK
columns* : seq[ColumnDefinition]
rows* : seq[seq[T]]
PreparedStatement* = ref PreparedStatementObj
PreparedStatementObj = object
statement_id: array[4, char]
parameters: seq[ColumnDefinition]
columns: seq[ColumnDefinition]
warnings: Natural
type sqlNull = distinct tuple[]
const SQLNULL*: sqlNull = sqlNull( () )
## `SQLNULL` is a singleton value corresponding to SQL's NULL.
## This is used to send a NULL value for a parameter when
## executing a prepared statement.
const advertisedMaxPacketSize: uint32 = 65536 # max packet size, TODO: what should I put here?
# ######################################################################
#
# Forward declarations
proc selectDatabase*(conn: Connection, database: string): Future[ResponseOK]
# ######################################################################
#
# Basic datatype packers/unpackers
# Integers
proc scanU32(buf: string, pos: int): uint32 =
result = uint32(buf[pos]) + `shl`(uint32(buf[pos+1]), 8'u32) + (uint32(buf[pos+2]) shl 16'u32) + (uint32(buf[pos+3]) shl 24'u32)
proc putU32(buf: var string, val: uint32) =
buf.add( char( val and 0xff ) )
buf.add( char( (val shr 8) and 0xff ) )
buf.add( char( (val shr 16) and 0xff ) )
buf.add( char( (val shr 24) and 0xff ) )
proc scanU16(buf: string, pos: int): uint16 =
result = uint16(buf[pos]) + (uint16(buf[pos+1]) shl 8'u16)
proc putU16(buf: var string, val: uint16) =
buf.add( char( val and 0xFF ) )
buf.add( char( (val shr 8) and 0xFF ) )
proc putU8(buf: var string, val: uint8) {.inline.} =
buf.add( char(val) )
proc putU8(buf: var string, val: range[0..255]) {.inline.} =
buf.add( char(val) )
proc scanU64(buf: string, pos: int): uint64 =
let l32 = scanU32(buf, pos)
let h32 = scanU32(buf, pos+4)
return uint64(l32) + ( (uint64(h32) shl 32 ) )
proc putS64(buf: var string, val: int64) =
let compl: uint64 = cast[uint64](val)
buf.putU32(uint32(compl and 0xFFFFFFFF'u64))
buf.putU32(uint32(compl shr 32))
proc scanLenInt(buf: string, pos: var int): int =
let b1 = uint8(buf[pos])
if b1 < 251:
inc(pos)
return int(b1)
if b1 == LenEnc_16:
result = int(uint16(buf[pos+1]) + ( uint16(buf[pos+2]) shl 8 ))
pos = pos + 3
return
if b1 == LenEnc_24:
result = int(uint32(buf[pos+1]) + ( uint32(buf[pos+2]) shl 8 ) + ( uint32(buf[pos+3]) shl 16 ))
pos = pos + 4
return
return -1
proc putLenInt(buf: var string, val: int) =
if val < 0:
raise newException(ProtocolError, "trying to send a negative lenenc-int")
elif val < 251:
buf.add( char(val) )
elif val < 65536:
buf.add( char(LenEnc_16) )
buf.add( char( val and 0xFF ) )
buf.add( char( (val shr 8) and 0xFF ) )
elif val <= 0xFFFFFF:
buf.add( char(LenEnc_24) )
buf.add( char( val and 0xFF ) )
buf.add( char( (val shr 8) and 0xFF ) )
buf.add( char( (val shr 16) and 0xFF ) )
else:
raise newException(ProtocolError, "lenenc-int too long for me!")
# Strings
proc scanNulString(buf: string, pos: var int): string =
result = ""
while buf[pos] != char(0):
result.add(buf[pos])
inc(pos)
inc(pos)
proc scanNulStringX(buf: string, pos: var int): string =
result = ""
while pos <= high(buf) and buf[pos] != char(0):
result.add(buf[pos])
inc(pos)
inc(pos)
proc putNulString(buf: var string, val: string) =
buf.add(val)
buf.add( char(0) )
proc scanLenStr(buf: string, pos: var int): string =
let slen = scanLenInt(buf, pos)
if slen < 0:
raise newException(ProtocolError, "lenenc-int: is 0x" & toHex(int(buf[pos]), 2))
result = substr(buf, pos, pos+slen-1)
pos = pos + slen
proc putLenStr(buf: var string, val: string) =
putLenInt(buf, val.len)
buf.add(val)
# Floating point numbers. We assume that the wire protocol is always
# little-endian IEEE-754 (because all the world's a Vax^H^H^H 386),
# and we assume that the native representation is also IEEE-754 (but
# we check that second assumption in our unit tests).
proc scanIEEE754Single(buf: string, pos: int): float32 =
endians.littleEndian32(addr(result), unsafeAddr(buf[pos]))
proc scanIEEE754Double(buf: string, pos: int): float64 =
endians.littleEndian64(addr(result), unsafeAddr(buf[pos]))
proc putIEEE754(buf: var string, val: float32) =
let oldLen = buf.len()
buf.setLen(oldLen + 4)
endians.littleEndian32(addr(buf[oldLen]), unsafeAddr val)
proc putIEEE754(buf: var string, val: float64) =
let oldLen = buf.len()
buf.setLen(oldLen + 8)
endians.littleEndian64(addr(buf[oldLen]), unsafeAddr val)
when isMainModule: suite "Packing/unpacking of primitive types":
test "Integers":
var buf: string = ""
putLenInt(buf, 0)
putLenInt(buf, 1)
putLenInt(buf, 250)
putLenInt(buf, 251)
putLenInt(buf, 252)
putLenInt(buf, 512)
putLenInt(buf, 640)
putLenInt(buf, 65535)
putLenInt(buf, 65536)
putLenInt(buf, 15715755)
putU32(buf, uint32(65535))
putU32(buf, uint32(65536))
putU32(buf, 0x80C00AAA'u32)
check "0001fafcfb00fcfc00fc0002fc8002fcfffffd000001fdabcdefffff000000000100aa0ac080" == hexstr(buf)
var pos: int = 0
check 0 == scanLenInt(buf, pos)
check 1 == scanLenInt(buf, pos)
check 250 == scanLenInt(buf, pos)
check 251 == scanLenInt(buf, pos)
check 252 == scanLenInt(buf, pos)
check 512 == scanLenInt(buf, pos)
check 640 == scanLenInt(buf, pos)
check 0x0FFFF == scanLenInt(buf, pos)
check 0x10000 == scanLenInt(buf, pos)
check 15715755 == scanLenInt(buf, pos)
check 65535'u32 == scanU32(buf, pos)
check 65535'u16 == scanU16(buf, pos)
check 255'u16 == scanU16(buf, pos+1)
check 0'u16 == scanU16(buf, pos+2)
pos += 4
check 65536'u32 == scanU32(buf, pos)
pos += 4
check 0x80C00AAA'u32 == scanU32(buf, pos)
pos += 4
check 0x80C00AAA00010000'u64 == scanU64(buf, pos-8)
check len(buf) == pos
test "Integers (bit-walking tests)":
for bit in 0..63:
var byhand: string = "\xFF"
var test: string
for b_off in 0..7:
if b_off == bit div 8:
byhand.add(chr(0x01 shl (bit mod 8)))
else:
byhand.add(chr(0))
if bit < 16:
let v16: uint16 = (1'u16) shl bit
check scanU16(byhand, 1) == v16
test = "\xFF"
putU16(test, v16)
test &= "\x00\x00\x00\x00\x00\x00"
check test == byhand
check hexstr(test) == hexstr(byhand)
if bit < 32:
let v32: uint32 = (1'u32) shl bit
check scanU32(byhand, 1) == v32
test = "\xFF"
putU32(test, v32)
test &= "\x00\x00\x00\x00"
check test == byhand
if bit < 63:
test = "\xFF"
putS64(test, (1'i64) shl bit)
check test == byhand
check hexstr(test) == hexstr(byhand)
let v64: uint64 = (1'u64) shl bit
check scanU64(byhand, 1) == v64
const e32: float32 = 0.00000011920928955078125'f32
test "Floats":
var buf: string = ""
putIEEE754(buf, 1.0'f32)
putIEEE754(buf, e32)
putIEEE754(buf, 1.0'f32 + e32)
check "0000803f000000340100803f" == hexstr(buf)
check:
scanIEEE754Single(buf, 0) == 1.0'f32
scanIEEE754Single(buf, 4) == e32
scanIEEE754Single(buf, 8) == 1.0'f32 + e32
# Non-word-aligned
check:
scanIEEE754Single("XAB\x01\x49Y", 1) == 0x81424 + 0.0625'f32
test "Doubles":
var buf: string = ""
putIEEE754(buf, -2.0'f64)
putIEEE754(buf, float64(e32))
putIEEE754(buf, 1024'f64 + float64(e32))
check "00000000000000c0000000000000803e0000080000009040" == hexstr(buf)
check:
scanIEEE754Double(buf, 0) == -2'f64
scanIEEE754Double(buf, 8) == float64(e32)
scanIEEE754Double(buf, 16) == 1024'f64 + float64(e32)
# Non-word-aligned
check:
scanIEEE754Double("XYZGFEDCB\xFA\x42QRS", 3) == float64(0x1A42434445464) + 0.4375'f64
proc hexdump(buf: openarray[char], fp: File) {.used.} =
var pos = low(buf)
while pos <= high(buf):
for i in 0 .. 15:
fp.write(' ')
if i == 8: fp.write(' ')
let p = i+pos
fp.write( if p <= high(buf): toHex(int(buf[p]), 2) else: " " )
fp.write(" |")
for i in 0 .. 15:
var ch = ( if (i+pos) > high(buf): ' ' else: buf[i+pos] )
if ch < ' ' or ch > '~':
ch = '.'
fp.write(ch)
pos += 16
fp.write("|\n")
# ######################################################################
#
# Parameter and result packers/unpackers
proc addTypeUnlessNULL(p: ParameterBinding, pkt: var string) =
case p.typ
of paramNull:
return
of paramString:
pkt.add(char(fieldTypeString))
pkt.add(char(0))
of paramBlob:
pkt.add(char(fieldTypeBlob))
pkt.add(char(0))
of paramInt:
if p.intVal >= 0:
if p.intVal < 256'i64:
pkt.add(char(fieldTypeTiny))
elif p.intVal < 65536'i64:
pkt.add(char(fieldTypeShort))
elif p.intVal < (65536'i64 * 65536'i64):
pkt.add(char(fieldTypeLong))
else:
pkt.add(char(fieldTypeLongLong))
pkt.add(char(0x80))
else:
if p.intVal >= -128:
pkt.add(char(fieldTypeTiny))
elif p.intVal >= -32768:
pkt.add(char(fieldTypeShort))
else:
pkt.add(char(fieldTypeLongLong))
pkt.add(char(0))
of paramUInt:
if p.uintVal < (65536'u64 * 65536'u64):
pkt.add(char(fieldTypeLong))
else:
pkt.add(char(fieldTypeLongLong))
pkt.add(char(0x80))
of paramFloat:
pkt.add(char(fieldTypeFloat))
pkt.add(char(0))
of paramDouble:
pkt.add(char(fieldTypeDouble))
pkt.add(char(0))
proc addValueUnlessNULL(p: ParameterBinding, pkt: var string) =
case p.typ
of paramNull:
return
of paramString, paramBlob:
putLenStr(pkt, p.strVal)
of paramInt:
if p.intVal >= 0:
pkt.putU8(p.intVal and 0xFF)
if p.intVal >= 256:
pkt.putU8((p.intVal shr 8) and 0xFF)
if p.intVal >= 65536:
pkt.putU16( ((p.intVal shr 16) and 0xFFFF).uint16 )
if p.intVal >= (65536'i64 * 65536'i64):
pkt.putU32(uint32(p.intVal shr 32))
else:
if p.intVal >= -128:
pkt.putU8(uint8(p.intVal + 256))
elif p.intVal >= -32768:
pkt.putU16(uint16(p.intVal + 65536))
else:
pkt.putS64(p.intVal)
of paramUInt:
putU32(pkt, uint32(p.uintVal and 0xFFFFFFFF'u64))
if p.uintVal >= 0xFFFFFFFF'u64:
putU32(pkt, uint32(p.uintVal shr 32))
of paramFloat:
pkt.putIEEE754(p.floatVal)
of paramDouble:
pkt.putIEEE754(p.doubleVal)
proc approximatePackedSize(p: ParameterBinding): int {.inline.} =
case p.typ
of paramNull:
return 0
of paramString, paramBlob:
return 5 + len(p.strVal)
of paramInt, paramUInt, paramFloat:
return 4
of paramDouble:
return 8
proc asParam*(n: sqlNull): ParameterBinding {. inline .} = ParameterBinding(typ: paramNull)
proc asParam*(n: typeof(nil)): ParameterBinding {. deprecated("Do not use nil for NULL parameters, use SQLNULL") .} = ParameterBinding(typ: paramNull)
proc asParam*(s: string): ParameterBinding =
ParameterBinding(typ: paramString, strVal: s)
proc asParam*(i: int): ParameterBinding {. inline .} = ParameterBinding(typ: paramInt, intVal: i)
proc asParam*(i: uint): ParameterBinding =
if i > uint(high(int)):
ParameterBinding(typ: paramUInt, uintVal: uint64(i))
else:
ParameterBinding(typ: paramInt, intVal: int64(i))
proc asParam*(i: int64): ParameterBinding =
ParameterBinding(typ: paramInt, intVal: i)
proc asParam*(i: uint64): ParameterBinding =
if i > uint64(high(int)):
ParameterBinding(typ: paramUInt, uintVal: i)
else:
ParameterBinding(typ: paramInt, intVal: int64(i))
proc asParam*(b: bool): ParameterBinding = ParameterBinding(typ: paramInt, intVal: if b: 1 else: 0)
proc asParam*(f: float32): ParameterBinding {. inline .} =
ParameterBinding(typ: paramFloat, floatVal:f)
proc asParam*(f: float64): ParameterBinding {. inline .} =
ParameterBinding(typ: paramDouble, doubleVal:f)
proc isNil*(v: ResultValue): bool {.inline.} = v.typ == rvtNull
proc `$`*(v: ResultValue): string =
## Produce an approximate string representation of the value. This
## should mainly be restricted to debugging uses, since it is impossible
## to distingiuish between, *e.g.*, a NULL value and the four-character
## string "NULL".
case v.typ
of rvtNull:
return "NULL"
of rvtString, rvtBlob:
return v.strVal
of rvtInteger:
return $(v.intVal)
of rvtLong:
return $(v.longVal)
of rvtULong:
return $(v.uLongVal)
of rvtFloat32:
return $(v.floatVal)
of rvtFloat64:
return $(v.doubleVal)
else:
return "(unrepresentable!)"
{.push overflowChecks: on .}
proc toNumber[T: SomeInteger](v: ResultValue): T {.inline.} =
case v.typ
of rvtInteger:
return T(v.intVal)
of rvtLong:
return T(v.longVal)
of rvtULong:
return T(v.uLongVal)
of rvtNull:
raise newException(ValueError, "NULL value")
else:
raise newException(ValueError, "cannot convert " & $(v.typ) & " to " & $(T))
# Converters can't be generic; we need to explicitly instantiate
# the ones we think might be needed.
converter asInt8*(v: ResultValue): uint8 = return toNumber[uint8](v)
converter asInt*(v: ResultValue): int = return toNumber[int](v)
converter asUInt*(v: ResultValue): uint = return toNumber[uint](v)
converter asInt64*(v: ResultValue): int64 = return toNumber[int64](v)
converter asUInt64*(v: ResultValue): uint64 = return toNumber[uint64](v)
proc toFloat[T: SomeFloat](v: ResultValue): T {.inline.} =
case v.typ
of rvtFloat32:
return v.floatVal
of rvtFloat64:
return v.doubleVal
of rvtNULL:
raise newException(ValueError, "NULL value")
else:
raise newException(ValueError, "cannot convert " & $(v.typ) & " to float")
converter asFloat32*(v: ResultValue): float32 = toFloat[float32](v)
converter asFloat64*(v: ResultValue): float64 = toFloat[float64](v)
{. pop .}
converter asString*(v: ResultValue): string =
## If the value is a string, return it; otherwise raise a `ValueError`.
case v.typ
of rvtNull:
raise newException(ValueError, "NULL value")
of rvtString, rvtBlob:
return v.strVal
else:
raise newException(ValueError, "cannot convert " & $(v.typ) & " to string")
converter asBool*(v: ResultValue): bool =
## If the value is numeric, return it as a boolean; otherwise
## raise a `ValueError`. Note that `NULL` is neither true nor
## false and will raise.
case v.typ
of rvtInteger:
return v.intVal != 0
of rvtLong:
return v.longVal != 0
of rvtULong:
return v.uLongVal != 0
of rvtNull:
raise newException(ValueError, "NULL value")
else:
raise newException(ValueError, "cannot convert " & $(v.typ) & " to boolean")
proc `==`*(v: ResultValue, s: string): bool =
## Compare the result value to a string.
## NULL values are not equal to any string.
## Non-string non-NULL values will result in an exception.
case v.typ
of rvtNull:
return false
of rvtString, rvtBlob:
return v.strVal == s
else:
raise newException(ValueError, "cannot convert " & $(v.typ) & " to string")
proc floatEqualsInt[F: SomeFloat, I: SomeInteger](v: F, n: I): bool =
## Compare a float to an integer. Note that this is inherently a
## dodgy operation (which is why it's not overloading `==`). Floats
## are inexact, and each float corresponds to a range of real numbers;
## for larger numbers, a single float value can be "equal to" many
## different integers. (Or maybe it''s equal to none of them if it
## can't represent any of them exactly — it really depends on what
## you're modeling with that float, doesn''t it?) Anyway, for my particular
## case I don't care about that.
# Infinities, NaNs, etc., are not equal to any integer. Subnormals
# are also always less than 1 (and nonzero) so cannot be integers.
case math.classify(v)
of fcNormal:
if n == 0:
return false
else:
return v == F(n) # kludge
of fcZero, fcNegZero:
return n == 0
of fcSubnormal, fcNan, fcInf, fcNegInf:
return false
proc `==`[S: SomeSignedInt, U: SomeUnsignedInt](s: S, u: U): bool =
## Safely compare a signed and an unsigned integer of possibly
## different widths.
if s < 0:
return false
when sizeof(U) >= sizeof(S):
if u > U(high(S)):
return false
else:
return S(u) == s
else:
if s > S(high(U)):
return false
else:
return U(s) == u
when (NimMajor, NimMinor) < (1, 2) and uint isnot uint64:
# Support for Nim < 1.2
proc `==`(a: uint, b: uint64): bool =
return uint64(a) == b
proc `==`*[T: SomeInteger](v: ResultValue, n: T): bool =
## Compare the result value to an integer.
## NULL values are not equal to any integer.
## Non-numeric non-NULL values (strings, etc.) will result in an exception.
##
## As a special case, this allows comparing a floating point ResultValue
## to an integer.
case v.typ
of rvtInteger:
return v.intVal == n
of rvtLong:
return v.longVal == n
of rvtULong:
return n == v.uLongVal
of rvtFloat32:
return floatEqualsInt(v.floatVal, n)
of rvtFloat64:
return floatEqualsInt(v.doubleVal, n)
of rvtNull:
return false
else:
raise newException(ValueError, "cannot compare " & $(v.typ) & " to integer")
proc `==`*[F: SomeFloat](v: ResultValue, n: F): bool =
## Compare the result value to a float.
## NULL values are not equal to anything.
## Non-float values (including integers) will result in an exception.
case v.typ
of rvtFloat32:
return v.floatVal == n
of rvtFloat64:
return v.doubleVal == n
of rvtNull:
return false
else:
raise newException(ValueError, "cannot compare " & $(v.typ) & " to floating-point number")
proc `==`*(v: ResultValue, b: bool): bool =
## Compare a result value to a boolean.
##
## The MySQL wire protocol does
## not have an explicit boolean type, so this tests an integer type against
## zero. NULL values are not equal to true *or* false (therefore,
## `if v == true:` is not equivalent to `if v:`: the latter will raise
## an exception if v is NULL). Non-integer values will result in an exception.
if v.typ == rvtNull:
return false
else:
return bool(v) == b
proc isNil*(v: ResultString): bool {.inline.} = v.isNull
proc `$`*(v: ResultString): string =
## Produce an approximate string representation of the value. This
## should mainly be restricted to debugging uses, since it is impossible
## to distingiuish between a NULL value and the four-character
## string "NULL".
case v.isNull
of true:
return "NULL"
of false:
return v.value
converter asString*(v: ResultString): string =
## Return the result as a string.
## Raise `ValueError` if the result is NULL.
case v.isNull:
of true:
raise newException(ValueError, "NULL value")
of false:
return v.value
proc `==`*(a: ResultString, b: ResultString): bool =
## Compare two result strings. **Note:** This does not
## follow SQL semantics; NULL will compare equal to NULL.
case a.isNull
of true:
return b.isNull
of false:
return (not b.isNull) and (a.value == b.value)
proc `==`*(a: ResultString, b: string): bool =
## Compare a result to a string. NULL results are not
## equal to any string.
case a.isNull
of true:
return false
of false:
return (a.value == b)
proc asResultString*(s: string): ResultString {.inline.} =
ResultString(isNull: false, value: s)
proc asResultString*(n: sqlNull): ResultString {.inline.} =
ResultString(isNull: true)
# ######################################################################
#
# MySQL packet packers/unpackers
proc processHeader(c: Connection, hdr: array[4, char]): nat24 =
result = int32(hdr[0]) + int32(hdr[1])*256 + int32(hdr[2])*65536
let pnum = uint8(hdr[3])
if pnum != c.packet_number:
raise newException(ProtocolError, "Bad packet number (got sequence number " & $(pnum) & ", expected " & $(c.packet_number) & ")")
c.packet_number += 1
proc receivePacket(conn:Connection, drop_ok: bool = false): Future[string] {.async.} =
let hdr = await conn.socket.recv(4)
if len(hdr) == 0:
if drop_ok:
return ""
else:
raise newException(ProtocolError, "Connection closed")
if len(hdr) != 4:
raise newException(ProtocolError, "Connection closed unexpectedly")
let b = cast[ptr array[4,char]](cstring(hdr))
let packet_length = conn.processHeader(b[])
if packet_length == 0:
return ""
result = await conn.socket.recv(packet_length)
if len(result) == 0:
raise newException(ProtocolError, "Connection closed unexpectedly")
if len(result) != packet_length:
raise newException(ProtocolError, "TODO finish this part")
# Caller must have left the first four bytes of the buffer available for
# us to write the packet header.
proc sendPacket(conn: Connection, buf: var string, reset_seq_no = false): Future[void] =
let bodylen = len(buf) - 4
buf[0] = char( (bodylen and 0xFF) )
buf[1] = char( ((bodylen shr 8) and 0xFF) )
buf[2] = char( ((bodylen shr 16) and 0xFF) )
if reset_seq_no:
conn.packet_number = 0
buf[3] = char( conn.packet_number )
inc(conn.packet_number)
# hexdump(buf, stdmsg)
return conn.socket.send(buf)
type
greetingVars {.final.} = object
scramble: string
authentication_plugin: string