-
Notifications
You must be signed in to change notification settings - Fork 196
/
Copy pathXInternalSession.cs
1052 lines (938 loc) · 38.3 KB
/
XInternalSession.cs
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
// Copyright (c) 2015, 2021, Oracle and/or its affiliates.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, version 2.0, as
// published by the Free Software Foundation.
//
// This program is also distributed with certain software (including
// but not limited to OpenSSL) that is licensed under separate terms,
// as designated in a particular file or component or in included license
// documentation. The authors of MySQL hereby grant you an
// additional permission to link the program and your derivative works
// with the separately licensed software that they have included with
// MySQL.
//
// Without limiting anything contained in the foregoing, this file,
// which is part of MySQL Connector/NET, is also subject to the
// Universal FOSS Exception, version 1.0, a copy of which can be found at
// http://oss.oracle.com/licenses/universal-foss-exception.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License, version 2.0, for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using MySql.Data;
using MySql.Data.Common;
using MySql.Data.MySqlClient;
using MySql.Data.MySqlClient.Authentication;
using MySqlX.Communication;
using MySqlX.Protocol;
using MySqlX.Protocol.X;
using MySqlX.Security;
using MySqlX.XDevAPI;
using MySqlX.XDevAPI.Common;
using MySqlX.XDevAPI.CRUD;
using MySqlX.XDevAPI.Relational;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Diagnostics;
using System.Collections;
using System.Threading;
namespace MySqlX.Sessions
{
/// <summary>
/// Implementation class of InternalSession to manage connections using the Xprotocol type object.
/// </summary>
internal class XInternalSession : InternalSession
{
/// <summary>
/// Defines the compression controller that will be passed on the <see cref="XPacketReaderWriter"/> instance when
/// compression is enabled.
/// </summary>
private XCompressionController _readerCompressionController;
/// <summary>
/// Defines the compression controller that will be passed on the <see cref="XPacketReaderWriter"/> instance when
/// compression is enabled.
/// </summary>
private XCompressionController _writerCompressionController;
private XProtocol _protocol;
private XPacketReaderWriter _packetReaderWriter;
private bool _serverSupportsTls = false;
private const string mysqlxNamespace = "mysqlx";
internal bool _supportsPreparedStatements = true;
private int _stmtId = 0;
private List<int> _preparedStatements = new List<int>();
internal bool? _sessionResetNoReauthentication = null;
internal MyNetworkStream _myNetworkStream;
public XInternalSession(MySqlXConnectionStringBuilder settings) : base(settings)
{
}
protected override void Open()
{
bool isUnix = Settings.ConnectionProtocol == MySqlConnectionProtocol.Unix ||
Settings.ConnectionProtocol == MySqlConnectionProtocol.UnixSocket;
_stream = MyNetworkStream.CreateStream(
Settings.Server == "127.0.0.1" || Settings.Server == "::1"
? "localhost"
: Settings.Server,
Settings.ConnectTimeout,
Settings.Keepalive,
Settings.Port,
isUnix);
_myNetworkStream = (MyNetworkStream)_stream;
if (_stream == null)
throw new MySqlException(ResourcesX.UnableToConnect);
_packetReaderWriter = new XPacketReaderWriter(_stream, _myNetworkStream.Socket);
_protocol = new XProtocol(_packetReaderWriter);
Settings.CharacterSet = string.IsNullOrWhiteSpace(Settings.CharacterSet) ? "utf8mb4" : Settings.CharacterSet;
var encoding = Encoding.GetEncoding(string.Compare(Settings.CharacterSet, "utf8mb4", true) == 0 ? "UTF-8" : Settings.CharacterSet);
SetState(SessionState.Connecting, false);
try
{
GetAndSetCapabilities();
}
catch (Exception)
{
throw;
}
// Validates use of TLS.
if (Settings.SslMode != MySqlSslMode.None)
{
if (_serverSupportsTls)
{
new Ssl(
Settings.Server,
Settings.SslMode,
Settings.CertificateFile,
Settings.CertificateStoreLocation,
Settings.CertificatePassword,
Settings.CertificateThumbprint,
Settings.SslCa,
Settings.SslCert,
Settings.SslKey,
Settings.TlsVersion)
.StartSSL(ref _stream, encoding, Settings.ToString());
if (_readerCompressionController != null && _readerCompressionController.IsCompressionEnabled)
{
_packetReaderWriter = new XPacketReaderWriter(_stream, _readerCompressionController, _writerCompressionController, _myNetworkStream.Socket);
}
else
{
_packetReaderWriter = new XPacketReaderWriter(_stream, _myNetworkStream.Socket);
}
_protocol.SetXPackets(_packetReaderWriter);
}
else
{
// Client requires SSL connections.
string message = String.Format(Resources.NoServerSSLSupport,
Settings.Server);
throw new MySqlException(message);
}
}
else if (_readerCompressionController != null && _readerCompressionController.IsCompressionEnabled)
{
_packetReaderWriter = new XPacketReaderWriter(_stream, _readerCompressionController, _writerCompressionController, _myNetworkStream.Socket);
_protocol.SetXPackets(_packetReaderWriter);
}
Authenticate();
SetState(SessionState.Open, false);
}
internal void Authenticate()
{
// Default authentication
if (Settings.Auth == MySqlAuthenticationMode.Default)
{
if ((Settings.SslMode != MySqlSslMode.None && _serverSupportsTls) || Settings.ConnectionProtocol == MySqlConnectionProtocol.Unix)
{
Settings.Auth = MySqlAuthenticationMode.PLAIN;
AuthenticatePlain();
}
else
{
bool authenticated = false;
// first try using MYSQL41
Settings.Auth = MySqlAuthenticationMode.MYSQL41;
try
{
AuthenticateMySQL41();
authenticated = true;
}
catch (MySqlException ex)
{
// code 1045 Invalid user or password
if (ex.Code != 1045)
throw;
}
// second try using SHA256_MEMORY
if (!authenticated)
{
try
{
Settings.Auth = MySqlAuthenticationMode.SHA256_MEMORY;
AuthenticateSha256Memory();
authenticated = true;
}
catch (MySqlException ex)
{
// code 1045 Invalid user or password
if (ex.Code == 1045)
throw new MySqlException(1045, "HY000", ResourcesX.AuthenticationFailed);
else
throw;
}
}
}
}
// User defined authentication
else
{
switch (Settings.Auth)
{
case MySqlAuthenticationMode.PLAIN:
AuthenticatePlain();
break;
case MySqlAuthenticationMode.MYSQL41:
AuthenticateMySQL41();
break;
case MySqlAuthenticationMode.EXTERNAL:
AuthenticateExternal();
break;
case MySqlAuthenticationMode.SHA256_MEMORY:
AuthenticateSha256Memory();
break;
default:
throw new NotImplementedException(Settings.Auth.ToString());
}
}
}
private void GetAndSetCapabilities()
{
_protocol.GetServerCapabilities();
var clientCapabilities = new Dictionary<string, object>();
Mysqlx.Connection.Capability capability = null;
// Validates TLS use.
if (Settings.SslMode != MySqlSslMode.None)
{
capability = _protocol.Capabilities.Capabilities_.FirstOrDefault(i => i.Name.ToLowerInvariant() == "tls");
if (capability != null)
{
_serverSupportsTls = true;
clientCapabilities.Add("tls", "1");
}
}
// Set connection-attributes.
if (Settings.ConnectionAttributes.ToLower() != "false")
clientCapabilities.Add("session_connect_attrs", GetConnectionAttributes(Settings.ConnectionAttributes));
// Set compression algorithm.
if (Settings.Compression != CompressionType.Disabled)
{
capability = _protocol.Capabilities.Capabilities_.FirstOrDefault(i => i.Name.ToLowerInvariant() == XCompressionController.COMPRESSION_KEY);
// Raise error if client expects compression but server doesn't support it.
if (Settings.Compression == CompressionType.Required && capability == null)
{
throw new NotSupportedException(ResourcesX.CompressionNotSupportedByServer);
}
// Update capabilities with the compression algorithm negotiation if server supports compression.
if (capability != null)
{
var algorithmsDictionary = capability.Value.Obj.Fld.ToDictionary(
field => field.Key,
field => field.Value.Array.Value.ToDictionary(value => value.Scalar.VString.Value.ToStringUtf8().ToLowerInvariant()).Keys.ToList());
if (algorithmsDictionary.ContainsKey(XCompressionController.ALGORITHMS_SUBKEY))
{
var supportedCompressionAlgorithms = algorithmsDictionary[XCompressionController.ALGORITHMS_SUBKEY].ToList().ToArray();
VerifyDefaultOrder(ref supportedCompressionAlgorithms);
var userCompressionAlgorithms = NegotiateUserAgainstClientAlgorithms(Settings.CompressionAlgorithm);
var compressionCapabilities = NegotiateCompression(supportedCompressionAlgorithms, userCompressionAlgorithms);
if (compressionCapabilities != null)
{
clientCapabilities.Add(XCompressionController.COMPRESSION_KEY, compressionCapabilities);
var compressionAlgorithm = compressionCapabilities.First().Value.ToString();
_readerCompressionController = new XCompressionController((CompressionAlgorithms)Enum.Parse(typeof(CompressionAlgorithms), compressionAlgorithm), false);
_writerCompressionController = new XCompressionController((CompressionAlgorithms)Enum.Parse(typeof(CompressionAlgorithms), compressionAlgorithm), true);
_packetReaderWriter = new XPacketReaderWriter(_stream, _readerCompressionController, _writerCompressionController, _myNetworkStream.Socket);
}
}
}
}
try
{
_protocol.SetCapabilities(clientCapabilities);
}
catch (MySqlException ex)
{
if (ex.Message == "Capability 'session_connect_attrs' doesn't exist")
clientCapabilities.Remove("session_connect_attrs");
_protocol.SetCapabilities(clientCapabilities);
}
}
/// <summary>
/// Reorder the list of algorithms retrieved from server to the preferred order
/// </summary>
private void VerifyDefaultOrder(ref string[] algorithms)
{
var clientSupportedAlgorithms = Enum.GetNames(typeof(CompressionAlgorithms));
List<string> output = new List<string>();
foreach (var item in clientSupportedAlgorithms)
{
if (algorithms.Contains(item))
{
output.Add(item);
}
}
algorithms = output.ToArray();
}
/// <summary>
/// Validate the algorithms given in the connection string are valid compared with enum CompressionAlgorithms
/// </summary>
public string[] NegotiateUserAgainstClientAlgorithms(string inputString)
{
inputString = inputString.Contains("[") ? inputString.Replace("[", string.Empty) : inputString;
inputString = inputString.Contains("]") ? inputString.Replace("]", string.Empty) : inputString;
inputString.Trim();
if (string.IsNullOrEmpty(inputString))
{
return Enum.GetNames(typeof(CompressionAlgorithms));
}
var elements = inputString.ToLowerInvariant().Split(',');
List<string> ret = new List<string>();
for (var i = 0; i < elements.Length; i++)
{
switch (elements[i].ToLowerInvariant())
{
case "lz4":
case "lz4_message":
elements[i] = CompressionAlgorithms.lz4_message.ToString();
break;
case "zstd":
case "zstd_stream":
elements[i] = CompressionAlgorithms.zstd_stream.ToString();
break;
case "deflate":
case "deflate_stream":
#if NETFRAMEWORK
if (elements.Length == 1 && Settings.Compression == CompressionType.Required)
{
throw new NotSupportedException(string.Format(ResourcesX.CompressionForSpecificAlgorithmNotSupportedInNetFramework, elements[i]));
}
#else
elements[i] = CompressionAlgorithms.deflate_stream.ToString();
#endif
break;
}
if (Enum.IsDefined(typeof(CompressionAlgorithms), elements[i]))
{
ret.Add(elements[i]);
}
}
return ret.ToArray();
}
/// <summary>
/// Negotiates compression capabilities with the server.
/// </summary>
/// <param name="serverSupportedAlgorithms">An array containing the compression algorithms supported by the server.</param>
/// <param name="clientAgainstUserAlgorithms">An array containing the compression algorithms given by user/client.</param>
private Dictionary<string, object> NegotiateCompression(string[] serverSupportedAlgorithms, string[] clientAgainstUserAlgorithms)
{
if (serverSupportedAlgorithms == null || serverSupportedAlgorithms.Length == 0)
{
if (Settings.Compression == CompressionType.Required && clientAgainstUserAlgorithms.Length > 0)
{
throw new NotSupportedException(ResourcesX.CompressionAlgorithmNegotiationFailed);
}
return null;
}
// If server and client don't have matching compression algorithms either log a warning message
// or raise an exception based on the selected compression type.
XCompressionController.LoadLibzstdLibrary();
if (!clientAgainstUserAlgorithms.Any(element => serverSupportedAlgorithms.Contains(element)))
{
if (Settings.Compression == CompressionType.Preferred)
{
MySqlTrace.LogWarning(-1, ResourcesX.CompressionAlgorithmNegotiationFailed);
return null;
}
else if (Settings.Compression == CompressionType.Required)
{
throw new NotSupportedException(ResourcesX.CompressionAlgorithmNegotiationFailed);
}
}
string negotiatedAlgorithm = null;
for (int index = 0; index < clientAgainstUserAlgorithms.Length; index++)
{
if (!serverSupportedAlgorithms.Contains(clientAgainstUserAlgorithms[index]))
{
continue;
}
negotiatedAlgorithm = clientAgainstUserAlgorithms[index];
break;
}
if (negotiatedAlgorithm == null)
{
return null;
}
// Create the compression capability object.
var compressionCapabilities = new Dictionary<string, object>();
compressionCapabilities.Add(XCompressionController.ALGORITHMS_SUBKEY, negotiatedAlgorithm);
compressionCapabilities.Add(XCompressionController.SERVER_COMBINE_MIXED_MESSAGES_SUBKEY, XCompressionController.DEFAULT_SERVER_COMBINE_MIXED_MESSAGES_VALUE);
// TODO: For future use.
//compressionCapabilities.Add(XCompressionController.SERVER_MAX_COMBINE_MESSAGES_SUBKEY, XCompressionController.DEFAULT_SERVER_MAX_COMBINE_MESSAGES_VALUE);
return compressionCapabilities;
}
private Dictionary<string, string> GetConnectionAttributes(string connectionAttrs)
{
Dictionary<string, string> attrs = new Dictionary<string, string>();
if (connectionAttrs.StartsWith("[") && connectionAttrs.EndsWith("]"))
{
connectionAttrs = connectionAttrs.Substring(1, connectionAttrs.Length - 2);
if (!string.IsNullOrWhiteSpace(connectionAttrs))
{
foreach (var pair in connectionAttrs.Split(','))
{
string[] keyValue = pair.Split('=');
string key = keyValue[0].Trim();
string value = keyValue.Length > 1 ? keyValue[1].Trim() : string.Empty;
if (key == string.Empty)
throw new MySqlException(ResourcesX.EmptyKeyConnectionAttribute);
if (key.StartsWith("_"))
throw new MySqlException(ResourcesX.InvalidUserDefinedAttribute);
try { attrs.Add(key, value); }
catch (ArgumentException) { throw new MySqlException(string.Format(ResourcesX.DuplicateUserDefinedAttribute, key)); }
}
}
}
else if (connectionAttrs != "true")
throw new MySqlException(ResourcesX.InvalidConnectionAttributes);
MySqlConnectAttrs clientAttrs = new MySqlConnectAttrs();
attrs.Add("_pid", clientAttrs.PID);
attrs.Add("_platform", clientAttrs.Platform);
attrs.Add("_os", clientAttrs.OSName);
attrs.Add("_source_host", Settings.Server);
attrs.Add("_client_name", clientAttrs.ClientName);
attrs.Add("_client_version", clientAttrs.ClientVersion);
attrs.Add("_client_license", clientAttrs.ClientLicence);
attrs.Add("_framework", clientAttrs.Framework);
return attrs;
}
private void AuthenticateMySQL41()
{
MySQL41AuthenticationPlugin plugin = new MySQL41AuthenticationPlugin(Settings);
_protocol.SendAuthStart(plugin.AuthName, null, null);
byte[] extraData = _protocol.ReadAuthContinue();
_protocol.SendAuthContinue(plugin.Continue(extraData));
_protocol.ReadAuthOk();
}
private void AuthenticatePlain()
{
PlainAuthenticationPlugin plugin = new PlainAuthenticationPlugin(Settings);
_protocol.SendAuthStart(plugin.AuthName, plugin.GetAuthData(), null);
_protocol.ReadAuthOk();
}
private void AuthenticateExternal()
{
ExternalAuthenticationPlugin plugin = new ExternalAuthenticationPlugin(Settings);
_protocol.SendAuthStart(plugin.AuthName, Encoding.UTF8.GetBytes(""), null);
_protocol.ReadAuthOk();
}
private void AuthenticateSha256Memory()
{
Sha256MemoryAuthenticationPlugin plugin = new Sha256MemoryAuthenticationPlugin();
_protocol.SendAuthStart(plugin.PluginName, null, null);
byte[] nonce = _protocol.ReadAuthContinue();
string data = $"{Settings.Database}\0{Settings.UserID}\0";
byte[] byteData = Encoding.UTF8.GetBytes(data);
byte[] clientHash = plugin.GetClientHash(Settings.Password, nonce);
byte[] authData = new byte[byteData.Length + clientHash.Length];
byteData.CopyTo(authData, 0);
clientHash.CopyTo(authData, byteData.Length);
_protocol.SendAuthContinue(authData);
_protocol.ReadAuthOk();
}
protected internal void SetState(SessionState newState, bool broadcast)
{
if (newState == SessionState && !broadcast)
return;
SessionState oldSessionState = SessionState;
SessionState = newState;
//TODO check if we need to send this event
//if (broadcast)
//OnStateChange(new StateChangeEventArgs(oldConnectionState, connectionState));
}
internal override ProtocolBase GetProtocol()
{
return _protocol;
}
public override void Close()
{
try
{
try
{
// Deallocate compression objects.
_readerCompressionController?.Close();
_writerCompressionController?.Close();
// Deallocate all the remaining prepared statements for current session.
foreach (int stmtId in _preparedStatements)
{
if (!_myNetworkStream.IsSocketClosed)
{
DeallocatePreparedStatement(stmtId);
}
_preparedStatements.Remove(stmtId);
}
}
catch (Exception)
{
//TODO log exception
}
if (!_myNetworkStream.IsSocketClosed)
{
_protocol.SendSessionClose();
}
}
finally
{
SessionState = SessionState.Closed;
_stream.Dispose();
}
}
public void CreateCollection(string schemaName, string collectionName)
{
ExecuteCmdNonQuery(XpluginStatementCommand.XPLUGIN_STMT_CREATE_COLLECTION,
true,
new KeyValuePair<string, object>("schema", schemaName),
new KeyValuePair<string, object>("name", collectionName));
}
/// <summary>
/// Prepare the dictionary of arguments required to create a MySQL message.
/// </summary>
/// <param name="schemaName">The name of the MySQL schema.</param>
/// <param name="collectionName">The name of the collection.</param>
/// <param name="options">This object hold the parameters required to create the collection.</param>
/// <see cref="CreateCollectionOptions"/>
/// <returns>Collection referente.</returns>
public void CreateCollection(string schemaName, string collectionName, CreateCollectionOptions options)
{
var dictionary = new Dictionary<string, object>();
if (!options.Equals(null))
{
if (!string.IsNullOrEmpty(options.Validation.Level.ToString()))
{
dictionary.Add("level", (string)options.Validation.Level.ToString().ToLowerInvariant());
}
if (!string.IsNullOrEmpty(options.Validation.Schema))
{
dictionary.Add("schema", new DbDoc(options.Validation.Schema));
}
}
ExecuteCmdNonQueryOptions(XpluginStatementCommand.XPLUGIN_STMT_CREATE_COLLECTION,
true,
new KeyValuePair<string, object>("schema", schemaName),
new KeyValuePair<string, object>("name", collectionName),
new KeyValuePair<string, object>("reuse_existing", options.ReuseExisting),
new KeyValuePair<string, object>("options", dictionary)
);
}
/// <summary>
/// Prepare the dictionary of arguments required to Modify a MySQL message.
/// </summary>
/// <param name="schemaName">The name of the MySQL schema.</param>
/// <param name="collectionName">The name of the collection.</param>
/// <param name="options">This object hold the parameters required to Modify the collection.</param>
/// <see cref="ModifyCollectionOptions"/>
public void ModifyCollection(string schemaName, string collectionName, ModifyCollectionOptions? options)
{
var dictionary = new Dictionary<string, object>();
if (!options.Equals(null))
{
if (options.Value.Validation.Level != null)
{
dictionary.Add("level", options.Value.Validation.Level.ToString().ToLowerInvariant());
}
if (options.Value.Validation.Schema != null)
{
dictionary.Add("schema", new DbDoc(options.Value.Validation.Schema));
}
}
ExecuteCmdNonQueryOptions(XpluginStatementCommand.XPLUGIN_STMT_MODIFY_COLLECTION,
true,
new KeyValuePair<string, object>("schema", schemaName),
new KeyValuePair<string, object>("name", collectionName),
new KeyValuePair<string, object>("options", dictionary));
}
public void DropCollection(string schemaName, string collectionName)
{
ExecuteCmdNonQuery(XpluginStatementCommand.XPLUGIN_STMT_DROP_COLLECTION,
true,
new KeyValuePair<string, object>("schema", schemaName),
new KeyValuePair<string, object>("name", collectionName));
}
public Result CreateCollectionIndex(CreateCollectionIndexStatement statement)
{
List<KeyValuePair<string, object>> args = new List<KeyValuePair<string, object>>();
args.Add(new KeyValuePair<string, object>("name", statement.createIndexParams.IndexName));
args.Add(new KeyValuePair<string, object>("collection", statement.Target.Name));
args.Add(new KeyValuePair<string, object>("schema", statement.Target.Schema.Name));
args.Add(new KeyValuePair<string, object>("unique", false));
if (statement.createIndexParams.Type != null)
args.Add(new KeyValuePair<string, object>("type", statement.createIndexParams.Type));
for (int i = 0; i < statement.createIndexParams.Fields.Count; i++)
{
var field = statement.createIndexParams.Fields[i];
var dictionary = new Dictionary<string, object>();
dictionary.Add("member", field.Field);
if (field.Type != null)
dictionary.Add("type", field.Type);
if (field.Required == null)
dictionary.Add("required", false);
else
dictionary.Add("required", (bool)field.Required);
if (field.Options != null)
dictionary.Add("options", (ulong)field.Options);
if (field.Srid != null)
dictionary.Add("srid", (ulong)field.Srid);
if (field.Array != null)
dictionary.Add("array", (bool)field.Array);
args.Add(new KeyValuePair<string, object>("constraint", dictionary));
}
return ExecuteCreateCollectionIndex(XpluginStatementCommand.XPLUGIN_STMT_CREATE_COLLECTION_INDEX, false, args.ToArray());
}
public void DropCollectionIndex(string schemaName, string collectionName, string indexName)
{
List<KeyValuePair<string, object>> args = new List<KeyValuePair<string, object>>();
args.Add(new KeyValuePair<string, object>("schema", schemaName));
args.Add(new KeyValuePair<string, object>("collection", collectionName));
args.Add(new KeyValuePair<string, object>("name", indexName));
ExecuteCmdNonQuery(XpluginStatementCommand.XPLUGIN_STMT_DROP_COLLECTION_INDEX, false, args.ToArray());
}
public long TableCount(Schema schema, string name, string type)
{
try
{
string sql = String.Format("SELECT COUNT(*) FROM {0}.{1}",
ExprUnparser.QuoteIdentifier(schema.Name), ExprUnparser.QuoteIdentifier(name));
return (long)ExecuteQueryAsScalar(sql);
}
catch (MySqlException ex) when (ex.Code == 1146)
{
throw new MySqlException(string.Format(ResourcesX.CollectionTableDoesNotExist, type.ToString(), name, schema.Name), (int)ex.Code);
}
}
public bool TableExists(Schema schema, string name)
{
string sql = String.Format("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '{1}'",
schema.Name, name);
long count = (long)ExecuteQueryAsScalar(sql);
return count != 0;
}
private Result ExecuteCmdNonQuery(string cmd, bool throwOnFail, params KeyValuePair<string, object>[] args)
{
_protocol.SendExecuteStatement(mysqlxNamespace, cmd, args);
return new Result(this);
}
private Result ExecuteCmdNonQueryOptions(string cmd, bool throwOnFail, params KeyValuePair<string, object>[] args)
{
_protocol.SendExecuteStatementOptions(mysqlxNamespace, cmd, args);
return new Result(this);
}
private Result ExecuteCreateCollectionIndex(string cmd, bool throwOnFail, params KeyValuePair<string, object>[] args)
{
_protocol.SendCreateCollectionIndexStatement(mysqlxNamespace, cmd, args);
return new Result(this);
}
public List<T> GetObjectList<T>(Schema s, params string[] types) where T : DatabaseObject
{
for (int i = 0; i < types.Length; i++)
types[i] = types[i].ToUpperInvariant();
RowResult result = GetRowResult("list_objects", new KeyValuePair<string, object>("schema", s.Name));
var rows = result.FetchAll();
List<T> docs = new List<T>();
foreach (var row in rows)
{
if (!types.Contains(row.GetString("type").ToUpperInvariant())) continue;
List<object> parameters = new List<object>(new object[] { s, row.GetString("name") });
if (row["name"] is Byte[])
{
Byte[] byteArray = row["name"] as Byte[];
parameters[1] = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
}
switch (row.GetString("type").ToUpperInvariant())
{
case "TABLE":
parameters.Add(false);
break;
case "VIEW":
parameters.Add(true);
break;
}
T t = (T)Activator.CreateInstance(typeof(T),
BindingFlags.NonPublic | BindingFlags.Instance,
null, parameters.ToArray(), null);
docs.Add(t);
}
return docs;
}
public string GetObjectType(Schema s, string name)
{
RowResult result = GetRowResult("list_objects",
new KeyValuePair<string, object>("schema", s.Name),
new KeyValuePair<string, object>("pattern", name));
var row = result.FetchOne();
if (row == null)
throw new MySqlException(string.Format(ResourcesX.NoObjectFound, name));
System.Diagnostics.Debug.Assert(result.FetchOne() == null);
return row.GetString("type");
}
public RowResult GetRowResult(string cmd, params KeyValuePair<string, object>[] args)
{
_protocol.SendExecuteStatement(mysqlxNamespace, cmd, args);
return new RowResult(this);
}
public Result Insert(Collection collection, DbDoc[] json, List<string> newIds, bool upsert)
{
_protocol.SendInsert(collection.Schema.Name, false, collection.Name, json, null, upsert);
return new Result(this);
}
public Result DeleteDocs(RemoveStatement rs)
{
_protocol.SendDelete(rs.Target.Schema.Name, rs.Target.Name, false, rs.FilterData);
return new Result(this);
}
public Result DeleteRows(TableDeleteStatement statement)
{
_protocol.SendDelete(statement.Target.Schema.Name,
statement.Target.Name, true,
statement.FilterData);
return new Result(this);
}
public Result ModifyDocs(ModifyStatement ms)
{
_protocol.SendUpdate(ms.Target.Schema.Name, ms.Target.Name, false, ms.FilterData, ms.Updates);
return new Result(this);
}
public Result UpdateRows(TableUpdateStatement statement)
{
_protocol.SendUpdate(statement.Target.Schema.Name,
statement.Target.Name, true,
statement.FilterData,
statement.updates);
return new Result(this);
}
public DocResult FindDocs(FindStatement fs)
{
_protocol.SendFind(fs.Target.Schema.Name, fs.Target.Name, false, fs.FilterData, fs.findParams);
DocResult result = new DocResult(this);
return result;
}
public RowResult FindRows(TableSelectStatement ss)
{
_protocol.SendFind(ss.Target.Schema.Name, ss.Target.Name, true, ss.FilterData, ss.findParams);
return new RowResult(this);
}
public Result InsertRows(TableInsertStatement statement)
{
_protocol.SendInsert(statement.Target.Schema.Name, true, statement.Target.Name, statement.values.ToArray(), statement.fields, false);
return new Result(this);
}
protected Result ExpectOpen(Mysqlx.Expect.Open.Types.Condition.Types.Key condition, object value = null)
{
_protocol.SendExpectOpen(condition, value);
return new Result(this);
}
public Result ExpectDocidGenerated()
{
return ExpectOpen(Mysqlx.Expect.Open.Types.Condition.Types.Key.ExpectDocidGenerated);
}
public void ResetSession()
{
if (_sessionResetNoReauthentication == null)
{
try
{
if (!_myNetworkStream.IsSocketClosed)
{
ExpectOpen(Mysqlx.Expect.Open.Types.Condition.Types.Key.ExpectFieldExist, "6.1");
}
_sessionResetNoReauthentication = true;
}
catch
{
_sessionResetNoReauthentication = false;
}
}
if (!_myNetworkStream.IsSocketClosed)
{
_protocol.SendResetSession((bool)_sessionResetNoReauthentication);
_protocol.ReadOk();
}
}
public int PrepareStatement<TResult>(BaseStatement<TResult> statement)
where TResult : BaseResult
{
int stmtId = Interlocked.Increment(ref _stmtId);
switch (statement.GetType().Name)
{
case nameof(FindStatement):
FindStatement fs = statement as FindStatement;
Debug.Assert(fs != null);
_protocol.SendPrepareStatement(
(uint)stmtId,
DataAccess.PreparedStatementType.Find,
fs.Target.Schema.Name,
fs.Target.Name,
false,
fs.FilterData,
fs.findParams);
break;
case nameof(TableSelectStatement):
TableSelectStatement ss = statement as TableSelectStatement;
Debug.Assert(ss != null);
_protocol.SendPrepareStatement(
(uint)stmtId,
DataAccess.PreparedStatementType.Find,
ss.Target.Schema.Name,
ss.Target.Name,
true,
ss.FilterData,
ss.findParams);
break;
case nameof(ModifyStatement):
ModifyStatement ms = statement as ModifyStatement;
Debug.Assert(ms != null);
_protocol.SendPrepareStatement(
(uint)stmtId,
DataAccess.PreparedStatementType.Update,
ms.Target.Schema.Name,
ms.Target.Name,
false,
ms.FilterData,
null,
ms.Updates);
break;
case nameof(TableUpdateStatement):
TableUpdateStatement us = statement as TableUpdateStatement;
Debug.Assert(us != null);
_protocol.SendPrepareStatement(
(uint)stmtId,
DataAccess.PreparedStatementType.Update,
us.Target.Schema.Name,
us.Target.Name,
true,
us.FilterData,
null,
us.updates);
break;
case nameof(RemoveStatement):
RemoveStatement rs = statement as RemoveStatement;
Debug.Assert(rs != null);
_protocol.SendPrepareStatement(
(uint)stmtId,
DataAccess.PreparedStatementType.Delete,
rs.Target.Schema.Name,
rs.Target.Name,
false,
rs.FilterData,
null);
break;
case nameof(TableDeleteStatement):
TableDeleteStatement ds = statement as TableDeleteStatement;
Debug.Assert(ds != null);
_protocol.SendPrepareStatement(
(uint)stmtId,
DataAccess.PreparedStatementType.Delete,
ds.Target.Schema.Name,
ds.Target.Name,
true,
ds.FilterData,
null);
break;
case nameof(TableInsertStatement):
TableInsertStatement insert = statement as TableInsertStatement;
Debug.Assert(insert != null);
_protocol.SendPrepareStatement(
(uint)stmtId,
DataAccess.PreparedStatementType.Insert,
insert.Target.Schema.Name,
insert.Target.Name,
true,
null,
null,
null,
insert.values.ToArray(),
insert.fields,
false);
break;
case nameof(SqlStatement):
SqlStatement sqlStatement = statement as SqlStatement;
Debug.Assert(sqlStatement != null);
_protocol.SendPrepareStatement(
(uint)stmtId,
DataAccess.PreparedStatementType.SqlStatement,
null,
null,
true,
null,
null,
null,
sqlStatement.parameters.ToArray(),
null,
false,
sqlStatement.SQL);
break;
default:
throw new NotSupportedException(statement.GetType().Name);