- 
                Notifications
    
You must be signed in to change notification settings  - Fork 4
 
Feature/add table support #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
acac07c
              2d86448
              b49ba59
              5a903b5
              372ef2b
              ce7cc5f
              8e908ff
              File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | 
|---|---|---|
| 
          
            
          
           | 
    @@ -14,6 +14,8 @@ | |
| import os | ||
| 
     | 
||
| import yaml | ||
| from sqlalchemy import MetaData | ||
| 
     | 
||
| try: | ||
| from yaml import CLoader as Loader | ||
| except ImportError: | ||
| 
          
            
          
           | 
    @@ -90,6 +92,22 @@ def _create_model_instance(fixture): | |
| return instances | ||
| 
     | 
||
| 
     | 
||
| def _create_table_object_data(fixture, session): | ||
| """Create a Table object entry. | ||
| 
     | 
||
| :param fixture: Fixtures | ||
| """ | ||
| for data in fixture: | ||
| if 'table' in data: | ||
| module_name, class_name = data['table'].rsplit('.', 1) | ||
| importlib.import_module(module_name) | ||
| metadata = MetaData() | ||
| metadata.reflect(bind=session.get_bind()) | ||
| table = metadata.tables[class_name] | ||
| insert = table.insert() | ||
| session.execute(insert.values(**data['fields'])) | ||
| 
         There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not familier with  What about do something like followings? def _create_table_object_data(fixture, session):
    """Create a Table object entry.
    :param fixture: Fixtures
    :param session: Session
    """
    table_values = []
    for data in fixture:
        if 'table' in data:
            module_name, class_name = data['table'].rsplit('.', 1)
            importlib.import_module(module_name)
            metadata = MetaData()
            metadata.reflect(bind=session.get_bind())
            table = metadata.tables[class_name]
            insert = table.insert()
            insert.values(**data['fields'])
            table_values.append(insert)
    return table_values
def load_fixtures(session, fixtures):
    """Load fixture.
    :param base: `sqlalchemy.ext.declarative`
    :param fixtures: Fixture files
    """
    instances = []
    tables = []
    for fixture in fixtures:
        _instances = _create_model_instance(fixture)
        for instance in _instances:
            instances.append(instance)
        _tables = _create_table_object_data(fixture, session)
        for table in _tables:
            tables.append(table)
    try:
        for instance in instances:
            session.merge(instance)
        for table in tables:
            session.execute(table)
        session.flush()
        session.commit()
    except Exception:
        session.rollback()
        raiseThere was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nn- I think I wrote something strange? 🤔  | 
||
| 
     | 
||
| 
     | 
||
| def load_fixtures(session, fixtures): | ||
| """Load fixture. | ||
| 
     | 
||
| 
        
          
        
         | 
    @@ -99,6 +117,7 @@ def load_fixtures(session, fixtures): | |
| instances = [] | ||
| for fixture in fixtures: | ||
| _instances = _create_model_instance(fixture) | ||
| _create_table_object_data(fixture, session) | ||
| for instance in _instances: | ||
| instances.append(instance) | ||
| 
     | 
||
| 
          
            
          
           | 
    ||
| Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| - model: tests.test_sqlalchey_seed.PictureCategory | ||
| id: 1 | ||
| fields: | ||
| name: Category1 | ||
| - model: tests.test_sqlalchey_seed.PictureCategory | ||
| id: 2 | ||
| fields: | ||
| name: Category2 | ||
| 
     | 
| Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| - table: tests.test_sqlalchey_seed.picture_category_picture | ||
| 
         There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🙆♂  | 
||
| id: 1 | ||
| fields: | ||
| picture_id: 1 | ||
| picture_category_id: 1 | ||
| 
     | 
||
| - table: tests.test_sqlalchey_seed.picture_category_picture | ||
| id: 2 | ||
| fields: | ||
| picture_id: 1 | ||
| picture_category_id: 2 | ||
| 
     | 
||
| Original file line number | Diff line number | Diff line change | 
|---|---|---|
| 
          
            
          
           | 
    @@ -13,7 +13,7 @@ | |
| import os | ||
| from unittest import TestCase | ||
| 
     | 
||
| from sqlalchemy import Column, create_engine, ForeignKey, Integer, String | ||
| from sqlalchemy import Column, create_engine, ForeignKey, Integer, String, Table | ||
| from sqlalchemy.exc import OperationalError | ||
| from sqlalchemy.ext.declarative import declarative_base | ||
| from sqlalchemy.orm import relationship, scoped_session, sessionmaker | ||
| 
          
            
          
           | 
    @@ -75,6 +75,28 @@ def __repr__(self): | |
| ) | ||
| 
     | 
||
| 
     | 
||
| class PictureCategory(Base): | ||
| __tablename__ = 'picture_category' | ||
| 
     | 
||
| id = Column(Integer, primary_key=True) | ||
| name = Column(String(120)) | ||
| 
     | 
||
| def __repr__(self): | ||
| """Repr.""" | ||
| return 'PictureCategory(id={0}, name={1})'.format( | ||
| self.id, | ||
| self.name, | ||
| ) | ||
| 
     | 
||
| 
     | 
||
| picture_category_picture = Table( | ||
| 'picture_category_picture', | ||
| Base.metadata, | ||
| Column('picture_id', Integer, ForeignKey('pictures.id')), | ||
| Column('picture_category_id', Integer, ForeignKey('picture_category.id')), | ||
| ) | ||
| 
     | 
||
| 
     | 
||
| class TestFixtures(TestCase): | ||
| path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures') | ||
| 
     | 
||
| 
          
            
          
           | 
    @@ -105,13 +127,17 @@ def test_load_fixture(self): | |
| def test_load_fixtures(self): | ||
| create_table(Base) | ||
| fixtures = load_fixture_files( | ||
| self.path, ['accounts.yaml', 'pictures.yaml'], | ||
| self.path, ['accounts.yaml', 'pictures.yaml', 'picture_categories.yaml', 'picture_category_picture.yaml'], | ||
| 
         There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please add new test case, such as   | 
||
| ) | ||
| load_fixtures(session, fixtures) | ||
| accounts = session.query(Account).all() | ||
| self.assertEqual(len(accounts), 2) | ||
| pictures = session.query(Picture).all() | ||
| self.assertEqual(len(pictures), 4) | ||
| picture_categories = session.query(PictureCategory).all() | ||
| self.assertEqual(len(picture_categories), 2) | ||
| category_rels = session.query(picture_category_picture).all() | ||
| self.assertEqual(len(category_rels), 2) | ||
| 
     | 
||
| drop_table(Base, session) | ||
| 
     | 
||
| 
          
            
          
           | 
    ||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please add
sessionto docstringparam😉