1
1
import sqlalchemy
2
2
import os
3
+ import re
3
4
4
5
class ConnectionError (Exception ):
5
6
pass
6
7
7
8
9
+ def rough_dict_get (dct , sought , default = None ):
10
+ '''
11
+ Like dct.get(sought), but any key containing sought will do.
12
+
13
+ If there is a `@` in sought, seek each piece separately.
14
+ This lets `me@server` match `me:***@myserver/db`
15
+ '''
16
+
17
+ sought = sought .split ('@' )
18
+ for (key , val ) in dct .items ():
19
+ if not any (s .lower () not in key .lower () for s in sought ):
20
+ return val
21
+ return default
22
+
23
+
8
24
class Connection (object ):
9
25
current = None
10
26
connections = {}
@@ -25,8 +41,7 @@ def __init__(self, connect_str=None):
25
41
self .metadata = sqlalchemy .MetaData (bind = engine )
26
42
self .name = self .assign_name (engine )
27
43
self .session = engine .connect ()
28
- self .connections [self .name ] = self
29
- self .connections [str (self .metadata .bind .url )] = self
44
+ self .connections [repr (self .metadata .bind .url )] = self
30
45
Connection .current = self
31
46
32
47
@classmethod
@@ -37,8 +52,7 @@ def set(cls, descriptor):
37
52
if isinstance (descriptor , Connection ):
38
53
cls .current = descriptor
39
54
else :
40
- existing = cls .connections .get (descriptor ) or \
41
- cls .connections .get (descriptor .lower ())
55
+ existing = rough_dict_get (cls .connections , descriptor )
42
56
cls .current = existing or Connection (descriptor )
43
57
else :
44
58
if cls .connections :
@@ -52,12 +66,7 @@ def set(cls, descriptor):
52
66
53
67
@classmethod
54
68
def assign_name (cls , engine ):
55
- core_name = '%s@%s' % (engine .url .username or '' , engine .url .database )
56
- incrementer = 1
57
- name = core_name
58
- while name in cls .connections :
59
- name = '%s_%d' % (core_name , incrementer )
60
- incrementer += 1
69
+ name = '%s@%s' % (engine .url .username or '' , engine .url .database )
61
70
return name
62
71
63
72
@classmethod
0 commit comments