コード例 #1
0
 def test_multiple_classes_with_data_parameter(self):
     assert get_class_by_table(
         self.Base,
         self.Entity.__table__,
         {'type': 'entity'}
     ) == self.Entity
     assert get_class_by_table(
         self.Base,
         self.Entity.__table__,
         {'type': 'user'}
     ) == self.User
コード例 #2
0
 def test_multiple_classes_with_data_parameter(self, Base, Entity, User):
     assert get_class_by_table(
         Base,
         Entity.__table__,
         {'type': 'entity'}
     ) == Entity
     assert get_class_by_table(
         Base,
         Entity.__table__,
         {'type': 'user'}
     ) == User
コード例 #3
0
 def test_multiple_classes_with_bogus_data(self, Base, Entity, User):
     with pytest.raises(ValueError):
         assert get_class_by_table(
             Base,
             Entity.__table__,
             {'type': 'unknown'}
         )
コード例 #4
0
 def test_table_with_no_associated_class(self):
     table = sa.Table(
         'some_table',
         self.Base.metadata,
         sa.Column('id', sa.Integer)
     )
     assert get_class_by_table(self.Base, table) is None
コード例 #5
0
 def test_multiple_classes_with_bogus_data(self):
     with raises(ValueError):
         assert get_class_by_table(
             self.Base,
             self.Entity.__table__,
             {'type': 'unknown'}
         )
コード例 #6
0
ファイル: converters.py プロジェクト: Encrylize/MyDictionary
 def to_python(self, value):
     try:
         word_class = get_class_by_table(
             Word, Word.__table__, data={'type': value})
         return word_class
     except ValueError:
         raise ValidationError()
コード例 #7
0
def import_db(archive_path_or_buf):
    """DESTROY THE OLD DATABASE and import all of the tables in an archive as
    prepared by `export_db()`."""

    app.db.create_all()

    connection = app.db.engine.connect()
    transaction = connection.begin()

    # Open the in-memory zip file.
    with zipfile.ZipFile(archive_path_or_buf, 'r') as archive:
        # For each table in the database, check if there is a CSV file
        # associated.
        for table in app.db.metadata.sorted_tables:
            table_name = "{}.csv".format(table.name)
            try:
                with archive.open(table_name, 'r') as table_buf:
                    app.logger.debug("Opened %r for import", table_name)
                    table_buf_str = io.TextIOWrapper(table_buf, encoding='utf-8')
                    table_reader = csv.DictReader(table_buf_str,
                                                  fieldnames=[c.name for c in table.columns])


                    # Some tables need special treatment, and cannot dump the
                    # rows directly back into the database. If so, the model
                    # will have `transform_csv_row` as a classmethod.
                    model = sqlalchemy_utils.get_class_by_table(app.db.Model, table)
                    if hasattr(model, 'transform_csv_row'):
                        app.logger.debug("Using row transformer from model %r for %s",
                                         model, table.name)
                        transform = model.transform_csv_row
                    else:
                        # No-op
                        transform = lambda row: row

                    app.logger.warning("Deleting all rows of %s", table.name)
                    connection.execute(table.delete())

                    for row in table_reader:
                        app.logger.debug("Importing row into %s: %r", table.name, row)
                        row = transform(row)
                        connection.execute(table.insert(values=row))
            except:
                transaction.rollback()
                raise

    transaction.commit()
    return
コード例 #8
0
ファイル: main.py プロジェクト: Encrylize/MyDictionary
def edit_word(id):
    word = Word.query.filter_by(id=id, dictionary=current_user.dictionary).first_or_404()
    form = word.form(obj=word)

    if form.validate_on_submit():
        new_word = get_class_by_table(Word,
                                      Word.__table__,
                                      data={'type': word.type}).query.filter_by(
                                          **{key: value
                                             for key, value in form.data.items() if key != 'next'}).first()
        if new_word is None:
            form.populate_obj(word)
            word.save()
            flash('Successfully edited word!', 'success')
            return form.redirect('index')
        else:
            flash('An identical word already exists.', 'error')

    return render_template('form.html', title='Edit Word', form=form)
コード例 #9
0
    def get_columns_for_table(self, table):
        """
        Function that fetches the details about the columns of a particular
        table
        """
        metadata = MetaData(bind=self.engine, reflect=True)
        Base = automap_base(metadata=metadata)
        Base.prepare()
        relations = Table(table, metadata)
        cl = get_class_by_table(Base, relations)

        table_props = {}
        columns = self.inspector.get_columns(table)
        fks = self.inspector.get_foreign_keys(table)
        all_columns = {}
        for column in columns:
            col_name = column['name']
            column_props = {
                'data_type': column['type'],
                'is_primary_key': bool(column['primary_key'])
            }
            column_props = self.fetch_fks(table, column_props, fks, col_name)
            all_columns[col_name] = column_props
        """
        This part fetches the type of relations
        ____ISSUE: Not able to find out any relation other
        ____that ManyToOne and OneToMany
        """
        try:
            for relation in cl.__mapper__.relationships:
                column_props['relationship_info'] = {
                    'type': str(relation.direction)
                }
        except Exception:
            pass


# code not working for relations other than manytoone and onetomany
        table_props['columns'] = all_columns
        return table_props
コード例 #10
0
 def test_returns_class(self, Base, User, Entity):
     assert get_class_by_table(Base, User.__table__) == User
     assert get_class_by_table(Base, Entity.__table__) == Entity
コード例 #11
0
 def test_multiple_classes_with_data_parameter(self):
     assert get_class_by_table(self.Base, self.Entity.__table__,
                               {'type': 'entity'}) == self.Entity
     assert get_class_by_table(self.Base, self.Entity.__table__,
                               {'type': 'user'}) == self.User
コード例 #12
0
 def test_multiple_classes_with_bogus_data(self):
     with raises(ValueError):
         assert get_class_by_table(self.Base, self.Entity.__table__,
                                   {'type': 'unknown'})
コード例 #13
0
 def test_multiple_classes_without_data_parameter(self):
     with raises(ValueError):
         assert get_class_by_table(
             self.Base,
             self.Entity.__table__
         )
コード例 #14
0
 def test_multiple_classes_without_data_parameter(self):
     with raises(ValueError):
         assert get_class_by_table(self.Base, self.Entity.__table__)
コード例 #15
0
 def test_returns_class(self, Base, User, Entity):
     assert get_class_by_table(Base, User.__table__) == User
     assert get_class_by_table(
         Base,
         Entity.__table__
     ) == Entity
コード例 #16
0
 def object(self):
     table = Base.metadata.tables[self.table_name]
     cls = get_class_by_table(Base, table, self.data)
     return cls(**self.data)
コード例 #17
0
 def test_multiple_classes_with_data_parameter(self, Base, Entity, User):
     assert get_class_by_table(Base, Entity.__table__,
                               {'type': 'entity'}) == Entity
     assert get_class_by_table(Base, Entity.__table__,
                               {'type': 'user'}) == User
コード例 #18
0
 def test_table_with_no_associated_class(self, Base):
     table = sa.Table('some_table', Base.metadata,
                      sa.Column('id', sa.Integer))
     assert get_class_by_table(Base, table) is None
コード例 #19
0
ファイル: util.py プロジェクト: carlosmontoya89/finance
def get_model_class_by_tablename(table):
    mclass = sqlalchemy_utils.get_class_by_table(db.Model,
                                                 get_tableobj_by_name(table))
    if not mclass:
        raise ValueError("Can't find model class for table name %s" % table)
    return mclass
コード例 #20
0
 def test_multiple_classes_without_data_parameter(self, Base, Entity, User):
     with pytest.raises(ValueError):
         assert get_class_by_table(
             Base,
             Entity.__table__
         )
コード例 #21
0
 def test_multiple_classes_without_data_parameter(self, Base, Entity, User):
     with pytest.raises(ValueError):
         assert get_class_by_table(Base, Entity.__table__)
コード例 #22
0
from sqlalchemy_utils import get_class_by_table
from sqlalchemy import Boolean, Column, DECIMAL, DateTime, Float, ForeignKey, Integer, LargeBinary, String, UniqueConstraint
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
""" IGNORE - internal testing """


class User(Base):
    __tablename__ = 'entity'
    id = Column(Integer, primary_key=True)
    name = Column(String)


cls = get_class_by_table(Base, User.__table__)  # User class given table entity
print(cls)
コード例 #23
0
 def test_multiple_classes_with_bogus_data(self, Base, Entity, User):
     with pytest.raises(ValueError):
         assert get_class_by_table(Base, Entity.__table__,
                                   {'type': 'unknown'})
コード例 #24
0
 def test_returns_class(self):
     assert get_class_by_table(self.Base, self.User.__table__) == self.User
     assert get_class_by_table(
         self.Base,
         self.Entity.__table__
     ) == self.Entity
コード例 #25
0
ファイル: base.py プロジェクト: modlinltd/postgresql-audit
 def object(self):
     table = base.metadata.tables[self.table_name]
     cls = get_class_by_table(base, table, self.data)
     return cls(**self.data)
コード例 #26
0
 def test_returns_class(self):
     assert get_class_by_table(self.Base, self.User.__table__) == self.User
     assert get_class_by_table(self.Base,
                               self.Entity.__table__) == self.Entity