forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextHandler.cs
More file actions
executable file
·368 lines (320 loc) · 13.5 KB
/
TextHandler.cs
File metadata and controls
executable file
·368 lines (320 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#region License
// The PostgreSQL License
//
// Copyright (C) 2015 The Npgsql Development Team
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text;
using Npgsql.BackendMessages;
using NpgsqlTypes;
using System.Data;
using JetBrains.Annotations;
namespace Npgsql.TypeHandlers
{
[TypeMapping("text", NpgsqlDbType.Text,
new[] { DbType.String, DbType.StringFixedLength, DbType.AnsiString, DbType.AnsiStringFixedLength },
new[] { typeof(string), typeof(char[]), typeof(char) },
DbType.String
)]
[TypeMapping("xml", NpgsqlDbType.Xml, dbType: DbType.Xml)]
[TypeMapping("varchar", NpgsqlDbType.Varchar, inferredDbType: DbType.String)]
[TypeMapping("bpchar", NpgsqlDbType.Char, inferredDbType: DbType.String)]
[TypeMapping("name", NpgsqlDbType.Name, inferredDbType: DbType.String)]
[TypeMapping("json", NpgsqlDbType.Json, inferredDbType: DbType.String)]
[TypeMapping("refcursor", NpgsqlDbType.Refcursor, inferredDbType: DbType.String)]
[TypeMapping("citext", NpgsqlDbType.Citext, inferredDbType: DbType.String)]
[TypeMapping("unknown")]
internal class TextHandler : ChunkingTypeHandler<string>, IChunkingTypeHandler<char[]>
{
internal override bool PreferTextWrite => true;
#region State
string _str;
char[] _chars;
byte[] _tempBuf;
int _byteLen, _charLen, _bytePos, _charPos;
NpgsqlBuffer _buf;
readonly char[] _singleCharArray = new char[1];
#endregion
#region Read
internal virtual void PrepareRead(NpgsqlBuffer buf, FieldDescription fieldDescription, int len)
{
_buf = buf;
_byteLen = len;
_bytePos = -1;
}
public override void PrepareRead(NpgsqlBuffer buf, int len, FieldDescription fieldDescription)
{
PrepareRead(buf, fieldDescription, len);
}
public override bool Read([CanBeNull] out string result)
{
if (_bytePos == -1)
{
if (_byteLen <= _buf.ReadBytesLeft)
{
// Already have the entire string in the buffer, decode and return
result = _buf.ReadString(_byteLen);
_buf = null;
return true;
}
if (_byteLen <= _buf.UsableSize) {
// Don't have the entire string in the buffer, but it can fit. Force a read to fill.
result = null;
return false;
}
// Bad case: the string doesn't fit in our buffer.
// Allocate a temporary byte buffer to hold the entire string and read it in chunks.
// TODO: Pool/recycle the buffer?
_tempBuf = new byte[_byteLen];
_bytePos = 0;
}
var len = Math.Min(_buf.ReadBytesLeft, _byteLen - _bytePos);
_buf.ReadBytes(_tempBuf, _bytePos, len);
_bytePos += len;
if (_bytePos < _byteLen)
{
result = null;
return false;
}
result = _buf.TextEncoding.GetString(_tempBuf);
_tempBuf = null;
_buf = null;
return true;
}
public bool Read([CanBeNull] out char[] result)
{
if (_bytePos == -1)
{
if (_byteLen <= _buf.ReadBytesLeft)
{
// Already have the entire string in the buffer, decode and return
result = _buf.ReadChars(_byteLen);
_buf = null;
return true;
}
if (_byteLen <= _buf.UsableSize)
{
// Don't have the entire string in the buffer, but it can fit. Force a read to fill.
result = null;
return false;
}
// Bad case: the string doesn't fit in our buffer.
// Allocate a temporary byte buffer to hold the entire string and read it in chunks.
// TODO: Pool/recycle the buffer?
_tempBuf = new byte[_byteLen];
_bytePos = 0;
}
var len = Math.Min(_buf.ReadBytesLeft, _byteLen - _bytePos);
_buf.ReadBytes(_tempBuf, _bytePos, len);
_bytePos += len;
if (_bytePos < _byteLen) {
result = null;
return false;
}
result = _buf.TextEncoding.GetChars(_tempBuf);
_tempBuf = null;
_buf = null;
return true;
}
public long GetChars(DataRowMessage row, int charOffset, [CanBeNull] char[] output, int outputOffset, int charsCount, FieldDescription field)
{
if (row.PosInColumn == 0) {
_charPos = 0;
}
if (output == null)
{
// Note: Getting the length of a text column means decoding the entire field,
// very inefficient and also consumes the column in sequential mode. But this seems to
// be SqlClient's behavior as well.
int bytesSkipped, charsSkipped;
row.Buffer.SkipChars(int.MaxValue, row.ColumnLen - row.PosInColumn, out bytesSkipped, out charsSkipped);
Contract.Assume(bytesSkipped == row.ColumnLen - row.PosInColumn);
row.PosInColumn += bytesSkipped;
_charPos += charsSkipped;
return _charPos;
}
if (charOffset < _charPos) {
row.SeekInColumn(0);
_charPos = 0;
}
if (charOffset > _charPos)
{
var charsToSkip = charOffset - _charPos;
int bytesSkipped, charsSkipped;
row.Buffer.SkipChars(charsToSkip, row.ColumnLen - row.PosInColumn, out bytesSkipped, out charsSkipped);
row.PosInColumn += bytesSkipped;
_charPos += charsSkipped;
if (charsSkipped < charsToSkip) {
// TODO: What is the actual required behavior here?
throw new IndexOutOfRangeException();
}
}
int bytesRead, charsRead;
row.Buffer.ReadAllChars(output, outputOffset, charsCount, row.ColumnLen - row.PosInColumn, out bytesRead, out charsRead);
row.PosInColumn += bytesRead;
_charPos += charsRead;
return charsRead;
}
#endregion
#region Write
public override int ValidateAndGetLength(object value, ref LengthCache lengthCache, NpgsqlParameter parameter = null)
{
if (lengthCache == null) {
lengthCache = new LengthCache(1);
}
if (lengthCache.IsPopulated) {
return lengthCache.Get();
}
//return lengthCache.Set(DoValidateAndGetLength(value, parameter));
var asString = value as string;
if (asString != null)
{
return lengthCache.Set(
parameter == null || parameter.Size <= 0 || parameter.Size >= asString.Length
? PGUtil.UTF8Encoding.GetByteCount(asString)
: PGUtil.UTF8Encoding.GetByteCount(asString.ToCharArray(), 0, parameter.Size)
);
}
var asCharArray = value as char[];
if (asCharArray != null)
{
return lengthCache.Set(
parameter == null || parameter.Size <= 0 || parameter.Size >= asCharArray.Length
? PGUtil.UTF8Encoding.GetByteCount(asCharArray)
: PGUtil.UTF8Encoding.GetByteCount(asCharArray, 0, parameter.Size)
);
}
if (value is char)
{
_singleCharArray[0] = (char)value;
return lengthCache.Set(PGUtil.UTF8Encoding.GetByteCount(_singleCharArray));
}
// Fallback - try to convert the value to string
var converted = Convert.ToString(value);
if (parameter == null)
{
throw CreateConversionButNoParamException(value.GetType());
}
parameter.ConvertedValue = converted;
return lengthCache.Set(
parameter.Size <= 0 || parameter.Size >= converted.Length
? PGUtil.UTF8Encoding.GetByteCount(converted)
: PGUtil.UTF8Encoding.GetByteCount(converted.ToCharArray(), 0, parameter.Size)
);
}
public override void PrepareWrite(object value, NpgsqlBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter=null)
{
_buf = buf;
_charPos = -1;
_byteLen = lengthCache.GetLast();
if (parameter?.ConvertedValue != null) {
value = parameter.ConvertedValue;
}
_str = value as string;
if (_str != null)
{
_charLen = parameter == null || parameter.Size <= 0 || parameter.Size >= _str.Length ? _str.Length : parameter.Size;
return;
}
_chars = value as char[];
if (_chars != null)
{
_charLen = parameter == null || parameter.Size <= 0 || parameter.Size >= _chars.Length ? _chars.Length : parameter.Size;
return;
}
if (value is char)
{
_singleCharArray[0] = (char)value;
_chars = _singleCharArray;
_charLen = 1;
return;
}
_str = Convert.ToString(value);
_charLen = parameter == null || parameter.Size <= 0 || parameter.Size >= _str.Length ? _str.Length : parameter.Size;
}
public override bool Write(ref DirectBuffer directBuf)
{
if (_charPos == -1)
{
if (_byteLen <= _buf.WriteSpaceLeft)
{
// Can simply write the string to the buffer
if (_str != null)
{
_buf.WriteString(_str, _charLen);
_str = null;
}
else
{
Contract.Assert(_chars != null);
_buf.WriteChars(_chars, _charLen);
_str = null;
}
_buf = null;
return true;
}
if (_byteLen <= _buf.UsableSize)
{
// Buffer is currently too full, but the string can fit. Force a write to fill.
return false;
}
// Bad case: the string doesn't fit in our buffer.
_charPos = 0;
// For strings, chunked/incremental conversion isn't supported
// (see https://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/6584398-add-system-text-encoder-convert-method-string-in)
// So for now allocate a temporary byte buffer to hold the entire string and write it directly.
if (_str != null)
{
directBuf.Buffer = new byte[_byteLen];
_buf.TextEncoding.GetBytes(_str, 0, _charLen, directBuf.Buffer, 0);
return false;
}
Contract.Assert(_chars != null);
// For char arrays, fall through to chunked writing below
}
if (_str != null)
{
// We did a direct buffer write above, and must now clean up
_str = null;
_buf = null;
return true;
}
int charsUsed;
bool completed;
_buf.WriteStringChunked(_chars, _charPos, _chars.Length - _charPos, false, out charsUsed, out completed);
if (completed)
{
// Flush encoder
_buf.WriteStringChunked(_chars, _charPos, _chars.Length - _charPos, true, out charsUsed, out completed);
_chars = null;
_buf = null;
return true;
}
_charPos += charsUsed;
return false;
}
#endregion
}
}