-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBasicCliClient.roc
More file actions
459 lines (371 loc) Β· 11.9 KB
/
Copy pathBasicCliClient.roc
File metadata and controls
459 lines (371 loc) Β· 11.9 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
## Unfortunately, the regular `Pg.Client` module runs into the
## infamous "Error during alias analysis" compiler bug when used from basic-cli.
## This version does not.
module [
connect,
command,
batch,
prepare,
Error,
errorToStr,
Client,
]
import Protocol.Backend
import Protocol.Frontend
import Bytes.Encode
import Bytes.Decode exposing [decode]
import Pg.Result exposing [CmdResult]
import Pg.Cmd exposing [Cmd]
import Pg.Batch exposing [Batch]
import pf.Tcp
import Cmd
import Batch
Client := {
stream : Tcp.Stream,
backendKey : Result Protocol.Backend.KeyData [Pending],
}
connect :
{
host : Str,
port : U16,
user : Str,
auth ? [None, Password Str],
database : Str,
}
-> Task Client _
connect = \{ host, port, database, auth ? None, user } ->
stream = Tcp.connect! host port
Tcp.write! stream (Protocol.Frontend.startup { user, database })
msg, state <- messageLoop stream {
parameters: Dict.empty {},
backendKey: Err Pending,
}
when msg is
AuthOk ->
next state
AuthCleartextPassword ->
when auth is
None ->
Task.err PasswordRequired
Password pwd ->
Tcp.write! stream (Protocol.Frontend.passwordMessage pwd)
next state
AuthUnsupported ->
Task.err UnsupportedAuth
BackendKeyData backendKey ->
next { state & backendKey: Ok backendKey }
ReadyForQuery _ ->
client = @Client {
stream,
backendKey: state.backendKey,
}
return client
_ ->
unexpected msg
# Single command
command : Cmd a err,
Client
-> Task
a
[
PgExpectErr err,
PgErr Error,
PgProtoErr _,
TcpReadErr _,
TcpUnexpectedEOF,
TcpWriteErr _,
]
command = \cmd, @Client { stream } ->
{ kind, limit, bindings } = Cmd.params cmd
{ formatCodes, paramValues } = Cmd.encodeBindings bindings
init =
when kind is
SqlCmd sql ->
{
messages: Bytes.Encode.sequence [
Protocol.Frontend.parse { sql },
Protocol.Frontend.bind { formatCodes, paramValues },
Protocol.Frontend.describePortal {},
Protocol.Frontend.execute { limit },
],
fields: [],
}
PreparedCmd prepared ->
{
messages: Bytes.Encode.sequence [
Protocol.Frontend.bind {
formatCodes,
paramValues,
preparedStatement: prepared.name,
},
Protocol.Frontend.execute { limit },
],
fields: prepared.fields,
}
sendWithSync! stream init.messages
result = readCmdResult! init.fields stream
decoded =
Cmd.decode result cmd
|> Result.mapErr PgExpectErr
|> Task.fromResult!
readReadyForQuery! stream
Task.ok decoded
# Batches
batch : Batch a err,
Client
-> Task
a
[
PgExpectErr err,
PgErr Error,
PgProtoErr _,
TcpReadErr _,
TcpUnexpectedEOF,
TcpWriteErr _,
]
batch = \cmdBatch, @Client { stream } ->
{ commands, seenSql, decode: batchDecode } = Batch.params cmdBatch
reusedIndexes =
seenSql
|> Dict.walk (Set.empty {}) \set, _, { index, reused } ->
if reused then
set |> Set.insert index
else
set
inits =
commands
|> List.mapWithIndex (\cmd, ix -> initBatchedCmd reusedIndexes cmd ix)
commandMessages =
inits
|> List.map .messages
|> Bytes.Encode.sequence
closeMessages =
reusedIndexes
|> Set.toList
|> List.map \ix ->
Protocol.Frontend.closeStatement { name: Batch.reuseName ix }
|> Bytes.Encode.sequence
messages = commandMessages |> List.concat closeMessages
sendWithSync! stream messages
Task.loop
{
remaining: inits,
results: List.withCapacity (List.len commands),
}
(\state -> batchReadStep batchDecode stream state)
initBatchedCmd : Set U64,
Batch.BatchedCmd,
U64
-> {
messages : List U8,
fields : [
Describe,
ReuseFrom U64,
Known (List Pg.Result.RowField),
],
}
initBatchedCmd = \reusedIndexes, cmd, cmdIndex ->
{ formatCodes, paramValues } = Cmd.encodeBindings cmd.bindings
when cmd.kind is
SqlCmd sql ->
name =
if Set.contains reusedIndexes cmdIndex then
Batch.reuseName cmdIndex
else
""
{
messages: Bytes.Encode.sequence [
Protocol.Frontend.parse { sql, name },
Protocol.Frontend.bind {
formatCodes,
paramValues,
preparedStatement: name,
},
Protocol.Frontend.describePortal {},
Protocol.Frontend.execute { limit: cmd.limit },
],
fields: Describe,
}
ReuseSql index ->
{
messages: Bytes.Encode.sequence [
Protocol.Frontend.bind {
formatCodes,
paramValues,
preparedStatement: Batch.reuseName index,
},
Protocol.Frontend.execute { limit: cmd.limit },
],
fields: ReuseFrom index,
}
PreparedCmd prepared ->
{
messages: Bytes.Encode.sequence [
Protocol.Frontend.bind {
formatCodes,
paramValues,
preparedStatement: prepared.name,
},
Protocol.Frontend.execute { limit: cmd.limit },
],
fields: Known prepared.fields,
}
batchReadStep = \batchDecode, stream, { remaining, results } ->
when remaining is
[] ->
when batchDecode results is
Ok { value } ->
readReadyForQuery! stream
return value
Err (MissingCmdResult index) ->
Task.err (PgProtoErr (MissingBatchedCmdResult index))
Err (ExpectErr err) ->
Task.err (PgExpectErr err)
[first, ..] ->
fields = batchedCmdFields! results first.fields
result = readCmdResult! fields stream
next {
remaining: remaining |> List.dropFirst 1,
results: results |> List.append result,
}
batchedCmdFields = \results, fieldsMethod ->
when fieldsMethod is
Describe ->
Task.ok []
ReuseFrom index ->
when List.get results index is
Ok result ->
Task.ok (Pg.Result.fields result)
Err OutOfBounds ->
# TODO: better name
Task.err (PgProtoErr ResultOutOfBounds)
Known fields ->
Task.ok fields
# Execute helpers
readCmdResult = \initFields, stream ->
msg, state <- messageLoop stream {
fields: initFields,
rows: [],
parameters: [],
}
when msg is
ParseComplete | BindComplete | NoData ->
next state
ParameterDescription parameters ->
next { state & parameters: parameters }
RowDescription fields ->
next { state & fields: fields }
DataRow row ->
next { state & rows: List.append state.rows row }
CommandComplete _ | EmptyQueryResponse | PortalSuspended ->
return (Pg.Result.create state)
_ ->
unexpected msg
readReadyForQuery = \stream ->
msg, {} <- messageLoop stream {}
when msg is
CloseComplete ->
next {}
ReadyForQuery _ ->
return {}
_ ->
unexpected msg
# Prepared Statements
prepare : Str,{ name : Str, client : Client }
-> Task
(Cmd CmdResult [])
[
PgErr Error,
PgProtoErr _,
TcpReadErr _,
TcpUnexpectedEOF,
TcpWriteErr _,
]
prepare = \sql, { name, client } ->
(@Client { stream }) = client
parseAndDescribe = Bytes.Encode.sequence [
Protocol.Frontend.parse { sql, name },
Protocol.Frontend.describeStatement { name },
Protocol.Frontend.sync,
]
Tcp.write! stream parseAndDescribe
msg, state <- messageLoop stream { fields: [], parameters: [] }
when msg is
ParseComplete | NoData ->
next state
ParameterDescription parameters ->
next { state & parameters: parameters }
RowDescription fields ->
next { state & fields: fields }
ReadyForQuery _ ->
return (Cmd.prepared { name, fields: state.fields, parameters: state.parameters })
_ ->
unexpected msg
# Errors
Error : Protocol.Backend.Error
errorToStr : Error -> Str
errorToStr = \err ->
addField = \str, name, result ->
when result is
Ok value ->
"$(str)\n$(name): $(value)"
Err {} ->
str
fieldsStr =
""
|> addField "Detail" err.detail
|> addField "Hint" err.hint
|> addField "Position" (err.position |> Result.map Num.toStr)
|> addField "Internal Position" (err.internalPosition |> Result.map Num.toStr)
|> addField "Internal Query" err.internalQuery
|> addField "Where" err.ewhere
|> addField "Schema" err.schemaName
|> addField "Table" err.tableName
|> addField "Data type" err.dataTypeName
|> addField "Constraint" err.constraintName
|> addField "File" err.file
|> addField "Line" err.line
|> addField "Routine" err.line
"$(err.localizedSeverity) ($(err.code)): $(err.message)\n$(fieldsStr)"
|> Str.trim
# Helpers
readMessage : Tcp.Stream -> Task Protocol.Backend.Message [PgProtoErr _, TcpReadErr _, TcpUnexpectedEOF]
readMessage = \stream ->
headerBytes = Tcp.readExactly! stream 5
protoDecode = \bytes, dec ->
decode bytes dec
|> Result.mapErr PgProtoErr
|> Task.fromResult
meta = headerBytes |> protoDecode! Protocol.Backend.header
if meta.len > 0 then
payload = Tcp.readExactly! stream (Num.toU64 meta.len)
protoDecode payload (Protocol.Backend.message meta.msgType)
else
protoDecode [] (Protocol.Backend.message meta.msgType)
messageLoop : Tcp.Stream, state, (Protocol.Backend.Message, state -> Task [Done done, Step state] _) -> Task done _
messageLoop = \stream, initState, stepFn ->
state <- Task.loop initState
message = readMessage! stream
when message is
ErrorResponse error ->
Task.err (PgErr error)
ParameterStatus _ ->
Task.ok (Step state)
_ ->
stepFn message state
next : a -> Task [Step a] *
next = \state ->
Task.ok (Step state)
return : a -> Task [Done a] *
return = \result ->
Task.ok (Done result)
unexpected : a -> Task * [PgProtoErr [UnexpectedMsg a]]
unexpected = \msg ->
Task.err (PgProtoErr (UnexpectedMsg msg))
sendWithSync : Tcp.Stream, List U8 -> Task {} _
sendWithSync = \stream, bytes ->
content = Bytes.Encode.sequence [
bytes,
Protocol.Frontend.sync,
]
Tcp.write stream content