source: trunk/pgmodule.c

Last change on this file was 1002, checked in by cito, 7 weeks ago

Use same prefix for all C files

So that they are not scattered among the other files
in the root directory.

  • Property svn:keywords set to Id
File size: 38.6 KB
Line 
1/*
2 * $Id: pgmodule.c 1002 2019-04-25 22:33:57Z cito $
3 *
4 * PyGreSQL - a Python interface for the PostgreSQL database.
5 *
6 * This is the main file for the C extension module.
7 *
8 * Copyright (c) 2019 by the PyGreSQL Development Team
9 *
10 * Please see the LICENSE.TXT file for specific restrictions.
11 *
12 */
13
14/* Note: This should be linked against the same C runtime lib as Python */
15
16#include <Python.h>
17
18#include <libpq-fe.h>
19#include <libpq/libpq-fs.h>
20
21/* The type definitions from <server/catalog/pg_type.h> */
22#include "pgtypes.h"
23
24/* Macros for single-source Python 2/3 compatibility */
25#include "py3c.h"
26
27static PyObject *Error, *Warning, *InterfaceError, *DatabaseError,
28                *InternalError, *OperationalError, *ProgrammingError,
29                *IntegrityError, *DataError, *NotSupportedError,
30                *InvalidResultError, *NoResultError, *MultipleResultsError;
31
32#define _TOSTRING(x) #x
33#define TOSTRING(x) _TOSTRING(x)
34static const char *PyPgVersion = TOSTRING(PYGRESQL_VERSION);
35
36#if SIZEOF_SIZE_T != SIZEOF_INT
37#define Py_InitModule4 Py_InitModule4_64
38#endif
39
40/* Default values */
41#define PG_ARRAYSIZE 1
42
43/* Flags for object validity checks */
44#define CHECK_OPEN   1
45#define CHECK_CLOSE  2
46#define CHECK_CNX    4
47#define CHECK_RESULT 8
48#define CHECK_DQL   16
49
50/* Query result types */
51#define RESULT_EMPTY 1
52#define RESULT_DML   2
53#define RESULT_DDL   3
54#define RESULT_DQL   4
55
56/* Flags for move methods */
57#define QUERY_MOVEFIRST 1
58#define QUERY_MOVELAST  2
59#define QUERY_MOVENEXT  3
60#define QUERY_MOVEPREV  4
61
62#define MAX_BUFFER_SIZE 8192  /* maximum transaction size */
63#define MAX_ARRAY_DEPTH 16    /* maximum allowed depth of an array */
64
65/* MODULE GLOBAL VARIABLES */
66
67#ifdef DEFAULT_VARS
68static PyObject *pg_default_host;   /* default database host */
69static PyObject *pg_default_base;   /* default database name */
70static PyObject *pg_default_opt;    /* default connection options */
71static PyObject *pg_default_port;   /* default connection port */
72static PyObject *pg_default_user;   /* default username */
73static PyObject *pg_default_passwd; /* default password */
74#endif  /* DEFAULT_VARS */
75
76static PyObject *decimal = NULL,    /* decimal type */
77                *dictiter = NULL,   /* function for getting named results */
78                *namediter = NULL,  /* function for getting named results */
79                *namednext = NULL,  /* function for getting one named result */
80                *scalariter = NULL, /* function for getting scalar results */
81                *jsondecode = NULL; /* function for decoding json strings */
82static const char *date_format = NULL; /* date format that is always assumed */
83static char decimal_point = '.';    /* decimal point used in money values */
84static int bool_as_text = 0;   /* whether bool shall be returned as text */
85static int array_as_text = 0;  /* whether arrays shall be returned as text */
86static int bytea_escaped = 0;  /* whether bytea shall be returned escaped */
87
88static int pg_encoding_utf8 = 0;
89static int pg_encoding_latin1 = 0;
90static int pg_encoding_ascii = 0;
91
92/*
93OBJECTS
94=======
95
96  Each object has a number of elements.  The naming scheme will be based on
97  the object type.  Here are the elements using example object type "foo".
98   - fooType: Type definition for object.
99   - fooObject: A structure to hold local object information.
100   - foo_methods: Methods declaration.
101   - foo_method_name: Object methods.
102
103  The objects that we need to create:
104   - pg: The module itself.
105   - conn: Connection object returned from pg.connect().
106   - notice: Notice object returned from pg.notice().
107   - large: Large object returned by pg.conn.locreate() and pg.conn.loimport().
108   - query: Query object returned by pg.conn.query().
109   - source: Source object returned by pg.conn.source().
110*/
111
112/* Forward declarations for types */
113static PyTypeObject connType, sourceType, queryType, noticeType, largeType;
114
115/* Forward static declarations */
116static void notice_receiver(void *, const PGresult *);
117
118/* Object declarations */
119
120typedef struct
121{
122    PyObject_HEAD
123    int        valid;             /* validity flag */
124    PGconn     *cnx;              /* Postgres connection handle */
125    const char *date_format;      /* date format derived from datestyle */
126    PyObject   *cast_hook;        /* external typecast method */
127    PyObject   *notice_receiver;  /* current notice receiver */
128}   connObject;
129#define is_connObject(v) (PyType(v) == &connType)
130
131typedef struct
132{
133    PyObject_HEAD
134    int        valid;        /* validity flag */
135    connObject *pgcnx;       /* parent connection object */
136    PGresult   *result;      /* result content */
137    int        encoding;     /* client encoding */
138    int        result_type;  /* result type (DDL/DML/DQL) */
139    long       arraysize;    /* array size for fetch method */
140    int        current_row;  /* currently selected row */
141    int        max_row;      /* number of rows in the result */
142    int        num_fields;   /* number of fields in each row */
143}   sourceObject;
144#define is_sourceObject(v) (PyType(v) == &sourceType)
145
146typedef struct
147{
148    PyObject_HEAD
149    connObject *pgcnx;    /* parent connection object */
150    PGresult const *res;  /* an error or warning */
151}   noticeObject;
152#define is_noticeObject(v) (PyType(v) == &noticeType)
153
154typedef struct
155{
156    PyObject_HEAD
157    connObject *pgcnx;       /* parent connection object */
158    PGresult   *result;      /* result content */
159    int        encoding;     /* client encoding */
160    int        current_row;  /* currently selected row */
161    int        max_row;      /* number of rows in the result */
162    int        num_fields;   /* number of fields in each row */
163    int        *col_types;   /* PyGreSQL column types */
164}   queryObject;
165#define is_queryObject(v) (PyType(v) == &queryType)
166
167#ifdef LARGE_OBJECTS
168typedef struct
169{
170    PyObject_HEAD
171    connObject *pgcnx;  /* parent connection object */
172    Oid lo_oid;         /* large object oid */
173    int lo_fd;          /* large object fd */
174}   largeObject;
175#define is_largeObject(v) (PyType(v) == &largeType)
176#endif /* LARGE_OBJECTS */
177
178/* Internal functions */
179#include "pginternal.c"
180
181/* Connection object */
182#include "pgconn.c"
183
184/* Query object */
185#include "pgquery.c"
186
187/* Source object */
188#include "pgsource.c"
189
190/* Notice object */
191#include "pgnotice.c"
192
193/* Large objects */
194#ifdef LARGE_OBJECTS
195#include "pglarge.c"
196#endif
197
198/* MODULE FUNCTIONS */
199
200/* Connect to a database. */
201static char pg_connect__doc__[] =
202"connect(dbname, host, port, opt) -- connect to a PostgreSQL database\n\n"
203"The connection uses the specified parameters (optional, keywords aware).\n";
204
205static PyObject *
206pg_connect(PyObject *self, PyObject *args, PyObject *dict)
207{
208    static const char *kwlist[] =
209    {
210        "dbname", "host", "port", "opt", "user", "passwd", NULL
211    };
212
213    char *pghost, *pgopt, *pgdbname, *pguser, *pgpasswd;
214    int pgport;
215    char port_buffer[20];
216    connObject *conn_obj;
217
218    pghost = pgopt = pgdbname = pguser = pgpasswd = NULL;
219    pgport = -1;
220
221    /*
222     * parses standard arguments With the right compiler warnings, this
223     * will issue a diagnostic. There is really no way around it.  If I
224     * don't declare kwlist as const char *kwlist[] then it complains when
225     * I try to assign all those constant strings to it.
226     */
227    if (!PyArg_ParseTupleAndKeywords(
228        args, dict, "|zzizzz", (char**)kwlist,
229        &pgdbname, &pghost, &pgport, &pgopt, &pguser, &pgpasswd))
230    {
231        return NULL;
232    }
233
234#ifdef DEFAULT_VARS
235    /* handles defaults variables (for uninitialised vars) */
236    if ((!pghost) && (pg_default_host != Py_None))
237        pghost = PyBytes_AsString(pg_default_host);
238
239    if ((pgport == -1) && (pg_default_port != Py_None))
240        pgport = (int) PyInt_AsLong(pg_default_port);
241
242    if ((!pgopt) && (pg_default_opt != Py_None))
243        pgopt = PyBytes_AsString(pg_default_opt);
244
245    if ((!pgdbname) && (pg_default_base != Py_None))
246        pgdbname = PyBytes_AsString(pg_default_base);
247
248    if ((!pguser) && (pg_default_user != Py_None))
249        pguser = PyBytes_AsString(pg_default_user);
250
251    if ((!pgpasswd) && (pg_default_passwd != Py_None))
252        pgpasswd = PyBytes_AsString(pg_default_passwd);
253#endif /* DEFAULT_VARS */
254
255    if (!(conn_obj = PyObject_NEW(connObject, &connType))) {
256        set_error_msg(InternalError, "Can't create new connection object");
257        return NULL;
258    }
259
260    conn_obj->valid = 1;
261    conn_obj->cnx = NULL;
262    conn_obj->date_format = date_format;
263    conn_obj->cast_hook = NULL;
264    conn_obj->notice_receiver = NULL;
265
266    if (pgport != -1) {
267        memset(port_buffer, 0, sizeof(port_buffer));
268        sprintf(port_buffer, "%d", pgport);
269    }
270
271    Py_BEGIN_ALLOW_THREADS
272    conn_obj->cnx = PQsetdbLogin(pghost, pgport == -1 ? NULL : port_buffer,
273        pgopt, NULL, pgdbname, pguser, pgpasswd);
274    Py_END_ALLOW_THREADS
275
276    if (PQstatus(conn_obj->cnx) == CONNECTION_BAD) {
277        set_error(InternalError, "Cannot connect", conn_obj->cnx, NULL);
278        Py_XDECREF(conn_obj);
279        return NULL;
280    }
281
282    return (PyObject *) conn_obj;
283}
284
285/* Escape string */
286static char pg_escape_string__doc__[] =
287"escape_string(string) -- escape a string for use within SQL";
288
289static PyObject *
290pg_escape_string(PyObject *self, PyObject *string)
291{
292    PyObject *tmp_obj = NULL,  /* auxiliary string object */
293             *to_obj;          /* string object to return */
294    char *from,  /* our string argument as encoded string */
295         *to;    /* the result as encoded string */
296    Py_ssize_t from_length;    /* length of string */
297    size_t to_length;          /* length of result */
298    int encoding = -1;         /* client encoding */
299
300    if (PyBytes_Check(string)) {
301        PyBytes_AsStringAndSize(string, &from, &from_length);
302    }
303    else if (PyUnicode_Check(string)) {
304        encoding = pg_encoding_ascii;
305        tmp_obj = get_encoded_string(string, encoding);
306        if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
307        PyBytes_AsStringAndSize(tmp_obj, &from, &from_length);
308    }
309    else {
310        PyErr_SetString(PyExc_TypeError,
311                        "Method escape_string() expects a string as argument");
312        return NULL;
313    }
314
315    to_length = 2*from_length + 1;
316    if ((Py_ssize_t ) to_length < from_length) { /* overflow */
317        to_length = from_length;
318        from_length = (from_length - 1)/2;
319    }
320    to = (char *) PyMem_Malloc(to_length);
321    to_length = (int) PQescapeString(to, from, (size_t) from_length);
322
323    Py_XDECREF(tmp_obj);
324
325    if (encoding == -1)
326        to_obj = PyBytes_FromStringAndSize(to, to_length);
327    else
328        to_obj = get_decoded_string(to, to_length, encoding);
329    PyMem_Free(to);
330    return to_obj;
331}
332
333/* Escape bytea */
334static char pg_escape_bytea__doc__[] =
335"escape_bytea(data) -- escape binary data for use within SQL as type bytea";
336
337static PyObject *
338pg_escape_bytea(PyObject *self, PyObject *data)
339{
340    PyObject *tmp_obj = NULL,  /* auxiliary string object */
341             *to_obj;          /* string object to return */
342    char *from,  /* our string argument as encoded string */
343         *to;    /* the result as encoded string */
344    Py_ssize_t from_length;    /* length of string */
345    size_t to_length;          /* length of result */
346    int encoding = -1;         /* client encoding */
347
348    if (PyBytes_Check(data)) {
349        PyBytes_AsStringAndSize(data, &from, &from_length);
350    }
351    else if (PyUnicode_Check(data)) {
352        encoding = pg_encoding_ascii;
353        tmp_obj = get_encoded_string(data, encoding);
354        if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
355        PyBytes_AsStringAndSize(tmp_obj, &from, &from_length);
356    }
357    else {
358        PyErr_SetString(PyExc_TypeError,
359                        "Method escape_bytea() expects a string as argument");
360        return NULL;
361    }
362
363    to = (char *) PQescapeBytea(
364        (unsigned char*) from, (size_t) from_length, &to_length);
365
366    Py_XDECREF(tmp_obj);
367
368    if (encoding == -1)
369        to_obj = PyBytes_FromStringAndSize(to, to_length - 1);
370    else
371        to_obj = get_decoded_string(to, to_length - 1, encoding);
372    if (to)
373        PQfreemem(to);
374    return to_obj;
375}
376
377/* Unescape bytea */
378static char pg_unescape_bytea__doc__[] =
379"unescape_bytea(string) -- unescape bytea data retrieved as text";
380
381static PyObject *
382pg_unescape_bytea(PyObject *self, PyObject *data)
383{
384    PyObject *tmp_obj = NULL,  /* auxiliary string object */
385             *to_obj;          /* string object to return */
386    char *from,  /* our string argument as encoded string */
387         *to;    /* the result as encoded string */
388    Py_ssize_t from_length;    /* length of string */
389    size_t to_length;          /* length of result */
390
391    if (PyBytes_Check(data)) {
392        PyBytes_AsStringAndSize(data, &from, &from_length);
393    }
394    else if (PyUnicode_Check(data)) {
395        tmp_obj = get_encoded_string(data, pg_encoding_ascii);
396        if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
397        PyBytes_AsStringAndSize(tmp_obj, &from, &from_length);
398    }
399    else {
400        PyErr_SetString(
401            PyExc_TypeError,
402            "Method unescape_bytea() expects a string as argument");
403        return NULL;
404    }
405
406    to = (char *) PQunescapeBytea((unsigned char*) from, &to_length);
407
408    Py_XDECREF(tmp_obj);
409
410    if (!to) return PyErr_NoMemory();
411
412    to_obj = PyBytes_FromStringAndSize(to, to_length);
413    PQfreemem(to);
414
415    return to_obj;
416}
417
418/* Set fixed datestyle. */
419static char pg_set_datestyle__doc__[] =
420"set_datestyle(style) -- set which style is assumed";
421
422static PyObject *
423pg_set_datestyle(PyObject *self, PyObject *args)
424{
425    const char *datestyle = NULL;
426
427    /* gets arguments */
428    if (!PyArg_ParseTuple(args, "z", &datestyle)) {
429        PyErr_SetString(
430            PyExc_TypeError,
431            "Function set_datestyle() expects a string or None as argument");
432        return NULL;
433    }
434
435    date_format = datestyle ? date_style_to_format(datestyle) : NULL;
436
437    Py_INCREF(Py_None); return Py_None;
438}
439
440/* Get fixed datestyle. */
441static char pg_get_datestyle__doc__[] =
442"get_datestyle() -- get which date style is assumed";
443
444static PyObject *
445pg_get_datestyle(PyObject *self, PyObject *noargs)
446{
447    if (date_format) {
448        return PyStr_FromString(date_format_to_style(date_format));
449    }
450    else {
451        Py_INCREF(Py_None); return Py_None;
452    }
453}
454
455/* Get decimal point. */
456static char pg_get_decimal_point__doc__[] =
457"get_decimal_point() -- get decimal point to be used for money values";
458
459static PyObject *
460pg_get_decimal_point(PyObject *self, PyObject *noargs)
461{
462    PyObject *ret;
463    char s[2];
464
465    if (decimal_point) {
466        s[0] = decimal_point; s[1] = '\0';
467        ret = PyStr_FromString(s);
468    }
469    else {
470        Py_INCREF(Py_None); ret = Py_None;
471    }
472
473    return ret;
474}
475
476/* Set decimal point. */
477static char pg_set_decimal_point__doc__[] =
478"set_decimal_point(char) -- set decimal point to be used for money values";
479
480static PyObject *
481pg_set_decimal_point(PyObject *self, PyObject *args)
482{
483    PyObject *ret = NULL;
484    char *s = NULL;
485
486    /* gets arguments */
487    if (PyArg_ParseTuple(args, "z", &s)) {
488        if (!s)
489            s = "\0";
490        else if (*s && (*(s+1) || !strchr(".,;: '*/_`|", *s)))
491            s = NULL;
492    }
493
494    if (s) {
495        decimal_point = *s;
496        Py_INCREF(Py_None); ret = Py_None;
497    }
498    else {
499        PyErr_SetString(PyExc_TypeError,
500                        "Function set_decimal_mark() expects"
501                        " a decimal mark character as argument");
502    }
503    return ret;
504}
505
506/* Get decimal type. */
507static char pg_get_decimal__doc__[] =
508"get_decimal() -- get the decimal type to be used for numeric values";
509
510static PyObject *
511pg_get_decimal(PyObject *self, PyObject *noargs)
512{
513    PyObject *ret;
514
515    ret = decimal ? decimal : Py_None;
516    Py_INCREF(ret);
517
518    return ret;
519}
520
521/* Set decimal type. */
522static char pg_set_decimal__doc__[] =
523"set_decimal(cls) -- set a decimal type to be used for numeric values";
524
525static PyObject *
526pg_set_decimal(PyObject *self, PyObject *cls)
527{
528    PyObject *ret = NULL;
529
530    if (cls == Py_None) {
531        Py_XDECREF(decimal); decimal = NULL;
532        Py_INCREF(Py_None); ret = Py_None;
533    }
534    else if (PyCallable_Check(cls)) {
535        Py_XINCREF(cls); Py_XDECREF(decimal); decimal = cls;
536        Py_INCREF(Py_None); ret = Py_None;
537    }
538    else {
539        PyErr_SetString(PyExc_TypeError,
540                        "Function set_decimal() expects"
541                        " a callable or None as argument");
542    }
543
544    return ret;
545}
546
547/* Get usage of bool values. */
548static char pg_get_bool__doc__[] =
549"get_bool() -- check whether boolean values are converted to bool";
550
551static PyObject *
552pg_get_bool(PyObject *self, PyObject *noargs)
553{
554    PyObject *ret;
555
556    ret = bool_as_text ? Py_False : Py_True;
557    Py_INCREF(ret);
558
559    return ret;
560}
561
562/* Set usage of bool values. */
563static char pg_set_bool__doc__[] =
564"set_bool(on) -- set whether boolean values should be converted to bool";
565
566static PyObject *
567pg_set_bool(PyObject *self, PyObject *args)
568{
569    PyObject *ret = NULL;
570    int i;
571
572    /* gets arguments */
573    if (PyArg_ParseTuple(args, "i", &i)) {
574        bool_as_text = i ? 0 : 1;
575        Py_INCREF(Py_None); ret = Py_None;
576    }
577    else {
578        PyErr_SetString(
579            PyExc_TypeError,
580            "Function set_bool() expects a boolean value as argument");
581    }
582
583    return ret;
584}
585
586/* Get conversion of arrays to lists. */
587static char pg_get_array__doc__[] =
588"get_array() -- check whether arrays are converted as lists";
589
590static PyObject *
591pg_get_array(PyObject *self, PyObject *noargs)
592{
593    PyObject *ret;
594
595    ret = array_as_text ? Py_False : Py_True;
596    Py_INCREF(ret);
597
598    return ret;
599}
600
601/* Set conversion of arrays to lists. */
602static char pg_set_array__doc__[] =
603"set_array(on) -- set whether arrays should be converted to lists";
604
605static PyObject *
606pg_set_array(PyObject* self, PyObject* args)
607{
608    PyObject* ret = NULL;
609    int i;
610
611    /* gets arguments */
612    if (PyArg_ParseTuple(args, "i", &i)) {
613        array_as_text = i ? 0 : 1;
614        Py_INCREF(Py_None); ret = Py_None;
615    }
616    else {
617        PyErr_SetString(
618            PyExc_TypeError,
619            "Function set_array() expects a boolean value as argument");
620    }
621
622    return ret;
623}
624
625/* Check whether bytea values are unescaped. */
626static char pg_get_bytea_escaped__doc__[] =
627"get_bytea_escaped() -- check whether bytea will be returned escaped";
628
629static PyObject *
630pg_get_bytea_escaped(PyObject *self, PyObject *noargs)
631{
632    PyObject *ret;
633
634    ret = bytea_escaped ? Py_True : Py_False;
635    Py_INCREF(ret);
636
637    return ret;
638}
639
640/* Set usage of bool values. */
641static char pg_set_bytea_escaped__doc__[] =
642"set_bytea_escaped(on) -- set whether bytea will be returned escaped";
643
644static PyObject *
645pg_set_bytea_escaped(PyObject *self, PyObject *args)
646{
647    PyObject *ret = NULL;
648    int i;
649
650    /* gets arguments */
651    if (PyArg_ParseTuple(args, "i", &i)) {
652        bytea_escaped = i ? 1 : 0;
653        Py_INCREF(Py_None); ret = Py_None;
654    }
655    else {
656        PyErr_SetString(PyExc_TypeError,
657                        "Function set_bytea_escaped() expects"
658                        " a boolean value as argument");
659    }
660
661    return ret;
662}
663
664/* set query helper functions (not part of public API) */
665
666static char pg_set_query_helpers__doc__[] =
667"set_query_helpers(*helpers) -- set internal query helper functions";
668
669static PyObject *
670pg_set_query_helpers(PyObject *self, PyObject *args)
671{
672    /* gets arguments */
673    if (!PyArg_ParseTuple(args, "O!O!O!O!",
674        &PyFunction_Type, &dictiter,
675        &PyFunction_Type, &namediter,
676        &PyFunction_Type, &namednext,
677        &PyFunction_Type, &scalariter))
678    {
679        return NULL;
680    }
681
682    Py_INCREF(Py_None);
683    return Py_None;
684}
685
686/* Get json decode function. */
687static char pg_get_jsondecode__doc__[] =
688"get_jsondecode() -- get the function used for decoding json results";
689
690static PyObject *
691pg_get_jsondecode(PyObject *self, PyObject *noargs)
692{
693    PyObject *ret;
694
695    ret = jsondecode;
696    if (!ret)
697        ret = Py_None;
698    Py_INCREF(ret);
699
700    return ret;
701}
702
703/* Set json decode function. */
704static char pg_set_jsondecode__doc__[] =
705"set_jsondecode(func) -- set a function to be used for decoding json results";
706
707static PyObject *
708pg_set_jsondecode(PyObject *self, PyObject *func)
709{
710    PyObject *ret = NULL;
711
712    if (func == Py_None) {
713        Py_XDECREF(jsondecode); jsondecode = NULL;
714        Py_INCREF(Py_None); ret = Py_None;
715    }
716    else if (PyCallable_Check(func)) {
717        Py_XINCREF(func); Py_XDECREF(jsondecode); jsondecode = func;
718        Py_INCREF(Py_None); ret = Py_None;
719    }
720    else {
721        PyErr_SetString(PyExc_TypeError,
722                        "Function jsondecode() expects"
723                        " a callable or None as argument");
724    }
725
726    return ret;
727}
728
729#ifdef DEFAULT_VARS
730
731/* Get default host. */
732static char pg_get_defhost__doc__[] =
733"get_defhost() -- return default database host";
734
735static PyObject *
736pg_get_defhost(PyObject *self, PyObject *noargs)
737{
738    Py_XINCREF(pg_default_host);
739    return pg_default_host;
740}
741
742/* Set default host. */
743static char pg_set_defhost__doc__[] =
744"set_defhost(string) -- set default database host and return previous value";
745
746static PyObject *
747pg_set_defhost(PyObject *self, PyObject *args)
748{
749    char *tmp = NULL;
750    PyObject *old;
751
752    /* gets arguments */
753    if (!PyArg_ParseTuple(args, "z", &tmp)) {
754        PyErr_SetString(
755            PyExc_TypeError,
756            "Function set_defhost() expects a string or None as argument");
757        return NULL;
758    }
759
760    /* adjusts value */
761    old = pg_default_host;
762
763    if (tmp) {
764        pg_default_host = PyStr_FromString(tmp);
765    }
766    else {
767        Py_INCREF(Py_None);
768        pg_default_host = Py_None;
769    }
770
771    return old;
772}
773
774/* Get default database. */
775static char pg_get_defbase__doc__[] =
776"get_defbase() -- return default database name";
777
778static PyObject *
779pg_get_defbase(PyObject *self, PyObject *noargs)
780{
781    Py_XINCREF(pg_default_base);
782    return pg_default_base;
783}
784
785/* Set default database. */
786static char pg_set_defbase__doc__[] =
787"set_defbase(string) -- set default database name and return previous value";
788
789static PyObject *
790pg_set_defbase(PyObject *self, PyObject *args)
791{
792    char *tmp = NULL;
793    PyObject *old;
794
795    /* gets arguments */
796    if (!PyArg_ParseTuple(args, "z", &tmp)) {
797        PyErr_SetString(
798            PyExc_TypeError,
799            "Function set_defbase() Argument a string or None as argument");
800        return NULL;
801    }
802
803    /* adjusts value */
804    old = pg_default_base;
805
806    if (tmp) {
807        pg_default_base = PyStr_FromString(tmp);
808    }
809    else {
810        Py_INCREF(Py_None);
811        pg_default_base = Py_None;
812    }
813
814    return old;
815}
816
817/* Get default options. */
818static char pg_get_defopt__doc__[] =
819"get_defopt() -- return default database options";
820
821static PyObject *
822pg_get_defopt(PyObject *self, PyObject *noargs)
823{
824    Py_XINCREF(pg_default_opt);
825    return pg_default_opt;
826}
827
828/* Set default options. */
829static char pg_set_defopt__doc__[] =
830"set_defopt(string) -- set default options and return previous value";
831
832static PyObject *
833pg_setdefopt(PyObject *self, PyObject *args)
834{
835    char *tmp = NULL;
836    PyObject *old;
837
838    /* gets arguments */
839    if (!PyArg_ParseTuple(args, "z", &tmp)) {
840        PyErr_SetString(
841            PyExc_TypeError,
842            "Function set_defopt() expects a string or None as argument");
843        return NULL;
844    }
845
846    /* adjusts value */
847    old = pg_default_opt;
848
849    if (tmp) {
850        pg_default_opt = PyStr_FromString(tmp);
851    }
852    else {
853        Py_INCREF(Py_None);
854        pg_default_opt = Py_None;
855    }
856
857    return old;
858}
859
860/* Get default username. */
861static char pg_get_defuser__doc__[] =
862"get_defuser() -- return default database username";
863
864static PyObject *
865pg_get_defuser(PyObject *self, PyObject *noargs)
866{
867    Py_XINCREF(pg_default_user);
868    return pg_default_user;
869}
870
871/* Set default username. */
872
873static char pg_set_defuser__doc__[] =
874"set_defuser(name) -- set default username and return previous value";
875
876static PyObject *
877pg_set_defuser(PyObject *self, PyObject *args)
878{
879    char *tmp = NULL;
880    PyObject *old;
881
882    /* gets arguments */
883    if (!PyArg_ParseTuple(args, "z", &tmp)) {
884        PyErr_SetString(
885            PyExc_TypeError,
886            "Function set_defuser() expects a string or None as argument");
887        return NULL;
888    }
889
890    /* adjusts value */
891    old = pg_default_user;
892
893    if (tmp) {
894        pg_default_user = PyStr_FromString(tmp);
895    }
896    else {
897        Py_INCREF(Py_None);
898        pg_default_user = Py_None;
899    }
900
901    return old;
902}
903
904/* Set default password. */
905static char pg_set_defpasswd__doc__[] =
906"set_defpasswd(password) -- set default database password";
907
908static PyObject *
909pg_set_defpasswd(PyObject *self, PyObject *args)
910{
911    char *tmp = NULL;
912
913    /* gets arguments */
914    if (!PyArg_ParseTuple(args, "z", &tmp)) {
915        PyErr_SetString(
916            PyExc_TypeError,
917            "Function set_defpasswd() expects a string or None as argument");
918        return NULL;
919    }
920
921    if (tmp) {
922        pg_default_passwd = PyStr_FromString(tmp);
923    }
924    else {
925        Py_INCREF(Py_None);
926        pg_default_passwd = Py_None;
927    }
928
929    Py_INCREF(Py_None);
930    return Py_None;
931}
932
933/* Get default port. */
934static char pg_get_defport__doc__[] =
935"get_defport() -- return default database port";
936
937static PyObject *
938pg_get_defport(PyObject *self, PyObject *noargs)
939{
940    Py_XINCREF(pg_default_port);
941    return pg_default_port;
942}
943
944/* Set default port. */
945static char pg_set_defport__doc__[] =
946"set_defport(port) -- set default port and return previous value";
947
948static PyObject *
949pg_set_defport(PyObject *self, PyObject *args)
950{
951    long int port = -2;
952    PyObject *old;
953
954    /* gets arguments */
955    if ((!PyArg_ParseTuple(args, "l", &port)) || (port < -1)) {
956        PyErr_SetString(PyExc_TypeError,
957                        "Function set_deport expects"
958                        " a positive integer or -1 as argument");
959        return NULL;
960    }
961
962    /* adjusts value */
963    old = pg_default_port;
964
965    if (port != -1) {
966        pg_default_port = PyInt_FromLong(port);
967    }
968    else {
969        Py_INCREF(Py_None);
970        pg_default_port = Py_None;
971    }
972
973    return old;
974}
975#endif /* DEFAULT_VARS */
976
977/* Cast a string with a text representation of an array to a list. */
978static char pg_cast_array__doc__[] =
979"cast_array(string, cast=None, delim=',') -- cast a string as an array";
980
981PyObject *
982pg_cast_array(PyObject *self, PyObject *args, PyObject *dict)
983{
984    static const char *kwlist[] = {"string", "cast", "delim", NULL};
985    PyObject *string_obj, *cast_obj = NULL, *ret;
986    char *string, delim = ',';
987    Py_ssize_t size;
988    int encoding;
989
990    if (!PyArg_ParseTupleAndKeywords(
991        args, dict, "O|Oc",
992        (char**) kwlist, &string_obj, &cast_obj, &delim))
993    {
994        return NULL;
995    }
996
997    if (PyBytes_Check(string_obj)) {
998        PyBytes_AsStringAndSize(string_obj, &string, &size);
999        string_obj = NULL;
1000        encoding = pg_encoding_ascii;
1001    }
1002    else if (PyUnicode_Check(string_obj)) {
1003        string_obj = PyUnicode_AsUTF8String(string_obj);
1004        if (!string_obj) return NULL; /* pass the UnicodeEncodeError */
1005        PyBytes_AsStringAndSize(string_obj, &string, &size);
1006        encoding = pg_encoding_utf8;
1007    }
1008    else {
1009        PyErr_SetString(
1010            PyExc_TypeError,
1011            "Function cast_array() expects a string as first argument");
1012        return NULL;
1013    }
1014
1015    if (!cast_obj || cast_obj == Py_None) {
1016        if (cast_obj) {
1017            Py_DECREF(cast_obj); cast_obj = NULL;
1018        }
1019    }
1020    else if (!PyCallable_Check(cast_obj)) {
1021        PyErr_SetString(
1022            PyExc_TypeError,
1023            "Function cast_array() expects a callable as second argument");
1024        return NULL;
1025    }
1026
1027    ret = cast_array(string, size, encoding, 0, cast_obj, delim);
1028
1029    Py_XDECREF(string_obj);
1030
1031    return ret;
1032}
1033
1034/* Cast a string with a text representation of a record to a tuple. */
1035static char pg_cast_record__doc__[] =
1036"cast_record(string, cast=None, delim=',') -- cast a string as a record";
1037
1038PyObject *
1039pg_cast_record(PyObject *self, PyObject *args, PyObject *dict)
1040{
1041    static const char *kwlist[] = {"string", "cast", "delim", NULL};
1042    PyObject *string_obj, *cast_obj = NULL, *ret;
1043    char *string, delim = ',';
1044    Py_ssize_t size, len;
1045    int encoding;
1046
1047    if (!PyArg_ParseTupleAndKeywords(
1048        args, dict, "O|Oc",
1049        (char**) kwlist, &string_obj, &cast_obj, &delim))
1050    {
1051        return NULL;
1052    }
1053
1054    if (PyBytes_Check(string_obj)) {
1055        PyBytes_AsStringAndSize(string_obj, &string, &size);
1056        string_obj = NULL;
1057        encoding = pg_encoding_ascii;
1058    }
1059    else if (PyUnicode_Check(string_obj)) {
1060        string_obj = PyUnicode_AsUTF8String(string_obj);
1061        if (!string_obj) return NULL; /* pass the UnicodeEncodeError */
1062        PyBytes_AsStringAndSize(string_obj, &string, &size);
1063        encoding = pg_encoding_utf8;
1064    }
1065    else {
1066        PyErr_SetString(
1067            PyExc_TypeError,
1068            "Function cast_record() expects a string as first argument");
1069        return NULL;
1070    }
1071
1072    if (!cast_obj || PyCallable_Check(cast_obj)) {
1073        len = 0;
1074    }
1075    else if (cast_obj == Py_None) {
1076        Py_DECREF(cast_obj); cast_obj = NULL; len = 0;
1077    }
1078    else if (PyTuple_Check(cast_obj) || PyList_Check(cast_obj)) {
1079        len = PySequence_Size(cast_obj);
1080        if (!len) {
1081            Py_DECREF(cast_obj); cast_obj = NULL;
1082        }
1083    }
1084    else {
1085        PyErr_SetString(PyExc_TypeError,
1086                        "Function cast_record() expects a callable"
1087                        " or tuple or list of callables as second argument");
1088        return NULL;
1089    }
1090
1091    ret = cast_record(string, size, encoding, 0, cast_obj, len, delim);
1092
1093    Py_XDECREF(string_obj);
1094
1095    return ret;
1096}
1097
1098/* Cast a string with a text representation of an hstore to a dict. */
1099static char pg_cast_hstore__doc__[] =
1100"cast_hstore(string) -- cast a string as an hstore";
1101
1102PyObject *
1103pg_cast_hstore(PyObject *self, PyObject *string)
1104{
1105    PyObject *tmp_obj = NULL, *ret;
1106    char *s;
1107    Py_ssize_t size;
1108    int encoding;
1109
1110    if (PyBytes_Check(string)) {
1111        PyBytes_AsStringAndSize(string, &s, &size);
1112        encoding = pg_encoding_ascii;
1113    }
1114    else if (PyUnicode_Check(string)) {
1115        tmp_obj = PyUnicode_AsUTF8String(string);
1116        if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
1117        PyBytes_AsStringAndSize(tmp_obj, &s, &size);
1118        encoding = pg_encoding_utf8;
1119    }
1120    else {
1121        PyErr_SetString(
1122            PyExc_TypeError,
1123            "Function cast_hstore() expects a string as first argument");
1124        return NULL;
1125    }
1126
1127    ret = cast_hstore(s, size, encoding);
1128
1129    Py_XDECREF(tmp_obj);
1130
1131    return ret;
1132}
1133
1134/* The list of functions defined in the module */
1135
1136static struct PyMethodDef pg_methods[] = {
1137    {"connect", (PyCFunction) pg_connect,
1138        METH_VARARGS|METH_KEYWORDS, pg_connect__doc__},
1139    {"escape_string", (PyCFunction) pg_escape_string,
1140        METH_O, pg_escape_string__doc__},
1141    {"escape_bytea", (PyCFunction) pg_escape_bytea,
1142        METH_O, pg_escape_bytea__doc__},
1143    {"unescape_bytea", (PyCFunction) pg_unescape_bytea,
1144        METH_O, pg_unescape_bytea__doc__},
1145    {"get_datestyle", (PyCFunction) pg_get_datestyle,
1146        METH_NOARGS, pg_get_datestyle__doc__},
1147    {"set_datestyle", (PyCFunction) pg_set_datestyle,
1148        METH_VARARGS, pg_set_datestyle__doc__},
1149    {"get_decimal_point", (PyCFunction) pg_get_decimal_point,
1150        METH_NOARGS, pg_get_decimal_point__doc__},
1151    {"set_decimal_point", (PyCFunction) pg_set_decimal_point,
1152        METH_VARARGS, pg_set_decimal_point__doc__},
1153    {"get_decimal", (PyCFunction) pg_get_decimal,
1154        METH_NOARGS, pg_get_decimal__doc__},
1155    {"set_decimal", (PyCFunction) pg_set_decimal,
1156        METH_O, pg_set_decimal__doc__},
1157    {"get_bool", (PyCFunction) pg_get_bool,
1158        METH_NOARGS, pg_get_bool__doc__},
1159    {"set_bool", (PyCFunction) pg_set_bool,
1160        METH_VARARGS, pg_set_bool__doc__},
1161    {"get_array", (PyCFunction) pg_get_array,
1162        METH_NOARGS, pg_get_array__doc__},
1163    {"set_array", (PyCFunction) pg_set_array,
1164        METH_VARARGS, pg_set_array__doc__},
1165    {"set_query_helpers", (PyCFunction) pg_set_query_helpers,
1166        METH_VARARGS, pg_set_query_helpers__doc__},
1167    {"get_bytea_escaped", (PyCFunction) pg_get_bytea_escaped,
1168        METH_NOARGS, pg_get_bytea_escaped__doc__},
1169    {"set_bytea_escaped", (PyCFunction) pg_set_bytea_escaped,
1170        METH_VARARGS, pg_set_bytea_escaped__doc__},
1171    {"get_jsondecode", (PyCFunction) pg_get_jsondecode,
1172        METH_NOARGS, pg_get_jsondecode__doc__},
1173    {"set_jsondecode", (PyCFunction) pg_set_jsondecode,
1174        METH_O, pg_set_jsondecode__doc__},
1175    {"cast_array", (PyCFunction) pg_cast_array,
1176        METH_VARARGS|METH_KEYWORDS, pg_cast_array__doc__},
1177    {"cast_record", (PyCFunction) pg_cast_record,
1178        METH_VARARGS|METH_KEYWORDS, pg_cast_record__doc__},
1179    {"cast_hstore", (PyCFunction) pg_cast_hstore,
1180        METH_O, pg_cast_hstore__doc__},
1181
1182#ifdef DEFAULT_VARS
1183    {"get_defhost", pg_get_defhost, METH_NOARGS, pg_get_defhost__doc__},
1184    {"set_defhost", pg_set_defhost, METH_VARARGS, pg_set_defhost__doc__},
1185    {"get_defbase", pg_get_defbase, METH_NOARGS, pg_get_defbase__doc__},
1186    {"set_defbase", pg_set_defbase, METH_VARARGS, pg_set_defbase__doc__},
1187    {"get_defopt", pg_get_defopt, METH_NOARGS, pg_get_defopt__doc__},
1188    {"set_defopt", pg_setdefopt, METH_VARARGS, pg_set_defopt__doc__},
1189    {"get_defport", pg_get_defport, METH_NOARGS, pg_get_defport__doc__},
1190    {"set_defport", pg_set_defport, METH_VARARGS, pg_set_defport__doc__},
1191    {"get_defuser", pg_get_defuser, METH_NOARGS, pg_get_defuser__doc__},
1192    {"set_defuser", pg_set_defuser, METH_VARARGS, pg_set_defuser__doc__},
1193    {"set_defpasswd", pg_set_defpasswd, METH_VARARGS, pg_set_defpasswd__doc__},
1194#endif /* DEFAULT_VARS */
1195    {NULL, NULL} /* sentinel */
1196};
1197
1198static char pg__doc__[] = "Python interface to PostgreSQL DB";
1199
1200static struct PyModuleDef moduleDef = {
1201    PyModuleDef_HEAD_INIT,
1202    "_pg",     /* m_name */
1203    pg__doc__, /* m_doc */
1204    -1,        /* m_size */
1205    pg_methods /* m_methods */
1206};
1207
1208/* Initialization function for the module */
1209MODULE_INIT_FUNC(_pg)
1210{
1211    PyObject *mod, *dict, *s;
1212
1213    /* Create the module and add the functions */
1214
1215    mod = PyModule_Create(&moduleDef);
1216
1217    /* Initialize here because some Windows platforms get confused otherwise */
1218#if IS_PY3
1219    connType.tp_base = noticeType.tp_base =
1220        queryType.tp_base = sourceType.tp_base = &PyBaseObject_Type;
1221#ifdef LARGE_OBJECTS
1222    largeType.tp_base = &PyBaseObject_Type;
1223#endif
1224#else
1225    connType.ob_type = noticeType.ob_type =
1226        queryType.ob_type = sourceType.ob_type = &PyType_Type;
1227#ifdef LARGE_OBJECTS
1228    largeType.ob_type = &PyType_Type;
1229#endif
1230#endif
1231
1232    if (PyType_Ready(&connType)
1233        || PyType_Ready(&noticeType)
1234        || PyType_Ready(&queryType)
1235        || PyType_Ready(&sourceType)
1236#ifdef LARGE_OBJECTS
1237        || PyType_Ready(&largeType)
1238#endif
1239        )
1240    {
1241        return NULL;
1242    }
1243
1244    dict = PyModule_GetDict(mod);
1245
1246    /* Exceptions as defined by DB-API 2.0 */
1247    Error = PyErr_NewException("pg.Error", PyExc_Exception, NULL);
1248    PyDict_SetItemString(dict, "Error", Error);
1249
1250    Warning = PyErr_NewException("pg.Warning", PyExc_Exception, NULL);
1251    PyDict_SetItemString(dict, "Warning", Warning);
1252
1253    InterfaceError = PyErr_NewException(
1254        "pg.InterfaceError", Error, NULL);
1255    PyDict_SetItemString(dict, "InterfaceError", InterfaceError);
1256
1257    DatabaseError = PyErr_NewException(
1258        "pg.DatabaseError", Error, NULL);
1259    PyDict_SetItemString(dict, "DatabaseError", DatabaseError);
1260
1261    InternalError = PyErr_NewException(
1262        "pg.InternalError", DatabaseError, NULL);
1263    PyDict_SetItemString(dict, "InternalError", InternalError);
1264
1265    OperationalError = PyErr_NewException(
1266        "pg.OperationalError", DatabaseError, NULL);
1267    PyDict_SetItemString(dict, "OperationalError", OperationalError);
1268
1269    ProgrammingError = PyErr_NewException(
1270        "pg.ProgrammingError", DatabaseError, NULL);
1271    PyDict_SetItemString(dict, "ProgrammingError", ProgrammingError);
1272
1273    IntegrityError = PyErr_NewException(
1274        "pg.IntegrityError", DatabaseError, NULL);
1275    PyDict_SetItemString(dict, "IntegrityError", IntegrityError);
1276
1277    DataError = PyErr_NewException(
1278        "pg.DataError", DatabaseError, NULL);
1279    PyDict_SetItemString(dict, "DataError", DataError);
1280
1281    NotSupportedError = PyErr_NewException(
1282        "pg.NotSupportedError", DatabaseError, NULL);
1283    PyDict_SetItemString(dict, "NotSupportedError", NotSupportedError);
1284
1285    InvalidResultError = PyErr_NewException(
1286        "pg.InvalidResultError", DataError, NULL);
1287    PyDict_SetItemString(dict, "InvalidResultError", InvalidResultError);
1288
1289    NoResultError = PyErr_NewException(
1290        "pg.NoResultError", InvalidResultError, NULL);
1291    PyDict_SetItemString(dict, "NoResultError", NoResultError);
1292
1293    MultipleResultsError = PyErr_NewException(
1294        "pg.MultipleResultsError", InvalidResultError, NULL);
1295    PyDict_SetItemString(dict, "MultipleResultsError", MultipleResultsError);
1296
1297    /* Make the version available */
1298    s = PyStr_FromString(PyPgVersion);
1299    PyDict_SetItemString(dict, "version", s);
1300    PyDict_SetItemString(dict, "__version__", s);
1301    Py_DECREF(s);
1302
1303    /* Result types for queries */
1304    PyDict_SetItemString(dict, "RESULT_EMPTY", PyInt_FromLong(RESULT_EMPTY));
1305    PyDict_SetItemString(dict, "RESULT_DML", PyInt_FromLong(RESULT_DML));
1306    PyDict_SetItemString(dict, "RESULT_DDL", PyInt_FromLong(RESULT_DDL));
1307    PyDict_SetItemString(dict, "RESULT_DQL", PyInt_FromLong(RESULT_DQL));
1308
1309    /* Transaction states */
1310    PyDict_SetItemString(dict,"TRANS_IDLE",PyInt_FromLong(PQTRANS_IDLE));
1311    PyDict_SetItemString(dict,"TRANS_ACTIVE",PyInt_FromLong(PQTRANS_ACTIVE));
1312    PyDict_SetItemString(dict,"TRANS_INTRANS",PyInt_FromLong(PQTRANS_INTRANS));
1313    PyDict_SetItemString(dict,"TRANS_INERROR",PyInt_FromLong(PQTRANS_INERROR));
1314    PyDict_SetItemString(dict,"TRANS_UNKNOWN",PyInt_FromLong(PQTRANS_UNKNOWN));
1315
1316#ifdef LARGE_OBJECTS
1317    /* Create mode for large objects */
1318    PyDict_SetItemString(dict, "INV_READ", PyInt_FromLong(INV_READ));
1319    PyDict_SetItemString(dict, "INV_WRITE", PyInt_FromLong(INV_WRITE));
1320
1321    /* Position flags for lo_lseek */
1322    PyDict_SetItemString(dict, "SEEK_SET", PyInt_FromLong(SEEK_SET));
1323    PyDict_SetItemString(dict, "SEEK_CUR", PyInt_FromLong(SEEK_CUR));
1324    PyDict_SetItemString(dict, "SEEK_END", PyInt_FromLong(SEEK_END));
1325#endif /* LARGE_OBJECTS */
1326
1327#ifdef DEFAULT_VARS
1328    /* Prepare default values */
1329    Py_INCREF(Py_None);
1330    pg_default_host = Py_None;
1331    Py_INCREF(Py_None);
1332    pg_default_base = Py_None;
1333    Py_INCREF(Py_None);
1334    pg_default_opt = Py_None;
1335    Py_INCREF(Py_None);
1336    pg_default_port = Py_None;
1337    Py_INCREF(Py_None);
1338    pg_default_user = Py_None;
1339    Py_INCREF(Py_None);
1340    pg_default_passwd = Py_None;
1341#endif /* DEFAULT_VARS */
1342
1343    /* Store common pg encoding ids */
1344
1345    pg_encoding_utf8 = pg_char_to_encoding("UTF8");
1346    pg_encoding_latin1 = pg_char_to_encoding("LATIN1");
1347    pg_encoding_ascii = pg_char_to_encoding("SQL_ASCII");
1348
1349    /* Check for errors */
1350    if (PyErr_Occurred()) {
1351        return NULL;
1352    }
1353
1354    return mod;
1355}
Note: See TracBrowser for help on using the repository browser.