forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlDataReader.cs
More file actions
1763 lines (1588 loc) · 65.7 KB
/
NpgsqlDataReader.cs
File metadata and controls
1763 lines (1588 loc) · 65.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Npgsql.NpgsqlDataReader.cs
//
// Author:
// Francisco Jr. (fxjrlists@yahoo.com.br)
//
// Copyright (C) 2002 The Npgsql Development Team
// npgsql-general@gborg.postgresql.org
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Reflection;
using System.Threading;
using NpgsqlTypes;
namespace Npgsql
{
/// <summary>
/// Provides a means of reading a forward-only stream of rows from a PostgreSQL backend. This class cannot be inherited.
/// </summary>
public abstract class NpgsqlDataReader : DbDataReader
{
//NpgsqlDataReader is abstract because the desired implementation depends upon whether the user
//is using the backwards-compatibility option of preloading the entire reader (configurable from the
//connection string).
//Everything that can be done here is, but where the implementation must be different between the
//two modi operandi, that code will differ between the two implementations, ForwardsOnlyDataReader
//and CachingDataReader.
//Since the concrete classes are internal and returned to the user through an NpgsqlDataReader reference,
//the differences between the two is hidden from the user. Because CachingDataReader is a less efficient
//class supplied only to resolve some backwards-compatibility issues that are possible with some code, all
//internal use uses ForwardsOnlyDataReader directly.
internal NpgsqlConnector _connector;
internal NpgsqlConnection _connection;
internal DataTable _currentResultsetSchema;
internal CommandBehavior _behavior;
internal NpgsqlCommand _command;
internal Version Npgsql205 = new Version("2.0.5");
internal NpgsqlDataReader(NpgsqlCommand command, CommandBehavior behavior)
{
_behavior = behavior;
_connection = (_command = command).Connection;
_connector = command.Connector;
}
internal bool _isClosed = false;
/// <summary>
/// Is raised whenever Close() is called.
/// </summary>
public event EventHandler ReaderClosed;
internal abstract long? LastInsertedOID { get; }
internal bool TryGetTypeInfo(int fieldIndex, out NpgsqlBackendTypeInfo backendTypeInfo)
{
if (CurrentDescription == null)
{
throw new IndexOutOfRangeException(); //Essentially, all indices are out of range.
}
return (backendTypeInfo = CurrentDescription[fieldIndex].TypeInfo) != null;
}
internal abstract void CheckHaveRow();
internal abstract NpgsqlRowDescription CurrentDescription { get; }
/// <summary>
/// Return the data type name of the column at index <param name="Index"></param>.
/// </summary>
public override String GetDataTypeName(Int32 Index)
{
NpgsqlBackendTypeInfo TI;
return TryGetTypeInfo(Index, out TI) ? TI.Name : GetDataTypeOID(Index);
}
/// <summary>
/// Return the data type of the column at index <param name="Index"></param>.
/// </summary>
public override Type GetFieldType(Int32 Index)
{
NpgsqlBackendTypeInfo TI;
return TryGetTypeInfo(Index, out TI) ? TI.FrameworkType : typeof (string); //Default type is string.
}
/// <summary>
/// Return the Npgsql specific data type of the column at requested ordinal.
/// </summary>
/// <param name="ordinal">column position</param>
/// <returns>Appropriate Npgsql type for column.</returns>
public override Type GetProviderSpecificFieldType(int ordinal)
{
NpgsqlBackendTypeInfo TI;
return TryGetTypeInfo(ordinal, out TI) ? TI.Type : typeof(string); //Default type is string.
}
/// <summary>
/// Gets the number of columns in the current row.
/// </summary>
public override Int32 FieldCount
{
get {
if (_connector.CompatVersion <= Npgsql205)
return CurrentDescription == null ? -1 : CurrentDescription.NumFields;
else
// We read msdn documentation and bug report #1010649 that the common return value is 0.
return CurrentDescription == null ? 0 : CurrentDescription.NumFields;
}
}
/// <summary>
/// Return the column name of the column at index <param name="Index"></param>.
/// </summary>
public override String GetName(Int32 Index)
{
if (CurrentDescription == null)
{
throw new IndexOutOfRangeException(); //Essentially, all indices are out of range.
}
return CurrentDescription[Index].Name;
}
/// <summary>
/// Return the data type OID of the column at index <param name="Index"></param>.
/// </summary>
/// FIXME: Why this method returns String?
public String GetDataTypeOID(Int32 Index)
{
if (CurrentDescription == null)
{
throw new IndexOutOfRangeException(); //Essentially, all indices are out of range.
}
return CurrentDescription[Index].TypeOID.ToString();
}
/// <summary>
/// Gets the value of a column in its native format.
/// </summary>
public override Object this[Int32 i]
{
get { return GetValue(i); }
}
/// <summary>
/// Has ordinal.
/// </summary>
/// <param name="fieldName"></param>
/// <returns></returns>
public bool HasOrdinal(string fieldName)
{
if(CurrentDescription == null)
throw new InvalidOperationException("Invalid attempt to read when no data is present.");
return CurrentDescription.HasOrdinal(fieldName);
}
/// <summary>
/// Return the column name of the column named <param name="Name"></param>.
/// </summary>
public override Int32 GetOrdinal(String Name)
{
if (CurrentDescription == null)
throw new InvalidOperationException("Invalid attempt to read when no data is present.");
return CurrentDescription.FieldIndex(Name);
}
/// <summary>
/// Gets the value of a column in its native format.
/// </summary>
public override Object this[String name]
{
get
{
return GetValue(GetOrdinal(name));
}
}
/// <summary>
/// Return the data DbType of the column at index <param name="Index"></param>.
/// </summary>
public DbType GetFieldDbType(Int32 Index)
{
NpgsqlBackendTypeInfo TI;
return TryGetTypeInfo(Index, out TI) ? TI.DbType : DbType.String;
}
/// <summary>
/// Return the data NpgsqlDbType of the column at index <param name="Index"></param>.
/// </summary>
public NpgsqlDbType GetFieldNpgsqlDbType(Int32 Index)
{
NpgsqlBackendTypeInfo TI;
return TryGetTypeInfo(Index, out TI) ? TI.NpgsqlDbType : NpgsqlDbType.Text;
}
/// <summary>
/// Get specified field value.
/// /// </summary>
/// <param name="i"></param>
/// <returns></returns>
public BitString GetBitString(int i)
{
object ret = GetValue(i);
if(ret is bool)
return new BitString((bool)ret);
else
return (BitString)ret;
}
/// <summary>
/// Get the value of a column as a <see cref="NpgsqlInterval"/>.
/// <remarks>If the differences between <see cref="NpgsqlInterval"/> and <see cref="System.TimeSpan"/>
/// in handling of days and months is not important to your application, use <see cref="GetTimeSpan(Int32)"/>
/// instead.</remarks>
/// </summary>
/// <param name="i">Index of the field to find.</param>
/// <returns><see cref="NpgsqlInterval"/> value of the field.</returns>
public NpgsqlInterval GetInterval(Int32 i)
{
return (NpgsqlInterval)GetProviderSpecificValue(i);
}
/// <summary>
/// Get specified field value.
/// /// </summary>
/// <param name="i"></param>
/// <returns></returns>
public NpgsqlTime GetTime(int i)
{
return (NpgsqlTime)GetProviderSpecificValue(i);
}
/// <summary>
/// Get specified field value.
/// /// </summary>
/// <param name="i"></param>
/// <returns></returns>
public NpgsqlTimeTZ GetTimeTZ(int i)
{
return (NpgsqlTimeTZ)GetProviderSpecificValue(i);
}
/// <summary>
/// Get specified field value.
/// /// </summary>
/// <param name="i"></param>
/// <returns></returns>
public NpgsqlTimeStamp GetTimeStamp(int i)
{
return (NpgsqlTimeStamp)GetProviderSpecificValue(i);
}
/// <summary>
/// Get specified field value.
/// /// </summary>
/// <param name="i"></param>
/// <returns></returns>
public NpgsqlTimeStampTZ GetTimeStampTZ(int i)
{
return (NpgsqlTimeStampTZ)GetProviderSpecificValue(i);
}
/// <summary>
/// Get specified field value.
/// /// </summary>
/// <param name="i"></param>
/// <returns></returns>
public NpgsqlDate GetDate(int i)
{
return (NpgsqlDate)GetProviderSpecificValue(i);
}
/// <summary>
/// Send closed event.
/// </summary>
protected void SendClosedEvent()
{
if (this.ReaderClosed != null)
{
this.ReaderClosed(this, EventArgs.Empty);
}
}
/// <summary>
/// Gets the value of a column converted to a Guid.
/// </summary>
public override Guid GetGuid(Int32 i)
{
return (Guid) GetValue(i);
}
/// <summary>
/// Gets the value of a column as Int16.
/// </summary>
public override Int16 GetInt16(Int32 i)
{
return (Int16) GetValue(i);
}
/// <summary>
/// Gets the value of a column as Int32.
/// </summary>
public override Int32 GetInt32(Int32 i)
{
return (Int32) GetValue(i);
}
/// <summary>
/// Gets the value of a column as Int64.
/// </summary>
public override Int64 GetInt64(Int32 i)
{
return (Int64) GetValue(i);
}
/// <summary>
/// Gets the value of a column as Single.
/// </summary>
public override Single GetFloat(Int32 i)
{
return (Single) GetValue(i);
}
/// <summary>
/// Gets the value of a column as Double.
/// </summary>
public override Double GetDouble(Int32 i)
{
return (Double) GetValue(i);
}
/// <summary>
/// Gets the value of a column as String.
/// </summary>
public override String GetString(Int32 i)
{
return (String) GetValue(i);
}
/// <summary>
/// Gets the value of a column as Decimal.
/// </summary>
public override Decimal GetDecimal(Int32 i)
{
return (Decimal) GetValue(i);
}
/// <summary>
/// Gets the value of a column as TimeSpan.
/// </summary>
public TimeSpan GetTimeSpan(Int32 i)
{
return (TimeSpan) GetValue(i);
}
/// <summary>
/// Gets a value indicating the depth of nesting for the current row. Always returns zero.
/// </summary>
public override Int32 Depth
{
get { return 0; }
}
/// <summary>
/// Gets a value indicating whether the data reader is closed.
/// </summary>
public override Boolean IsClosed
{
get { return _isClosed; }
}
/// <summary>
/// Copy values from each column in the current row into <paramref name="values"/>.
/// </summary>
/// <param name="values">Destination for column values.</param>
/// <returns>The number of column values copied.</returns>
public override Int32 GetValues(Object[] values)
{
return LoadValues(values, GetValue);
}
/// <summary>
/// Copy values from each column in the current row into <paramref name="values"></paramref>.
/// </summary>
/// <param name="values">An array appropriately sized to store values from all columns.</param>
/// <returns>The number of column values copied.</returns>
public override int GetProviderSpecificValues(object[] values)
{
return LoadValues(values, GetProviderSpecificValue);
}
private delegate object ValueLoader(int ordinal);
private int LoadValues(object[] values, ValueLoader getValue)
{
CheckHaveRow();
// Only the number of elements in the array are filled.
// It's also possible to pass an array with more that FieldCount elements.
Int32 maxColumnIndex = (values.Length < FieldCount) ? values.Length : FieldCount;
for (Int32 i = 0; i < maxColumnIndex; i++)
{
values[i] = getValue(i);
}
return maxColumnIndex;
}
/// <summary>
/// Gets the value of a column as Boolean.
/// </summary>
public override Boolean GetBoolean(Int32 i)
{
// Should this be done using the GetValue directly and not by converting to String
// and parsing from there?
return (Boolean) GetValue(i);
}
/// <summary>
/// Gets the value of a column as Byte. Not implemented.
/// </summary>
public override Byte GetByte(Int32 i)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the value of a column as Char.
/// </summary>
public override Char GetChar(Int32 i)
{
//This is an interesting one. In the world of databases we've the idea of chars which is 0 to n characters
//where n is stated (and can perhaps be infinite) and various variations upon that (postgres is admirable
//in being relatively consistent and in not generally encouraging limiting n purely for performance reasons,
//but across many different platforms we'll find such things as text, ntext, char, nchar, varchar, nvarchar,
//and so on with some platforms not having them all and many implementaiton differences).
//
//In the world of .NET, and many other languages, we have the idea of characters and of strings - which are
//sequences of characters with differing degress of encapsulation from C just having char* through to .NET
//having full-blown objects
//
//Database char, varchar, text, etc. are all generally mapped to strings. There's a bit of a question as to
//what maps to a .NET char. Interestingly enough, SQLDataReader doesn't support GetChar() and neither do
//a few other providers (Oracle for example). It would seem that IDataReader.GetChar() was defined largely
//to have a complete set of .NET base types. Still, the closets thing in the database world to a char value
//is a char(1) or varchar(1) - that is to say the value of a string of length one, so that's what is used here.
string s = GetString(i);
if (s.Length != 1)
{
throw new InvalidCastException();
}
return s[0];
}
/// <summary>
/// Gets the value of a column as DateTime.
/// </summary>
public override DateTime GetDateTime(Int32 i)
{
return (DateTime) GetValue(i);
}
/// <summary>
/// Returns a System.Data.DataTable that describes the column metadata of the DataReader.
/// </summary>
public override DataTable GetSchemaTable()
{
return _currentResultsetSchema = _currentResultsetSchema ?? GetResultsetSchema();
}
private DataTable GetResultsetSchema()
{
DataTable result = null;
if (CurrentDescription.NumFields > 0)
{
result = new DataTable("SchemaTable");
result.Columns.Add("ColumnName", typeof (string));
result.Columns.Add("ColumnOrdinal", typeof (int));
result.Columns.Add("ColumnSize", typeof (int));
result.Columns.Add("NumericPrecision", typeof (int));
result.Columns.Add("NumericScale", typeof (int));
result.Columns.Add("IsUnique", typeof (bool));
result.Columns.Add("IsKey", typeof (bool));
result.Columns.Add("BaseCatalogName", typeof (string));
result.Columns.Add("BaseColumnName", typeof (string));
result.Columns.Add("BaseSchemaName", typeof (string));
result.Columns.Add("BaseTableName", typeof (string));
result.Columns.Add("DataType", typeof (Type));
result.Columns.Add("AllowDBNull", typeof (bool));
result.Columns.Add("ProviderType", typeof (string));
result.Columns.Add("IsAliased", typeof (bool));
result.Columns.Add("IsExpression", typeof (bool));
result.Columns.Add("IsIdentity", typeof (bool));
result.Columns.Add("IsAutoIncrement", typeof (bool));
result.Columns.Add("IsRowVersion", typeof (bool));
result.Columns.Add("IsHidden", typeof (bool));
result.Columns.Add("IsLong", typeof (bool));
result.Columns.Add("IsReadOnly", typeof (bool));
if (_connector.BackendProtocolVersion == ProtocolVersion.Version2)
{
FillSchemaTable_v2(result);
}
else if (_connector.BackendProtocolVersion == ProtocolVersion.Version3)
{
FillSchemaTable_v3(result);
}
}
return result;
}
private void FillSchemaTable_v2(DataTable schema)
{
List<string> keyList = (_behavior & CommandBehavior.KeyInfo) == CommandBehavior.KeyInfo
? new List<string>(GetPrimaryKeys(GetTableNameFromQuery()))
: new List<string>();
for (Int16 i = 0; i < CurrentDescription.NumFields; i++)
{
DataRow row = schema.NewRow();
row["ColumnName"] = GetName(i);
row["ColumnOrdinal"] = i + 1;
if (CurrentDescription[i].TypeModifier != -1 && CurrentDescription[i].TypeInfo != null &&
(CurrentDescription[i].TypeInfo.Name == "varchar" || CurrentDescription[i].TypeInfo.Name == "bpchar"))
{
row["ColumnSize"] = CurrentDescription[i].TypeModifier - 4;
}
else if (CurrentDescription[i].TypeModifier != -1 && CurrentDescription[i].TypeInfo != null &&
(CurrentDescription[i].TypeInfo.Name == "bit" || CurrentDescription[i].TypeInfo.Name == "varbit"))
{
row["ColumnSize"] = CurrentDescription[i].TypeModifier;
}
else
{
row["ColumnSize"] = (int) CurrentDescription[i].TypeSize;
}
if (CurrentDescription[i].TypeModifier != -1 && CurrentDescription[i].TypeInfo != null &&
CurrentDescription[i].TypeInfo.Name == "numeric")
{
row["NumericPrecision"] = ((CurrentDescription[i].TypeModifier - 4) >> 16) & ushort.MaxValue;
row["NumericScale"] = (CurrentDescription[i].TypeModifier - 4) & ushort.MaxValue;
}
else
{
row["NumericPrecision"] = 0;
row["NumericScale"] = 0;
}
row["IsUnique"] = false;
row["IsKey"] = IsKey(GetName(i), keyList);
row["BaseCatalogName"] = "";
row["BaseSchemaName"] = "";
row["BaseTableName"] = "";
row["BaseColumnName"] = GetName(i);
row["DataType"] = GetFieldType(i);
row["AllowDBNull"] = true;
// without other information, must allow dbnull on the client
if (CurrentDescription[i].TypeInfo != null)
{
row["ProviderType"] = CurrentDescription[i].TypeInfo.Name;
}
row["IsAliased"] = false;
row["IsExpression"] = false;
row["IsIdentity"] = false;
row["IsAutoIncrement"] = false;
row["IsRowVersion"] = false;
row["IsHidden"] = false;
row["IsLong"] = false;
row["IsReadOnly"] = false;
schema.Rows.Add(row);
}
}
private void FillSchemaTable_v3(DataTable schema)
{
Dictionary<long, Table> oidTableLookup = new Dictionary<long, Table>();
KeyLookup keyLookup = new KeyLookup();
// needs to be null because there is a difference
// between an empty dictionary and not setting it
// the default values will be different
Dictionary<string, Column> columnLookup = null;
if ((_behavior & CommandBehavior.KeyInfo) == CommandBehavior.KeyInfo)
{
List<int> tableOids = new List<int>();
for (int i = 0; i != CurrentDescription.NumFields; ++i)
{
if (CurrentDescription[i].TableOID != 0 && !tableOids.Contains(CurrentDescription[i].TableOID))
{
tableOids.Add(CurrentDescription[i].TableOID);
}
}
oidTableLookup = GetTablesFromOids(tableOids);
if (oidTableLookup.Count == 1)
{
// only 1, but we can't index into the Dictionary
foreach (int key in oidTableLookup.Keys)
{
keyLookup = GetKeys(key);
}
}
columnLookup = GetColumns();
}
for (Int16 i = 0; i < CurrentDescription.NumFields; i++)
{
DataRow row = schema.NewRow();
string baseColumnName = GetBaseColumnName(columnLookup, i);
row["ColumnName"] = GetName(i);
row["ColumnOrdinal"] = i + 1;
if (CurrentDescription[i].TypeModifier != -1 && CurrentDescription[i].TypeInfo != null &&
(CurrentDescription[i].TypeInfo.Name == "varchar" || CurrentDescription[i].TypeInfo.Name == "bpchar"))
{
row["ColumnSize"] = CurrentDescription[i].TypeModifier - 4;
}
else if (CurrentDescription[i].TypeModifier != -1 && CurrentDescription[i].TypeInfo != null &&
(CurrentDescription[i].TypeInfo.Name == "bit" || CurrentDescription[i].TypeInfo.Name == "varbit"))
{
row["ColumnSize"] = CurrentDescription[i].TypeModifier;
}
else
{
row["ColumnSize"] = (int) CurrentDescription[i].TypeSize;
}
if (CurrentDescription[i].TypeModifier != -1 && CurrentDescription[i].TypeInfo != null &&
CurrentDescription[i].TypeInfo.Name == "numeric")
{
row["NumericPrecision"] = ((CurrentDescription[i].TypeModifier - 4) >> 16) & ushort.MaxValue;
row["NumericScale"] = (CurrentDescription[i].TypeModifier - 4) & ushort.MaxValue;
}
else
{
row["NumericPrecision"] = 0;
row["NumericScale"] = 0;
}
row["IsUnique"] = IsUnique(keyLookup, baseColumnName);
row["IsKey"] = IsKey(keyLookup, baseColumnName);
if (CurrentDescription[i].TableOID != 0 && oidTableLookup.ContainsKey(CurrentDescription[i].TableOID))
{
row["BaseCatalogName"] = oidTableLookup[CurrentDescription[i].TableOID].Catalog;
row["BaseSchemaName"] = oidTableLookup[CurrentDescription[i].TableOID].Schema;
row["BaseTableName"] = oidTableLookup[CurrentDescription[i].TableOID].Name;
}
else
{
row["BaseCatalogName"] = row["BaseSchemaName"] = row["BaseTableName"] = "";
}
row["BaseColumnName"] = baseColumnName;
row["DataType"] = GetFieldType(i);
row["AllowDBNull"] = IsNullable(columnLookup, i);
if (CurrentDescription[i].TypeInfo != null)
{
row["ProviderType"] = CurrentDescription[i].TypeInfo.Name;
}
row["IsAliased"] = string.CompareOrdinal((string) row["ColumnName"], baseColumnName) != 0;
row["IsExpression"] = false;
row["IsIdentity"] = false;
row["IsAutoIncrement"] = IsAutoIncrement(columnLookup, i);
row["IsRowVersion"] = false;
row["IsHidden"] = false;
row["IsLong"] = false;
row["IsReadOnly"] = false;
schema.Rows.Add(row);
}
}
private static Boolean IsKey(String ColumnName, IEnumerable<string> ListOfKeys)
{
foreach (String s in ListOfKeys)
{
if (s == ColumnName)
{
return true;
}
}
return false;
}
private IEnumerable<string> GetPrimaryKeys(String tablename)
{
if (string.IsNullOrEmpty(tablename))
{
yield break;
}
String getPKColumns =
"select a.attname from pg_catalog.pg_class ct, pg_catalog.pg_class ci, pg_catalog.pg_attribute a, pg_catalog.pg_index i WHERE ct.oid=i.indrelid AND ci.oid=i.indexrelid AND a.attrelid=ci.oid AND i.indisprimary AND ct.relname = :tablename";
using (NpgsqlConnection metadataConn = _connection.Clone())
{
using (NpgsqlCommand c = new NpgsqlCommand(getPKColumns, metadataConn))
{
c.Parameters.Add(new NpgsqlParameter("tablename", NpgsqlDbType.Text));
c.Parameters["tablename"].Value = tablename;
using (NpgsqlDataReader dr = c.GetReader(CommandBehavior.SingleResult | CommandBehavior.SequentialAccess))
{
while (dr.Read())
{
yield return dr.GetString(0);
}
}
}
}
}
private static bool IsKey(KeyLookup keyLookup, string fieldName)
{
return keyLookup.primaryKey.Contains(fieldName);
}
private static bool IsUnique(KeyLookup keyLookup, string fieldName)
{
return keyLookup.uniqueColumns.Contains(fieldName);
}
private class KeyLookup
{
/// <summary>
/// Contains the column names as the keys
/// </summary>
public readonly List<string> primaryKey = new List<string>();
/// <summary>
/// Contains all unique columns
/// </summary>
public readonly List<string> uniqueColumns = new List<string>();
}
private KeyLookup GetKeys(Int32 tableOid)
{
string getKeys =
"select a.attname, ci.relname, i.indisprimary from pg_catalog.pg_class ct, pg_catalog.pg_class ci, pg_catalog.pg_attribute a, pg_catalog.pg_index i WHERE ct.oid=i.indrelid AND ci.oid=i.indexrelid AND a.attrelid=ci.oid AND i.indisunique AND ct.oid = :tableOid order by ci.relname";
KeyLookup lookup = new KeyLookup();
using (NpgsqlConnection metadataConn = _connection.Clone())
{
NpgsqlCommand c = new NpgsqlCommand(getKeys, metadataConn);
c.Parameters.Add(new NpgsqlParameter("tableOid", NpgsqlDbType.Integer)).Value = tableOid;
using (NpgsqlDataReader dr = c.GetReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
{
string previousKeyName = null;
string possiblyUniqueColumn = null;
string columnName;
string currentKeyName;
// loop through adding any column that is primary to the primary key list
// add any column that is the only column for that key to the unique list
// unique here doesn't mean general unique constraint (with possibly multiple columns)
// it means all values in this single column must be unique
while (dr.Read())
{
columnName = dr.GetString(0);
currentKeyName = dr.GetString(1);
// if i.indisprimary
if (dr.GetBoolean(2))
{
// add column name as part of the primary key
lookup.primaryKey.Add(columnName);
}
if (currentKeyName != previousKeyName)
{
if (possiblyUniqueColumn != null)
{
lookup.uniqueColumns.Add(possiblyUniqueColumn);
}
possiblyUniqueColumn = columnName;
}
else
{
possiblyUniqueColumn = null;
}
previousKeyName = currentKeyName;
}
// if finished reading and have a possiblyUniqueColumn name that is
// not null, then it is the name of a unique column
if (possiblyUniqueColumn != null)
{
lookup.uniqueColumns.Add(possiblyUniqueColumn);
}
return lookup;
}
}
}
private Boolean IsNullable(Dictionary<string, Column> columnLookup, Int32 FieldIndex)
{
if (columnLookup == null || CurrentDescription[FieldIndex].TableOID == 0)
{
return true;
}
string lookupKey = string.Format("{0},{1}", CurrentDescription[FieldIndex].TableOID, CurrentDescription[FieldIndex].ColumnAttributeNumber);
Column col = null;
return columnLookup.TryGetValue(lookupKey, out col) ? !col.NotNull : true;
}
private string GetBaseColumnName(Dictionary<string, Column> columnLookup, Int32 FieldIndex)
{
if (columnLookup == null || CurrentDescription[FieldIndex].TableOID == 0)
{
return GetName(FieldIndex);
}
string lookupKey = string.Format("{0},{1}", CurrentDescription[FieldIndex].TableOID, CurrentDescription[FieldIndex].ColumnAttributeNumber);
Column col = null;
return columnLookup.TryGetValue(lookupKey, out col) ? col.Name : GetName(FieldIndex);
}
private bool IsAutoIncrement(Dictionary<string, Column> columnLookup, Int32 FieldIndex)
{
if (columnLookup == null || CurrentDescription[FieldIndex].TableOID == 0)
{
return false;
}
string lookupKey = string.Format("{0},{1}", CurrentDescription[FieldIndex].TableOID, CurrentDescription[FieldIndex].ColumnAttributeNumber);
Column col = null;
return
columnLookup.TryGetValue(lookupKey, out col)
? col.ColumnDefault is string && col.ColumnDefault.ToString().StartsWith("nextval(")
: true;
}
///<summary>
/// This methods parses the command text and tries to get the tablename
/// from it.
///</summary>
private String GetTableNameFromQuery()
{
Int32 fromClauseIndex = _command.CommandText.ToLowerInvariant().IndexOf("from");
String tableName = _command.CommandText.Substring(fromClauseIndex + 4).Trim();
if (string.IsNullOrEmpty(tableName))// == String.Empty)
{
return String.Empty;
}
/*if (tableName.EndsWith("."));
return String.Empty;
*/
foreach (Char c in tableName.Substring(0, tableName.Length - 1))
{
if (!Char.IsLetterOrDigit(c) && c != '_' && c != '.')
{
return String.Empty;
}
}
return tableName;
}
private struct Table
{
public readonly string Catalog;
public readonly string Schema;
public readonly string Name;
public readonly int Id;
public Table(IDataReader rdr)
{
Catalog = rdr.GetString(0);
Schema = rdr.GetString(1);
Name = rdr.GetString(2);
Id = rdr.GetInt32(3);
}
}
private Dictionary<long, Table> GetTablesFromOids(List<int> oids)
{
if (oids.Count == 0)
{
return new Dictionary<long, Table>(); //Empty collection is simpler than requiring tests for null;
}
// the column index is used to find data.
// any changes to the order of the columns needs to be reflected in struct Tables
StringBuilder sb =
new StringBuilder(
"SELECT current_database(), nc.nspname, c.relname, c.oid FROM pg_namespace nc, pg_class c WHERE c.relnamespace = nc.oid AND (c.relkind = 'r' OR c.relkind = 'v') AND c.oid IN (");
bool first = true;
foreach (int oid in oids)
{
if (!first)
{
sb.Append(',');
}
sb.Append(oid);
first = false;
}
sb.Append(')');
using (NpgsqlConnection connection = _connection.Clone())
{
using (NpgsqlCommand command = new NpgsqlCommand(sb.ToString(), connection))
{
using (NpgsqlDataReader reader = command.GetReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult)
)
{
Dictionary<long, Table> oidLookup = new Dictionary<long, Table>(oids.Count);
int columnCount = reader.FieldCount;
while (reader.Read())
{
Table t = new Table(reader);
oidLookup.Add(t.Id, t);
}
return oidLookup;
}
}
}
}
private class Column
{
public readonly string Name;
public readonly bool NotNull;
public readonly int TableId;
public readonly short ColumnNum;
public readonly object ColumnDefault;
public string Key
{
get { return string.Format("{0},{1}", TableId, ColumnNum); }
}
public Column(IDataReader rdr)
{
Name = rdr.GetString(0);
NotNull = rdr.GetBoolean(1);
TableId = rdr.GetInt32(2);
ColumnNum = rdr.GetInt16(3);
ColumnDefault = rdr.GetValue(4);
}
}
private Dictionary<string, Column> GetColumns()
{
StringBuilder sb = new StringBuilder();
// the column index is used to find data.
// any changes to the order of the columns needs to be reflected in struct Columns
sb.Append(
"SELECT a.attname AS column_name, a.attnotnull AS column_notnull, a.attrelid AS table_id, a.attnum AS column_num, d.adsrc as column_default");
sb.Append(
" FROM pg_attribute a LEFT OUTER JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum WHERE a.attnum > 0 AND (");
bool first = true;
for (int i = 0; i < CurrentDescription.NumFields; ++i)
{
if (CurrentDescription[i].TableOID != 0)
{
if (!first)
{
sb.Append(" OR ");
}
sb.AppendFormat("(a.attrelid={0} AND a.attnum={1})", CurrentDescription[i].TableOID,
CurrentDescription[i].ColumnAttributeNumber);
first = false;
}
}
sb.Append(')');
// if the loop ended without setting first to false, then there will be no results from the query
if (first)