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
use crate::conn::AmConnCore;
use crate::hdb_response::InternalReturnValue;
use crate::protocol::parts::{
HdbValue, LobFlags, ParameterDescriptors, ParameterRows, ResultSetMetadata, TypeId,
};
use crate::protocol::{
Part, PartKind, Request, RequestType, ServerUsage, HOLD_CURSORS_OVER_COMMIT,
};
use crate::types_impl::lob::LobWriter;
use crate::{HdbError, HdbResponse, HdbResult};
use std::io::Write;
use std::sync::{Arc, Mutex};
#[derive(Debug)]
pub struct PreparedStatement {
am_ps_core: Arc<Mutex<PreparedStatementCore>>,
server_usage: ServerUsage,
a_descriptors: Arc<ParameterDescriptors>,
o_a_rsmd: Option<Arc<ResultSetMetadata>>,
batch: ParameterRows<'static>,
_o_table_location: Option<Vec<i32>>,
}
pub(crate) type AmPsCore = Arc<Mutex<PreparedStatementCore>>;
#[derive(Debug)]
pub(crate) struct PreparedStatementCore {
am_conn_core: AmConnCore,
statement_id: u64,
}
impl<'a> PreparedStatement {
pub fn execute<T: serde::ser::Serialize>(&mut self, input: &T) -> HdbResult<HdbResponse> {
trace!("PreparedStatement::execute()");
if self.a_descriptors.has_in() {
let mut par_rows = ParameterRows::new();
par_rows.push(input, &self.a_descriptors)?;
return self.execute_parameter_rows(Some(par_rows));
}
self.execute_parameter_rows(None)
}
pub fn execute_row(&'a mut self, hdb_values: Vec<HdbValue<'a>>) -> HdbResult<HdbResponse> {
if self.a_descriptors.has_in() {
let mut ps_core_guard = self.am_ps_core.lock()?;
let mut request = Request::new(RequestType::Execute, HOLD_CURSORS_OVER_COMMIT);
request.push(Part::StatementId(ps_core_guard.statement_id));
let mut readers: Vec<(HdbValue, TypeId)> = vec![];
let hdb_values = hdb_values
.into_iter()
.zip(self.a_descriptors.iter_in())
.map(|(v, d)| {
if let HdbValue::LOBSTREAM(Some(_)) = v {
readers.push((v, d.type_id()));
HdbValue::LOBSTREAM(None)
} else {
v
}
})
.collect();
let mut par_rows = ParameterRows::new();
par_rows.push_hdb_values(hdb_values, &self.a_descriptors)?;
request.push(Part::Parameters(par_rows));
if ps_core_guard
.am_conn_core
.lock()?
.connect_options()
.get_implicit_lob_streaming()
.unwrap_or(false)
{
request.push(Part::LobFlags(LobFlags::for_implicit_streaming()));
}
let mut main_reply = ps_core_guard.am_conn_core.full_send_sync(
request,
self.o_a_rsmd.as_ref(),
Some(&self.a_descriptors),
&mut None,
)?;
let write_lob_reply = main_reply
.parts
.remove_first_of_kind(PartKind::WriteLobReply);
let (mut internal_return_values, replytype) = (
main_reply
.parts
.into_internal_return_values(&mut ps_core_guard.am_conn_core, None)?,
main_reply.replytype,
);
if let Some(Part::WriteLobReply(wlr)) = write_lob_reply {
let locator_ids = wlr.into_locator_ids();
if locator_ids.len() != readers.len() {
return Err(HdbError::UsageDetailed(format!(
"The number of provided readers ({}) does not match \
the number of required readers ({})",
readers.len(),
locator_ids.len()
)));
}
for (locator_id, (reader, type_id)) in locator_ids.into_iter().zip(readers) {
debug!("writing content to locator with id {:?}", locator_id);
if let HdbValue::LOBSTREAM(Some(reader)) = reader {
let mut reader = reader.lock()?;
let mut writer = LobWriter::new(
locator_id,
type_id,
ps_core_guard.am_conn_core.clone(),
self.o_a_rsmd.as_ref(),
Some(&self.a_descriptors),
)?;
std::io::copy(&mut *reader, &mut writer).map_err(HdbError::LobStreaming)?;
writer.flush().map_err(HdbError::LobStreaming)?;
if let Some(mut irvs) = writer.into_internal_return_values() {
internal_return_values.append(&mut irvs);
}
}
}
}
for rv in &mut internal_return_values {
if let InternalReturnValue::ResultSet(rs) = rv {
rs.inject_statement_id(Arc::clone(&self.am_ps_core))?;
}
}
HdbResponse::try_new(internal_return_values, replytype)
} else {
self.execute_parameter_rows(None)
}
}
pub fn add_batch<T: serde::ser::Serialize>(&mut self, input: &T) -> HdbResult<()> {
trace!("PreparedStatement::add_batch()");
if self.a_descriptors.has_in() {
self.batch.push(input, &self.a_descriptors)?;
return Ok(());
}
Err(HdbError::Usage(
"Batch not usable for PreparedStatements without input parameter",
))
}
pub fn add_row_to_batch(&mut self, hdb_values: Vec<HdbValue<'static>>) -> HdbResult<()> {
trace!("PreparedStatement::add_row_to_batch()");
if self.a_descriptors.has_in() {
self.batch
.push_hdb_values(hdb_values, &self.a_descriptors)?;
return Ok(());
}
Err(HdbError::Usage(
"Batch not possible, PreparedStatement has no input parameter",
))
}
pub fn execute_batch(&mut self) -> HdbResult<HdbResponse> {
if self.batch.is_empty() && self.a_descriptors.has_in() {
return Err(HdbError::Usage("Empty batch cannot be executed"));
}
let mut rows2 = ParameterRows::new();
std::mem::swap(&mut self.batch, &mut rows2);
self.execute_parameter_rows(Some(rows2))
}
pub fn parameter_descriptors(&self) -> Arc<ParameterDescriptors> {
Arc::clone(&self.a_descriptors)
}
fn execute_parameter_rows(&mut self, o_rows: Option<ParameterRows>) -> HdbResult<HdbResponse> {
trace!("PreparedStatement::execute_parameter_rows()");
let mut ps_core_guard = self.am_ps_core.lock()?;
let mut request = Request::new(RequestType::Execute, HOLD_CURSORS_OVER_COMMIT);
request.push(Part::StatementId(ps_core_guard.statement_id));
if let Some(rows) = o_rows {
request.push(Part::Parameters(rows));
}
let (mut internal_return_values, replytype) = ps_core_guard
.am_conn_core
.full_send_sync(
request,
self.o_a_rsmd.as_ref(),
Some(&self.a_descriptors),
&mut None,
)?
.into_internal_return_values(&mut ps_core_guard.am_conn_core, None)?;
for rv in &mut internal_return_values {
if let InternalReturnValue::ResultSet(rs) = rv {
rs.inject_statement_id(Arc::clone(&self.am_ps_core))?;
}
}
HdbResponse::try_new(internal_return_values, replytype)
}
pub fn server_usage(&self) -> ServerUsage {
self.server_usage
}
pub(crate) fn try_new(mut am_conn_core: AmConnCore, stmt: &str) -> HdbResult<Self> {
let mut request = Request::new(RequestType::Prepare, HOLD_CURSORS_OVER_COMMIT);
request.push(Part::Command(stmt));
let reply = am_conn_core.send_sync(request)?;
let mut o_table_location: Option<Vec<i32>> = None;
let mut o_stmt_id: Option<u64> = None;
let mut a_descriptors: Arc<ParameterDescriptors> = Arc::new(ParameterDescriptors::new());
let mut o_a_rsmd: Option<Arc<ResultSetMetadata>> = None;
let mut server_usage = ServerUsage::default();
for part in reply.parts.into_iter() {
match part {
Part::ParameterMetadata(descriptors) => {
a_descriptors = Arc::new(descriptors);
}
Part::StatementId(id) => {
o_stmt_id = Some(id);
}
Part::TransactionFlags(ta_flags) => {
let mut guard = am_conn_core.lock()?;
(*guard).evaluate_ta_flags(ta_flags)?;
}
Part::TableLocation(vec_i) => {
o_table_location = Some(vec_i);
}
Part::ResultSetMetadata(rs_md) => {
o_a_rsmd = Some(Arc::new(rs_md));
}
Part::StatementContext(ref stmt_ctx) => {
let mut guard = am_conn_core.lock()?;
(*guard).evaluate_statement_context(stmt_ctx)?;
server_usage.update(
stmt_ctx.server_processing_time(),
stmt_ctx.server_cpu_time(),
stmt_ctx.server_memory_usage(),
);
}
x => warn!("try_new(): Unexpected reply part found {:?}", x),
}
}
let statement_id = o_stmt_id.ok_or_else(|| HdbError::Impl("No StatementId received"))?;
let am_ps_core = Arc::new(Mutex::new(PreparedStatementCore {
am_conn_core,
statement_id,
}));
debug!(
"PreparedStatement created with parameter descriptors = {:?}",
a_descriptors
);
Ok(Self {
am_ps_core,
server_usage,
batch: ParameterRows::new(),
a_descriptors,
o_a_rsmd,
_o_table_location: o_table_location,
})
}
}
impl Drop for PreparedStatementCore {
fn drop(&mut self) {
let mut request = Request::new(RequestType::DropStatementId, 0);
request.push(Part::StatementId(self.statement_id));
if let Ok(mut reply) = self.am_conn_core.send_sync(request) {
reply.parts.pop_if_kind(PartKind::StatementContext);
}
}
}