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