1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
# standard library dependencies
import logging
from petl.compat import next, text_type, string_types
# internal dependencies
from petl.errors import ArgumentError
from petl.util.base import Table
from petl.io.db_utils import _is_dbapi_connection, _is_dbapi_cursor, \
_is_sqlalchemy_connection, _is_sqlalchemy_engine, _is_sqlalchemy_session, \
_is_clikchouse_dbapi_connection, _quote, _placeholders
from petl.io.db_create import drop_table, create_table
logger = logging.getLogger(__name__)
debug = logger.debug
warning = logger.warning
def fromdb(dbo, query, *args, **kwargs):
"""Provides access to data from any DB-API 2.0 connection via a given query.
E.g., using :mod:`sqlite3`::
>>> import petl as etl
>>> import sqlite3
>>> connection = sqlite3.connect('example.db')
>>> table = etl.fromdb(connection, 'SELECT * FROM example')
E.g., using :mod:`psycopg2` (assuming you've installed it first)::
>>> import petl as etl
>>> import psycopg2
>>> connection = psycopg2.connect('dbname=example user=postgres')
>>> table = etl.fromdb(connection, 'SELECT * FROM example')
E.g., using :mod:`pymysql` (assuming you've installed it first)::
>>> import petl as etl
>>> import pymysql
>>> connection = pymysql.connect(password='moonpie', database='thangs')
>>> table = etl.fromdb(connection, 'SELECT * FROM example')
The `dbo` argument may also be a function that creates a cursor. N.B., each
call to the function should return a new cursor. E.g.::
>>> import petl as etl
>>> import psycopg2
>>> connection = psycopg2.connect('dbname=example user=postgres')
>>> mkcursor = lambda: connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
>>> table = etl.fromdb(mkcursor, 'SELECT * FROM example')
The parameter `dbo` may also be an SQLAlchemy engine, session or
connection object.
The parameter `dbo` may also be a string, in which case it is interpreted as
the name of a file containing an :mod:`sqlite3` database.
Note that the default behaviour of most database servers and clients is for
the entire result set for each query to be sent from the server to the
client. If your query returns a large result set this can result in
significant memory usage at the client. Some databases support server-side
cursors which provide a means for client libraries to fetch result sets
incrementally, reducing memory usage at the client.
To use a server-side cursor with a PostgreSQL database, e.g.::
>>> import petl as etl
>>> import psycopg2
>>> connection = psycopg2.connect('dbname=example user=postgres')
>>> table = etl.fromdb(lambda: connection.cursor(name='arbitrary'),
... 'SELECT * FROM example')
For more information on server-side cursors see the following links:
* http://initd.org/psycopg/docs/usage.html#server-side-cursors
* http://mysql-python.sourceforge.net/MySQLdb.html#using-and-extending
"""
# convenience for working with sqlite3
if isinstance(dbo, string_types):
import sqlite3
dbo = sqlite3.connect(dbo)
return DbView(dbo, query, *args, **kwargs)
class DbView(Table):
def __init__(self, dbo, query, *args, **kwargs):
self.dbo = dbo
self.query = query
self.args = args
self.kwargs = kwargs
def __iter__(self):
# does it quack like a standard DB-API 2.0 connection?
if _is_dbapi_connection(self.dbo):
debug('assuming %r is standard DB-API 2.0 connection', self.dbo)
_iter = _iter_dbapi_connection
# does it quack like a standard DB-API 2.0 cursor?
elif _is_dbapi_cursor(self.dbo):
debug('assuming %r is standard DB-API 2.0 cursor')
warning('using a DB-API cursor with fromdb() is not recommended '
'and may lead to unexpected results, a DB-API connection '
'is better')
_iter = _iter_dbapi_cursor
# does it quack like an SQLAlchemy engine?
elif _is_sqlalchemy_engine(self.dbo):
debug('assuming %r instance of sqlalchemy.engine.base.Engine',
self.dbo)
_iter = _iter_sqlalchemy_engine
# does it quack like an SQLAlchemy session?
elif _is_sqlalchemy_session(self.dbo):
debug('assuming %r instance of sqlalchemy.orm.session.Session',
self.dbo)
_iter = _iter_sqlalchemy_session
# does it quack like an SQLAlchemy connection?
elif _is_sqlalchemy_connection(self.dbo):
debug('assuming %r instance of sqlalchemy.engine.base.Connection',
self.dbo)
_iter = _iter_sqlalchemy_connection
elif callable(self.dbo):
debug('assuming %r is a function returning a cursor', self.dbo)
_iter = _iter_dbapi_mkcurs
# some other sort of duck...
else:
raise ArgumentError('unsupported database object type: %r' % self.dbo)
return _iter(self.dbo, self.query, *self.args, **self.kwargs)
def _iter_dbapi_mkcurs(mkcurs, query, *args, **kwargs):
cursor = mkcurs()
try:
for row in _iter_dbapi_cursor(cursor, query, *args, **kwargs):
yield row
finally:
cursor.close()
def _iter_dbapi_connection(connection, query, *args, **kwargs):
cursor = connection.cursor()
try:
for row in _iter_dbapi_cursor(cursor, query, *args, **kwargs):
yield row
finally:
cursor.close()
def _iter_dbapi_cursor(cursor, query, *args, **kwargs):
cursor.execute(query, *args, **kwargs)
# fetch one row before iterating, to force population of cursor.description
# which may be postponed if using server-side cursors
# not all database drivers populate cursor after execute so we call fetchall
try:
it = iter(cursor)
except TypeError:
it = iter(cursor.fetchall())
try:
first_row = next(it)
except StopIteration:
first_row = None
# fields should be available now
hdr = [d[0] for d in cursor.description]
yield tuple(hdr)
if first_row is None:
return
yield first_row
for row in it:
yield row # don't wrap, return whatever the database engine returns
def _iter_sqlalchemy_engine(engine, query, *args, **kwargs):
connection = engine.connect()
for row in _iter_sqlalchemy_connection(connection, query, *args, **kwargs):
yield row
connection.close()
def _iter_sqlalchemy_connection(connection, query, *args, **kwargs):
debug('connection: %r', connection)
results = connection.execute(query, *args, **kwargs)
hdr = results.keys()
yield tuple(hdr)
for row in results:
yield row
def _iter_sqlalchemy_session(session, query, *args, **kwargs):
results = session.execute(query, *args, **kwargs)
hdr = results.keys()
yield tuple(hdr)
for row in results:
yield row
def todb(table, dbo, tablename, schema=None, commit=True,
create=False, drop=False, constraints=True, metadata=None,
dialect=None, sample=1000):
"""
Load data into an existing database table via a DB-API 2.0
connection or cursor. Note that the database table will be truncated,
i.e., all existing rows will be deleted prior to inserting the new data.
E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 2]]
>>> # using sqlite3
... import sqlite3
>>> connection = sqlite3.connect('example.db')
>>> # assuming table "foobar" already exists in the database
... etl.todb(table, connection, 'foobar')
>>> # using psycopg2
>>> import psycopg2
>>> connection = psycopg2.connect('dbname=example user=postgres')
>>> # assuming table "foobar" already exists in the database
... etl.todb(table, connection, 'foobar')
>>> # using pymysql
>>> import pymysql
>>> connection = pymysql.connect(password='moonpie', database='thangs')
>>> # tell MySQL to use standard quote character
... connection.cursor().execute('SET SQL_MODE=ANSI_QUOTES')
>>> # load data, assuming table "foobar" already exists in the database
... etl.todb(table, connection, 'foobar')
N.B., for MySQL the statement ``SET SQL_MODE=ANSI_QUOTES`` is required to
ensure MySQL uses SQL-92 standard quote characters.
A cursor can also be provided instead of a connection, e.g.::
>>> import psycopg2
>>> connection = psycopg2.connect('dbname=example user=postgres')
>>> cursor = connection.cursor()
>>> etl.todb(table, cursor, 'foobar')
The parameter `dbo` may also be an SQLAlchemy engine, session or
connection object.
The parameter `dbo` may also be a string, in which case it is interpreted
as the name of a file containing an :mod:`sqlite3` database.
If ``create=True`` this function will attempt to automatically create a
database table before loading the data. This functionality requires
`SQLAlchemy <http://www.sqlalchemy.org/>`_ to be installed.
**Keyword arguments:**
table : table container
Table data to load
dbo : database object
DB-API 2.0 connection, callable returning a DB-API 2.0 cursor, or
SQLAlchemy connection, engine or session
tablename : string
Name of the table in the database
schema : string
Name of the database schema to find the table in
commit : bool
If True commit the changes
create : bool
If True attempt to create the table before loading, inferring types
from a sample of the data (requires SQLAlchemy)
drop : bool
If True attempt to drop the table before recreating (only relevant if
create=True)
constraints : bool
If True use length and nullable constraints (only relevant if
create=True)
metadata : sqlalchemy.MetaData
Custom table metadata (only relevant if create=True)
dialect : string
One of {'access', 'sybase', 'sqlite', 'informix', 'firebird', 'mysql',
'oracle', 'maxdb', 'postgresql', 'mssql'} (only relevant if
create=True)
sample : int
Number of rows to sample when inferring types etc. Set to 0 to use the
whole table (only relevant if create=True)
.. note::
This function is in principle compatible with any DB-API 2.0
compliant database driver. However, at the time of writing some DB-API
2.0 implementations, including cx_Oracle and MySQL's
Connector/Python, are not compatible with this function, because they
only accept a list argument to the cursor.executemany() function
called internally by :mod:`petl`. This can be worked around by
proxying the cursor objects, e.g.::
>>> import cx_Oracle
>>> connection = cx_Oracle.Connection(...)
>>> class CursorProxy(object):
... def __init__(self, cursor):
... self._cursor = cursor
... def executemany(self, statement, parameters, **kwargs):
... # convert parameters to a list
... parameters = list(parameters)
... # pass through to proxied cursor
... return self._cursor.executemany(statement, parameters, **kwargs)
... def __getattr__(self, item):
... return getattr(self._cursor, item)
...
>>> def get_cursor():
... return CursorProxy(connection.cursor())
...
>>> import petl as etl
>>> etl.todb(tbl, get_cursor, ...)
Note however that this does imply loading the entire table into
memory as a list prior to inserting into the database.
"""
needs_closing = False
# convenience for working with sqlite3
if isinstance(dbo, string_types):
import sqlite3
dbo = sqlite3.connect(dbo)
needs_closing = True
try:
if create:
if drop:
drop_table(dbo, tablename, schema=schema, commit=commit)
create_table(table, dbo, tablename, schema=schema, commit=commit,
constraints=constraints, metadata=metadata,
dialect=dialect, sample=sample)
_todb(table, dbo, tablename, schema=schema, commit=commit,
truncate=True)
finally:
if needs_closing:
dbo.close()
Table.todb = todb
def _todb(table, dbo, tablename, schema=None, commit=True, truncate=False):
# need to deal with polymorphic dbo argument
# what sort of duck is it?
if _is_clikchouse_dbapi_connection(dbo):
debug('assuming %r is clickhosue DB-API 2.0 connection', dbo)
_todb_clikchouse_dbapi_connection(table, dbo, tablename, schema=schema,
commit=commit, truncate=truncate)
# does it quack like a standard DB-API 2.0 connection?
elif _is_dbapi_connection(dbo):
debug('assuming %r is standard DB-API 2.0 connection', dbo)
_todb_dbapi_connection(table, dbo, tablename, schema=schema,
commit=commit, truncate=truncate)
# does it quack like a standard DB-API 2.0 cursor?
elif _is_dbapi_cursor(dbo):
debug('assuming %r is standard DB-API 2.0 cursor')
_todb_dbapi_cursor(table, dbo, tablename, schema=schema, commit=commit,
truncate=truncate)
# does it quack like an SQLAlchemy engine?
elif _is_sqlalchemy_engine(dbo):
debug('assuming %r instance of sqlalchemy.engine.base.Engine', dbo)
_todb_sqlalchemy_engine(table, dbo, tablename, schema=schema,
commit=commit, truncate=truncate)
# does it quack like an SQLAlchemy session?
elif _is_sqlalchemy_session(dbo):
debug('assuming %r instance of sqlalchemy.orm.session.Session', dbo)
_todb_sqlalchemy_session(table, dbo, tablename, schema=schema,
commit=commit, truncate=truncate)
# does it quack like an SQLAlchemy connection?
elif _is_sqlalchemy_connection(dbo):
debug('assuming %r instance of sqlalchemy.engine.base.Connection', dbo)
_todb_sqlalchemy_connection(table, dbo, tablename, schema=schema,
commit=commit, truncate=truncate)
elif callable(dbo):
debug('assuming %r is a function returning standard DB-API 2.0 cursor '
'objects', dbo)
_todb_dbapi_mkcurs(table, dbo, tablename, schema=schema, commit=commit,
truncate=truncate)
# some other sort of duck...
else:
raise ArgumentError('unsupported database object type: %r' % dbo)
SQL_TRUNCATE_QUERY = 'DELETE FROM %s'
SQL_INSERT_QUERY = 'INSERT INTO %s (%s) VALUES (%s)'
def _todb_dbapi_connection(table, connection, tablename, schema=None,
commit=True, truncate=False):
# sanitise table name
tablename = _quote(tablename)
if schema is not None:
tablename = _quote(schema) + '.' + tablename
debug('tablename: %r', tablename)
# sanitise field names
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
colnames = [_quote(n) for n in flds]
debug('column names: %r', colnames)
# determine paramstyle and build placeholders string
placeholders = _placeholders(connection, colnames)
debug('placeholders: %r', placeholders)
# get a cursor
cursor = connection.cursor()
if truncate:
# TRUNCATE is not supported in some databases and causing locks with
# MySQL used via SQLAlchemy, fall back to DELETE FROM for now
truncatequery = SQL_TRUNCATE_QUERY % tablename
debug('truncate the table via query %r', truncatequery)
cursor.execute(truncatequery)
# just in case, close and resurrect cursor
cursor.close()
cursor = connection.cursor()
insertcolnames = ', '.join(colnames)
insertquery = SQL_INSERT_QUERY % (tablename, insertcolnames, placeholders)
debug('insert data via query %r' % insertquery)
cursor.executemany(insertquery, it)
# finish up
debug('close the cursor')
cursor.close()
if commit:
debug('commit transaction')
connection.commit()
def _todb_clikchouse_dbapi_connection(table, connection, tablename, schema=None,
commit=True, truncate=False):
# sanitise table name
tablename = _quote(tablename)
if schema is not None:
tablename = _quote(schema) + '.' + tablename
debug('tablename: %r', tablename)
# sanitise field names
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
colnames = [_quote(n) for n in flds]
debug('column names: %r', colnames)
# determine paramstyle and build placeholders string
placeholders = _placeholders(connection, colnames)
debug('placeholders: %r', placeholders)
# get a cursor
cursor = connection.cursor()
if truncate:
# TRUNCATE is not supported in some databases and causing locks with
# MySQL used via SQLAlchemy, fall back to DELETE FROM for now
truncatequery = 'TRUNCATE TABLE IF EXISTS %s' % tablename
debug('truncate the table via query %r', truncatequery)
cursor.execute(truncatequery)
# just in case, close and resurrect cursor
cursor.close()
cursor = connection.cursor()
insertcolnames = ', '.join(colnames)
insertquery = 'INSERT INTO %s (%s) VALUES' % (tablename, insertcolnames)
debug('insert data via query %r' % insertquery)
cursor.executemany(insertquery, it)
# finish up
debug('close the cursor')
cursor.close()
if commit:
debug('commit transaction')
connection.commit()
def _todb_dbapi_mkcurs(table, mkcurs, tablename, schema=None, commit=True,
truncate=False):
# sanitise table name
tablename = _quote(tablename)
if schema is not None:
tablename = _quote(schema) + '.' + tablename
debug('tablename: %r', tablename)
# sanitise field names
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
colnames = [_quote(n) for n in flds]
debug('column names: %r', colnames)
debug('obtain cursor and connection')
cursor = mkcurs()
# N.B., we depend on this optional DB-API 2.0 attribute being implemented
assert hasattr(cursor, 'connection'), \
'could not obtain connection via cursor'
connection = cursor.connection
# determine paramstyle and build placeholders string
placeholders = _placeholders(connection, colnames)
debug('placeholders: %r', placeholders)
if truncate:
# TRUNCATE is not supported in some databases and causing locks with
# MySQL used via SQLAlchemy, fall back to DELETE FROM for now
truncatequery = SQL_TRUNCATE_QUERY % tablename
debug('truncate the table via query %r', truncatequery)
cursor.execute(truncatequery)
# N.B., may be server-side cursor, need to resurrect
cursor.close()
cursor = mkcurs()
insertcolnames = ', '.join(colnames)
insertquery = SQL_INSERT_QUERY % (tablename, insertcolnames, placeholders)
debug('insert data via query %r' % insertquery)
cursor.executemany(insertquery, it)
cursor.close()
if commit:
debug('commit transaction')
connection.commit()
def _todb_dbapi_cursor(table, cursor, tablename, schema=None, commit=True,
truncate=False):
# sanitise table name
tablename = _quote(tablename)
if schema is not None:
tablename = _quote(schema) + '.' + tablename
debug('tablename: %r', tablename)
# sanitise field names
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
colnames = [_quote(n) for n in flds]
debug('column names: %r', colnames)
debug('obtain connection via cursor')
# N.B., we depend on this optional DB-API 2.0 attribute being implemented
assert hasattr(cursor, 'connection'), \
'could not obtain connection via cursor'
connection = cursor.connection
# determine paramstyle and build placeholders string
placeholders = _placeholders(connection, colnames)
debug('placeholders: %r', placeholders)
if truncate:
# TRUNCATE is not supported in some databases and causing locks with
# MySQL used via SQLAlchemy, fall back to DELETE FROM for now
truncatequery = SQL_TRUNCATE_QUERY % tablename
debug('truncate the table via query %r', truncatequery)
cursor.execute(truncatequery)
insertcolnames = ', '.join(colnames)
insertquery = SQL_INSERT_QUERY % (tablename, insertcolnames, placeholders)
debug('insert data via query %r' % insertquery)
cursor.executemany(insertquery, it)
# N.B., don't close the cursor, leave that to the application
if commit:
debug('commit transaction')
connection.commit()
def _todb_sqlalchemy_engine(table, engine, tablename, schema=None, commit=True,
truncate=False):
_todb_sqlalchemy_connection(table, engine.connect(), tablename,
schema=schema, commit=commit, truncate=truncate)
def _todb_sqlalchemy_connection(table, connection, tablename, schema=None,
commit=True, truncate=False):
debug('connection: %r', connection)
# sanitise table name
tablename = _quote(tablename)
if schema is not None:
tablename = _quote(schema) + '.' + tablename
debug('tablename: %r', tablename)
# sanitise field names
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
colnames = [_quote(n) for n in flds]
debug('column names: %r', colnames)
# N.B., we need to obtain a reference to the underlying DB-API connection so
# we can import the module and determine the paramstyle
proxied_raw_connection = connection.connection
actual_raw_connection = proxied_raw_connection.connection
# determine paramstyle and build placeholders string
placeholders = _placeholders(actual_raw_connection, colnames)
debug('placeholders: %r', placeholders)
if commit:
debug('begin transaction')
trans = connection.begin()
if truncate:
# TRUNCATE is not supported in some databases and causing locks with
# MySQL used via SQLAlchemy, fall back to DELETE FROM for now
truncatequery = SQL_TRUNCATE_QUERY % tablename
debug('truncate the table via query %r', truncatequery)
connection.execute(truncatequery)
insertcolnames = ', '.join(colnames)
insertquery = SQL_INSERT_QUERY % (tablename, insertcolnames, placeholders)
debug('insert data via query %r' % insertquery)
for row in it:
connection.execute(insertquery, row)
# finish up
if commit:
debug('commit transaction')
trans.commit()
# N.B., don't close connection, leave that to the application
def _todb_sqlalchemy_session(table, session, tablename, schema=None,
commit=True, truncate=False):
_todb_sqlalchemy_connection(table, session.connection(), tablename,
schema=schema, commit=commit,
truncate=truncate)
def appenddb(table, dbo, tablename, schema=None, commit=True):
"""
Load data into an existing database table via a DB-API 2.0
connection or cursor. As :func:`petl.io.db.todb` except that the database
table will be appended, i.e., the new data will be inserted into the
table, and any existing rows will remain.
"""
needs_closing = False
# convenience for working with sqlite3
if isinstance(dbo, string_types):
import sqlite3
dbo = sqlite3.connect(dbo)
needs_closing = True
try:
_todb(table, dbo, tablename, schema=schema, commit=commit,
truncate=False)
finally:
if needs_closing:
dbo.close()
Table.appenddb = appenddb
|