forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlConnector.FrontendMessages.cs
More file actions
456 lines (367 loc) · 18 KB
/
NpgsqlConnector.FrontendMessages.cs
File metadata and controls
456 lines (367 loc) · 18 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Npgsql.Util;
// ReSharper disable VariableHidesOuterVariable
namespace Npgsql
{
partial class NpgsqlConnector
{
internal Task WriteDescribe(StatementOrPortal statementOrPortal, string name, bool async)
{
Debug.Assert(name.All(c => c < 128));
var len = sizeof(byte) + // Message code
sizeof(int) + // Length
sizeof(byte) + // Statement or portal
(name.Length + 1); // Statement/portal name
if (WriteBuffer.WriteSpaceLeft < len)
return FlushAndWrite(len, statementOrPortal, name, async);
Write(len, statementOrPortal, name);
return Task.CompletedTask;
async Task FlushAndWrite(int len, StatementOrPortal statementOrPortal, string name, bool async)
{
await Flush(async);
Debug.Assert(len <= WriteBuffer.WriteSpaceLeft, $"Message of type {GetType().Name} has length {len} which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
Write(len, statementOrPortal, name);
}
void Write(int len, StatementOrPortal statementOrPortal, string name)
{
WriteBuffer.WriteByte(FrontendMessageCode.Describe);
WriteBuffer.WriteInt32(len - 1);
WriteBuffer.WriteByte((byte)statementOrPortal);
WriteBuffer.WriteNullTerminatedString(name);
}
}
internal Task WriteSync(bool async)
{
const int len = sizeof(byte) + // Message code
sizeof(int); // Length
if (WriteBuffer.WriteSpaceLeft < len)
return FlushAndWrite(async);
Write();
return Task.CompletedTask;
async Task FlushAndWrite(bool async)
{
await Flush(async);
Debug.Assert(len <= WriteBuffer.WriteSpaceLeft, $"Message of type {GetType().Name} has length {len} which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
Write();
}
void Write()
{
WriteBuffer.WriteByte(FrontendMessageCode.Sync);
WriteBuffer.WriteInt32(len - 1);
}
}
internal Task WriteExecute(int maxRows, bool async)
{
// Note: non-empty portal currently not supported
const int len = sizeof(byte) + // Message code
sizeof(int) + // Length
sizeof(byte) + // Null-terminated portal name (always empty for now)
sizeof(int); // Max number of rows
if (WriteBuffer.WriteSpaceLeft < len)
return FlushAndWrite(maxRows, async);
Write(maxRows);
return Task.CompletedTask;
async Task FlushAndWrite(int maxRows, bool async)
{
await Flush(async);
Debug.Assert(10 <= WriteBuffer.WriteSpaceLeft, $"Message of type {GetType().Name} has length 10 which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
Write(maxRows);
}
void Write(int maxRows)
{
WriteBuffer.WriteByte(FrontendMessageCode.Execute);
WriteBuffer.WriteInt32(len - 1);
WriteBuffer.WriteByte(0); // Portal is always empty for now
WriteBuffer.WriteInt32(maxRows);
}
}
internal async Task WriteParse(string sql, string statementName, List<NpgsqlParameter> inputParameters, bool async)
{
Debug.Assert(statementName.All(c => c < 128));
var queryByteLen = TextEncoding.GetByteCount(sql);
if (WriteBuffer.WriteSpaceLeft < 1 + 4 + statementName.Length + 1)
await Flush(async);
var messageLength =
sizeof(byte) + // Message code
sizeof(int) + // Length
statementName.Length + // Statement name
sizeof(byte) + // Null terminator for the statement name
queryByteLen + sizeof(byte) + // SQL query length plus null terminator
sizeof(short) + // Number of parameters
inputParameters.Count * sizeof(int); // Parameter OIDs
WriteBuffer.WriteByte(FrontendMessageCode.Parse);
WriteBuffer.WriteInt32(messageLength - 1);
WriteBuffer.WriteNullTerminatedString(statementName);
await WriteBuffer.WriteString(sql, queryByteLen, async);
if (WriteBuffer.WriteSpaceLeft < 1 + 2)
await Flush(async);
WriteBuffer.WriteByte(0); // Null terminator for the query
WriteBuffer.WriteInt16((short)inputParameters.Count);
foreach (var p in inputParameters)
{
if (WriteBuffer.WriteSpaceLeft < 4)
await Flush(async);
WriteBuffer.WriteInt32((int)p.Handler!.PostgresType.OID);
}
}
internal async Task WriteBind(
List<NpgsqlParameter> inputParameters,
string portal,
string statement,
bool allResultTypesAreUnknown,
bool[]? unknownResultTypeList,
bool async)
{
Debug.Assert(statement.All(c => c < 128));
Debug.Assert(portal.All(c => c < 128));
var headerLength =
sizeof(byte) + // Message code
sizeof(int) + // Message length
sizeof(byte) + // Portal is always empty (only a null terminator)
statement.Length + sizeof(byte) + // Statement name plus null terminator
sizeof(short); // Number of parameter format codes that follow
if (WriteBuffer.WriteSpaceLeft < headerLength)
{
Debug.Assert(WriteBuffer.Size >= headerLength, "Write buffer too small for Bind header");
await Flush(async);
}
var formatCodesSum = 0;
var paramsLength = 0;
foreach (var p in inputParameters)
{
formatCodesSum += (int)p.FormatCode;
p.LengthCache?.Rewind();
paramsLength += p.ValidateAndGetLength();
}
var formatCodeListLength = formatCodesSum == 0 ? 0 : formatCodesSum == inputParameters.Count ? 1 : inputParameters.Count;
var messageLength = headerLength +
sizeof(short) * formatCodeListLength + // List of format codes
sizeof(short) + // Number of parameters
sizeof(int) * inputParameters.Count + // Parameter lengths
paramsLength + // Parameter values
sizeof(short) + // Number of result format codes
sizeof(short) * (unknownResultTypeList?.Length ?? 1); // Result format codes
WriteBuffer.WriteByte(FrontendMessageCode.Bind);
WriteBuffer.WriteInt32(messageLength - 1);
Debug.Assert(portal == string.Empty);
WriteBuffer.WriteByte(0); // Portal is always empty
WriteBuffer.WriteNullTerminatedString(statement);
WriteBuffer.WriteInt16(formatCodeListLength);
// 0 length implicitly means all-text, 1 means all-binary, >1 means mix-and-match
if (formatCodeListLength == 1)
{
if (WriteBuffer.WriteSpaceLeft < 2)
await Flush(async);
WriteBuffer.WriteInt16((short)FormatCode.Binary);
}
else if (formatCodeListLength > 1)
{
foreach (var p in inputParameters)
{
if (WriteBuffer.WriteSpaceLeft < 2)
await Flush(async);
WriteBuffer.WriteInt16((short)p.FormatCode);
}
}
if (WriteBuffer.WriteSpaceLeft < 2)
await Flush(async);
WriteBuffer.WriteInt16(inputParameters.Count);
foreach (var param in inputParameters)
{
param.LengthCache?.Rewind();
await param.WriteWithLength(WriteBuffer, async);
}
if (unknownResultTypeList != null)
{
if (WriteBuffer.WriteSpaceLeft < 2 + unknownResultTypeList.Length * 2)
await Flush(async);
WriteBuffer.WriteInt16(unknownResultTypeList.Length);
foreach (var t in unknownResultTypeList)
WriteBuffer.WriteInt16(t ? 0 : 1);
}
else
{
if (WriteBuffer.WriteSpaceLeft < 4)
await Flush(async);
WriteBuffer.WriteInt16(1);
WriteBuffer.WriteInt16(allResultTypesAreUnknown ? 0 : 1);
}
}
internal Task WriteClose(StatementOrPortal type, string name, bool async)
{
var len = sizeof(byte) + // Message code
sizeof(int) + // Length
sizeof(byte) + // Statement or portal
name.Length + sizeof(byte); // Statement or portal name plus null terminator
if (WriteBuffer.WriteSpaceLeft < 10)
return FlushAndWrite(len, type, name, async);
Write(len, type, name);
return Task.CompletedTask;
async Task FlushAndWrite(int len, StatementOrPortal type, string name, bool async)
{
await Flush(async);
Debug.Assert(len <= WriteBuffer.WriteSpaceLeft, $"Message of type {GetType().Name} has length {len} which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
Write(len, type, name);
}
void Write(int len, StatementOrPortal type, string name)
{
WriteBuffer.WriteByte(FrontendMessageCode.Close);
WriteBuffer.WriteInt32(len - 1);
WriteBuffer.WriteByte((byte)type);
WriteBuffer.WriteNullTerminatedString(name);
}
}
internal void WriteQuery(string sql) => WriteQuery(sql, false).GetAwaiter().GetResult();
internal async Task WriteQuery(string sql, bool async)
{
var queryByteLen = TextEncoding.GetByteCount(sql);
if (WriteBuffer.WriteSpaceLeft < 1 + 4)
await Flush(async);
WriteBuffer.WriteByte(FrontendMessageCode.Query);
WriteBuffer.WriteInt32(
sizeof(int) + // Message length (including self excluding code)
queryByteLen + // Query byte length
sizeof(byte)); // Null terminator
await WriteBuffer.WriteString(sql, queryByteLen, async);
if (WriteBuffer.WriteSpaceLeft < 1)
await Flush(async);
WriteBuffer.WriteByte(0); // Null terminator
}
internal void WriteCopyDone() => WriteCopyDone(false).GetAwaiter().GetResult();
internal async Task WriteCopyDone(bool async)
{
const int len = sizeof(byte) + // Message code
sizeof(int); // Length
if (WriteBuffer.WriteSpaceLeft < len)
await Flush(async);
WriteBuffer.WriteByte(FrontendMessageCode.CopyDone);
WriteBuffer.WriteInt32(len - 1);
}
internal async Task WriteCopyFail(bool async)
{
// Note: error message not supported for now
const int len = sizeof(byte) + // Message code
sizeof(int) + // Length
sizeof(byte); // Error message is always empty (only a null terminator)
if (WriteBuffer.WriteSpaceLeft < len)
await Flush(async);
WriteBuffer.WriteByte(FrontendMessageCode.CopyFail);
WriteBuffer.WriteInt32(len - 1);
WriteBuffer.WriteByte(0); // Error message is always empty (only a null terminator)
}
internal void WriteCancelRequest(int backendProcessId, int backendSecretKey)
{
const int len = sizeof(int) + // Length
sizeof(int) + // Cancel request code
sizeof(int) + // Backend process id
sizeof(int); // Backend secret key
Debug.Assert(backendProcessId != 0);
if (WriteBuffer.WriteSpaceLeft < len)
Flush(false).GetAwaiter().GetResult();
WriteBuffer.WriteInt32(len);
WriteBuffer.WriteInt32(1234 << 16 | 5678);
WriteBuffer.WriteInt32(backendProcessId);
WriteBuffer.WriteInt32(backendSecretKey);
}
internal void WriteTerminate()
{
const int len = sizeof(byte) + // Message code
sizeof(int); // Length
if (WriteBuffer.WriteSpaceLeft < len)
Flush(false).GetAwaiter().GetResult();
WriteBuffer.WriteByte(FrontendMessageCode.Terminate);
WriteBuffer.WriteInt32(len - 1);
}
internal void WriteSslRequest()
{
const int len = sizeof(int) + // Length
sizeof(int); // SSL request code
if (WriteBuffer.WriteSpaceLeft < len)
Flush(false).GetAwaiter().GetResult();
WriteBuffer.WriteInt32(len);
WriteBuffer.WriteInt32(80877103);
}
internal void WriteStartup(Dictionary<string, string> parameters)
{
const int protocolVersion3 = 3 << 16; // 196608
var len = sizeof(int) + // Length
sizeof(int) + // Protocol version
sizeof(byte); // Trailing zero byte
foreach (var kvp in parameters)
len += PGUtil.UTF8Encoding.GetByteCount(kvp.Key) + 1 +
PGUtil.UTF8Encoding.GetByteCount(kvp.Value) + 1;
// Should really never happen, just in case
if (len > WriteBuffer.Size)
throw new Exception("Startup message bigger than buffer");
WriteBuffer.WriteInt32(len);
WriteBuffer.WriteInt32(protocolVersion3);
foreach (var kv in parameters)
{
WriteBuffer.WriteString(kv.Key);
WriteBuffer.WriteByte(0);
WriteBuffer.WriteString(kv.Value);
WriteBuffer.WriteByte(0);
}
WriteBuffer.WriteByte(0);
}
#region Authentication
internal Task WritePassword(byte[] payload, bool async) => WritePassword(payload, 0, payload.Length, async);
internal async Task WritePassword(byte[] payload, int offset, int count, bool async)
{
if (WriteBuffer.WriteSpaceLeft < sizeof(byte) + sizeof(int))
await WriteBuffer.Flush(async);
WriteBuffer.WriteByte(FrontendMessageCode.Password);
WriteBuffer.WriteInt32(sizeof(int) + count);
if (count <= WriteBuffer.WriteSpaceLeft)
{
// The entire array fits in our WriteBuffer, copy it into the WriteBuffer as usual.
WriteBuffer.WriteBytes(payload, offset, count);
return;
}
await WriteBuffer.Flush(async);
await WriteBuffer.DirectWrite(payload, offset, count, async);
}
internal async Task WriteSASLInitialResponse(string mechanism, byte[] initialResponse, bool async)
{
var len = sizeof(byte) + // Message code
sizeof(int) + // Length
PGUtil.UTF8Encoding.GetByteCount(mechanism) + sizeof(byte) + // Mechanism plus null terminator
sizeof(int) + // Initial response length
(initialResponse?.Length ?? 0); // Initial response payload
if (WriteBuffer.WriteSpaceLeft < len)
await WriteBuffer.Flush(async);
WriteBuffer.WriteByte(FrontendMessageCode.Password);
WriteBuffer.WriteInt32(len - 1);
WriteBuffer.WriteString(mechanism);
WriteBuffer.WriteByte(0); // null terminator
if (initialResponse == null)
WriteBuffer.WriteInt32(-1);
else
{
WriteBuffer.WriteInt32(initialResponse.Length);
WriteBuffer.WriteBytes(initialResponse);
}
}
internal Task WriteSASLResponse(byte[] payload, bool async) => WritePassword(payload, async);
#endregion Authentication
internal Task WritePregenerated(byte[] data, bool async=false)
{
if (WriteBuffer.WriteSpaceLeft < data.Length)
return FlushAndWrite(data, async);
WriteBuffer.WriteBytes(data, 0, data.Length);
return Task.CompletedTask;
async Task FlushAndWrite(byte[] data, bool async)
{
await Flush(async);
Debug.Assert(data.Length <= WriteBuffer.WriteSpaceLeft, $"Pregenerated message has length {data.Length} which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
WriteBuffer.WriteBytes(data, 0, data.Length);
}
}
internal void Flush() => WriteBuffer.Flush(false).GetAwaiter().GetResult();
internal Task Flush(bool async) => WriteBuffer.Flush(async);
}
}