Debian Codegraph @

petl/io/db_create.py

raw
1 # -*- coding: utf-8 -*-
2 """
3 Module providing some convenience functions for working with SQL databases.
4 SQLAlchemy is required, try ``apt-get install python-sqlalchemy``
5 or ``pip install SQLAlchemy``.
6
7 Acknowledgments: much of the code of this module is based on the ``csvsql``
8 utility in the `csvkit <https://github.com/onyxfish/csvkit>`_ package.
9
10 """
11
12
13 import datetime
14 import logging
15 from petl.compat import long, text_type
16
17
18 from petl.errors import ArgumentError
19 from petl.util.materialise import columns
20 from petl.transform.basics import head
21 from petl.io.db_utils import _is_dbapi_connection, _is_dbapi_cursor, \
22 _is_sqlalchemy_engine, _is_sqlalchemy_session, _is_sqlalchemy_connection,\
23 _quote
24
25
26 logger = logging.getLogger(__name__)
27 debug = logger.debug
28
29
30 DIALECTS = {
31 'access': 'access.base',
32 'firebird': 'firebird.kinterbasdb',
33 'informix': 'informix.informixdb',
34 'maxdb': 'maxdb.sapdb',
35 'mssql': 'mssql.pyodbc',
36 'mysql': 'mysql.mysqlconnector',
37 'oracle': 'oracle.cx_oracle',
38 'postgresql': 'postgresql.psycopg2',
39 'sqlite': 'sqlite.pysqlite',
40 'sybase': 'sybase.pyodbc'
41 }
42
43
44 SQL_INTEGER_MAX = 2147483647
45 SQL_INTEGER_MIN = -2147483647
46 NULL_COLUMN_MAX_LENGTH = 32
47
48
49 def make_sqlalchemy_column(col, colname, constraints=True):
50 """
51 Infer an appropriate SQLAlchemy column type based on a sequence of values.
52
53 Keyword arguments:
54
55 col : sequence
56 A sequence of values to use to infer type, length etc.
57 colname : string
58 Name of column
59 constraints : bool
60 If True use length and nullable constraints
61
62 """
63
64 import sqlalchemy
65
66 col_not_none = [v for v in col if v is not None]
67 sql_column_kwargs = {}
68 sql_type_kwargs = {}
69
70 if len(col_not_none) == 0:
71 sql_column_type = sqlalchemy.String
72 if constraints:
73 sql_type_kwargs['length'] = NULL_COLUMN_MAX_LENGTH
74
75 elif all(isinstance(v, bool) for v in col_not_none):
76 sql_column_type = sqlalchemy.Boolean
77
78 elif all(isinstance(v, int) for v in col_not_none):
79 if max(col_not_none) > SQL_INTEGER_MAX \
80 or min(col_not_none) < SQL_INTEGER_MIN:
81 sql_column_type = sqlalchemy.BigInteger
82 else:
83 sql_column_type = sqlalchemy.Integer
84
85 elif all(isinstance(v, long) for v in col_not_none):
86 sql_column_type = sqlalchemy.BigInteger
87
88 elif all(isinstance(v, (int, long)) for v in col_not_none):
89 sql_column_type = sqlalchemy.BigInteger
90
91 elif all(isinstance(v, (int, long, float)) for v in col_not_none):
92 sql_column_type = sqlalchemy.Float
93
94 elif all(isinstance(v, datetime.datetime) for v in col_not_none):
95 sql_column_type = sqlalchemy.DateTime
96
97 elif all(isinstance(v, datetime.date) for v in col_not_none):
98 sql_column_type = sqlalchemy.Date
99
100 elif all(isinstance(v, datetime.time) for v in col_not_none):
101 sql_column_type = sqlalchemy.Time
102
103 elif all(isinstance(v, (dict, list)) for v in col_not_none):
104 sql_column_type = sqlalchemy.JSON
105
106 else:
107 sql_column_type = sqlalchemy.String
108 if constraints:
109 sql_type_kwargs['length'] = max([len(text_type(v)) for v in col])
110
111 if constraints:
112 sql_column_kwargs['nullable'] = len(col_not_none) < len(col)
113
114 return sqlalchemy.Column(colname, sql_column_type(**sql_type_kwargs),
115 **sql_column_kwargs)
116
117
118 def make_sqlalchemy_table(table, tablename, schema=None, constraints=True,
119 metadata=None):
120 """
121 Create an SQLAlchemy table definition based on data in `table`.
122
123 Keyword arguments:
124
125 table : table container
126 Table data to use to infer types etc.
127 tablename : text
128 Name of the table
129 schema : text
130 Name of the database schema to create the table in
131 constraints : bool
132 If True use length and nullable constraints
133 metadata : sqlalchemy.MetaData
134 Custom table metadata
135
136 """
137
138 import sqlalchemy
139
140 if not metadata:
141 metadata = sqlalchemy.MetaData()
142
143 sql_table = sqlalchemy.Table(tablename, metadata, schema=schema)
144 cols = columns(table)
145 flds = list(cols.keys())
146 for f in flds:
147 sql_column = make_sqlalchemy_column(cols[f], f,
148 constraints=constraints)
149 sql_table.append_column(sql_column)
150
151 return sql_table
152
153
154 def make_create_table_statement(table, tablename, schema=None,
155 constraints=True, metadata=None, dialect=None):
156 """
157 Generate a CREATE TABLE statement based on data in `table`.
158
159 Keyword arguments:
160
161 table : table container
162 Table data to use to infer types etc.
163 tablename : text
164 Name of the table
165 schema : text
166 Name of the database schema to create the table in
167 constraints : bool
168 If True use length and nullable constraints
169 metadata : sqlalchemy.MetaData
170 Custom table metadata
171 dialect : text
172 One of {'access', 'sybase', 'sqlite', 'informix', 'firebird', 'mysql',
173 'oracle', 'maxdb', 'postgresql', 'mssql'}
174
175 """
176
177 import sqlalchemy
178 sql_table = make_sqlalchemy_table(table, tablename, schema=schema,
179 constraints=constraints,
180 metadata=metadata)
181
182 if dialect:
183 module = __import__('sqlalchemy.dialects.%s' % DIALECTS[dialect],
184 fromlist=['dialect'])
185 sql_dialect = module.dialect()
186 else:
187 sql_dialect = None
188
189 return text_type(sqlalchemy.schema.CreateTable(sql_table)
190 .compile(dialect=sql_dialect)).strip()
191
192
193 def create_table(table, dbo, tablename, schema=None, commit=True,
194 constraints=True, metadata=None, dialect=None, sample=1000):
195 """
196 Create a database table based on a sample of data in the given `table`.
197
198 Keyword arguments:
199
200 table : table container
201 Table data to load
202 dbo : database object
203 DB-API 2.0 connection, callable returning a DB-API 2.0 cursor, or
204 SQLAlchemy connection, engine or session
205 tablename : text
206 Name of the table
207 schema : text
208 Name of the database schema to create the table in
209 commit : bool
210 If True commit the changes
211 constraints : bool
212 If True use length and nullable constraints
213 metadata : sqlalchemy.MetaData
214 Custom table metadata
215 dialect : text
216 One of {'access', 'sybase', 'sqlite', 'informix', 'firebird', 'mysql',
217 'oracle', 'maxdb', 'postgresql', 'mssql'}
218 sample : int
219 Number of rows to sample when inferring types etc., set to 0 to use
220 the whole table
221
222 """
223
224 if sample > 0:
225 table = head(table, sample)
226 sql = make_create_table_statement(table, tablename, schema=schema,
227 constraints=constraints,
228 metadata=metadata, dialect=dialect)
229 _execute(sql, dbo, commit=commit)
230
231
232 def drop_table(dbo, tablename, schema=None, commit=True, if_exists=False):
233 """
234 Drop a database table.
235
236 Keyword arguments:
237
238 dbo : database object
239 DB-API 2.0 connection, callable returning a DB-API 2.0 cursor, or
240 SQLAlchemy connection, engine or session
241 tablename : text
242 Name of the table
243 schema : text
244 Name of the database schema the table is in
245 commit : bool
246 If True commit the changes
247 if_exists : bool
248 If True, do not raise an error if the table does not exist
249
250 """
251
252 # sanitise table name
253 tablename = _quote(tablename)
254 if schema is not None:
255 tablename = _quote(schema) + '.' + tablename
256
257 if if_exists:
258 sql = u'DROP TABLE IF EXISTS %s' % tablename
259 else:
260 sql = u'DROP TABLE %s' % tablename
261 _execute(sql, dbo, commit)
262
263
264 def _execute(sql, dbo, commit):
265
266 debug(sql)
267
268 # need to deal with polymorphic dbo argument
269 # what sort of duck is it?
270
271 # does it quack like a standard DB-API 2.0 connection?
272 if _is_dbapi_connection(dbo):
273 debug('assuming %r is standard DB-API 2.0 connection', dbo)
274 _execute_dbapi_connection(sql, dbo, commit)
275
276 # does it quack like a standard DB-API 2.0 cursor?
277 elif _is_dbapi_cursor(dbo):
278 debug('assuming %r is standard DB-API 2.0 cursor')
279 _execute_dbapi_cursor(sql, dbo, commit)
280
281 # does it quack like an SQLAlchemy engine?
282 elif _is_sqlalchemy_engine(dbo):
283 debug('assuming %r is an instance of sqlalchemy.engine.base.Engine',
284 dbo)
285 _execute_sqlalchemy_engine(sql, dbo, commit)
286
287 # does it quack like an SQLAlchemy session?
288 elif _is_sqlalchemy_session(dbo):
289 debug('assuming %r is an instance of sqlalchemy.orm.session.Session',
290 dbo)
291 _execute_sqlalchemy_session(sql, dbo, commit)
292
293 # does it quack like an SQLAlchemy connection?
294 elif _is_sqlalchemy_connection(dbo):
295 debug('assuming %r is an instance of '
296 'sqlalchemy.engine.base.Connection',
297 dbo)
298 _execute_sqlalchemy_connection(sql, dbo, commit)
299
300 elif callable(dbo):
301 debug('assuming %r is a function returning standard DB-API 2.0 cursor '
302 'objects', dbo)
303 _execute_dbapi_mkcurs(sql, dbo, commit)
304
305 # some other sort of duck...
306 else:
307 raise ArgumentError('unsupported database object type: %r' % dbo)
308
309
310 def _execute_dbapi_connection(sql, connection, commit):
311
312 debug('obtain a cursor')
313 cursor = connection.cursor()
314
315 debug('execute SQL')
316 cursor.execute(sql)
317
318 debug('close the cursor')
319 cursor.close()
320
321 if commit:
322 debug('commit transaction')
323 connection.commit()
324
325
326 def _execute_dbapi_mkcurs(sql, mkcurs, commit):
327
328 debug('obtain a cursor')
329 cursor = mkcurs()
330
331 debug('execute SQL')
332 cursor.execute(sql)
333
334 debug('close the cursor')
335 cursor.close()
336
337 if commit:
338 debug('commit transaction')
339 # N.B., we depend on this optional DB-API 2.0 attribute being
340 # implemented
341 assert hasattr(cursor, 'connection'), \
342 'could not obtain connection via cursor'
343 connection = cursor.connection
344 connection.commit()
345
346
347 def _execute_dbapi_cursor(sql, cursor, commit):
348
349 debug('execute SQL')
350 cursor.execute(sql)
351
352 # don't close the cursor, leave that to the application
353
354 if commit:
355 debug('commit transaction')
356 # N.B., we depend on this optional DB-API 2.0 attribute being
357 # implemented
358 assert hasattr(cursor, 'connection'),\
359 'could not obtain connection via cursor'
360 connection = cursor.connection
361 connection.commit()
362
363
364 def _execute_sqlalchemy_connection(sql, connection, commit):
365
366 if commit:
367 debug('begin transaction')
368 trans = connection.begin()
369
370 debug('execute SQL')
371 connection.execute(sql)
372
373 if commit:
374 debug('commit transaction')
375 trans.commit()
376
377 # N.B., don't close connection, leave that to the application
378
379
380 def _execute_sqlalchemy_engine(sql, engine, commit):
381 _execute_sqlalchemy_connection(sql, engine.connect(), commit)
382
383
384 def _execute_sqlalchemy_session(sql, session, commit):
385 _execute_sqlalchemy_connection(sql, session.connection(), commit)