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
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
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'} )
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
def test_multiple_classes_with_bogus_data(self): with raises(ValueError): assert get_class_by_table( self.Base, self.Entity.__table__, {'type': 'unknown'} )
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()
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
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)
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
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
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
def test_multiple_classes_with_bogus_data(self): with raises(ValueError): assert get_class_by_table(self.Base, self.Entity.__table__, {'type': 'unknown'})
def test_multiple_classes_without_data_parameter(self): with raises(ValueError): assert get_class_by_table( self.Base, self.Entity.__table__ )
def test_multiple_classes_without_data_parameter(self): with raises(ValueError): assert get_class_by_table(self.Base, self.Entity.__table__)
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
def object(self): table = Base.metadata.tables[self.table_name] cls = get_class_by_table(Base, table, self.data) return cls(**self.data)
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
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
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
def test_multiple_classes_without_data_parameter(self, Base, Entity, User): with pytest.raises(ValueError): assert get_class_by_table( Base, Entity.__table__ )
def test_multiple_classes_without_data_parameter(self, Base, Entity, User): with pytest.raises(ValueError): assert get_class_by_table(Base, Entity.__table__)
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)
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'})
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
def object(self): table = base.metadata.tables[self.table_name] cls = get_class_by_table(base, table, self.data) return cls(**self.data)
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