pypy-postgresql / pypy / module / postgresql / interp_connection.py

  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
from pypy.interpreter.baseobjspace import Wrappable
from pypy.interpreter.error import OperationError
from pypy.interpreter.gateway import unwrap_spec, interp2app, NoneNotWrapped
from pypy.interpreter.typedef import TypeDef, GetSetProperty
from pypy.module.postgresql import libpq
from pypy.module.postgresql.interp_xid import W_Xid
from pypy.rlib import jit
from pypy.rpython.lltypesystem import rffi, lltype


def conn_notice_callback(notices, message):
    notices = rffi.cast(lltype.Ptr(NOTICES), notices)

    message_len = 0
    while message[message_len] != "\0":
        message_len += 1
    new_message = lltype.malloc(rffi.CCHARP.TO, message_len, flavor="raw")
    for i in xrange(message_len):
        new_message[i] = message[i]

    if notices.stop == 50:
        idx = notices.start
        lltype.free(notices.items[idx], flavor="raw")
        notices.items[idx] = new_message
        rffi.setintfield(notices, "start", (notices.start + 1) % 50)
    else:
        notices.items[notices.stop] = new_message
        notices.stop += 1


NOTICES = lltype.Struct("NOTICES",
    ("start", rffi.SIZE_T),
    ("stop", rffi.SIZE_T),
    ("items", lltype.Array(rffi.CCHARP)),
)

class W_Connection(Wrappable):
    ISOLATION_LEVEL_AUTOCOMMIT = 0
    # ISOLATION_LEVEL_READ_UNCOMMITTED doesn't exist in PgSQL, expose the
    # constant anways
    ISOLATION_LEVEL_READ_COMMITTED = ISOLATION_LEVEL_READ_UNCOMMITTED= 1
    # ISOLATION_LEVEL_REPEATABLE_READ doesn't exist in PgSQL, expose the
    # constant anways
    ISOLATION_LEVEL_SERIALIZABLE = ISOLATION_LEVEL_REPEATABLE_READ = 2

    CONN_STATUS_SETUP = 0
    CONN_STATUS_READY = 1
    CONN_STATUS_BEGIN = 2
    CONN_STATUS_PREPARED = 5

    def __init__(self, space, dsn):
        from pypy.module.postgresql.interp_state import get

        self.dsn = dsn
        self.status = self.CONN_STATUS_SETUP
        self.pgconn = libpq.PQconnectdb(dsn)
        if not self.pgconn:
            raise OperationError(get(space).w_OperationalError,
                space.wrap("PQconnectdb() failed")
            )
        elif libpq.PQstatus(self.pgconn) == libpq.CONNECTION_BAD:
            error = rffi.charp2str(libpq.PQerrorMessage(self.pgconn))
            raise OperationError(get(space).w_OperationalError,
                space.wrap(error),
            )
        self.notices = lltype.malloc(NOTICES, 50, flavor="raw")
        rffi.setintfield(self.notices, "start", 0)
        rffi.setintfield(self.notices, "stop", 0)
        libpq.PQsetNoticeProcessor(
            self.pgconn, conn_notice_callback, rffi.cast(rffi.VOIDP, self.notices)
        )
        self.typecasts = {}
        self.w_tpc_xid = None
        self.setup(space)

    def __del__(self):
        self.close()

    def check_closed(self, space):
        from pypy.module.postgresql.interp_state import get

        if self.closed:
            raise OperationError(get(space).w_InterfaceError,
                space.wrap("connection already closed")
            )

    def check_tpc(self, space, command):
        from pypy.module.postgresql.interp_state import get

        if self.w_tpc_xid:
            raise OperationError(get(space).w_ProgrammingError,
                space.wrap("%s cannot be used during a two-phase transaction" % command)
            )

    def setup(self, space):
        from pypy.module.postgresql.interp_state import get

        pgres = libpq.PQexec(self.pgconn, "SHOW default_transaction_isolation")
        if not pgres or libpq.PQresultStatus(pgres) != libpq.PGRES_TUPLES_OK:
            raise OperationError(get(space).w_OperationalError,
                space.wrap("can't fetch default_isolation_level")
            )

        isolation_level = rffi.charp2str(libpq.PQgetvalue(pgres, 0, 0))
        libpq.PQclear(pgres)
        if (isolation_level == "read uncommitted" or
            isolation_level == "read committed"):
            self.isolation_level = self.ISOLATION_LEVEL_READ_COMMITTED
        else:
            self.isolation_level = self.ISOLATION_LEVEL_SERIALIZABLE

        client_encoding = libpq.PQparameterStatus(self.pgconn, "client_encoding")
        self.encoding = rffi.charp2str(client_encoding).upper()

        self.closed = False
        self.status = self.CONN_STATUS_READY

    def begin_transaction(self, space):
        if (self.isolation_level == self.ISOLATION_LEVEL_AUTOCOMMIT or
            self.status != self.CONN_STATUS_READY):
            return
        sql = [
            None,
            "BEGIN; SET TRANSACTION ISOLATION LEVEL READ COMMITTED",
            "BEGIN; SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",
        ][self.isolation_level]
        self.execute_command(
            space,
            sql
        )
        self.status = self.CONN_STATUS_BEGIN

    # TODO: until we support cast from Signed to opaque ptr.
    @jit.dont_look_inside
    def execute_command(self, space, command):
        pgres = libpq.PQexec(self.pgconn, command)
        if not pgres:
            self.raise_operational_error(space, rffi.cast(libpq.PGresult, 0))
        try:
            pgstatus = libpq.PQresultStatus(pgres)
            if pgstatus != libpq.PGRES_COMMAND_OK:
                self.raise_operational_error(space, pgres)
        finally:
            libpq.PQclear(pgres)

    def execute_tpc_command(self, space, command):
        from pypy.module.postgresql.interp_adapters import W_QuotedString

        tid = self.w_tpc_xid.as_tid(space)
        w_tid = W_QuotedString(space.wrap(tid))
        w_tid.descr_prepare(space, self)
        tid = space.str_w(w_tid.quote(space))
        cmd = "%s %s;" % (command, tid)
        self.execute_command(space, cmd)

    def finish_tpc(self, space, command, fallback):
        from pypy.module.postgresql.interp_state import get

        if not self.w_tpc_xid:
            raise OperationError(get(space).w_ProgrammingError,
                space.wrap("tpc_commit/tpc_rollback with no parameter must be "
                    "called in a two-phase transaction")
            )

        if self.status == self.CONN_STATUS_BEGIN:
            if fallback == "commit":
                self.commit(space)
            elif fallback == "abort":
                self.abort(space)
            else:
                raise OperationError(get(space).w_InternalError,
                    space.wrap("bad fallback passed to finish_tpc")
                )
        elif self.status == self.CONN_STATUS_PREPARED:
            self.execute_tpc_command(space, command)
        else:
            raise OperationError(get(space).w_InterfaceError,
                space.wrap("unexpected state in tpc_commit/tpc_rollback")
            )

        self.status = self.CONN_STATUS_READY
        self.w_tpc_xid = None


    def get_exc_type_for_state(self, space, code):
        from pypy.module.postgresql.interp_state import get

        state = get(space)
        exc_type = None
        if code[0] == "2":
            if code[1] == "3":
                exc_type = state.w_IntegrityError
        elif code[0] == "4":
            if code[1] == "2":
                exc_type = state.w_ProgrammingError
        return exc_type

    def raise_operational_error(self, space, pgres):
        from pypy.module.postgresql.interp_state import get

        code = None
        error = None
        if pgres:
            error = rffi.charp2str(libpq.PQresultErrorMessage(pgres))
            if error is not None:
                code = rffi.charp2str(
                    libpq.PQresultErrorField(pgres, libpq.PG_DIAG_SQLSTATE)
                )
        if error is None:
            error = rffi.charp2str(libpq.PQerrorMessage(self.pgconn))
        exc_type = None
        if code is not None:
            exc_type = self.get_exc_type_for_state(space, code)
        if exc_type is None:
            exc_type = get(space).w_OperationalError
        raise OperationError(exc_type, space.wrap(error))

    def close(self):
        self.closed = True

        if self.pgconn:
            libpq.PQfinish(self.pgconn)
            self.pgconn = rffi.cast(libpq.PGconn, 0)

        if self.notices:
            for i in xrange(self.notices.stop):
                lltype.free(self.notices.items[i], flavor="raw")
            lltype.free(self.notices, flavor="raw")
            self.notices = lltype.nullptr(NOTICES)

    def commit(self, space):
        if (self.isolation_level == self.ISOLATION_LEVEL_AUTOCOMMIT or
            self.status != self.CONN_STATUS_BEGIN):
            return
        self.execute_command(space, "COMMIT")
        self.status = self.CONN_STATUS_READY

    def abort(self, space):
        if (self.isolation_level == self.ISOLATION_LEVEL_AUTOCOMMIT or
            self.status != self.CONN_STATUS_BEGIN):
            return
        self.execute_command(space, "ROLLBACK")
        self.status = self.CONN_STATUS_READY

    def descr_get_closed(self, space):
        return space.wrap(self.closed)

    def descr_get_isolation_level(self, space):
        return space.wrap(self.isolation_level)

    def descr_get_notices(self, space):
        if self.notices.stop == 50:
            notices_w = []
            for i in xrange(self.notices.start, self.notices.stop):
                notices_w.append(space.wrap(rffi.charp2str(self.notices.items[i])))
            for i in xrange(self.notices.start):
                notices_w.append(space.wrap(rffi.charp2str(self.notices.items[i])))
            return space.newlist(notices_w)
        return space.newlist([
            space.wrap(rffi.charp2str(self.notices.items[i]))
            for i in xrange(self.notices.stop)
        ])

    def descr_close(self, space):
        self.check_closed(space)
        self.close()

    @unwrap_spec(level=int)
    def descr_set_isolation_level(self, space, level):
        self.check_closed(space)

        if level < 0 or level > 2:
            raise OperationError(space.w_ValueError,
                space.wrap("isolation level must be between 0 and 2")
            )
        if self.isolation_level == level:
            return
        if self.isolation_level != self.ISOLATION_LEVEL_AUTOCOMMIT:
            self.abort(space)
        self.isolation_level = level

    def descr_get_transaction_status(self, space):
        return space.wrap(libpq.PQtransactionStatus(self.pgconn))

    @unwrap_spec(encoding=str)
    def descr_set_client_encoding(self, space, encoding):
        self.check_closed(space)
        encoding = "".join([c for c in encoding if c != "-" and c != "_"])
        if self.encoding == encoding:
            return
        self.abort(space)
        self.execute_command(space, "SET client_encoding = %s" % encoding)
        self.encoding = encoding

    @unwrap_spec(name="str_or_None")
    def descr_cursor(self, space, name=None):
        from pypy.module.postgresql.interp_cursor import W_Cursor

        return W_Cursor(space, self, name)

    def descr_commit(self, space):
        self.check_closed(space)
        self.check_tpc(space, "commit")

        self.commit(space)

    def descr_rollback(self, space):
        self.check_closed(space)
        self.check_tpc(space, "rollback")

        self.abort(space)

    def descr_reset(self, space):
        self.check_closed(space)
        self.setup(space)

    @unwrap_spec(format_id=int, gtrid=str, bqual=str)
    def descr_xid(self, space, format_id, gtrid, bqual):
        self.check_closed(space)
        return W_Xid(space, format_id, gtrid, bqual)

    @unwrap_spec(xid=W_Xid)
    def descr_tpc_begin(self, space, xid):
        from pypy.module.postgresql.interp_state import get

        self.check_closed(space)

        if self.status != self.CONN_STATUS_READY:
            raise OperationError(get(space).w_ProgrammingError,
                space.wrap("tpc_begin must be called outside a transaction")
            )

        if self.isolation_level == self.ISOLATION_LEVEL_AUTOCOMMIT:
            raise OperationError(get(space).w_ProgrammingError,
                space.wrap("tpc_begin can't be called in autocommit mode")
            )

        self.begin_transaction(space)
        self.w_tpc_xid = xid

    def descr_tpc_commit(self, space):
        self.check_closed(space)

        self.finish_tpc(space, "COMMIT PREPARED", "commit")

    def descr_tpc_rollback(self, space):
        self.check_closed(space)

        self.finish_tpc(space, "ROLLBACK PREPARED", "abort")

    def descr_tpc_prepare(self, space):
        from pypy.module.postgresql.interp_state import get

        self.check_closed(space)

        if not self.w_tpc_xid:
            raise OperationError(get(space).w_ProgrammingError,
                space.wrap("prepare must be called inside a two-phase transaction")
            )

        self.execute_tpc_command(space, "PREPARE TRANSACTION")
        self.status = self.CONN_STATUS_PREPARED


W_Connection.typedef = TypeDef("connection",
    closed = GetSetProperty(W_Connection.descr_get_closed),
    isolation_level = GetSetProperty(W_Connection.descr_get_isolation_level),
    notices = GetSetProperty(W_Connection.descr_get_notices),

    close = interp2app(W_Connection.descr_close),
    set_isolation_level = interp2app(W_Connection.descr_set_isolation_level),
    get_transaction_status = interp2app(W_Connection.descr_get_transaction_status),
    set_client_encoding = interp2app(W_Connection.descr_set_client_encoding),
    cursor = interp2app(W_Connection.descr_cursor),
    commit = interp2app(W_Connection.descr_commit),
    rollback = interp2app(W_Connection.descr_rollback),
    reset = interp2app(W_Connection.descr_reset),

    xid = interp2app(W_Connection.descr_xid),
    tpc_begin = interp2app(W_Connection.descr_tpc_begin),
    tpc_commit = interp2app(W_Connection.descr_tpc_commit),
    tpc_rollback = interp2app(W_Connection.descr_tpc_rollback),
    tpc_prepare = interp2app(W_Connection.descr_tpc_prepare),
)


@unwrap_spec(dsn="str_or_None", database="str_or_None", host="str_or_None", user="str_or_None", password="str_or_None")
def connect(space, dsn=None, database=None, host=None, w_port=NoneNotWrapped, user=None, password=None):
    if dsn is None:
        dsn = ""
        if database is not None:
            dsn += "dbname=%s" % database
        if host is not None:
            dsn += " host=%s" % host
        if w_port is not None:
            port = -1
            if space.isinstance_w(w_port, space.w_str):
                port = space.int_w(space.call_function(space.w_int, w_port))
            elif space.isinstance_w(w_port, space.w_int):
                port = space.int_w(w_port)
            else:
                raise OperationError(space.w_TypeError,
                    space.wrap("port must be a string or int")
                )
            dsn += " port=%d" % port
        if user is not None:
            dsn += " user=%s" % user
        if password is not None:
            dsn += " password=%s" % password
    return W_Connection(space, dsn)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.