Skip to content

Working on new feature - don't run up() method on already executed mi… #2

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,19 @@ class Mongration(Database):
super(Database, self).__init__()

def up(self):
collection = self.db['members']
collection = self.db['moderators']
data = {
'accountId': 1,
'username': 'admin',
'email': 'admin@able.digital',
'firstName': 'Site',
'lastName': 'Owner'
'username': 'bot',
'email': 'bot@able.digital',
'firstName': 'Moderator',
'lastName': 'Bot'
}
collection.insert_one(data)

def down(self):
collection = self.db['members']
collection.delete_one({'username': 'admin'})
collection = self.db['moderators']
collection.delete_one({'username': 'bot'})


Mongrations(Mongration)
Expand Down
11 changes: 10 additions & 1 deletion mongrations/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ def _initial_write(self):
"createdAt": "",
"updatedAt": "",
"lastMigration": "",
"migrations": []
"migrations": [],
"executed": []
}
self._write_file_obj(data)

Expand Down Expand Up @@ -121,6 +122,7 @@ def undo_migration(self, remove_migration: bool = False):
cache = self._get_file_object()
if remove_migration:
cache['migrations'] = cache['migrations'][:-1]
cache['executed'].remove(cache['migrations'][-1])
self._write_file_obj(cache)
return cache['lastMigration']
except FileNotFoundError:
Expand Down Expand Up @@ -155,3 +157,10 @@ def create_migration_file(self):
with open(self._mongration_file, mode='r', encoding='utf-8') as open_mf:
data = json.load(open_mf)
mf.write(json.dumps(data, indent=2))

def has_executed(self, filepath):
cache = self._get_file_object()
if filepath in cache['executed']:
return True
return False

7 changes: 7 additions & 0 deletions mongrations/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ def undo():
if value.lower() == 'y':
main.undo()

@cli.command()
@click.argument('filename', nargs=1)
def down(filename):
"""Run the down() method on a specified migration file"""
main.down(last_migration_only=False, specific_file=filename)



@cli.command()
def inspect():
Expand Down
25 changes: 22 additions & 3 deletions mongrations/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@ def __init__(self):
self._cache = Cache()
self._cache._set_file_path()

@staticmethod
def _command_line_interface(migrations: list, state: str):
def _command_line_interface(self, migrations: list, state: str):
sucessful_runs =[]
success = True
if len(migrations) == 0:
print('No migrations to run.')
sys.exit(100)
print(f'{state.upper()}: Running {len(migrations)} migration{"" if len(migrations) <= 1 else "s"}...')
for migration in migrations:
migration_file_path = join(getcwd(), migration)
if self._cache.has_executed(migration_file_path):
print("Already ran migration.")
continue
command = shlex.split(f'python3 {migration_file_path}')
proc = subprocess.Popen(command, stdout=subprocess.PIPE, env=environ.copy())
for line in io.TextIOWrapper(proc.stdout, encoding='utf8', newline=''):
Expand All @@ -30,12 +33,28 @@ def _command_line_interface(migrations: list, state: str):
print(line)
if success is False:
break
if len(sucessful_runs) > 0:
config_file = self._cache._get_file_object()
new_data = config_file['executed']
new_data.extend(sucessful_runs)
self._cache._write_file_obj(new_data)
if success:
print('Migrations complete.')

def down(self, last_migration_only=False):
def down(self, last_migration_only=False, specific_file=None):
specific_file_found = False
environ['MIGRATION_MIGRATE_STATE'] = 'DOWN'
migrations = self._cache.migrations_file_list(last_migration=last_migration_only)
if specific_file is not None:
for migration in migrations:
name = basename(migration).replace('.py', '')
if name == specific_file.replace('.py', ''):
migrations = [migration]
specific_file_found = True
break
if not specific_file_found:
print(f'File not found: {specific_file}')
sys.exit(86)
self._command_line_interface(migrations, 'down')

def migrate(self):
Expand Down
2 changes: 1 addition & 1 deletion mongrations/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '1.1.1'
__version__ = '1.1.2'