summaryrefslogtreecommitdiff
path: root/psycopg/conninfo_type.c
blob: 9a10c94f28947bdc432e76986a7a24bbb61f5cbe (plain)
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
/* conninfo_type.c - present information about the libpq connection
 *
 * Copyright (C) 2018-2019  Daniele Varrazzo <daniele.varrazzo@gmail.com>
 * Copyright (C) 2020-2021 The Psycopg Team
 *
 * This file is part of psycopg.
 *
 * psycopg2 is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link this program with the OpenSSL library (or with
 * modified versions of OpenSSL that use the same license as OpenSSL),
 * and distribute linked combinations including the two.
 *
 * You must obey the GNU Lesser General Public License in all respects for
 * all of the code used other than OpenSSL.
 *
 * psycopg2 is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 * License for more details.
 */

#define PSYCOPG_MODULE
#include "psycopg/psycopg.h"

#include "psycopg/conninfo.h"


static const char connInfoType_doc[] =
"Details about the native PostgreSQL database connection.\n"
"\n"
"This class exposes several `informative functions`__ about the status\n"
"of the libpq connection.\n"
"\n"
"Objects of this class are exposed as the `connection.info` attribute.\n"
"\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html";


static const char dbname_doc[] =
"The database name of the connection.\n"
"\n"
".. seealso:: libpq docs for `PQdb()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQDB";

static PyObject *
dbname_get(connInfoObject *self)
{
    const char *val;

    val = PQdb(self->conn->pgconn);
    if (!val) {
        Py_RETURN_NONE;
    }
    return conn_text_from_chars(self->conn, val);
}


static const char user_doc[] =
"The user name of the connection.\n"
"\n"
".. seealso:: libpq docs for `PQuser()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQUSER";

static PyObject *
user_get(connInfoObject *self)
{
    const char *val;

    val = PQuser(self->conn->pgconn);
    if (!val) {
        Py_RETURN_NONE;
    }
    return conn_text_from_chars(self->conn, val);
}


static const char password_doc[] =
"The password of the connection.\n"
"\n"
".. seealso:: libpq docs for `PQpass()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQPASS";

static PyObject *
password_get(connInfoObject *self)
{
    const char *val;

    val = PQpass(self->conn->pgconn);
    if (!val) {
        Py_RETURN_NONE;
    }
    return conn_text_from_chars(self->conn, val);
}


static const char host_doc[] =
"The server host name of the connection.\n"
"\n"
"This can be a host name, an IP address, or a directory path if the\n"
"connection is via Unix socket. (The path case can be distinguished\n"
"because it will always be an absolute path, beginning with ``/``.)\n"
"\n"
".. seealso:: libpq docs for `PQhost()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQHOST";

static PyObject *
host_get(connInfoObject *self)
{
    const char *val;

    val = PQhost(self->conn->pgconn);
    if (!val) {
        Py_RETURN_NONE;
    }
    return conn_text_from_chars(self->conn, val);
}


static const char port_doc[] =
"The port of the connection.\n"
"\n"
":type: `!int`\n"
"\n"
".. seealso:: libpq docs for `PQport()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQPORT";

static PyObject *
port_get(connInfoObject *self)
{
    const char *val;

    val = PQport(self->conn->pgconn);
    if (!val || !val[0]) {
        Py_RETURN_NONE;
    }
    return PyInt_FromString((char *)val, NULL, 10);
}


static const char options_doc[] =
"The command-line options passed in the connection request.\n"
"\n"
".. seealso:: libpq docs for `PQoptions()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQOPTIONS";

static PyObject *
options_get(connInfoObject *self)
{
    const char *val;

    val = PQoptions(self->conn->pgconn);
    if (!val) {
        Py_RETURN_NONE;
    }
    return conn_text_from_chars(self->conn, val);
}


static const char dsn_parameters_doc[] =
"The effective connection parameters.\n"
"\n"
":type: `!dict`\n"
"\n"
"The results include values which weren't explicitly set by the connection\n"
"string, such as defaults, environment variables, etc.\n"
"The *password* parameter is removed from the results.\n"
"\n"
".. seealso:: libpq docs for `PQconninfo()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/libpq-connect.html"
    "#LIBPQ-PQCONNINFO";

static PyObject *
dsn_parameters_get(connInfoObject *self)
{
#if PG_VERSION_NUM >= 90300
    PyObject *res = NULL;
    PQconninfoOption *options = NULL;

    EXC_IF_CONN_CLOSED(self->conn);

    if (!(options = PQconninfo(self->conn->pgconn))) {
        PyErr_NoMemory();
        goto exit;
    }

    res = psyco_dict_from_conninfo_options(options, /* include_password = */ 0);

exit:
    PQconninfoFree(options);

    return res;
#else
    PyErr_SetString(NotSupportedError, "PQconninfo not available in libpq < 9.3");
    return NULL;
#endif
}


static const char status_doc[] =
"The status of the connection.\n"
"\n"
":type: `!int`\n"
"\n"
".. seealso:: libpq docs for `PQstatus()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQSTATUS";

static PyObject *
status_get(connInfoObject *self)
{
    ConnStatusType val;

    val = PQstatus(self->conn->pgconn);
    return PyInt_FromLong((long)val);
}


static const char transaction_status_doc[] =
"The current in-transaction status of the connection.\n"
"\n"
"Symbolic constants for the values are defined in the module\n"
"`psycopg2.extensions`: see :ref:`transaction-status-constants` for the\n"
"available values.\n"
"\n"
":type: `!int`\n"
"\n"
".. seealso:: libpq docs for `PQtransactionStatus()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQTRANSACTIONSTATUS";

static PyObject *
transaction_status_get(connInfoObject *self)
{
    PGTransactionStatusType val;

    val = PQtransactionStatus(self->conn->pgconn);
    return PyInt_FromLong((long)val);
}


static const char parameter_status_doc[] =
"Looks up a current parameter setting of the server.\n"
"\n"
":param name: The name of the parameter to return.\n"
":type name: `!str`\n"
":return: The parameter value, `!None` if the parameter is unknown.\n"
":rtype: `!str`\n"
"\n"
".. seealso:: libpq docs for `PQparameterStatus()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQPARAMETERSTATUS";

static PyObject *
parameter_status(connInfoObject *self, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"name", NULL};
    const char *name;
    const char *val;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &name)) {
        return NULL;
    }

    val = PQparameterStatus(self->conn->pgconn, name);

    if (!val) {
        Py_RETURN_NONE;
    }
    else {
        return conn_text_from_chars(self->conn, val);
    }
}


static const char protocol_version_doc[] =
"The frontend/backend protocol being used.\n"
"\n"
":type: `!int`\n"
"\n"
".. seealso:: libpq docs for `PQprotocolVersion()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQPROTOCOLVERSION";

static PyObject *
protocol_version_get(connInfoObject *self)
{
    int val;

    val = PQprotocolVersion(self->conn->pgconn);
    return PyInt_FromLong((long)val);
}


static const char server_version_doc[] =
"Returns an integer representing the server version.\n"
"\n"
":type: `!int`\n"
"\n"
".. seealso:: libpq docs for `PQserverVersion()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQSERVERVERSION";

static PyObject *
server_version_get(connInfoObject *self)
{
    int val;

    val = PQserverVersion(self->conn->pgconn);
    return PyInt_FromLong((long)val);
}


static const char error_message_doc[] =
"The error message most recently generated by an operation on the connection.\n"
"\n"
"`!None` if there is no current message.\n"
"\n"
".. seealso:: libpq docs for `PQerrorMessage()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQERRORMESSAGE";

static PyObject *
error_message_get(connInfoObject *self)
{
    const char *val;

    val = PQerrorMessage(self->conn->pgconn);
    if (!val || !val[0]) {
        Py_RETURN_NONE;
    }
    return conn_text_from_chars(self->conn, val);
}


static const char socket_doc[] =
"The file descriptor number of the connection socket to the server.\n"
"\n"
":type: `!int`\n"
"\n"
".. seealso:: libpq docs for `PQsocket()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQSOCKET";

static PyObject *
socket_get(connInfoObject *self)
{
    int val;

    val = PQsocket(self->conn->pgconn);
    return PyInt_FromLong((long)val);
}


static const char backend_pid_doc[] =
"The process ID (PID) of the backend process you connected to.\n"
"\n"
":type: `!int`\n"
"\n"
".. seealso:: libpq docs for `PQbackendPID()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQBACKENDPID";

static PyObject *
backend_pid_get(connInfoObject *self)
{
    int val;

    val = PQbackendPID(self->conn->pgconn);
    return PyInt_FromLong((long)val);
}


static const char needs_password_doc[] =
"The connection authentication method required a password, but none was available.\n"
"\n"
":type: `!bool`\n"
"\n"
".. seealso:: libpq docs for `PQconnectionNeedsPassword()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQCONNECTIONNEEDSPASSWORD";

static PyObject *
needs_password_get(connInfoObject *self)
{
    return PyBool_FromLong(PQconnectionNeedsPassword(self->conn->pgconn));
}


static const char used_password_doc[] =
"The connection authentication method used a password.\n"
"\n"
":type: `!bool`\n"
"\n"
".. seealso:: libpq docs for `PQconnectionUsedPassword()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQCONNECTIONUSEDPASSWORD";

static PyObject *
used_password_get(connInfoObject *self)
{
    return PyBool_FromLong(PQconnectionUsedPassword(self->conn->pgconn));
}


static const char ssl_in_use_doc[] =
"`!True` if the connection uses SSL, `!False` if not.\n"
"\n"
"Only available if psycopg was built with libpq >= 9.5; raise\n"
"`~psycopg2.NotSupportedError` otherwise.\n"
"\n"
":type: `!bool`\n"
"\n"
".. seealso:: libpq docs for `PQsslInUse()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQSSLINUSE";

static PyObject *
ssl_in_use_get(connInfoObject *self)
{
    PyObject *rv = NULL;

#if PG_VERSION_NUM >= 90500
    rv = PyBool_FromLong(PQsslInUse(self->conn->pgconn));
#else
    PyErr_SetString(NotSupportedError,
        "'ssl_in_use' not available in libpq < 9.5");
#endif
    return rv;
}


static const char ssl_attribute_doc[] =
"Returns SSL-related information about the connection.\n"
"\n"
":param name: The name of the attribute to return.\n"
":type name: `!str`\n"
":return: The attribute value, `!None` if unknown.\n"
":rtype: `!str`\n"
"\n"
"Only available if psycopg was built with libpq >= 9.5; raise\n"
"`~psycopg2.NotSupportedError` otherwise.\n"
"\n"
"Valid names are available in `ssl_attribute_names`.\n"
"\n"
".. seealso:: libpq docs for `PQsslAttribute()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQSSLATTRIBUTE";

static PyObject *
ssl_attribute(connInfoObject *self, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"name", NULL};
    const char *name;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &name)) {
        return NULL;
    }

#if PG_VERSION_NUM >= 90500
    {
        const char *val;

        val = PQsslAttribute(self->conn->pgconn, name);

        if (!val) {
            Py_RETURN_NONE;
        }
        else {
            return conn_text_from_chars(self->conn, val);
        }
    }
#else
    PyErr_SetString(NotSupportedError,
        "'ssl_attribute()' not available in libpq < 9.5");
    return NULL;
#endif
}

static const char ssl_attribute_names_doc[] =
"The list of the SSL attribute names available.\n"
"\n"
":type: `!list` of `!str`\n"
"\n"
"Only available if psycopg was built with libpq >= 9.5; raise\n"
"`~psycopg2.NotSupportedError` otherwise.\n"
"\n"
".. seealso:: libpq docs for `PQsslAttributeNames()`__ for details.\n"
".. __: https://www.postgresql.org/docs/current/static/libpq-status.html"
    "#LIBPQ-PQSSLATTRIBUTENAMES";

static PyObject *
ssl_attribute_names_get(connInfoObject *self)
{
#if PG_VERSION_NUM >= 90500
    const char* const* names;
    int i;
    PyObject *l = NULL, *s = NULL, *rv = NULL;

    names = PQsslAttributeNames(self->conn->pgconn);
    if (!(l = PyList_New(0))) { goto exit; }

    for (i = 0; names[i]; i++) {
        if (!(s = conn_text_from_chars(self->conn, names[i]))) { goto exit; }
        if (0 != PyList_Append(l, s)) { goto exit; }
        Py_CLEAR(s);
    }

    rv = l;
    l = NULL;

exit:
    Py_XDECREF(l);
    Py_XDECREF(s);
    return rv;
#else
    PyErr_SetString(NotSupportedError,
        "'ssl_attribute_names not available in libpq < 9.5");
    return NULL;
#endif
}


static struct PyGetSetDef connInfoObject_getsets[] = {
    { "dbname", (getter)dbname_get, NULL, (char *)dbname_doc },
    { "user", (getter)user_get, NULL, (char *)user_doc },
    { "password", (getter)password_get, NULL, (char *)password_doc },
    { "host", (getter)host_get, NULL, (char *)host_doc },
    { "port", (getter)port_get, NULL, (char *)port_doc },
    { "options", (getter)options_get, NULL, (char *)options_doc },
    { "dsn_parameters", (getter)dsn_parameters_get, NULL,
        (char *)dsn_parameters_doc },
    { "status", (getter)status_get, NULL, (char *)status_doc },
    { "transaction_status", (getter)transaction_status_get, NULL,
        (char *)transaction_status_doc },
    { "protocol_version", (getter)protocol_version_get, NULL,
        (char *)protocol_version_doc },
    { "server_version", (getter)server_version_get, NULL,
        (char *)server_version_doc },
    { "error_message", (getter)error_message_get, NULL,
        (char *)error_message_doc },
    { "socket", (getter)socket_get, NULL, (char *)socket_doc },
    { "backend_pid", (getter)backend_pid_get, NULL, (char *)backend_pid_doc },
    { "used_password", (getter)used_password_get, NULL,
        (char *)used_password_doc },
    { "needs_password", (getter)needs_password_get, NULL,
        (char *)needs_password_doc },
    { "ssl_in_use", (getter)ssl_in_use_get, NULL,
        (char *)ssl_in_use_doc },
    { "ssl_attribute_names", (getter)ssl_attribute_names_get, NULL,
        (char *)ssl_attribute_names_doc },
    {NULL}
};

static struct PyMethodDef connInfoObject_methods[] = {
    {"ssl_attribute", (PyCFunction)ssl_attribute,
     METH_VARARGS|METH_KEYWORDS, ssl_attribute_doc},
    {"parameter_status", (PyCFunction)parameter_status,
     METH_VARARGS|METH_KEYWORDS, parameter_status_doc},
    {NULL}
};

/* initialization and finalization methods */

static PyObject *
conninfo_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    return type->tp_alloc(type, 0);
}

static int
conninfo_init(connInfoObject *self, PyObject *args, PyObject *kwds)
{
    PyObject *conn = NULL;

    if (!PyArg_ParseTuple(args, "O", &conn))
        return -1;

    if (!PyObject_TypeCheck(conn, &connectionType)) {
        PyErr_SetString(PyExc_TypeError,
            "The argument must be a psycopg2 connection");
        return -1;
    }

    Py_INCREF(conn);
    self->conn = (connectionObject *)conn;
    return 0;
}

static void
conninfo_dealloc(connInfoObject* self)
{
    Py_CLEAR(self->conn);
    Py_TYPE(self)->tp_free((PyObject *)self);
}


/* object type */

PyTypeObject connInfoType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "psycopg2.extensions.ConnectionInfo",
    sizeof(connInfoObject), 0,
    (destructor)conninfo_dealloc, /*tp_dealloc*/
    0,          /*tp_print*/
    0,          /*tp_getattr*/
    0,          /*tp_setattr*/
    0,          /*tp_compare*/
    0,          /*tp_repr*/
    0,          /*tp_as_number*/
    0,          /*tp_as_sequence*/
    0,          /*tp_as_mapping*/
    0,          /*tp_hash */
    0,          /*tp_call*/
    0,          /*tp_str*/
    0,          /*tp_getattro*/
    0,          /*tp_setattro*/
    0,          /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
    connInfoType_doc, /*tp_doc*/
    0,          /*tp_traverse*/
    0,          /*tp_clear*/
    0,          /*tp_richcompare*/
    0,          /*tp_weaklistoffset*/
    0,          /*tp_iter*/
    0,          /*tp_iternext*/
    connInfoObject_methods, /*tp_methods*/
    0,          /*tp_members*/
    connInfoObject_getsets, /*tp_getset*/
    0,          /*tp_base*/
    0,          /*tp_dict*/
    0,          /*tp_descr_get*/
    0,          /*tp_descr_set*/
    0,          /*tp_dictoffset*/
    (initproc)conninfo_init, /*tp_init*/
    0,          /*tp_alloc*/
    conninfo_new, /*tp_new*/
};