sqlalchemy.exc.ProgrammingError

Here are the examples of the python api sqlalchemy.exc.ProgrammingError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

10 Examples 7

Example 1

Project: NOT_UPDATED_Sick-Beard-Dutch Source File: alchemyadapter.py
Function: drop_table
    def dropTable(self, checkfirst=True):
        """Drop the table."""
        dropParams = {'checkfirst': checkfirst}
        # Guess what?  Another work-around for a ibm_db bug.
        if self.table.bind.engine.url.drivername.startswith('ibm_db'):
            del dropParams['checkfirst']
        try:
            self.table.drop(**dropParams)
        except exc.ProgrammingError:
            # As above: re-raise the exception, but only if it's not ibm_db.
            if not self.table.bind.engine.url.drivername.startswith('ibm_db'):
                raise

Example 2

Project: sqlalchemy Source File: test_dialect.py
Function: test_autocommit_isolation_level
    @testing.requires.psycopg2_or_pg8000_compatibility
    @engines.close_open_connections
    def test_autocommit_isolation_level(self):
        c = testing.db.connect().execution_options(
            isolation_level='AUTOCOMMIT')
        # If we're really in autocommit mode then we'll get an error saying
        # that the prepared transaction doesn't exist. Otherwise, we'd
        # get an error saying that the command can't be run within a
        # transaction.
        assert_raises_message(
            exc.ProgrammingError,
            'prepared transaction with identifier "gilberte" does not exist',
            c.execute, "commit prepared 'gilberte'")

Example 3

Project: ibis Source File: test_functions.py
Function: test_union
    @pytest.mark.xfail(
        raises=sa.exc.ProgrammingError,
        reason='union not working yet'
    )
    def test_union(self):
        t = self.alltypes

        expr = (t.group_by('string_col')
                .aggregate(t.double_col.sum().name('foo'))
                .sort_by('string_col'))

        t1 = expr.limit(4)
        t2 = expr.limit(4, offset=4)
        t3 = expr.limit(8)

        result = t1.union(t2).execute()
        expected = t3.execute()

        assert (result.string_col == expected.string_col).all()

Example 4

Project: floof Source File: 016_UserArtwork_columns_need_not_be_nullable.py
Function: downgrade
def downgrade(migrate_engine):
    TableBase.metadata.bind = migrate_engine

    # Primary keys can't actually be NULLable in pg, so this will raise
    try:
        UserArtwork.__table__.c.user_id.alter(nullable=True)
        UserArtwork.__table__.c.artwork_id.alter(nullable=True)
        UserArtwork.__table__.c.relationship_type.alter(nullable=True)
    except sqlalchemy.exc.ProgrammingError:
        pass

Example 5

Project: pwnableweb Source File: models.py
Function: log_in_user
  @classmethod
  def login_user(cls, username, password):
    # Validate login, then get by username
    try:
      res = db.engine.execute("select username from " + cls.__tablename__ + 
          " where username='" + username + "' and pwhash='" +
          cls.hash_password(password) + "'")
    except exc.ProgrammingError:
      flask.flash('SQL Error in login.', 'danger')
      return None
    row = res.fetchone()
    if not row:
      return
    return cls.query.get(row[0])

Example 6

Project: kozmic-ci Source File: __init__.py
    def create_database(self, use_migrations=True):
        self.db.session = self.db.create_scoped_session({
            'scopefunc': get_scopefunc(),
        })

        self.db.session.execute('SET storage_engine=InnoDB;')
        if use_migrations:
            try:
                self.db.session.execute('TRUNCATE alembic_version;')
            except sqlalchemy.exc.ProgrammingError:
                self.db.session.rollback()
            config = Config('migrations/alembic.ini', 'alembic')
            alembic_upgrade(config, 'head')
        else:
            self.db.create_all()

Example 7

Project: gnocchi Source File: sqlalchemy.py
    @retry_on_deadlock
    def list_resources(self, resource_type='generic',
                       attribute_filter=None,
                       details=False,
                       history=False,
                       limit=None,
                       marker=None,
                       sorts=None):
        sorts = sorts or []

        with self.facade.independent_reader() as session:
            if history:
                target_cls = self._get_history_result_mapper(
                    session, resource_type)
            else:
                target_cls = self._resource_type_to_mappers(
                    session, resource_type)["resource"]

            q = session.query(target_cls)

            if attribute_filter:
                engine = session.connection()
                try:
                    f = QueryTransformer.build_filter(engine.dialect.name,
                                                      target_cls,
                                                      attribute_filter)
                except indexer.QueryAttributeError as e:
                    # NOTE(jd) The QueryAttributeError does not know about
                    # resource_type, so convert it
                    raise indexer.ResourceAttributeError(resource_type,
                                                         e.attribute)

                q = q.filter(f)

            sort_keys, sort_dirs = self._build_sort_keys(sorts)

            if marker:
                resource_marker = self.get_resource(resource_type, marker)
                if resource_marker is None:
                    raise indexer.InvalidPagination(
                        "Invalid marker: `%s'" % marker)
            else:
                resource_marker = None

            try:
                q = oslo_db_utils.paginate_query(q, target_cls, limit=limit,
                                                 sort_keys=sort_keys,
                                                 marker=resource_marker,
                                                 sort_dirs=sort_dirs)
            except ValueError as e:
                raise indexer.InvalidPagination(e)
            except exception.InvalidSortKey as e:
                raise indexer.InvalidPagination(e)

            # Always include metrics
            q = q.options(sqlalchemy.orm.joinedload("metrics"))
            all_resources = q.all()

            if details:
                grouped_by_type = itertools.groupby(
                    all_resources, lambda r: (r.revision != -1, r.type))
                all_resources = []
                for (is_history, type), resources in grouped_by_type:
                    if type == 'generic':
                        # No need for a second query
                        all_resources.extend(resources)
                    else:
                        try:
                            target_cls = self._resource_type_to_mappers(
                                session, type)['history' if is_history else
                                               'resource']
                        except (indexer.UnexpectedResourceTypeState,
                                indexer.NoSuchResourceType):
                            # NOTE(sileht): This resource_type have been
                            # removed in the meantime.
                            continue
                        if is_history:
                            f = target_cls.revision.in_([r.revision
                                                         for r in resources])
                        else:
                            f = target_cls.id.in_([r.id for r in resources])

                        q = session.query(target_cls).filter(f)
                        # Always include metrics
                        q = q.options(sqlalchemy.orm.joinedload('metrics'))
                        try:
                            all_resources.extend(q.all())
                        except sqlalchemy.exc.ProgrammingError as e:
                            # NOTE(jd) This exception can happen when the
                            # resources and their resource type have been
                            # deleted in the meantime:
                            #  sqlalchemy.exc.ProgrammingError:
                            #    (pymysql.err.ProgrammingError)
                            #    (1146, "Table \'test.rt_f00\' doesn\'t exist")
                            # In that case, just ignore those resources.
                            if (not pymysql
                               or not isinstance(
                                   e, sqlalchemy.exc.ProgrammingError)
                               or not isinstance(
                                   e.orig, pymysql.err.ProgrammingError)
                               or (e.orig.args[0]
                                   != pymysql.constants.ER.NO_SUCH_TABLE)):
                                raise

            return all_resources

Example 8

Project: sqlalchemy Source File: test_on_conflict.py
    def test_on_conflict_do_update_exotic_targets_five(self):
        users = self.tables.users_xtra

        with testing.db.connect() as conn:
            self._exotic_targets_fixture(conn)
            # try bogus index
            i = insert(users)
            i = i.on_conflict_do_update(
                index_elements=self.bogus_index.columns,
                index_where=self.
                bogus_index.dialect_options['postgresql']['where'],
                set_=dict(
                    name=i.excluded.name,
                    login_email=i.excluded.login_email)
            )

            assert_raises(
                exc.ProgrammingError, conn.execute, i,
                dict(
                    id=1, name='namebogus', login_email='[email protected]',
                    lets_index_this='bogus')
            )

Example 9

Project: catsnap Source File: __init__.py
Function: teardown_package
def tearDownPackage():
    terminate_query = """
        select pg_terminate_backend( %(pid_column)s )
        from pg_stat_activity
        where datname = '%(db_name)s'
    """
    try:
        db_info['master_engine'].execute(terminate_query % {
            'pid_column': 'procpid',
            'db_name': db_info['temp_db_name'],
        })
    except sqlalchemy.exc.ProgrammingError as e:
        if '"procpid" does not exist' in str(e):
            #postgres 9.2 changed pg_stat_activity.procpid to just .pid
            db_info['master_engine'].execute(terminate_query % {
                'pid_column': 'pid',
                'db_name': db_info['temp_db_name'],
            })
        else:
            raise
    drop_temp_database()

Example 10

Project: socorro Source File: postgresqlalchemymanager.py
Function: create_roles
    @ignore_if_on_heroku
    def create_roles(self, config):
        """
            This function creates two roles: breakpad_ro, breakpad_rw

            Then it creates roles defined in the config:
                config.read_write_users
                config.read_only_users

            Which all inherit from the two base roles.
        """
        self.logger.debug('creating roles from config')
        roles = []
        roles.append("""
            CREATE ROLE breakpad_ro WITH NOSUPERUSER
                INHERIT NOCREATEROLE NOCREATEDB LOGIN
        """)
        roles.append("""
            CREATE ROLE breakpad_rw WITH NOSUPERUSER
                INHERIT NOCREATEROLE NOCREATEDB LOGIN
        """)

        # Now create everything that inherits from those
        for rw in config.read_write_users.split(','):
            roles.append("CREATE ROLE %s IN ROLE breakpad_rw" % rw)
            # Set default password per old roles.sql
            roles.append("ALTER ROLE %s WITH PASSWORD '%s'" %
                         (rw, config.default_password))

        for ro in config.read_only_users.split(','):
            roles.append("CREATE ROLE %s IN ROLE breakpad_ro" % ro)
            # Set default password per old roles.sql
            roles.append("ALTER ROLE %s WITH PASSWORD '%s'" %
                         (rw, config.default_password))

        for r in roles:
            try:
                self.session.begin_nested()
                self.session.execute(r)
                self.session.commit()
            except exc.ProgrammingError, e:
                if 'already exists' not in e.orig.pgerror.strip():
                    raise
                self.session.rollback()
                continue
            except exc.DatabaseError, e:
                raise

        # Need to close the outer transaction
        self.session.commit()