Skip to content
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

Add the delete_missing_records option. #47

Merged
merged 5 commits into from
May 23, 2018
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Byte-compiled / optimized / DLL files
__pycache__/
.pytest_cache/
*.py[cod]
*$py.class
.venv/
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ This document describes changes between each past release.

- Add a ``--dry-run`` for the load command to see how many records
would be deleted. (#46)
- Add a ``--delete-record`` to remove existing records in the
collections we are importing. (#47)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something like To delete the existing records that are not in the YAML file would be better maybe ?



2.3.0 (2017-10-04)
Expand Down
6 changes: 5 additions & 1 deletion kinto_wizard/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ def main():
subparser.add_argument('--dry-run',
help="Do not apply write call to the server",
action='store_true')
subparser.add_argument('--delete-records',
help='Delete records that are not in the file.',
action='store_true')

# dump sub-command.
subparser = subparsers.add_parser('dump')
Expand Down Expand Up @@ -91,6 +94,7 @@ def main():
config,
bucket=args.bucket,
collection=args.collection,
force=args.force
force=args.force,
delete_missing_records=args.delete_records
)
)
27 changes: 24 additions & 3 deletions kinto_wizard/yaml2kinto.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@
from .kinto2yaml import introspect_server


async def initialize_server(async_client, config, bucket=None, collection=None, force=False):
async def initialize_server(async_client, config, bucket=None, collection=None,
force=False, delete_missing_records=False):
logger.debug("Converting YAML config into a server batch.")
bid = bucket
cid = collection
# 1. Introspect current server state.
if not force:
if not force or delete_missing_records:
current_server_status = await introspect_server(
async_client,
bucket=bucket,
collection=collection
collection=collection,
records=delete_missing_records
)
else:
# We don't need to load it because we will override it nevertheless.
Expand Down Expand Up @@ -143,5 +145,24 @@ async def initialize_server(async_client, config, bucket=None, collection=None,
data=record_data,
permissions=record_permissions)

if delete_missing_records and collection_records:
# Fetch all records IDs
file_records_ids = set(collection_records.keys())
server_records_ids = set(current_collection['records'].keys())

to_delete = server_records_ids - file_records_ids
if not force:
message = ("Are you sure that you want to delete the "
"following {} records?".format(len(list(to_delete))))
value = input(message)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't remember but we may have an option to always accept prompts, no?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We currently don't have any prompts. We might want to add a -y --yes option though.

print(to_delete)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we want this print?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I figured it would give extra information about the records that are going to be deleted. But I could do it only in verbose mode maybe?

if value.lower() not in ['y', 'yes']:
print("Exiting")
exit(1)
for record_id in to_delete:
batch.delete_record(id=record_id,
bucket=bucket_id,
collection=collection_id)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice if we could generalize it to bucket/collections/groups

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For groups it might make sense, but for buckets and collections I would rather not trust kinto-wizard for such a dangerous task 😂

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have created #48 for that purpose. I believe we might need specifics option for each --delete-records --delete-groups --delete-collections etc.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would rather not trust kinto-wizard for such a dangerous task joy

Why would be buckets so different? If we prompt, I don't see the problem...


logger.debug('Sending batch:\n\n%s' % batch.session.requests)
logger.info("Batch uploaded")
79 changes: 78 additions & 1 deletion tests/test_functional.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import builtins
import io
import os
import pytest
import unittest
import sys
from contextlib import redirect_stdout
from contextlib import contextmanager, redirect_stdout

import requests

Expand All @@ -29,6 +30,14 @@ def test_dry_round_trip(self):
client.get_bucket(id="staging")


@contextmanager
def mockInput(mock):
original_input = builtins.input
builtins.input = lambda _: mock
yield
builtins.input = original_input


class SimpleDump(unittest.TestCase):
def setUp(self):
self.server = os.getenv("SERVER_URL", "http://localhost:8888/v1")
Expand Down Expand Up @@ -108,6 +117,74 @@ def test_round_trip_with_client_wins(self):
id='0831d549-0a69-48dd-b240-feef94688d47')
assert set(record['data'].keys()) != {'id', 'last_modified'}

def test_round_trip_with_client_wins_and_delete_missing_records(self):
# Load some data
cmd = 'kinto-wizard {} --server={} --auth={}'
load_cmd = cmd.format("load {}".format(self.file),
self.server, self.auth)
sys.argv = load_cmd.split(" ")
main()

# Change something that could make the server to fail.
client = Client(server_url=self.server, auth=tuple(self.auth.split(':')))
client.create_record(bucket='build-hub', collection='archives',
id='8031d549-0a69-48dd-b240-feef94688d47', data={})
cmd = 'kinto-wizard {} --server={} -D --auth={} --force --delete-records'
load_cmd = cmd.format("load {}".format(self.file),
self.server, self.auth)
sys.argv = load_cmd.split(" ")
main()
with pytest.raises(exceptions.KintoException) as exc:
client.get_record(bucket='build-hub', collection='archives',
id='8031d549-0a69-48dd-b240-feef94688d47')
assert "'Not Found'" in str(exc.value)

def test_round_trip_with_delete_missing_records_ask_for_confirmation(self):
# Load some data
cmd = 'kinto-wizard {} --server={} --auth={}'
load_cmd = cmd.format("load {}".format(self.file),
self.server, self.auth)
sys.argv = load_cmd.split(" ")
main()

# Change something that could make the server to fail.
client = Client(server_url=self.server, auth=tuple(self.auth.split(':')))
client.create_record(bucket='build-hub', collection='archives',
id='8031d549-0a69-48dd-b240-feef94688d47', data={})
cmd = 'kinto-wizard {} --server={} -D --auth={} --delete-records'
load_cmd = cmd.format("load {}".format(self.file),
self.server, self.auth)
sys.argv = load_cmd.split(" ")

with mockInput('yes'):
main()

with pytest.raises(exceptions.KintoException) as exc:
client.get_record(bucket='build-hub', collection='archives',
id='8031d549-0a69-48dd-b240-feef94688d47')
assert "'Not Found'" in str(exc.value)

def test_round_trip_with_delete_missing_records_handle_misconfirmation(self):
# Load some data
cmd = 'kinto-wizard {} --server={} --auth={}'
load_cmd = cmd.format("load {}".format(self.file),
self.server, self.auth)
sys.argv = load_cmd.split(" ")
main()

# Change something that could make the server to fail.
client = Client(server_url=self.server, auth=tuple(self.auth.split(':')))
client.create_record(bucket='build-hub', collection='archives',
id='8031d549-0a69-48dd-b240-feef94688d47', data={})
cmd = 'kinto-wizard {} --server={} -D --auth={} --delete-records'
load_cmd = cmd.format("load {}".format(self.file),
self.server, self.auth)
sys.argv = load_cmd.split(" ")

with mockInput('no'):
with pytest.raises(SystemExit):
main()


class DataRecordsDump(unittest.TestCase):
def setUp(self):
Expand Down