How to use the psycopg.connect function in psycopg

To help you get started, we’ve selected a few psycopg examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github odoo / odoo / doc / migrate / 3.4.0-4.0.0 / post.py View on Github external
if not (hasattr(options, name) and getattr(options, name)):
            if value in ('true', 'True'):
                value = True
            if value in ('false', 'False'):
                value = False
            setattr(options, name, value)

# -----

host = hasattr(options, 'db_host') and "host=%s" % options.db_host or ''
port = hasattr(options, 'db_port') and "port=%s" % options.db_port or ''
name = "dbname=%s" % options.db_name
user = hasattr(options, 'db_user') and "user=%s" % options.db_user or ''
password = hasattr(options, 'db_password') and "password=%s" % options.db_password or ''

db = psycopg.connect('%s %s %s %s %s' % (host, port, name, user, password), serialize=0)
cr = db.cursor()

# ---------------------------------------------------------------- #
# move user id from hr_analytic_timesheet to account_analytic_line #
# ---------------------------------------------------------------- #

cr.execute("UPDATE account_analytic_line SET user_id = hr_analytic_timesheet.user_id FROM hr_analytic_timesheet WHERE hr_analytic_timesheet.line_id = account_analytic_line.id")
cr.commit()

# --------------- #
# remove old menu #
# --------------- #

while True:
    cr.execute("select id from ir_ui_menu where (id NOT IN (select parent_id from ir_ui_menu where parent_id is not null)) and (id NOT IN (select res_id from ir_values where model='ir.ui.menu'))")
    if not cr.rowcount:
github odoo / odoo / doc / migrate / 4.0.0-4.2.0 / tiny / pre-tiny.py View on Github external
value = True
            if value in ('false', 'False'):
                value = False
            setattr(options, name, value)

raise Exception('This script is provided as an example, you must custom it before')

# -----

host = hasattr(options, 'db_host') and "host=%s" % options.db_host or ''
port = hasattr(options, 'db_port') and "port=%s" % options.db_port or ''
name = "dbname=%s" % options.db_name
user = hasattr(options, 'db_user') and "user=%s" % options.db_user or ''
password = hasattr(options, 'db_password') and "password=%s" % options.db_password or ''

db = psycopg.connect('%s %s %s %s %s' % (host, port, name, user, password), serialize=0)
cr = db.cursor()

# fix country


cr.execute('SELECT code from res_country where code is not null group by code')
res = cr.fetchall()

for c in res:
    cr.execute('SELECT max(id) from res_country where code = %s group by code', (c[0],))
    res2 = cr.fetchone()
    cr.execute('SELECT id from res_country where code = %s', (c[0],))
    ids = ','.join(map(lambda x: str(x[0]), cr.fetchall()))
    cr.execute('UPDATE res_partner_address set country_id = %d where country_id in ('+ids+')', (res2[0],))
    cr.execute('DELETE FROM res_country WHERE code = %s and id <> %d', (c[0], res2[0],))
cr.commit()
github odoo / odoo / doc / migrate / 3.4.0-4.0.0 / post-tiny.py View on Github external
if not (hasattr(options, name) and getattr(options, name)):
            if value in ('true', 'True'):
                value = True
            if value in ('false', 'False'):
                value = False
            setattr(options, name, value)

# -----

host = hasattr(options, 'db_host') and "host=%s" % options.db_host or ''
port = hasattr(options, 'db_port') and "port=%s" % options.db_port or ''
name = "dbname=%s" % options.db_name
user = hasattr(options, 'db_user') and "user=%s" % options.db_user or ''
password = hasattr(options, 'db_password') and "password=%s" % options.db_password or ''

db = psycopg.connect('%s %s %s %s %s' % (host, port, name, user, password), serialize=0)
cr = db.cursor()

# --------------- #
# remove old menu #
# --------------- #

cr.execute("delete from ir_ui_menu where (id not in (select parent_id from ir_ui_menu where parent_id is not null)) and (id not in (select res_id from ir_values where model='ir.ui.menu'))")
cr.commit()

# --------------- #
# remove ir_value #
# --------------- #

cr.execute("delete from ir_values where model = 'ir.ui.menu' and res_id is null")
cr.commit()
github odoo / odoo / doc / migrate / 4.2.0-4.4.0 / pre.py View on Github external
if not (hasattr(options, name) and getattr(options, name)):
            if value in ('true', 'True'):
                value = True
            if value in ('false', 'False'):
                value = False
            setattr(options, name, value)

# -----

host = hasattr(options, 'db_host') and "host=%s" % options.db_host or ''
port = hasattr(options, 'db_port') and "port=%s" % options.db_port or ''
name = "dbname=%s" % options.db_name
user = hasattr(options, 'db_user') and "user=%s" % options.db_user or ''
password = hasattr(options, 'db_password') and "password=%s" % options.db_password or ''

db = psycopg.connect('%s %s %s %s %s' % (host, port, name, user, password), serialize=0)
cr = db.cursor()

# ------------------------------ #
# drop not null on ir_attachment #
# ------------------------------ #

cr.execute('ALTER TABLE ir_attachment \
        ALTER COLUMN res_model DROP NOT NULL, \
        ALTER COLUMN res_id DROP NOT NULL')
cr.commit()

# ---------------------------------- #
# change case date_deadline rounding #
# ---------------------------------- #

cr.execute("""SELECT
github joliebig / featurehouse / fstmerge / examples / SpamBayes / rev3103-3133 / base-trunk-3103 / spambayes / storage.py View on Github external
def load(self):
        '''Load state from database'''
        import psycopg
        if options["globals", "verbose"]:
            print >> sys.stderr, 'Loading state from',self.db_name,'database'
        self.db = psycopg.connect('dbname=' + self.db_name)
        c = self.cursor()
        try:
            c.execute("select count(*) from bayes")
        except psycopg.ProgrammingError:
            self.db.rollback()
            self.create_bayes()
        if self._has_key(self.statekey):
            row = self._get_row(self.statekey)
            self.nspam = row["nspam"]
            self.nham = row["nham"]
            if options["globals", "verbose"]:
                print >> sys.stderr, ('%s is an existing database,'
                                      ' with %d spam and %d ham') \
                      % (self.db_name, self.nspam, self.nham)
        else:
            if options["globals", "verbose"]:
github mandriva-management-console / mmc / core / agent / lmc / plugins / ox / __init__.py View on Github external
raise ConfigException("JAVA is not installed into %s" % self.javapath)
        if not os.path.exists(self.jarpath):
            raise ConfigException("Additional JAVA jar are not available into %s" % self.jarpath)
        if not os.path.exists(os.path.join(self.jarpath, "postgresql.jar")):
            raise ConfigException("postgresql.jar is not available into %s" % self.jarpath)
        # Verify if Open-Xchange LDAP schema is available in the directory
        try:
            ldapObj = ldapUserGroupControl()
        except ldap.INVALID_CREDENTIALS:
            raise ConfigException("Can't bind to LDAP: invalid credentials.")
        schema = ldapObj.getSchema("OXUserObject")
        if len(schema) <= 0:
            raise ConfigException("OX schema seems not be included into LDAP directory")
        # DB access check
        try:
            db = psycopg.connect("dbname=%s user=%s password=%s" % (self.oxdbname, self.oxdbuser, self.oxdbpassword))
        except psycopg.OperationalError, e:
            raise ConfigException("Can't connect to Open-Xchange database: " + str(e))
        db.close()
github joliebig / featurehouse / fstmerge / examples / SpamBayes / rev3103-3133 / right-branch-3133 / spambayes / storage.py View on Github external
def load(self):
        '''Load state from database'''
        import psycopg
        if options["globals", "verbose"]:
            print >> sys.stderr, 'Loading state from',self.db_name,'database'
        self.db = psycopg.connect('dbname=' + self.db_name)
        c = self.cursor()
        try:
            c.execute("select count(*) from bayes")
        except psycopg.ProgrammingError:
            self.db.rollback()
            self.create_bayes()
        if self._has_key(self.statekey):
            row = self._get_row(self.statekey)
            self.nspam = row["nspam"]
            self.nham = row["nham"]
            if options["globals", "verbose"]:
                print >> sys.stderr, ('%s is an existing database,'
                                      ' with %d spam and %d ham') \
                      % (self.db_name, self.nspam, self.nham)
        else:
            if options["globals", "verbose"]:
github odoo / odoo / doc / migrate / 4.0.0-4.2.0 / pre.py View on Github external
if not (hasattr(options, name) and getattr(options, name)):
            if value in ('true', 'True'):
                value = True
            if value in ('false', 'False'):
                value = False
            setattr(options, name, value)

# -----

host = hasattr(options, 'db_host') and "host=%s" % options.db_host or ''
port = hasattr(options, 'db_port') and "port=%s" % options.db_port or ''
name = "dbname=%s" % options.db_name
user = hasattr(options, 'db_user') and "user=%s" % options.db_user or ''
password = hasattr(options, 'db_password') and "password=%s" % options.db_password or ''

db = psycopg.connect('%s %s %s %s %s' % (host, port, name, user, password), serialize=0)
cr = db.cursor()

# ------------------------ #
# change currency rounding #
# ------------------------ #

cr.execute("""SELECT c.relname,a.attname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,t.typname,CASE WHEN a.attlen=-1 THEN a.atttypmod-4 ELSE a.attlen END as size FROM pg_class c,pg_attribute a,pg_type t WHERE c.relname='res_currency' AND a.attname='rounding' AND c.oid=a.attrelid AND a.atttypid=t.oid""")
res = cr.dictfetchall()
if res[0]['typname'] != 'numeric':
    for line in (
        "ALTER TABLE res_currency RENAME rounding TO rounding_bak",
        "ALTER TABLE res_currency ADD rounding NUMERIC(12,6)",
        "UPDATE res_currency SET rounding = power(10, - rounding_bak)",
        "ALTER TABLE res_currency DROP rounding_bak",
        ):
        cr.execute(line)
github odoo / odoo / doc / migrate / 3.4.0-4.0.0 / pre-tiny.py View on Github external
if not (hasattr(options, name) and getattr(options, name)):
            if value in ('true', 'True'):
                value = True
            if value in ('false', 'False'):
                value = False
            setattr(options, name, value)

# -----

host = hasattr(options, 'db_host') and "host=%s" % options.db_host or ''
port = hasattr(options, 'db_port') and "port=%s" % options.db_port or ''
name = "dbname=%s" % options.db_name
user = hasattr(options, 'db_user') and "user=%s" % options.db_user or ''
password = hasattr(options, 'db_password') and "password=%s" % options.db_password or ''

db = psycopg.connect('%s %s %s %s %s' % (host, port, name, user, password), serialize=0)
cr = db.cursor()

# ------------------------- #
# change some columns types #
# ------------------------- #

def change_column(cr, table, column, new_type, copy):
    commands = [
        "ALTER TABLE %s RENAME COLUMN %s TO temp_column" % (table, column),
        "ALTER TABLE %s ADD COLUMN %s %s" % (table, column, new_type),
        "ALTER TABLE %s DROP COLUMN temp_column" % table
    ]
    if copy:
        commands.insert(
            2, 
            "UPDATE %s SET %s=temp_column::%s" % (table, column, new_type))
github django / django / django / core / db / backends / postgresql.py View on Github external
def cursor(self):
        from django.conf.settings import DATABASE_USER, DATABASE_NAME, DATABASE_HOST, DATABASE_PORT, DATABASE_PASSWORD, DEBUG, TIME_ZONE
        if self.connection is None:
            if DATABASE_NAME == '':
                from django.core.exceptions import ImproperlyConfigured
                raise ImproperlyConfigured, "You need to specify DATABASE_NAME in your Django settings file."
            conn_string = "dbname=%s" % DATABASE_NAME
            if DATABASE_USER:
                conn_string = "user=%s %s" % (DATABASE_USER, conn_string)
            if DATABASE_PASSWORD:
                conn_string += " password='%s'" % DATABASE_PASSWORD
            if DATABASE_HOST:
                conn_string += " host=%s" % DATABASE_HOST
            if DATABASE_PORT:
                conn_string += " port=%s" % DATABASE_PORT
            self.connection = Database.connect(conn_string)
            self.connection.set_isolation_level(1) # make transactions transparent to all cursors
        cursor = self.connection.cursor()
        cursor.execute("SET TIME ZONE %s", [TIME_ZONE])
        if DEBUG:
            return base.CursorDebugWrapper(cursor, self)
        return cursor