diff --git a/+dj/conn.m b/+dj/conn.m index 52db07b6..b6c4cf10 100644 --- a/+dj/conn.m +++ b/+dj/conn.m @@ -32,8 +32,18 @@ if isa(CONN, 'dj.Connection') && ~reset - assert(nargin==0, ... - 'connection already instantiated. To reconnect, clear functions') + if nargin>0 + if strcmp(CONN.host,host) + warning('DataJoint:Connection:AlreadyInstantiated', sprintf([... + 'Connection already instantiated.\n' ... + 'Will use existing connection to "' CONN.host '".\n' ... + 'To reconnect, set reset to true'])); + else + error('DataJoint:Connection:AlreadyInstantiated', sprintf([... + 'Connection already instantiated to "' CONN.host '".\n' ... + 'To reconnect, set reset to true'])); + end + end else % invoke setupDJ % optional environment variables specifying the connection. diff --git a/+tests/TestConnection.m b/+tests/TestConnection.m index b52a083d..d57d901b 100644 --- a/+tests/TestConnection.m +++ b/+tests/TestConnection.m @@ -9,5 +9,26 @@ function testConnection(testCase) testCase.CONN_INFO.user,... testCase.CONN_INFO.password,'',true).isConnected); end + function testConnectionExists(testCase) + % testConnectionExists tests that will not fail if connection open + % to the same host. + % Fix https://github.com/datajoint/datajoint-matlab/issues/160 + st = dbstack; + disp(['---------------' st(1).name '---------------']); + dj.conn(testCase.CONN_INFO.host, '', '', '', '', true) + dj.conn(testCase.CONN_INFO.host, '', '', '', '', true) + end + function testConnectionDiffHost(testCase) + % testConnectionDiffHost tests that will fail if connection open + % to a different host. + % Fix https://github.com/datajoint/datajoint-matlab/issues/160 + st = dbstack; + disp(['---------------' st(1).name '---------------']); + dj.conn(testCase.CONN_INFO.host, '', '', '', '', true) + + testCase.verifyError(@() dj.conn(... + 'anything', '', '', '', '', true), ... + 'DataJoint:Connection:AlreadyInstantiated'); + end end end \ No newline at end of file