Debian Codegraph @

petl/test/io/test_db_create.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, print_function, division
3
4
5 import logging
6 from datetime import datetime, date
7 import sqlite3
8
9 import pytest
10
11 from petl.io.db import fromdb, todb
12 from petl.io.db_create import make_sqlalchemy_column
13 from petl.test.helpers import ieq, eq_
14 from petl.util.vis import look
15 from petl.test.io.test_db_server import get_pg_args, get_mysql_args
16
17
18 logger = logging.getLogger(__name__)
19 debug = logger.debug
20
21
22 def _test_create(dbo):
23
24 expect = (('foo', 'bar'),
25 ('a', 1),
26 ('b', 2))
27
28 expect_extended = (('foo', 'bar', 'baz'),
29 ('a', 1, 2.3),
30 ('b', 2, 4.1))
31 actual = fromdb(dbo, 'SELECT * FROM test_create')
32
33 debug('verify table does not exist to start with')
34 try:
35 debug(look(actual))
36 except Exception as e:
37 debug('expected exception: ' + str(e))
38 else:
39 raise Exception('expected exception not raised')
40
41 debug('verify cannot write without create')
42 try:
43 todb(expect, dbo, 'test_create')
44 except Exception as e:
45 debug('expected exception: ' + str(e))
46 else:
47 raise Exception('expected exception not raised')
48
49 debug('verify create with drop if exists when missing')
50 todb(expect, dbo, 'test_create_if_exists', create=True,
51 drop='if_exists')
52 actual_if_exists = fromdb(dbo, 'SELECT * FROM test_create_if_exists')
53 ieq(expect, actual_if_exists)
54 debug(look(actual_if_exists))
55
56 debug('verify recreate with drop if exists')
57 todb(expect_extended, dbo, 'test_create_if_exists', create=True,
58 drop='if_exists')
59 ieq(expect_extended, actual_if_exists)
60 debug(look(actual_if_exists))
61
62 debug('create table and verify')
63 todb(expect, dbo, 'test_create', create=True)
64 ieq(expect, actual)
65 debug(look(actual))
66
67 debug('verify cannot overwrite with new cols without recreate')
68 try:
69 todb(expect_extended, dbo, 'test_create')
70 except Exception as e:
71 debug('expected exception: ' + str(e))
72 else:
73 raise Exception('expected exception not raised')
74
75 debug('verify recreate')
76 todb(expect_extended, dbo, 'test_create', create=True, drop=True)
77 ieq(expect_extended, actual)
78 debug(look(actual))
79
80 debug('horrendous identifiers')
81 table = (('foo foo', 'bar.baz."spong`'),
82 ('a', 1),
83 ('b', 2),
84 ('c', 2))
85 todb(table, dbo, 'foo " bar`', create=True)
86 actual = fromdb(dbo, 'SELECT * FROM "foo "" bar`"')
87 ieq(table, actual)
88
89
90 def _setup_mysql(dbapi_connection):
91 # setup table
92 cursor = dbapi_connection.cursor()
93 # deal with quote compatibility
94 cursor.execute('SET SQL_MODE=ANSI_QUOTES')
95 cursor.execute('DROP TABLE IF EXISTS test_create')
96 cursor.execute('DROP TABLE IF EXISTS test_create_if_exists')
97 cursor.execute('DROP TABLE IF EXISTS "foo "" bar`"')
98 cursor.close()
99 dbapi_connection.commit()
100
101
102 def _setup_generic(dbapi_connection):
103 # setup table
104 cursor = dbapi_connection.cursor()
105 cursor.execute('DROP TABLE IF EXISTS test_create')
106 cursor.execute('DROP TABLE IF EXISTS test_create_if_exists')
107 cursor.execute('DROP TABLE IF EXISTS "foo "" bar`"')
108 cursor.close()
109 dbapi_connection.commit()
110
111
112 try:
113 import sqlalchemy
114 except ImportError as e:
115 pytest.skip('SKIP generic DB create tests: %s' % e, allow_module_level=True)
116 else:
117
118 from sqlalchemy import Column, DateTime, Date
119
120 def test_make_datetime_column():
121 sql_col = make_sqlalchemy_column([datetime(2014, 1, 1, 1, 1, 1, 1),
122 datetime(2014, 1, 1, 1, 1, 1, 2)],
123 'name')
124 expect = Column('name', DateTime(), nullable=False)
125 eq_(str(expect.type), str(sql_col.type))
126
127 def test_make_date_column():
128 sql_col = make_sqlalchemy_column([date(2014, 1, 1),
129 date(2014, 1, 2)],
130 'name')
131 expect = Column('name', Date(), nullable=False)
132 eq_(str(expect.type), str(sql_col.type))
133
134 def test_sqlite3_create():
135
136 dbapi_connection = sqlite3.connect(':memory:')
137
138 # exercise using a dbapi_connection
139 _setup_generic(dbapi_connection)
140 _test_create(dbapi_connection)
141
142 # exercise using a dbapi_cursor
143 _setup_generic(dbapi_connection)
144 dbapi_cursor = dbapi_connection.cursor()
145 _test_create(dbapi_cursor)
146 dbapi_cursor.close()
147
148 SKIP_PYMYSQL = False
149 try:
150 import pymysql
151 import sqlalchemy
152 myhost, myuser, mypassword, mydatabase = get_mysql_args()
153 pymysql.connect(host=myhost,
154 user=myuser,
155 password=mypassword,
156 database=mydatabase)
157 except Exception as e:
158 SKIP_PYMYSQL = 'SKIP pymysql create tests: %s' % e
159 finally:
160 @pytest.mark.skipif(bool(SKIP_PYMYSQL), reason=str(SKIP_PYMYSQL))
161 def test_mysql_create():
162
163 import pymysql
164
165 # assume database already created
166 dbapi_connection = pymysql.connect(host=myhost,
167 user=myuser,
168 password=mypassword,
169 database=mydatabase)
170
171 # exercise using a dbapi_connection
172 _setup_mysql(dbapi_connection)
173 _test_create(dbapi_connection)
174
175 # exercise using a dbapi_cursor
176 _setup_mysql(dbapi_connection)
177 dbapi_cursor = dbapi_connection.cursor()
178 _test_create(dbapi_cursor)
179 dbapi_cursor.close()
180
181 # exercise sqlalchemy dbapi_connection
182 _setup_mysql(dbapi_connection)
183 from sqlalchemy import create_engine
184 sqlalchemy_engine = create_engine('mysql+pymysql://%s:%s@%s/%s'
185 % (myuser, mypassword, myhost, mydatabase))
186 sqlalchemy_connection = sqlalchemy_engine.connect()
187 sqlalchemy_connection.execute('SET SQL_MODE=ANSI_QUOTES')
188 _test_create(sqlalchemy_connection)
189 sqlalchemy_connection.close()
190
191 # exercise sqlalchemy session
192 _setup_mysql(dbapi_connection)
193 from sqlalchemy.orm import sessionmaker
194 Session = sessionmaker(bind=sqlalchemy_engine)
195 sqlalchemy_session = Session()
196 _test_create(sqlalchemy_session)
197 sqlalchemy_session.close()
198
199
200 SKIP_POSTGRES = False
201 try:
202 import psycopg2
203 import sqlalchemy
204 pghost, pguser, pgpassword, pgdatabase = get_pg_args()
205 psycopg2.connect(
206 'host=%s dbname=%s user=%s password=%s'
207 % (pghost, pgdatabase, pguser, pgpassword)
208 )
209 except Exception as e:
210 SKIP_POSTGRES = 'SKIP psycopg2 create tests: %s' % e
211 finally:
212 @pytest.mark.skipif(bool(SKIP_POSTGRES), reason=str(SKIP_POSTGRES))
213 def test_postgresql_create():
214 import psycopg2
215 import psycopg2.extensions
216 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
217 psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
218
219 # assume database already created
220 dbapi_connection = psycopg2.connect(
221 'host=%s dbname=%s user=%s password=%s'
222 % (pghost, pgdatabase, pguser, pgpassword)
223 )
224 dbapi_connection.autocommit = True
225
226 # exercise using a dbapi_connection
227 _setup_generic(dbapi_connection)
228 _test_create(dbapi_connection)
229
230 # exercise using a dbapi_cursor
231 _setup_generic(dbapi_connection)
232 dbapi_cursor = dbapi_connection.cursor()
233 _test_create(dbapi_cursor)
234 dbapi_cursor.close()
235
236 # # ignore these for now, having trouble with autocommit
237 #
238 # # exercise sqlalchemy dbapi_connection
239 # _setup_generic(dbapi_connection)
240 # from sqlalchemy import create_engine
241 # sqlalchemy_engine = create_engine(
242 # 'postgresql+psycopg2://%s:%s@%s/%s'
243 # % (user, password, host, database)
244 # )
245 # sqlalchemy_connection = sqlalchemy_engine.connect()
246 # _test_create(sqlalchemy_connection)
247 # sqlalchemy_connection.close()
248 #
249 # # exercise sqlalchemy session
250 # _setup_generic(dbapi_connection)
251 # from sqlalchemy.orm import sessionmaker
252 # Session = sessionmaker(bind=sqlalchemy_engine)
253 # sqlalchemy_session = Session()
254 # _test_create(sqlalchemy_session)
255 # sqlalchemy_session.close()