PageRenderTime 99ms CodeModel.GetById 41ms RepoModel.GetById 6ms app.codeStats 0ms

/python/lib/Lib/dbexts.py

http://github.com/JetBrains/intellij-community
Python | 726 lines | 714 code | 1 blank | 11 comment | 0 complexity | b8080de093ebff0cfdc8fd0fb27f1530 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, MIT, EPL-1.0, AGPL-1.0
  1. # $Id: dbexts.py 6638 2009-08-10 17:05:49Z fwierzbicki $
  2. """
  3. This script provides platform independence by wrapping Python
  4. Database API 2.0 compatible drivers to allow seamless database
  5. usage across implementations.
  6. In order to use the C version, you need mxODBC and mxDateTime.
  7. In order to use the Java version, you need zxJDBC.
  8. >>> import dbexts
  9. >>> d = dbexts.dbexts() # use the default db
  10. >>> d.isql('select count(*) count from player')
  11. count
  12. -------
  13. 13569.0
  14. 1 row affected
  15. >>> r = d.raw('select count(*) count from player')
  16. >>> r
  17. ([('count', 3, 17, None, 15, 0, 1)], [(13569.0,)])
  18. >>>
  19. The configuration file follows the following format in a file name dbexts.ini:
  20. [default]
  21. name=mysql
  22. [jdbc]
  23. name=mysql
  24. url=jdbc:mysql://localhost/ziclix
  25. user=
  26. pwd=
  27. driver=org.gjt.mm.mysql.Driver
  28. datahandler=com.ziclix.python.sql.handler.MySQLDataHandler
  29. [jdbc]
  30. name=pg
  31. url=jdbc:postgresql://localhost:5432/ziclix
  32. user=bzimmer
  33. pwd=
  34. driver=org.postgresql.Driver
  35. datahandler=com.ziclix.python.sql.handler.PostgresqlDataHandler
  36. """
  37. import os, re
  38. from types import StringType
  39. __author__ = "brian zimmer (bzimmer@ziclix.com)"
  40. __version__ = "$Revision: 6638 $"[11:-2]
  41. __OS__ = os.name
  42. choose = lambda bool, a, b: (bool and [a] or [b])[0]
  43. def console(rows, headers=()):
  44. """Format the results into a list of strings (one for each row):
  45. <header>
  46. <headersep>
  47. <row1>
  48. <row2>
  49. ...
  50. headers may be given as list of strings.
  51. Columns are separated by colsep; the header is separated from
  52. the result set by a line of headersep characters.
  53. The function calls stringify to format the value data into a string.
  54. It defaults to calling str() and striping leading and trailing whitespace.
  55. - copied and modified from mxODBC
  56. """
  57. # Check row entry lengths
  58. output = []
  59. headers = map(lambda header: header.upper(), list(map(lambda x: x or "", headers)))
  60. collen = map(len,headers)
  61. output.append(headers)
  62. if rows and len(rows) > 0:
  63. for row in rows:
  64. row = map(lambda x: str(x), row)
  65. for i in range(len(row)):
  66. entry = row[i]
  67. if collen[i] < len(entry):
  68. collen[i] = len(entry)
  69. output.append(row)
  70. if len(output) == 1:
  71. affected = "0 rows affected"
  72. elif len(output) == 2:
  73. affected = "1 row affected"
  74. else:
  75. affected = "%d rows affected" % (len(output) - 1)
  76. # Format output
  77. for i in range(len(output)):
  78. row = output[i]
  79. l = []
  80. for j in range(len(row)):
  81. l.append('%-*s' % (collen[j],row[j]))
  82. output[i] = " | ".join(l)
  83. # Insert header separator
  84. totallen = len(output[0])
  85. output[1:1] = ["-"*(totallen/len("-"))]
  86. output.append("\n" + affected)
  87. return output
  88. def html(rows, headers=()):
  89. output = []
  90. output.append('<table class="results">')
  91. output.append('<tr class="headers">')
  92. headers = map(lambda x: '<td class="header">%s</td>' % (x.upper()), list(headers))
  93. map(output.append, headers)
  94. output.append('</tr>')
  95. if rows and len(rows) > 0:
  96. for row in rows:
  97. output.append('<tr class="row">')
  98. row = map(lambda x: '<td class="value">%s</td>' % (x), row)
  99. map(output.append, row)
  100. output.append('</tr>')
  101. output.append('</table>')
  102. return output
  103. comments = lambda x: re.compile("{.*?}", re.S).sub("", x, 0)
  104. class mxODBCProxy:
  105. """Wraps mxODBC to provide proxy support for zxJDBC's additional parameters."""
  106. def __init__(self, c):
  107. self.c = c
  108. def __getattr__(self, name):
  109. if name == "execute":
  110. return self.execute
  111. elif name == "gettypeinfo":
  112. return self.gettypeinfo
  113. else:
  114. return getattr(self.c, name)
  115. def execute(self, sql, params=None, bindings=None, maxrows=None):
  116. if params:
  117. self.c.execute(sql, params)
  118. else:
  119. self.c.execute(sql)
  120. def gettypeinfo(self, typeid=None):
  121. if typeid:
  122. self.c.gettypeinfo(typeid)
  123. class executor:
  124. """Handles the insertion of values given dynamic data."""
  125. def __init__(self, table, cols):
  126. self.cols = cols
  127. self.table = table
  128. if self.cols:
  129. self.sql = "insert into %s (%s) values (%s)" % (table, ",".join(self.cols), ",".join(("?",) * len(self.cols)))
  130. else:
  131. self.sql = "insert into %s values (%%s)" % (table)
  132. def execute(self, db, rows, bindings):
  133. assert rows and len(rows) > 0, "must have at least one row"
  134. if self.cols:
  135. sql = self.sql
  136. else:
  137. sql = self.sql % (",".join(("?",) * len(rows[0])))
  138. db.raw(sql, rows, bindings)
  139. def connect(dbname):
  140. return dbexts(dbname)
  141. def lookup(dbname):
  142. return dbexts(jndiname=dbname)
  143. class dbexts:
  144. def __init__(self, dbname=None, cfg=None, formatter=console, autocommit=0, jndiname=None, out=None):
  145. self.verbose = 1
  146. self.results = []
  147. self.headers = []
  148. self.autocommit = autocommit
  149. self.formatter = formatter
  150. self.out = out
  151. self.lastrowid = None
  152. self.updatecount = None
  153. if not jndiname:
  154. if cfg == None:
  155. fn = os.path.join(os.path.split(__file__)[0], "dbexts.ini")
  156. if not os.path.exists(fn):
  157. fn = os.path.join(os.environ['HOME'], ".dbexts")
  158. self.dbs = IniParser(fn)
  159. elif isinstance(cfg, IniParser):
  160. self.dbs = cfg
  161. else:
  162. self.dbs = IniParser(cfg)
  163. if dbname == None: dbname = self.dbs[("default", "name")]
  164. if __OS__ == 'java':
  165. from com.ziclix.python.sql import zxJDBC
  166. database = zxJDBC
  167. if not jndiname:
  168. t = self.dbs[("jdbc", dbname)]
  169. self.dburl, dbuser, dbpwd, jdbcdriver = t['url'], t['user'], t['pwd'], t['driver']
  170. if t.has_key('datahandler'):
  171. self.datahandler = []
  172. for dh in t['datahandler'].split(','):
  173. classname = dh.split(".")[-1]
  174. datahandlerclass = __import__(dh, globals(), locals(), classname)
  175. self.datahandler.append(datahandlerclass)
  176. keys = [x for x in t.keys() if x not in ['url', 'user', 'pwd', 'driver', 'datahandler', 'name']]
  177. props = {}
  178. for a in keys:
  179. props[a] = t[a]
  180. self.db = apply(database.connect, (self.dburl, dbuser, dbpwd, jdbcdriver), props)
  181. else:
  182. self.db = database.lookup(jndiname)
  183. self.db.autocommit = self.autocommit
  184. elif __OS__ == 'nt':
  185. for modname in ["mx.ODBC.Windows", "ODBC.Windows"]:
  186. try:
  187. database = __import__(modname, globals(), locals(), "Windows")
  188. break
  189. except:
  190. continue
  191. else:
  192. raise ImportError("unable to find appropriate mxODBC module")
  193. t = self.dbs[("odbc", dbname)]
  194. self.dburl, dbuser, dbpwd = t['url'], t['user'], t['pwd']
  195. self.db = database.Connect(self.dburl, dbuser, dbpwd, clear_auto_commit=1)
  196. self.dbname = dbname
  197. for a in database.sqltype.keys():
  198. setattr(self, database.sqltype[a], a)
  199. for a in dir(database):
  200. try:
  201. p = getattr(database, a)
  202. if issubclass(p, Exception):
  203. setattr(self, a, p)
  204. except:
  205. continue
  206. del database
  207. def __str__(self):
  208. return self.dburl
  209. def __repr__(self):
  210. return self.dburl
  211. def __getattr__(self, name):
  212. if "cfg" == name:
  213. return self.dbs.cfg
  214. raise AttributeError("'dbexts' object has no attribute '%s'" % (name))
  215. def close(self):
  216. """ close the connection to the database """
  217. self.db.close()
  218. def begin(self, style=None):
  219. """ reset ivars and return a new cursor, possibly binding an auxiliary datahandler """
  220. self.headers, self.results = [], []
  221. if style:
  222. c = self.db.cursor(style)
  223. else:
  224. c = self.db.cursor()
  225. if __OS__ == 'java':
  226. if hasattr(self, 'datahandler'):
  227. for dh in self.datahandler:
  228. c.datahandler = dh(c.datahandler)
  229. else:
  230. c = mxODBCProxy(c)
  231. return c
  232. def commit(self, cursor=None, close=1):
  233. """ commit the cursor and create the result set """
  234. if cursor and cursor.description:
  235. self.headers = cursor.description
  236. self.results = cursor.fetchall()
  237. if hasattr(cursor, "nextset"):
  238. s = cursor.nextset()
  239. while s:
  240. self.results += cursor.fetchall()
  241. s = cursor.nextset()
  242. if hasattr(cursor, "lastrowid"):
  243. self.lastrowid = cursor.lastrowid
  244. if hasattr(cursor, "updatecount"):
  245. self.updatecount = cursor.updatecount
  246. if not self.autocommit or cursor is None:
  247. if not self.db.autocommit:
  248. self.db.commit()
  249. if cursor and close: cursor.close()
  250. def rollback(self):
  251. """ rollback the cursor """
  252. self.db.rollback()
  253. def prepare(self, sql):
  254. """ prepare the sql statement """
  255. cur = self.begin()
  256. try:
  257. return cur.prepare(sql)
  258. finally:
  259. self.commit(cur)
  260. def display(self):
  261. """ using the formatter, display the results """
  262. if self.formatter and self.verbose > 0:
  263. res = self.results
  264. if res:
  265. print >> self.out, ""
  266. for a in self.formatter(res, map(lambda x: x[0], self.headers)):
  267. print >> self.out, a
  268. print >> self.out, ""
  269. def __execute__(self, sql, params=None, bindings=None, maxrows=None):
  270. """ the primary execution method """
  271. cur = self.begin()
  272. try:
  273. if bindings:
  274. cur.execute(sql, params, bindings, maxrows=maxrows)
  275. elif params:
  276. cur.execute(sql, params, maxrows=maxrows)
  277. else:
  278. cur.execute(sql, maxrows=maxrows)
  279. finally:
  280. self.commit(cur, close=isinstance(sql, StringType))
  281. def isql(self, sql, params=None, bindings=None, maxrows=None):
  282. """ execute and display the sql """
  283. self.raw(sql, params, bindings, maxrows=maxrows)
  284. self.display()
  285. def raw(self, sql, params=None, bindings=None, delim=None, comments=comments, maxrows=None):
  286. """ execute the sql and return a tuple of (headers, results) """
  287. if delim:
  288. headers = []
  289. results = []
  290. if type(sql) == type(StringType):
  291. if comments: sql = comments(sql)
  292. statements = filter(lambda x: len(x) > 0,
  293. map(lambda statement: statement.strip(), sql.split(delim)))
  294. else:
  295. statements = [sql]
  296. for a in statements:
  297. self.__execute__(a, params, bindings, maxrows=maxrows)
  298. headers.append(self.headers)
  299. results.append(self.results)
  300. self.headers = headers
  301. self.results = results
  302. else:
  303. self.__execute__(sql, params, bindings, maxrows=maxrows)
  304. return (self.headers, self.results)
  305. def callproc(self, procname, params=None, bindings=None, maxrows=None):
  306. """ execute a stored procedure """
  307. cur = self.begin()
  308. try:
  309. cur.callproc(procname, params=params, bindings=bindings, maxrows=maxrows)
  310. finally:
  311. self.commit(cur)
  312. self.display()
  313. def pk(self, table, owner=None, schema=None):
  314. """ display the table's primary keys """
  315. cur = self.begin()
  316. cur.primarykeys(schema, owner, table)
  317. self.commit(cur)
  318. self.display()
  319. def fk(self, primary_table=None, foreign_table=None, owner=None, schema=None):
  320. """ display the table's foreign keys """
  321. cur = self.begin()
  322. if primary_table and foreign_table:
  323. cur.foreignkeys(schema, owner, primary_table, schema, owner, foreign_table)
  324. elif primary_table:
  325. cur.foreignkeys(schema, owner, primary_table, schema, owner, None)
  326. elif foreign_table:
  327. cur.foreignkeys(schema, owner, None, schema, owner, foreign_table)
  328. self.commit(cur)
  329. self.display()
  330. def table(self, table=None, types=("TABLE",), owner=None, schema=None):
  331. """If no table argument, displays a list of all tables. If a table argument,
  332. displays the columns of the given table."""
  333. cur = self.begin()
  334. if table:
  335. cur.columns(schema, owner, table, None)
  336. else:
  337. cur.tables(schema, owner, None, types)
  338. self.commit(cur)
  339. self.display()
  340. def proc(self, proc=None, owner=None, schema=None):
  341. """If no proc argument, displays a list of all procedures. If a proc argument,
  342. displays the parameters of the given procedure."""
  343. cur = self.begin()
  344. if proc:
  345. cur.procedurecolumns(schema, owner, proc, None)
  346. else:
  347. cur.procedures(schema, owner, None)
  348. self.commit(cur)
  349. self.display()
  350. def stat(self, table, qualifier=None, owner=None, unique=0, accuracy=0):
  351. """ display the table's indicies """
  352. cur = self.begin()
  353. cur.statistics(qualifier, owner, table, unique, accuracy)
  354. self.commit(cur)
  355. self.display()
  356. def typeinfo(self, sqltype=None):
  357. """ display the types available for the database """
  358. cur = self.begin()
  359. cur.gettypeinfo(sqltype)
  360. self.commit(cur)
  361. self.display()
  362. def tabletypeinfo(self):
  363. """ display the table types available for the database """
  364. cur = self.begin()
  365. cur.gettabletypeinfo()
  366. self.commit(cur)
  367. self.display()
  368. def schema(self, table, full=0, sort=1, owner=None):
  369. """Displays a Schema object for the table. If full is true, then generates
  370. references to the table in addition to the standard fields. If sort is true,
  371. sort all the items in the schema, else leave them in db dependent order."""
  372. print >> self.out, str(Schema(self, table, owner, full, sort))
  373. def bulkcopy(self, dst, table, include=[], exclude=[], autobatch=0, executor=executor):
  374. """Returns a Bulkcopy object using the given table."""
  375. if type(dst) == type(""):
  376. dst = dbexts(dst, cfg=self.dbs)
  377. bcp = Bulkcopy(dst, table, include=include, exclude=exclude, autobatch=autobatch, executor=executor)
  378. return bcp
  379. def bcp(self, src, table, where='(1=1)', params=[], include=[], exclude=[], autobatch=0, executor=executor):
  380. """Bulkcopy of rows from a src database to the current database for a given table and where clause."""
  381. if type(src) == type(""):
  382. src = dbexts(src, cfg=self.dbs)
  383. bcp = self.bulkcopy(self, table, include, exclude, autobatch, executor)
  384. num = bcp.transfer(src, where, params)
  385. return num
  386. def unload(self, filename, sql, delimiter=",", includeheaders=1):
  387. """ Unloads the delimited results of the query to the file specified, optionally including headers. """
  388. u = Unload(self, filename, delimiter, includeheaders)
  389. u.unload(sql)
  390. class Bulkcopy:
  391. """The idea for a bcp class came from http://object-craft.com.au/projects/sybase"""
  392. def __init__(self, dst, table, include=[], exclude=[], autobatch=0, executor=executor):
  393. self.dst = dst
  394. self.table = table
  395. self.total = 0
  396. self.rows = []
  397. self.autobatch = autobatch
  398. self.bindings = {}
  399. include = map(lambda x: x.lower(), include)
  400. exclude = map(lambda x: x.lower(), exclude)
  401. _verbose = self.dst.verbose
  402. self.dst.verbose = 0
  403. try:
  404. self.dst.table(self.table)
  405. if self.dst.results:
  406. colmap = {}
  407. for a in self.dst.results:
  408. colmap[a[3].lower()] = a[4]
  409. cols = self.__filter__(colmap.keys(), include, exclude)
  410. for a in zip(range(len(cols)), cols):
  411. self.bindings[a[0]] = colmap[a[1]]
  412. colmap = None
  413. else:
  414. cols = self.__filter__(include, include, exclude)
  415. finally:
  416. self.dst.verbose = _verbose
  417. self.executor = executor(table, cols)
  418. def __str__(self):
  419. return "[%s].[%s]" % (self.dst, self.table)
  420. def __repr__(self):
  421. return "[%s].[%s]" % (self.dst, self.table)
  422. def __getattr__(self, name):
  423. if name == 'columns':
  424. return self.executor.cols
  425. def __filter__(self, values, include, exclude):
  426. cols = map(lambda col: col.lower(), values)
  427. if exclude:
  428. cols = filter(lambda x, ex=exclude: x not in ex, cols)
  429. if include:
  430. cols = filter(lambda x, inc=include: x in inc, cols)
  431. return cols
  432. def format(self, column, type):
  433. self.bindings[column] = type
  434. def done(self):
  435. if len(self.rows) > 0:
  436. return self.batch()
  437. return 0
  438. def batch(self):
  439. self.executor.execute(self.dst, self.rows, self.bindings)
  440. cnt = len(self.rows)
  441. self.total += cnt
  442. self.rows = []
  443. return cnt
  444. def rowxfer(self, line):
  445. self.rows.append(line)
  446. if self.autobatch: self.batch()
  447. def transfer(self, src, where="(1=1)", params=[]):
  448. sql = "select %s from %s where %s" % (", ".join(self.columns), self.table, where)
  449. h, d = src.raw(sql, params)
  450. if d:
  451. map(self.rowxfer, d)
  452. return self.done()
  453. return 0
  454. class Unload:
  455. """Unloads a sql statement to a file with optional formatting of each value."""
  456. def __init__(self, db, filename, delimiter=",", includeheaders=1):
  457. self.db = db
  458. self.filename = filename
  459. self.delimiter = delimiter
  460. self.includeheaders = includeheaders
  461. self.formatters = {}
  462. def format(self, o):
  463. if not o:
  464. return ""
  465. o = str(o)
  466. if o.find(",") != -1:
  467. o = "\"\"%s\"\"" % (o)
  468. return o
  469. def unload(self, sql, mode="w"):
  470. headers, results = self.db.raw(sql)
  471. w = open(self.filename, mode)
  472. if self.includeheaders:
  473. w.write("%s\n" % (self.delimiter.join(map(lambda x: x[0], headers))))
  474. if results:
  475. for a in results:
  476. w.write("%s\n" % (self.delimiter.join(map(self.format, a))))
  477. w.flush()
  478. w.close()
  479. class Schema:
  480. """Produces a Schema object which represents the database schema for a table"""
  481. def __init__(self, db, table, owner=None, full=0, sort=1):
  482. self.db = db
  483. self.table = table
  484. self.owner = owner
  485. self.full = full
  486. self.sort = sort
  487. _verbose = self.db.verbose
  488. self.db.verbose = 0
  489. try:
  490. if table: self.computeschema()
  491. finally:
  492. self.db.verbose = _verbose
  493. def computeschema(self):
  494. self.db.table(self.table, owner=self.owner)
  495. self.columns = []
  496. # (column name, type_name, size, nullable)
  497. if self.db.results:
  498. self.columns = map(lambda x: (x[3], x[5], x[6], x[10]), self.db.results)
  499. if self.sort: self.columns.sort(lambda x, y: cmp(x[0], y[0]))
  500. self.db.fk(None, self.table)
  501. # (pk table name, pk column name, fk column name, fk name, pk name)
  502. self.imported = []
  503. if self.db.results:
  504. self.imported = map(lambda x: (x[2], x[3], x[7], x[11], x[12]), self.db.results)
  505. if self.sort: self.imported.sort(lambda x, y: cmp(x[2], y[2]))
  506. self.exported = []
  507. if self.full:
  508. self.db.fk(self.table, None)
  509. # (pk column name, fk table name, fk column name, fk name, pk name)
  510. if self.db.results:
  511. self.exported = map(lambda x: (x[3], x[6], x[7], x[11], x[12]), self.db.results)
  512. if self.sort: self.exported.sort(lambda x, y: cmp(x[1], y[1]))
  513. self.db.pk(self.table)
  514. self.primarykeys = []
  515. if self.db.results:
  516. # (column name, key_seq, pk name)
  517. self.primarykeys = map(lambda x: (x[3], x[4], x[5]), self.db.results)
  518. if self.sort: self.primarykeys.sort(lambda x, y: cmp(x[1], y[1]))
  519. try:
  520. self.indices = None
  521. self.db.stat(self.table)
  522. self.indices = []
  523. # (non-unique, name, type, pos, column name, asc)
  524. if self.db.results:
  525. idxdict = {}
  526. # mxODBC returns a row of None's, so filter it out
  527. idx = map(lambda x: (x[3], x[5].strip(), x[6], x[7], x[8]), filter(lambda x: x[5], self.db.results))
  528. def cckmp(x, y):
  529. c = cmp(x[1], y[1])
  530. if c == 0: c = cmp(x[3], y[3])
  531. return c
  532. # sort this regardless, this gets the indicies lined up
  533. idx.sort(cckmp)
  534. for a in idx:
  535. if not idxdict.has_key(a[1]):
  536. idxdict[a[1]] = []
  537. idxdict[a[1]].append(a)
  538. self.indices = idxdict.values()
  539. if self.sort: self.indices.sort(lambda x, y: cmp(x[0][1], y[0][1]))
  540. except:
  541. pass
  542. def __str__(self):
  543. d = []
  544. d.append("Table")
  545. d.append(" " + self.table)
  546. d.append("\nPrimary Keys")
  547. for a in self.primarykeys:
  548. d.append(" %s {%s}" % (a[0], a[2]))
  549. d.append("\nImported (Foreign) Keys")
  550. for a in self.imported:
  551. d.append(" %s (%s.%s) {%s}" % (a[2], a[0], a[1], a[3]))
  552. if self.full:
  553. d.append("\nExported (Referenced) Keys")
  554. for a in self.exported:
  555. d.append(" %s (%s.%s) {%s}" % (a[0], a[1], a[2], a[3]))
  556. d.append("\nColumns")
  557. for a in self.columns:
  558. nullable = choose(a[3], "nullable", "non-nullable")
  559. d.append(" %-20s %s(%s), %s" % (a[0], a[1], a[2], nullable))
  560. d.append("\nIndices")
  561. if self.indices is None:
  562. d.append(" (failed)")
  563. else:
  564. for a in self.indices:
  565. unique = choose(a[0][0], "non-unique", "unique")
  566. cname = ", ".join(map(lambda x: x[4], a))
  567. d.append(" %s index {%s} on (%s)" % (unique, a[0][1], cname))
  568. return "\n".join(d)
  569. class IniParser:
  570. def __init__(self, cfg, key='name'):
  571. self.key = key
  572. self.records = {}
  573. self.ctypeRE = re.compile("\[(jdbc|odbc|default)\]")
  574. self.entryRE = re.compile("([a-zA-Z]+)[ \t]*=[ \t]*(.*)")
  575. self.cfg = cfg
  576. self.parse()
  577. def parse(self):
  578. fp = open(self.cfg, "r")
  579. data = fp.readlines()
  580. fp.close()
  581. lines = filter(lambda x: len(x) > 0 and x[0] not in ['#', ';'], map(lambda x: x.strip(), data))
  582. current = None
  583. for i in range(len(lines)):
  584. line = lines[i]
  585. g = self.ctypeRE.match(line)
  586. if g: # a section header
  587. current = {}
  588. if not self.records.has_key(g.group(1)):
  589. self.records[g.group(1)] = []
  590. self.records[g.group(1)].append(current)
  591. else:
  592. g = self.entryRE.match(line)
  593. if g:
  594. current[g.group(1)] = g.group(2)
  595. def __getitem__(self, (ctype, skey)):
  596. if skey == self.key: return self.records[ctype][0][skey]
  597. t = filter(lambda x, p=self.key, s=skey: x[p] == s, self.records[ctype])
  598. if not t or len(t) > 1:
  599. raise KeyError, "invalid key ('%s', '%s')" % (ctype, skey)
  600. return t[0]
  601. def random_table_name(prefix, num_chars):
  602. import random
  603. d = [prefix, '_']
  604. i = 0
  605. while i < num_chars:
  606. d.append(chr(int(100 * random.random()) % 26 + ord('A')))
  607. i += 1
  608. return "".join(d)
  609. class ResultSetRow:
  610. def __init__(self, rs, row):
  611. self.row = row
  612. self.rs = rs
  613. def __getitem__(self, i):
  614. if type(i) == type(""):
  615. i = self.rs.index(i)
  616. return self.row[i]
  617. def __getslice__(self, i, j):
  618. if type(i) == type(""): i = self.rs.index(i)
  619. if type(j) == type(""): j = self.rs.index(j)
  620. return self.row[i:j]
  621. def __len__(self):
  622. return len(self.row)
  623. def __repr__(self):
  624. return str(self.row)
  625. class ResultSet:
  626. def __init__(self, headers, results=[]):
  627. self.headers = map(lambda x: x.upper(), headers)
  628. self.results = results
  629. def index(self, i):
  630. return self.headers.index(i.upper())
  631. def __getitem__(self, i):
  632. return ResultSetRow(self, self.results[i])
  633. def __getslice__(self, i, j):
  634. return map(lambda x, rs=self: ResultSetRow(rs, x), self.results[i:j])
  635. def __repr__(self):
  636. return "<%s instance {cols [%d], rows [%d]} at %s>" % (self.__class__, len(self.headers), len(self.results), id(self))