Repository: speedyturkey/porthole

Issue:
Raise Error if QueryResult contains duplicate keys
QueryResult will have unexpected behavior if the query has returned a result with duplicate keys (blank columns written to Excel, etc.)

The query should raise an error at some stage so that the user is forced to fix this.

Discussion:

Patch:
diff --git a/porthole/queries.py b/porthole/queries.py
index 3dfded4..943dc0f 100644
--- a/porthole/queries.py
+++ b/porthole/queries.py
@@ -59,6 +59,8 @@ class RowDict(OrderedDict):
     def __init__(self, data=None, fields=None, values=None):
         fields_and_values_provided = fields is not None and values is not None
         if fields_and_values_provided is True and data is None:
+            if len(fields) > len(set(fields)):
+                raise ValueError("Field names must be unique, but your result set contains non-unique field names.")
             data = OrderedDict(zip(fields, values))
         else:
             data = data or OrderedDict()


Test patch:
diff --git a/tests/test_Queries.py b/tests/test_Queries.py
index 8ae1be1..f65c4c0 100644
--- a/tests/test_Queries.py
+++ b/tests/test_Queries.py
@@ -104,6 +104,18 @@ class TestRowDict(unittest.TestCase):
         self.assertIn('Bar', test_row.values())
         self.assertEqual(headers + ['Foo'], list(test_row.keys()))
 
+    def test_unique_field_name_constraint(self):
+        with self.assertRaises(ValueError):
+            RowDict(
+                fields=['A', 'A'],
+                values=[[1, 2]]
+            )
+        with self.assertRaises(ValueError):
+            RowDict(
+                fields=['A', 'B', 'A'],
+                values=[[1, 2, 3]]
+            )
+
 
 headers = ['Name', 'DOB']
 row1 = ['Billy', date(1988, 4, 24)]