Skip to content

Commit 97be203

Browse files
committed
Avoid "not master" error from update or remove with lazy-connecting MongoClient, PYTHON-653.
1 parent 4f23057 commit 97be203

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

pymongo/collection.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,10 @@ def update(self, spec, document, upsert=False, manipulate=False,
511511
if not isinstance(upsert, bool):
512512
raise TypeError("upsert must be an instance of bool")
513513

514+
client = self.database.connection
515+
# Need to connect to know the wire version, and may want to connect
516+
# before applying SON manipulators.
517+
client._ensure_connected(True)
514518
if manipulate:
515519
document = self.__database._fix_incoming(document, self)
516520

@@ -526,7 +530,6 @@ def update(self, spec, document, upsert=False, manipulate=False,
526530
if first.startswith('$'):
527531
check_keys = False
528532

529-
client = self.database.connection
530533
if client.max_wire_version > 1 and safe:
531534
# Update command
532535
command = SON([('update', self.name)])
@@ -642,6 +645,9 @@ def remove(self, spec_or_id=None, safe=None, multi=True, **kwargs):
642645
safe, options = self._get_write_mode(safe, **kwargs)
643646

644647
client = self.database.connection
648+
649+
# Need to connect to know the wire version.
650+
client._ensure_connected(True)
645651
if client.max_wire_version > 1 and safe:
646652
# Delete command
647653
command = SON([('delete', self.name)])

pymongo/mongo_client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1097,11 +1097,11 @@ def _send_message(self, message,
10971097
- `check_primary`: don't try to write to a non-primary; see
10981098
kill_cursors for an exception to this rule
10991099
"""
1100+
member = self.__ensure_member()
11001101
if check_primary and not with_last_error and not self.is_primary:
11011102
# The write won't succeed, bail as if we'd done a getLastError
11021103
raise AutoReconnect("not master")
11031104

1104-
member = self.__ensure_member()
11051105
sock_info = self.__socket(member)
11061106
try:
11071107
try:

test/test_client.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -980,6 +980,16 @@ def test_replica_set(self):
980980
ConfigurationError,
981981
MongoClient, host, port, replicaSet='bad' + name)
982982

983+
def test_lazy_connect_w0(self):
984+
client = get_client(_connect=False)
985+
client.pymongo_test.test.insert({}, w=0)
986+
987+
client = get_client(_connect=False)
988+
client.pymongo_test.test.update({}, {'$set': {'x': 1}}, w=0)
989+
990+
client = get_client(_connect=False)
991+
client.pymongo_test.test.remove(w=0)
992+
983993

984994
class TestClientLazyConnect(unittest.TestCase, _TestLazyConnectMixin):
985995
def _get_client(self, **kwargs):

0 commit comments

Comments
 (0)