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
|
# -*- coding: utf-8 -*-
"""
Module providing some convenience functions for working with SQL databases.
SQLAlchemy is required, try ``apt-get install python-sqlalchemy``
or ``pip install SQLAlchemy``.
Acknowledgments: much of the code of this module is based on the ``csvsql``
utility in the `csvkit <https://github.com/onyxfish/csvkit>`_ package.
"""
import datetime
import logging
from petl.compat import long, text_type
from petl.errors import ArgumentError
from petl.util.materialise import columns
from petl.transform.basics import head
from petl.io.db_utils import _is_dbapi_connection, _is_dbapi_cursor, \
_is_sqlalchemy_engine, _is_sqlalchemy_session, _is_sqlalchemy_connection,\
_quote
logger = logging.getLogger(__name__)
debug = logger.debug
DIALECTS = {
'access': 'access.base',
'firebird': 'firebird.kinterbasdb',
'informix': 'informix.informixdb',
'maxdb': 'maxdb.sapdb',
'mssql': 'mssql.pyodbc',
'mysql': 'mysql.mysqlconnector',
'oracle': 'oracle.cx_oracle',
'postgresql': 'postgresql.psycopg2',
'sqlite': 'sqlite.pysqlite',
'sybase': 'sybase.pyodbc'
}
SQL_INTEGER_MAX = 2147483647
SQL_INTEGER_MIN = -2147483647
NULL_COLUMN_MAX_LENGTH = 32
def make_sqlalchemy_column(col, colname, constraints=True):
"""
Infer an appropriate SQLAlchemy column type based on a sequence of values.
Keyword arguments:
col : sequence
A sequence of values to use to infer type, length etc.
colname : string
Name of column
constraints : bool
If True use length and nullable constraints
"""
import sqlalchemy
col_not_none = [v for v in col if v is not None]
sql_column_kwargs = {}
sql_type_kwargs = {}
if len(col_not_none) == 0:
sql_column_type = sqlalchemy.String
if constraints:
sql_type_kwargs['length'] = NULL_COLUMN_MAX_LENGTH
elif all(isinstance(v, bool) for v in col_not_none):
sql_column_type = sqlalchemy.Boolean
elif all(isinstance(v, int) for v in col_not_none):
if max(col_not_none) > SQL_INTEGER_MAX \
or min(col_not_none) < SQL_INTEGER_MIN:
sql_column_type = sqlalchemy.BigInteger
else:
sql_column_type = sqlalchemy.Integer
elif all(isinstance(v, long) for v in col_not_none):
sql_column_type = sqlalchemy.BigInteger
elif all(isinstance(v, (int, long)) for v in col_not_none):
sql_column_type = sqlalchemy.BigInteger
elif all(isinstance(v, (int, long, float)) for v in col_not_none):
sql_column_type = sqlalchemy.Float
elif all(isinstance(v, datetime.datetime) for v in col_not_none):
sql_column_type = sqlalchemy.DateTime
elif all(isinstance(v, datetime.date) for v in col_not_none):
sql_column_type = sqlalchemy.Date
elif all(isinstance(v, datetime.time) for v in col_not_none):
sql_column_type = sqlalchemy.Time
elif all(isinstance(v, (dict, list)) for v in col_not_none):
sql_column_type = sqlalchemy.JSON
else:
sql_column_type = sqlalchemy.String
if constraints:
sql_type_kwargs['length'] = max([len(text_type(v)) for v in col])
if constraints:
sql_column_kwargs['nullable'] = len(col_not_none) < len(col)
return sqlalchemy.Column(colname, sql_column_type(**sql_type_kwargs),
**sql_column_kwargs)
def make_sqlalchemy_table(table, tablename, schema=None, constraints=True,
metadata=None):
"""
Create an SQLAlchemy table definition based on data in `table`.
Keyword arguments:
table : table container
Table data to use to infer types etc.
tablename : text
Name of the table
schema : text
Name of the database schema to create the table in
constraints : bool
If True use length and nullable constraints
metadata : sqlalchemy.MetaData
Custom table metadata
"""
import sqlalchemy
if not metadata:
metadata = sqlalchemy.MetaData()
sql_table = sqlalchemy.Table(tablename, metadata, schema=schema)
cols = columns(table)
flds = list(cols.keys())
for f in flds:
sql_column = make_sqlalchemy_column(cols[f], f,
constraints=constraints)
sql_table.append_column(sql_column)
return sql_table
def make_create_table_statement(table, tablename, schema=None,
constraints=True, metadata=None, dialect=None):
"""
Generate a CREATE TABLE statement based on data in `table`.
Keyword arguments:
table : table container
Table data to use to infer types etc.
tablename : text
Name of the table
schema : text
Name of the database schema to create the table in
constraints : bool
If True use length and nullable constraints
metadata : sqlalchemy.MetaData
Custom table metadata
dialect : text
One of {'access', 'sybase', 'sqlite', 'informix', 'firebird', 'mysql',
'oracle', 'maxdb', 'postgresql', 'mssql'}
"""
import sqlalchemy
sql_table = make_sqlalchemy_table(table, tablename, schema=schema,
constraints=constraints,
metadata=metadata)
if dialect:
module = __import__('sqlalchemy.dialects.%s' % DIALECTS[dialect],
fromlist=['dialect'])
sql_dialect = module.dialect()
else:
sql_dialect = None
return text_type(sqlalchemy.schema.CreateTable(sql_table)
.compile(dialect=sql_dialect)).strip()
def create_table(table, dbo, tablename, schema=None, commit=True,
constraints=True, metadata=None, dialect=None, sample=1000):
"""
Create a database table based on a sample of data in the given `table`.
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 : text
Name of the table
schema : text
Name of the database schema to create the table in
commit : bool
If True commit the changes
constraints : bool
If True use length and nullable constraints
metadata : sqlalchemy.MetaData
Custom table metadata
dialect : text
One of {'access', 'sybase', 'sqlite', 'informix', 'firebird', 'mysql',
'oracle', 'maxdb', 'postgresql', 'mssql'}
sample : int
Number of rows to sample when inferring types etc., set to 0 to use
the whole table
"""
if sample > 0:
table = head(table, sample)
sql = make_create_table_statement(table, tablename, schema=schema,
constraints=constraints,
metadata=metadata, dialect=dialect)
_execute(sql, dbo, commit=commit)
def drop_table(dbo, tablename, schema=None, commit=True):
"""
Drop a database table.
Keyword arguments:
dbo : database object
DB-API 2.0 connection, callable returning a DB-API 2.0 cursor, or
SQLAlchemy connection, engine or session
tablename : text
Name of the table
schema : text
Name of the database schema the table is in
commit : bool
If True commit the changes
"""
# sanitise table name
tablename = _quote(tablename)
if schema is not None:
tablename = _quote(schema) + '.' + tablename
sql = u'DROP TABLE %s' % tablename
_execute(sql, dbo, commit)
def _execute(sql, dbo, commit):
debug(sql)
# need to deal with polymorphic dbo argument
# what sort of duck is it?
# does it quack like a standard DB-API 2.0 connection?
if _is_dbapi_connection(dbo):
debug('assuming %r is standard DB-API 2.0 connection', dbo)
_execute_dbapi_connection(sql, dbo, commit)
# 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')
_execute_dbapi_cursor(sql, dbo, commit)
# does it quack like an SQLAlchemy engine?
elif _is_sqlalchemy_engine(dbo):
debug('assuming %r is an instance of sqlalchemy.engine.base.Engine',
dbo)
_execute_sqlalchemy_engine(sql, dbo, commit)
# does it quack like an SQLAlchemy session?
elif _is_sqlalchemy_session(dbo):
debug('assuming %r is an instance of sqlalchemy.orm.session.Session',
dbo)
_execute_sqlalchemy_session(sql, dbo, commit)
# does it quack like an SQLAlchemy connection?
elif _is_sqlalchemy_connection(dbo):
debug('assuming %r is an instance of '
'sqlalchemy.engine.base.Connection',
dbo)
_execute_sqlalchemy_connection(sql, dbo, commit)
elif callable(dbo):
debug('assuming %r is a function returning standard DB-API 2.0 cursor '
'objects', dbo)
_execute_dbapi_mkcurs(sql, dbo, commit)
# some other sort of duck...
else:
raise ArgumentError('unsupported database object type: %r' % dbo)
def _execute_dbapi_connection(sql, connection, commit):
debug('obtain a cursor')
cursor = connection.cursor()
debug('execute SQL')
cursor.execute(sql)
debug('close the cursor')
cursor.close()
if commit:
debug('commit transaction')
connection.commit()
def _execute_dbapi_mkcurs(sql, mkcurs, commit):
debug('obtain a cursor')
cursor = mkcurs()
debug('execute SQL')
cursor.execute(sql)
debug('close the cursor')
cursor.close()
if commit:
debug('commit transaction')
# 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
connection.commit()
def _execute_dbapi_cursor(sql, cursor, commit):
debug('execute SQL')
cursor.execute(sql)
# don't close the cursor, leave that to the application
if commit:
debug('commit transaction')
# 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
connection.commit()
def _execute_sqlalchemy_connection(sql, connection, commit):
if commit:
debug('begin transaction')
trans = connection.begin()
debug('execute SQL')
connection.execute(sql)
if commit:
debug('commit transaction')
trans.commit()
# N.B., don't close connection, leave that to the application
def _execute_sqlalchemy_engine(sql, engine, commit):
_execute_sqlalchemy_connection(sql, engine.connect(), commit)
def _execute_sqlalchemy_session(sql, session, commit):
_execute_sqlalchemy_connection(sql, session.connection(), commit)
|