aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/libpqxx/src/transaction_base.cxx
blob: 84a7ab7e1b165b4c0876c5ed8dc2309e33bdfe2d (plain) (blame)
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
/** Common code and definitions for the transaction classes.
 *
 * pqxx::transaction_base defines the interface for any abstract class that
 * represents a database transaction.
 *
 * Copyright (c) 2000-2019, Jeroen T. Vermeulen.
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 */
#include "pqxx/compiler-internal.hxx"

#include <cstring>
#include <stdexcept>

#include "pqxx/connection_base"
#include "pqxx/result"
#include "pqxx/transaction_base"

#include "pqxx/internal/gates/connection-transaction.hxx"
#include "pqxx/internal/gates/connection-parameterized_invocation.hxx"
#include "pqxx/internal/gates/transaction-transactionfocus.hxx"

#include "pqxx/internal/encodings.hxx"


using namespace pqxx::internal;


pqxx::internal::parameterized_invocation::parameterized_invocation(
	connection_base &c,
	const std::string &query) :
  m_home{c},
  m_query{query}
{
}


pqxx::result pqxx::internal::parameterized_invocation::exec()
{
  std::vector<const char *> values;
  std::vector<int> lengths;
  std::vector<int> binaries;
  const int elements = marshall(values, lengths, binaries);

  return gate::connection_parameterized_invocation{m_home}.parameterized_exec(
	m_query,
	values.data(),
	lengths.data(),
	binaries.data(),
	elements);
}


pqxx::transaction_base::transaction_base(connection_base &C, bool direct) :
  namedclass{"transaction_base"},
  m_conn{C}
{
  if (direct)
  {
    gate::connection_transaction gate{conn()};
    gate.register_transaction(this);
    m_registered = true;
  }
}


pqxx::transaction_base::~transaction_base()
{
  try
  {
    reactivation_avoidance_clear();
    if (not m_pending_error.empty())
      process_notice("UNPROCESSED ERROR: " + m_pending_error + "\n");

    if (m_registered)
    {
      m_conn.process_notice(description() + " was never closed properly!\n");
      gate::connection_transaction gate{conn()};
      gate.unregister_transaction(this);
    }
  }
  catch (const std::exception &e)
  {
    try
    {
      process_notice(std::string{e.what()} + "\n");
    }
    catch (const std::exception &)
    {
      process_notice(e.what());
    }
  }
}


void pqxx::transaction_base::commit()
{
  CheckPendingError();

  // Check previous status code.  Caller should only call this function if
  // we're in "implicit" state, but multiple commits are silently accepted.
  switch (m_status)
  {
  case st_nascent:	// Empty transaction.  No skin off our nose.
    return;

  case st_active:	// Just fine.  This is what we expect.
    break;

  case st_aborted:
    throw usage_error{"Attempt to commit previously aborted " + description()};

  case st_committed:
    // Transaction has been committed already.  This is not exactly proper
    // behaviour, but throwing an exception here would only give the impression
    // that an abort is needed--which would only confuse things further at this
    // stage.
    // Therefore, multiple commits are accepted, though under protest.
    m_conn.process_notice(description() + " committed more than once.\n");
    return;

  case st_in_doubt:
    // Transaction may or may not have been committed.  The only thing we can
    // really do is keep telling the caller that the transaction is in doubt.
    throw in_doubt_error{
	description() + " committed again while in an indeterminate state."};

  default:
    throw internal_error{"pqxx::transaction: invalid status code."};
  }

  // Tricky one.  If stream is nested in transaction but inside the same scope,
  // the commit() will come before the stream is closed.  Which means the
  // commit is premature.  Punish this swiftly and without fail to discourage
  // the habit from forming.
  if (m_focus.get())
    throw failure{
	"Attempt to commit " + description() + " with " +
	m_focus.get()->description() + " still open."};

  // Check that we're still connected (as far as we know--this is not an
  // absolute thing!) before trying to commit.  If the connection was broken
  // already, the commit would fail anyway but this way at least we don't remain
  // in-doubt as to whether the backend got the commit order at all.
  if (not m_conn.is_open())
    throw broken_connection{
	"Broken connection to backend; cannot complete transaction."};

  try
  {
    do_commit();
    m_status = st_committed;
  }
  catch (const in_doubt_error &)
  {
    m_status = st_in_doubt;
    throw;
  }
  catch (const std::exception &)
  {
    m_status = st_aborted;
    throw;
  }

  gate::connection_transaction gate{conn()};
  gate.add_variables(m_vars);

  End();
}


void pqxx::transaction_base::abort()
{
  // Check previous status code.  Quietly accept multiple aborts to
  // simplify emergency bailout code.
  switch (m_status)
  {
  case st_nascent:	// Never began transaction.  No need to issue rollback.
    break;

  case st_active:
    try { do_abort(); } catch (const std::exception &) { }
    break;

  case st_aborted:
    return;

  case st_committed:
    throw usage_error{"Attempt to abort previously committed " + description()};

  case st_in_doubt:
    // Aborting an in-doubt transaction is probably a reasonably sane response
    // to an insane situation.  Log it, but do not complain.
    m_conn.process_notice(
	"Warning: " + description() + " aborted after going into "
	"indeterminate state; it may have been executed anyway.\n");
    return;

  default:
    throw internal_error{"Invalid transaction status."};
  }

  m_status = st_aborted;
  End();
}


std::string pqxx::transaction_base::esc_raw(const std::string &str) const
{
  const unsigned char *p = reinterpret_cast<const unsigned char *>(str.c_str());
  return conn().esc_raw(p, str.size());
}


std::string pqxx::transaction_base::quote_raw(const std::string &str) const
{
  const unsigned char *p = reinterpret_cast<const unsigned char *>(str.c_str());
  return conn().quote_raw(p, str.size());
}


void pqxx::transaction_base::activate()
{
  switch (m_status)
  {
  case st_nascent:
    // Make sure transaction has begun before executing anything
    Begin();
    break;

  case st_active:
    break;

  case st_committed:
  case st_aborted:
  case st_in_doubt:
    throw usage_error{
	"Attempt to activate " + description() + " "
	"which is already closed."};

  default:
    throw internal_error{"pqxx::transaction: invalid status code."};
  }
}


pqxx::result pqxx::transaction_base::exec(
	const std::string &Query,
	const std::string &Desc)
{
  CheckPendingError();

  const std::string N = (Desc.empty() ? "" : "'" + Desc + "' ");

  if (m_focus.get())
    throw usage_error{
	"Attempt to execute query " + N +
	"on " + description() + " "
	"with " + m_focus.get()->description() + " still open."};

  try
  {
    activate();
  }
  catch (const usage_error &e)
  {
    throw usage_error{"Error executing query " + N + ".  " + e.what()};
  }

  // TODO: Pass Desc to do_exec(), and from there on down
  return do_exec(Query.c_str());
}


pqxx::result pqxx::transaction_base::exec_n(
	size_t rows,
	const std::string &Query,
	const std::string &Desc)
{
  const result r = exec(Query, Desc);
  if (r.size() != rows)
  {
    const std::string N = (Desc.empty() ? "" : "'" + Desc + "'");
    throw unexpected_rows{
	"Expected " + to_string(rows) + " row(s) of data "
        "from query " + N + ", got " + to_string(r.size()) + "."};
  }
  return r;
}


void pqxx::transaction_base::check_rowcount_prepared(
	const std::string &statement,
	size_t expected_rows,
	size_t actual_rows)
{
  if (actual_rows != expected_rows)
  {
    throw unexpected_rows{
	"Expected " + to_string(expected_rows) + " row(s) of data "
	"from prepared statement '" + statement + "', got " +
	to_string(actual_rows) + "."};
  }
}


void pqxx::transaction_base::check_rowcount_params(
	size_t expected_rows,
	size_t actual_rows)
{
  if (actual_rows != expected_rows)
  {
    throw unexpected_rows{
	"Expected " + to_string(expected_rows) + " row(s) of data "
	"from parameterised query, got " + to_string(actual_rows) + "."};
  }
}


pqxx::internal::parameterized_invocation
pqxx::transaction_base::parameterized(const std::string &query)
{
#include "pqxx/internal/ignore-deprecated-pre.hxx"
  return internal::parameterized_invocation{conn(), query};
#include "pqxx/internal/ignore-deprecated-post.hxx"
}


pqxx::prepare::invocation
pqxx::transaction_base::prepared(const std::string &statement)
{
  try
  {
    activate();
  }
  catch (const usage_error &e)
  {
    throw usage_error{
	"Error executing prepared statement " + statement + ".  " + e.what()};
  }
#include "pqxx/internal/ignore-deprecated-pre.hxx"
  return prepare::invocation{*this, statement};
#include "pqxx/internal/ignore-deprecated-post.hxx"
}


pqxx::result pqxx::transaction_base::internal_exec_prepared(
	const std::string &statement,
	const internal::params &args,
	result_format format)
{
  gate::connection_transaction gate{conn()};
  return gate.exec_prepared(statement, args, format);
}


pqxx::result pqxx::transaction_base::internal_exec_params(
	const std::string &query,
	const internal::params &args)
{
  gate::connection_transaction gate{conn()};
  return gate.exec_params(query, args);
}


void pqxx::transaction_base::set_variable(
	const std::string &Var,
	const std::string &Value)
{
  // Before committing to this new value, see what the backend thinks about it
  gate::connection_transaction gate{conn()};
  gate.raw_set_var(Var, Value);
  m_vars[Var] = Value;
}


std::string pqxx::transaction_base::get_variable(const std::string &Var)
{
  const std::map<std::string,std::string>::const_iterator i = m_vars.find(Var);
  if (i != m_vars.end()) return i->second;
  return gate::connection_transaction{conn()}.raw_get_var(Var);
}


void pqxx::transaction_base::Begin()
{
  if (m_status != st_nascent)
    throw internal_error{
	"pqxx::transaction: Begin() called while not in nascent state."};

  try
  {
    // Better handle any pending notifications before we begin
    m_conn.get_notifs();

    do_begin();
    m_status = st_active;
  }
  catch (const std::exception &)
  {
    End();
    throw;
  }
}


void pqxx::transaction_base::End() noexcept
{
  try
  {
    try { CheckPendingError(); }
    catch (const std::exception &e) { m_conn.process_notice(e.what()); }

    gate::connection_transaction gate{conn()};
    if (m_registered)
    {
      m_registered = false;
      gate.unregister_transaction(this);
    }

    if (m_status != st_active) return;

    if (m_focus.get())
      m_conn.process_notice(
	"Closing " + description() + "  with " +
	m_focus.get()->description() + " still open.\n");

    try { abort(); }
    catch (const std::exception &e) { m_conn.process_notice(e.what()); }

    gate.take_reactivation_avoidance(m_reactivation_avoidance.get());
    m_reactivation_avoidance.clear();
  }
  catch (const std::exception &e)
  {
    try { m_conn.process_notice(e.what()); } catch (const std::exception &) {}
  }
}


void pqxx::transaction_base::register_focus(internal::transactionfocus *S)
{
  m_focus.register_guest(S);
}


void pqxx::transaction_base::unregister_focus(internal::transactionfocus *S)
	noexcept
{
  try
  {
    m_focus.unregister_guest(S);
  }
  catch (const std::exception &e)
  {
    m_conn.process_notice(std::string{e.what()} + "\n");
  }
}


pqxx::result pqxx::transaction_base::direct_exec(const char C[], int Retries)
{
  CheckPendingError();
  return gate::connection_transaction{conn()}.exec(C, Retries);
}


void pqxx::transaction_base::register_pending_error(const std::string &Err)
	noexcept
{
  if (m_pending_error.empty() and not Err.empty())
  {
    try
    {
      m_pending_error = Err;
    }
    catch (const std::exception &e)
    {
      try
      {
        process_notice("UNABLE TO PROCESS ERROR\n");
        process_notice(e.what());
        process_notice("ERROR WAS:");
        process_notice(Err);
      }
      catch (...)
      {
      }
    }
  }
}


void pqxx::transaction_base::CheckPendingError()
{
  if (not m_pending_error.empty())
  {
    const std::string Err{m_pending_error};
    m_pending_error.clear();
    throw failure{Err};
  }
}


namespace
{
std::string MakeCopyString(
        const std::string &Table,
        const std::string &Columns)
{
  std::string Q = "COPY " + Table + " ";
  if (not Columns.empty()) Q += "(" + Columns + ") ";
  return Q;
}
} // namespace


void pqxx::transaction_base::BeginCopyRead(
	const std::string &Table,
	const std::string &Columns)
{
  exec(MakeCopyString(Table, Columns) + "TO STDOUT");
}


void pqxx::transaction_base::BeginCopyWrite(
	const std::string &Table,
	const std::string &Columns)
{
  exec(MakeCopyString(Table, Columns) + "FROM STDIN");
}


bool pqxx::transaction_base::read_copy_line(std::string &line)
{
  return gate::connection_transaction{conn()}.read_copy_line(line);
}


void pqxx::transaction_base::write_copy_line(const std::string &line)
{
  gate::connection_transaction gate{conn()};
  gate.write_copy_line(line);
}


void pqxx::transaction_base::end_copy_write()
{
  gate::connection_transaction gate{conn()};
  gate.end_copy_write();
}


void pqxx::internal::transactionfocus::register_me()
{
  gate::transaction_transactionfocus gate{m_trans};
  gate.register_focus(this);
  m_registered = true;
}


void pqxx::internal::transactionfocus::unregister_me() noexcept
{
  gate::transaction_transactionfocus gate{m_trans};
  gate.unregister_focus(this);
  m_registered = false;
}

void
pqxx::internal::transactionfocus::reg_pending_error(const std::string &err)
	noexcept
{
  gate::transaction_transactionfocus gate{m_trans};
  gate.register_pending_error(err);
}