forked from Emill/Npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextHandler.cs
More file actions
executable file
·331 lines (285 loc) · 11.7 KB
/
TextHandler.cs
File metadata and controls
executable file
·331 lines (285 loc) · 11.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
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;
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("unknown")]
internal class TextHandler : TypeHandler<string>,
IChunkingTypeWriter,
IChunkingTypeReader<string>, IChunkingTypeReader<char[]>
{
public override bool PreferTextWrite { get { return true; } }
#region State
string _str;
char[] _chars;
byte[] _tempBuf;
int _byteLen, _charLen, _bytePos, _charPos;
NpgsqlBuffer _buf;
char[] _singleCharArray = new char[1];
#endregion
#region Read
internal virtual void PrepareRead(NpgsqlBuffer buf, FieldDescription fieldDescription, int len)
{
_buf = buf;
_byteLen = len;
_bytePos = -1;
}
void IChunkingTypeReader<string>.PrepareRead(NpgsqlBuffer buf, int len, FieldDescription fieldDescription)
{
PrepareRead(buf, fieldDescription, len);
}
void IChunkingTypeReader<char[]>.PrepareRead(NpgsqlBuffer buf, int len, FieldDescription fieldDescription)
{
PrepareRead(buf, fieldDescription, len);
}
public bool Read(out string result)
{
if (_bytePos == -1)
{
if (_byteLen <= _buf.ReadBytesLeft)
{
// Already have the entire string in the buffer, decode and return
result = _buf.ReadStringSimple(_byteLen);
_buf = null;
return true;
}
if (_byteLen <= _buf.Size) {
// 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.ReadBytesSimple(_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(out char[] result)
{
if (_bytePos == -1)
{
if (_byteLen <= _buf.ReadBytesLeft)
{
// Already have the entire string in the buffer, decode and return
result = _buf.ReadCharsSimple(_byteLen);
_buf = null;
return true;
}
if (_byteLen <= _buf.Size)
{
// 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.ReadBytesSimple(_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, 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.ReadChars(output, outputOffset, charsCount, row.ColumnLen - row.PosInColumn, out bytesRead, out charsRead);
row.PosInColumn += bytesRead;
_charPos += charsRead;
return charsRead;
}
#endregion
#region Write
public 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));
}
/// <summary>
/// Validates and calculates the length, but does not consult the length cache or stores
/// in it. Used by other type handlers which delegate to TextHandler.
/// </summary>
internal int DoValidateAndGetLength(object value, NpgsqlParameter parameter = null)
{
var asString = value as string;
if (asString != null) {
return 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 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 PGUtil.UTF8Encoding.GetByteCount(_singleCharArray);
}
throw new InvalidCastException("Can't write type as text: " + value.GetType());
}
public void PrepareWrite(object value, NpgsqlBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter=null)
{
_buf = buf;
_charPos = -1;
_byteLen = lengthCache.GetLast();
_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;
}
throw PGUtil.ThrowIfReached();
}
public bool Write(ref DirectBuffer directBuf)
{
if (_charPos == -1)
{
if (_byteLen <= _buf.WriteSpaceLeft)
{
// Can simply write the string to the buffer
if (_str != null)
{
_buf.WriteStringSimple(_str, _charLen);
_str = null;
}
else
{
Contract.Assert(_chars != null);
_buf.WriteCharsSimple(_chars, _charLen);
_str = null;
}
_buf = null;
return true;
}
if (_byteLen <= _buf.Size)
{
// 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, 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
}
}