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
|
#include "pqRecordSet.h"
#include "dbTypes.h"
#include "pqStmt.h"
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <helpers.h>
#include <libpq-fe.h>
#include <server/catalog/pg_type_d.h>
#include <stdexcept>
#include <string_view>
#include <utility>
namespace MyGrate::Output::Pq {
PqRecordSet::PqRecordSet(ResPtr r) : res {std::move(r)} { }
std::size_t
PqRecordSet::rows() const
{
return PQntuples(res.get());
}
std::size_t
PqRecordSet::columns() const
{
return PQnfields(res.get());
}
DbValue
PqRecordSet::at(std::size_t row, std::size_t col) const
{
if (PQgetisnull(res.get(), (int)row, (int)col)) {
return nullptr;
}
const auto value {PQgetvalue(res.get(), (int)row, (int)col)};
const auto size {static_cast<size_t>(PQgetlength(res.get(), (int)row, (int)col))};
const auto type {PQftype(res.get(), (int)col)};
switch (type) {
// case BITOID: TODO bool
// case BOOLOID: TODO bool
// case BOOLARRAYOID:
case VARBITOID:
case BYTEAOID:
// This is wrong :)
return Blob {reinterpret_cast<const std::byte *>(value), size};
case INT2OID:
return static_cast<int16_t>(std::strtol(value, nullptr, 10));
case INT4OID:
return static_cast<int32_t>(std::strtol(value, nullptr, 10));
case INT8OID:
return std::strtol(value, nullptr, 10);
case FLOAT4OID:
return std::strtof(value, nullptr);
case FLOAT8OID:
case CASHOID:
case NUMERICOID:
return std::strtod(value, nullptr);
case DATEOID: {
tm tm {};
const auto end = strptime(value, "%F", &tm);
verify<std::runtime_error>(end && !*end, "Invalid date string");
return Date {tm};
}
case TIMEOID: {
tm tm {};
const auto end = strptime(value, "%T", &tm);
verify<std::runtime_error>(end && !*end, "Invalid time string");
return Time {tm};
}
case TIMESTAMPOID: {
tm tm {};
const auto end = strptime(value, "%FT%T", &tm);
verify<std::runtime_error>(end && !*end, "Invalid timestamp string");
return DateTime {tm};
}
// case TIMESTAMPTZOID: Maybe add TZ support?
// case INTERVALOID: Maybe add interval support?
// case TIMETZOID: Maybe add TZ support?
case VOIDOID:
return nullptr;
default:
return std::string_view {value, size};
}
}
}
|