Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
cursor_mock.execute.side_effect = None
conn = server.postgres.connect()
pg_connect_mock.assert_called_with("valid conninfo")
assert conn is conn_mock
# call again and make sure it returns the cached connection
pg_connect_mock.reset_mock()
new_conn = server.postgres.connect()
assert new_conn is conn_mock
assert not pg_connect_mock.called
# call again with a broken connection
pg_connect_mock.reset_mock()
conn_mock.cursor.side_effect = [psycopg2.DatabaseError, cursor_mock]
new_conn = server.postgres.connect()
assert new_conn is conn_mock
pg_connect_mock.assert_called_with("valid conninfo")
# close it
pg_connect_mock.reset_mock()
conn_mock.cursor.side_effect = None
conn_mock.closed = False
server.postgres.close()
assert conn_mock.close.called
# close it with an already closed connection
def test_relvar_delete_missing(self):
"Attempt to delete a tuple that has been deleted since it was fetched"
self.insert_one()
keytuple = self.relvar.key_tuple(1)
currtuple = self.relvar.get_one(keytuple)
self.delete_one(1)
with pytest.raises(DatabaseError):
self.relvar.delete_one(currtuple, keytuple)
for bank_account in bank_accounts:
get_paged_data_and_load(cursor,'bank_transactions','bank_account=' + bank_account["url"])
# get_paged_data_and_load(cursor, 'bank_transaction_explanations','bank_account=' + bank_account["url"])
get_paged_data_and_load(cursor, 'bills')
get_paged_data_and_load(cursor, 'contacts')
get_paged_data_and_load(cursor, 'expenses')
get_paged_data_and_load(cursor, 'invoices')
get_paged_data_and_load(cursor, 'projects')
get_paged_data_and_load(cursor, 'users')
get_csv_and_load(cursor, "server_costs", ["project_name","value"])
connection.commit()
except psycopg2.DatabaseError, e:
print 'Error %s' % e
sys.exit(1)
finally:
if connection:
connection.close()
print "All done."
user=_options.get("user"),
password=_options.get("passwd"),
database=_options.get("db"),
port=_options.get("port"),
)
except psycopg2.OperationalError as exc:
raise salt.exceptions.SaltMasterError(
"postgres returner could not connect to database: {exc}".format(exc=exc)
)
cursor = conn.cursor()
try:
yield cursor
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(str(error))
raise err
finally:
conn.close()
def execute(self, query, args=None):
try:
return self.cursor.execute(query, args)
except Database.IntegrityError, e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def _increase_rank(self, field):
if self.ids and field in ['customer_rank', 'supplier_rank']:
try:
with self.env.cr.savepoint():
query = sql.SQL("""
SELECT {field} FROM res_partner WHERE ID IN %(partner_ids)s FOR UPDATE NOWAIT;
UPDATE res_partner SET {field} = {field} + 1
WHERE id IN %(partner_ids)s
""").format(field=sql.Identifier(field))
self.env.cr.execute(query, {'partner_ids': tuple(self.ids)})
for partner in self:
self.env.cache.remove(partner, partner._fields[field])
except DatabaseError as e:
if e.pgcode == '55P03':
_logger.debug('Another transaction already locked partner rows. Cannot update partner ranks.')
else:
raise e
def __init__(self, *args, **kwargs):
super(Postgres, self).__init__(*args, **kwargs)
self._current_cursor = None
dbname = kwargs.pop('db', None) or os.environ.get('PGDATABASE')
try:
self.conn = psycopg2.connect(dbname=dbname, **kwargs)
except psycopg2.DatabaseError as e:
raise BackendError("Error connecting to Postgresql DB: {}"
.format(e))
# authorize uuids objects in queries
psycopg2.extras.register_uuid()
# authorize dicts objects for hstore in queries
try:
psycopg2.extras.register_hstore(self.conn)
except psycopg2.ProgrammingError:
# this probably means that the hstore extension is not
# installed in the db, no need to register it then
pass
from django.db.backends.signals import connection_created
from django.db.backends.postgresql.operations import DatabaseOperations as PostgresqlDatabaseOperations
from django.db.backends.postgresql.client import DatabaseClient
from django.db.backends.postgresql.creation import DatabaseCreation
from django.db.backends.postgresql.version import get_version
from django.db.backends.postgresql_psycopg2.introspection import DatabaseIntrospection
from django.utils.safestring import SafeUnicode, SafeString
try:
import psycopg2 as Database
import psycopg2.extensions
except ImportError, e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
DatabaseError = Database.DatabaseError
IntegrityError = Database.IntegrityError
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_adapter(SafeString, psycopg2.extensions.QuotedString)
psycopg2.extensions.register_adapter(SafeUnicode, psycopg2.extensions.QuotedString)
class CursorWrapper(object):
"""
A thin wrapper around psycopg2's normal cursor class so that we can catch
particular exception instances and reraise them with the right types.
"""
def __init__(self, cursor):
self.cursor = cursor
def execute(self, query, args=None):
def drop_repslot(self, slot_name):
"""
Drop a physical replication slot using the streaming connection
:param str slot_name: Replication slot name
"""
cursor = self._cursor()
try:
# In the following query, the slot name is directly passed
# to the DROP_REPLICATION_SLOT command, without any
# quoting. This is a characteristic of the streaming
# connection, otherwise if will fail with a generic
# "syntax error"
cursor.execute('DROP_REPLICATION_SLOT %s' % slot_name)
_logger.info("Replication slot '%s' successfully dropped",
slot_name)
except psycopg2.DatabaseError as exc:
if exc.pgcode == UNDEFINED_OBJECT:
# A replication slot with the that name does not exist
raise PostgresInvalidReplicationSlot()
if exc.pgcode == OBJECT_IN_USE:
# The replication slot is still in use
raise PostgresReplicationSlotInUse()
else:
raise PostgresException(force_str(exc).strip())