Package Bio :: Module DocSQL
[hide private]
[frames] | no frames]

Source Code for Module Bio.DocSQL

  1  #!/usr/bin/env python 
  2  # 
  3  # Copyright 2002-2003 by Michael Hoffman.  All rights reserved. 
  4  # This code is part of the Biopython distribution and governed by its 
  5  # license.  Please see the LICENSE file that should have been included 
  6  # as part of this package. 
  7   
  8  """Bio.DocSQL: easy access to DB API databases (DEPRECATED). 
  9   
 10  >>> import os 
 11  >>> import MySQLdb 
 12  >>> from Bio import DocSQL 
 13  >>> db=MySQLdb.connect(passwd='', db='test') 
 14  >>> class CreatePeople(DocSQL.Create): 
 15  ...     ''' 
 16  ...     CREATE TEMPORARY TABLE people 
 17  ...     (id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, 
 18  ...     last_name TINYTEXT, 
 19  ...     first_name TINYTEXT) 
 20  ...     ''' 
 21  ... 
 22  >>> CreatePeople(connection=db) 
 23  CreatePeople(message=Success) 
 24  """ 
 25   
 26  from __future__ import print_function 
 27   
 28  import sys 
 29  import warnings 
 30   
 31  from Bio import MissingPythonDependencyError 
 32  from Bio import BiopythonDeprecationWarning 
 33   
 34  warnings.warn("Bio.DocSQL is now deprecated will be removed in a " 
 35                "future release of Biopython.", BiopythonDeprecationWarning) 
 36   
 37  try: 
 38      import MySQLdb 
 39  except ImportError: 
 40      raise MissingPythonDependencyError("Install MySQLdb if you want to use " 
 41                                         "Bio.DocSQL.") 
 42   
 43   
 44  connection = None 
 45   
 46   
47 -class NoInsertionError(Exception):
48 pass
49 50
51 -def _check_is_public(name):
52 if name[:6] == "_names": 53 raise AttributeError
54 55
56 -class QueryRow(list):
57 - def __init__(self, cursor):
58 try: 59 row = cursor.fetchone() 60 super(QueryRow, self).__init__(row) 61 except TypeError: 62 raise StopIteration 63 64 object.__setattr__(self, "_names", [x[0] for x in cursor.description]) # FIXME: legacy 65 object.__setattr__(self, "_names_hash", {}) 66 67 for i, name in enumerate(self._names): 68 self._names_hash[name] = i
69
70 - def __getattr__(self, name):
71 _check_is_public(name) 72 try: 73 return self[self._names_hash[name]] 74 except (KeyError, AttributeError): 75 raise AttributeError("'%s' object has no attribute '%s'" 76 % (self.__class__.__name__, name))
77
78 - def __setattr__(self, name, value):
79 try: 80 self._names_hash 81 except AttributeError: 82 return object.__setattr__(self, name, value) 83 84 _check_is_public(name) 85 try: 86 index = self._names_hash[name] 87 self[index] = value 88 except KeyError: 89 return object.__setattr__(self, name, value)
90 91
92 -class Query(object):
93 """SHOW TABLES.""" 94 95 MSG_FAILURE = "Failure" 96 MSG_SUCCESS = "Success" 97 message = "not executed" 98 error_message = "" 99 prefix = "" 100 suffix = "" 101 row_class = QueryRow 102
103 - def __init__(self, *args, **keywds):
104 try: 105 self.connection = keywds['connection'] 106 except KeyError: 107 self.connection = connection 108 try: 109 self.diagnostics = keywds['diagnostics'] 110 except KeyError: 111 self.diagnostics = 0 112 113 self.statement = self.prefix + self.__doc__ + self.suffix 114 self.params = args
115
116 - def __iter__(self):
117 return IterationCursor(self, self.connection)
118
119 - def __repr__(self):
120 return "%s(message=%s)" % (self.__class__.__name__, self.message)
121
122 - def cursor(self):
123 return iter(self).cursor
124
125 - def dump(self):
126 for item in self: 127 print(item)
128 129
130 -class QueryGeneric(Query):
131 - def __init__(self, statement, *args, **keywds):
132 Query.__init__(self, *args, **keywds) 133 self.statement = statement,
134 135
136 -class IterationCursor(object):
137 - def __init__(self, query, connection=connection):
138 if connection is None: 139 raise TypeError("database connection is None") 140 self.cursor = connection.cursor() 141 self.row_class = query.row_class 142 if query.diagnostics: 143 sys.stderr.write("Query statement: %s\n" % query.statement) 144 sys.stderr.write("Query params: %s\n" % query.params) 145 self.cursor.execute(query.statement, query.params)
146
147 - def __next__(self):
148 return self.row_class(self.cursor)
149 150 if sys.version_info[0] < 3:
151 - def next(self):
152 """Python 2 style alias for Python 3 style __next__ method.""" 153 return self.__next__()
154 155
156 -class QuerySingle(Query, QueryRow):
157 ignore_warnings = 0 158
159 - def __init__(self, *args, **keywds):
160 message = self.MSG_FAILURE 161 Query.__init__(self, *args, **keywds) 162 try: 163 self.single_cursor = Query.cursor(self) 164 except MySQLdb.Warning: 165 if not self.ignore_warnings: 166 raise 167 self.row_class.__init__(self, self.cursor()) 168 object.__setattr__(self, "message", self.MSG_SUCCESS)
169
170 - def cursor(self):
171 return self.single_cursor
172 173
174 -class QueryAll(list, Query):
175 - def __init__(self, *args, **keywds):
176 Query.__init__(self, *args, **keywds) 177 list.__init__(self, [self.process_row(r) for r in self.cursor().fetchall()])
178
179 - def process_row(self, row):
180 return row
181 182
183 -class QueryAllFirstItem(QueryAll):
184 - def process_row(self, row):
185 return row[0]
186 187
188 -class Create(QuerySingle):
189 - def __init__(self, *args, **keywds):
190 try: 191 QuerySingle.__init__(self, *args, **keywds) 192 except StopIteration: 193 self.message = self.MSG_SUCCESS
194 195
196 -class Update(Create):
197 pass
198 199
200 -class Insert(Create):
201 MSG_INTEGRITY_ERROR = "Couldn't insert: %s. " 202
203 - def __init__(self, *args, **keywds):
204 try: 205 Create.__init__(self, *args, **keywds) 206 except MySQLdb.IntegrityError as error_data: 207 self.error_message += self.MSG_INTEGRITY_ERROR % error_data[1] 208 try: 209 self.total_count 210 except AttributeError: 211 self.total_count = 0 212 213 raise MySQLdb.IntegrityError(self.error_message) 214 215 self.id = self.cursor().insert_id() 216 try: 217 self.total_count += self.cursor().rowcount 218 except AttributeError: 219 self.total_count = self.cursor().rowcount 220 221 if self.cursor().rowcount == 0: 222 raise NoInsertionError
223 224
225 -def _test(*args, **keywds):
226 import doctest 227 doctest.testmod(sys.modules[__name__], *args, **keywds)
228 229 230 if __name__ == "__main__": 231 if __debug__: 232 _test() 233