database.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. import itertools
  2. import os
  3. from collections.abc import Mapping, Sequence
  4. from copy import copy
  5. import sqlalchemy as sa
  6. from sqlalchemy.engine.url import make_url
  7. from sqlalchemy.exc import OperationalError, ProgrammingError
  8. from ..utils import starts_with
  9. from .orm import quote
  10. def escape_like(string, escape_char='*'):
  11. """
  12. Escape the string paremeter used in SQL LIKE expressions.
  13. ::
  14. from sqlalchemy_utils import escape_like
  15. query = session.query(User).filter(
  16. User.name.ilike(escape_like('John'))
  17. )
  18. :param string: a string to escape
  19. :param escape_char: escape character
  20. """
  21. return (
  22. string
  23. .replace(escape_char, escape_char * 2)
  24. .replace('%', escape_char + '%')
  25. .replace('_', escape_char + '_')
  26. )
  27. def json_sql(value, scalars_to_json=True):
  28. """
  29. Convert python data structures to PostgreSQL specific SQLAlchemy JSON
  30. constructs. This function is extremly useful if you need to build
  31. PostgreSQL JSON on python side.
  32. .. note::
  33. This function needs PostgreSQL >= 9.4
  34. Scalars are converted to to_json SQLAlchemy function objects
  35. ::
  36. json_sql(1) # Equals SQL: to_json(1)
  37. json_sql('a') # to_json('a')
  38. Mappings are converted to json_build_object constructs
  39. ::
  40. json_sql({'a': 'c', '2': 5}) # json_build_object('a', 'c', '2', 5)
  41. Sequences (other than strings) are converted to json_build_array constructs
  42. ::
  43. json_sql([1, 2, 3]) # json_build_array(1, 2, 3)
  44. You can also nest these data structures
  45. ::
  46. json_sql({'a': [1, 2, 3]})
  47. # json_build_object('a', json_build_array[1, 2, 3])
  48. :param value:
  49. value to be converted to SQLAlchemy PostgreSQL function constructs
  50. """
  51. scalar_convert = sa.text
  52. if scalars_to_json:
  53. def scalar_convert(a):
  54. return sa.func.to_json(sa.text(a))
  55. if isinstance(value, Mapping):
  56. return sa.func.json_build_object(
  57. *(
  58. json_sql(v, scalars_to_json=False)
  59. for v in itertools.chain(*value.items())
  60. )
  61. )
  62. elif isinstance(value, str):
  63. return scalar_convert("'{0}'".format(value))
  64. elif isinstance(value, Sequence):
  65. return sa.func.json_build_array(
  66. *(
  67. json_sql(v, scalars_to_json=False)
  68. for v in value
  69. )
  70. )
  71. elif isinstance(value, (int, float)):
  72. return scalar_convert(str(value))
  73. return value
  74. def jsonb_sql(value, scalars_to_jsonb=True):
  75. """
  76. Convert python data structures to PostgreSQL specific SQLAlchemy JSONB
  77. constructs. This function is extremly useful if you need to build
  78. PostgreSQL JSONB on python side.
  79. .. note::
  80. This function needs PostgreSQL >= 9.4
  81. Scalars are converted to to_jsonb SQLAlchemy function objects
  82. ::
  83. jsonb_sql(1) # Equals SQL: to_jsonb(1)
  84. jsonb_sql('a') # to_jsonb('a')
  85. Mappings are converted to jsonb_build_object constructs
  86. ::
  87. jsonb_sql({'a': 'c', '2': 5}) # jsonb_build_object('a', 'c', '2', 5)
  88. Sequences (other than strings) converted to jsonb_build_array constructs
  89. ::
  90. jsonb_sql([1, 2, 3]) # jsonb_build_array(1, 2, 3)
  91. You can also nest these data structures
  92. ::
  93. jsonb_sql({'a': [1, 2, 3]})
  94. # jsonb_build_object('a', jsonb_build_array[1, 2, 3])
  95. :param value:
  96. value to be converted to SQLAlchemy PostgreSQL function constructs
  97. :boolean jsonbb:
  98. Flag to alternatively convert the return with a to_jsonb construct
  99. """
  100. scalar_convert = sa.text
  101. if scalars_to_jsonb:
  102. def scalar_convert(a):
  103. return sa.func.to_jsonb(sa.text(a))
  104. if isinstance(value, Mapping):
  105. return sa.func.jsonb_build_object(
  106. *(
  107. jsonb_sql(v, scalars_to_jsonb=False)
  108. for v in itertools.chain(*value.items())
  109. )
  110. )
  111. elif isinstance(value, str):
  112. return scalar_convert("'{0}'".format(value))
  113. elif isinstance(value, Sequence):
  114. return sa.func.jsonb_build_array(
  115. *(
  116. jsonb_sql(v, scalars_to_jsonb=False)
  117. for v in value
  118. )
  119. )
  120. elif isinstance(value, (int, float)):
  121. return scalar_convert(str(value))
  122. return value
  123. def has_index(column_or_constraint):
  124. """
  125. Return whether or not given column or the columns of given foreign key
  126. constraint have an index. A column has an index if it has a single column
  127. index or it is the first column in compound column index.
  128. A foreign key constraint has an index if the constraint columns are the
  129. first columns in compound column index.
  130. :param column_or_constraint:
  131. SQLAlchemy Column object or SA ForeignKeyConstraint object
  132. .. versionadded: 0.26.2
  133. .. versionchanged: 0.30.18
  134. Added support for foreign key constaints.
  135. ::
  136. from sqlalchemy_utils import has_index
  137. class Article(Base):
  138. __tablename__ = 'article'
  139. id = sa.Column(sa.Integer, primary_key=True)
  140. title = sa.Column(sa.String(100))
  141. is_published = sa.Column(sa.Boolean, index=True)
  142. is_deleted = sa.Column(sa.Boolean)
  143. is_archived = sa.Column(sa.Boolean)
  144. __table_args__ = (
  145. sa.Index('my_index', is_deleted, is_archived),
  146. )
  147. table = Article.__table__
  148. has_index(table.c.is_published) # True
  149. has_index(table.c.is_deleted) # True
  150. has_index(table.c.is_archived) # False
  151. Also supports primary key indexes
  152. ::
  153. from sqlalchemy_utils import has_index
  154. class ArticleTranslation(Base):
  155. __tablename__ = 'article_translation'
  156. id = sa.Column(sa.Integer, primary_key=True)
  157. locale = sa.Column(sa.String(10), primary_key=True)
  158. title = sa.Column(sa.String(100))
  159. table = ArticleTranslation.__table__
  160. has_index(table.c.locale) # False
  161. has_index(table.c.id) # True
  162. This function supports foreign key constraints as well
  163. ::
  164. class User(Base):
  165. __tablename__ = 'user'
  166. first_name = sa.Column(sa.Unicode(255), primary_key=True)
  167. last_name = sa.Column(sa.Unicode(255), primary_key=True)
  168. class Article(Base):
  169. __tablename__ = 'article'
  170. id = sa.Column(sa.Integer, primary_key=True)
  171. author_first_name = sa.Column(sa.Unicode(255))
  172. author_last_name = sa.Column(sa.Unicode(255))
  173. __table_args__ = (
  174. sa.ForeignKeyConstraint(
  175. [author_first_name, author_last_name],
  176. [User.first_name, User.last_name]
  177. ),
  178. sa.Index(
  179. 'my_index',
  180. author_first_name,
  181. author_last_name
  182. )
  183. )
  184. table = Article.__table__
  185. constraint = list(table.foreign_keys)[0].constraint
  186. has_index(constraint) # True
  187. """
  188. table = column_or_constraint.table
  189. if not isinstance(table, sa.Table):
  190. raise TypeError(
  191. 'Only columns belonging to Table objects are supported. Given '
  192. 'column belongs to %r.' % table
  193. )
  194. primary_keys = table.primary_key.columns.values()
  195. if isinstance(column_or_constraint, sa.ForeignKeyConstraint):
  196. columns = list(column_or_constraint.columns.values())
  197. else:
  198. columns = [column_or_constraint]
  199. return (
  200. (primary_keys and starts_with(primary_keys, columns)) or
  201. any(
  202. starts_with(index.columns.values(), columns)
  203. for index in table.indexes
  204. )
  205. )
  206. def has_unique_index(column_or_constraint):
  207. """
  208. Return whether or not given column or given foreign key constraint has a
  209. unique index.
  210. A column has a unique index if it has a single column primary key index or
  211. it has a single column UniqueConstraint.
  212. A foreign key constraint has a unique index if the columns of the
  213. constraint are the same as the columns of table primary key or the coluns
  214. of any unique index or any unique constraint of the given table.
  215. :param column: SQLAlchemy Column object
  216. .. versionadded: 0.27.1
  217. .. versionchanged: 0.30.18
  218. Added support for foreign key constaints.
  219. Fixed support for unique indexes (previously only worked for unique
  220. constraints)
  221. ::
  222. from sqlalchemy_utils import has_unique_index
  223. class Article(Base):
  224. __tablename__ = 'article'
  225. id = sa.Column(sa.Integer, primary_key=True)
  226. title = sa.Column(sa.String(100))
  227. is_published = sa.Column(sa.Boolean, unique=True)
  228. is_deleted = sa.Column(sa.Boolean)
  229. is_archived = sa.Column(sa.Boolean)
  230. table = Article.__table__
  231. has_unique_index(table.c.is_published) # True
  232. has_unique_index(table.c.is_deleted) # False
  233. has_unique_index(table.c.id) # True
  234. This function supports foreign key constraints as well
  235. ::
  236. class User(Base):
  237. __tablename__ = 'user'
  238. first_name = sa.Column(sa.Unicode(255), primary_key=True)
  239. last_name = sa.Column(sa.Unicode(255), primary_key=True)
  240. class Article(Base):
  241. __tablename__ = 'article'
  242. id = sa.Column(sa.Integer, primary_key=True)
  243. author_first_name = sa.Column(sa.Unicode(255))
  244. author_last_name = sa.Column(sa.Unicode(255))
  245. __table_args__ = (
  246. sa.ForeignKeyConstraint(
  247. [author_first_name, author_last_name],
  248. [User.first_name, User.last_name]
  249. ),
  250. sa.Index(
  251. 'my_index',
  252. author_first_name,
  253. author_last_name,
  254. unique=True
  255. )
  256. )
  257. table = Article.__table__
  258. constraint = list(table.foreign_keys)[0].constraint
  259. has_unique_index(constraint) # True
  260. :raises TypeError: if given column does not belong to a Table object
  261. """
  262. table = column_or_constraint.table
  263. if not isinstance(table, sa.Table):
  264. raise TypeError(
  265. 'Only columns belonging to Table objects are supported. Given '
  266. 'column belongs to %r.' % table
  267. )
  268. primary_keys = list(table.primary_key.columns.values())
  269. if isinstance(column_or_constraint, sa.ForeignKeyConstraint):
  270. columns = list(column_or_constraint.columns.values())
  271. else:
  272. columns = [column_or_constraint]
  273. return (
  274. (columns == primary_keys) or
  275. any(
  276. columns == list(constraint.columns.values())
  277. for constraint in table.constraints
  278. if isinstance(constraint, sa.sql.schema.UniqueConstraint)
  279. ) or
  280. any(
  281. columns == list(index.columns.values())
  282. for index in table.indexes
  283. if index.unique
  284. )
  285. )
  286. def is_auto_assigned_date_column(column):
  287. """
  288. Returns whether or not given SQLAlchemy Column object's is auto assigned
  289. DateTime or Date.
  290. :param column: SQLAlchemy Column object
  291. """
  292. return (
  293. (
  294. isinstance(column.type, sa.DateTime) or
  295. isinstance(column.type, sa.Date)
  296. ) and
  297. (
  298. column.default or
  299. column.server_default or
  300. column.onupdate or
  301. column.server_onupdate
  302. )
  303. )
  304. def _set_url_database(url: sa.engine.url.URL, database):
  305. """Set the database of an engine URL.
  306. :param url: A SQLAlchemy engine URL.
  307. :param database: New database to set.
  308. """
  309. if hasattr(sa.engine, 'URL'):
  310. ret = sa.engine.URL.create(
  311. drivername=url.drivername,
  312. username=url.username,
  313. password=url.password,
  314. host=url.host,
  315. port=url.port,
  316. database=database,
  317. query=url.query
  318. )
  319. else: # SQLAlchemy <1.4
  320. url.database = database
  321. ret = url
  322. assert ret.database == database, ret
  323. return ret
  324. def _get_scalar_result(engine, sql):
  325. with engine.connect() as conn:
  326. return conn.scalar(sql)
  327. def _sqlite_file_exists(database):
  328. if not os.path.isfile(database) or os.path.getsize(database) < 100:
  329. return False
  330. with open(database, 'rb') as f:
  331. header = f.read(100)
  332. return header[:16] == b'SQLite format 3\x00'
  333. def database_exists(url):
  334. """Check if a database exists.
  335. :param url: A SQLAlchemy engine URL.
  336. Performs backend-specific testing to quickly determine if a database
  337. exists on the server. ::
  338. database_exists('postgresql://postgres@localhost/name') #=> False
  339. create_database('postgresql://postgres@localhost/name')
  340. database_exists('postgresql://postgres@localhost/name') #=> True
  341. Supports checking against a constructed URL as well. ::
  342. engine = create_engine('postgresql://postgres@localhost/name')
  343. database_exists(engine.url) #=> False
  344. create_database(engine.url)
  345. database_exists(engine.url) #=> True
  346. """
  347. url = copy(make_url(url))
  348. database = url.database
  349. dialect_name = url.get_dialect().name
  350. engine = None
  351. try:
  352. if dialect_name == 'postgresql':
  353. text = "SELECT 1 FROM pg_database WHERE datname='%s'" % database
  354. for db in (database, 'postgres', 'template1', 'template0', None):
  355. url = _set_url_database(url, database=db)
  356. engine = sa.create_engine(url)
  357. try:
  358. return bool(_get_scalar_result(engine, text))
  359. except (ProgrammingError, OperationalError):
  360. pass
  361. return False
  362. elif dialect_name == 'mysql':
  363. url = _set_url_database(url, database=None)
  364. engine = sa.create_engine(url)
  365. text = ("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA "
  366. "WHERE SCHEMA_NAME = '%s'" % database)
  367. return bool(_get_scalar_result(engine, text))
  368. elif dialect_name == 'sqlite':
  369. url = _set_url_database(url, database=None)
  370. engine = sa.create_engine(url)
  371. if database:
  372. return database == ':memory:' or _sqlite_file_exists(database)
  373. else:
  374. # The default SQLAlchemy database is in memory, and :memory is
  375. # not required, thus we should support that use case.
  376. return True
  377. else:
  378. text = 'SELECT 1'
  379. try:
  380. engine = sa.create_engine(url)
  381. return bool(_get_scalar_result(engine, text))
  382. except (ProgrammingError, OperationalError):
  383. return False
  384. finally:
  385. if engine:
  386. engine.dispose()
  387. def create_database(url, encoding='utf8', template=None):
  388. """Issue the appropriate CREATE DATABASE statement.
  389. :param url: A SQLAlchemy engine URL.
  390. :param encoding: The encoding to create the database as.
  391. :param template:
  392. The name of the template from which to create the new database. At the
  393. moment only supported by PostgreSQL driver.
  394. To create a database, you can pass a simple URL that would have
  395. been passed to ``create_engine``. ::
  396. create_database('postgresql://postgres@localhost/name')
  397. You may also pass the url from an existing engine. ::
  398. create_database(engine.url)
  399. Has full support for mysql, postgres, and sqlite. In theory,
  400. other database engines should be supported.
  401. """
  402. url = copy(make_url(url))
  403. database = url.database
  404. dialect_name = url.get_dialect().name
  405. dialect_driver = url.get_dialect().driver
  406. if dialect_name == 'postgresql':
  407. url = _set_url_database(url, database="postgres")
  408. elif dialect_name == 'mssql':
  409. url = _set_url_database(url, database="master")
  410. elif not dialect_name == 'sqlite':
  411. url = _set_url_database(url, database=None)
  412. if (dialect_name == 'mssql' and dialect_driver in {'pymssql', 'pyodbc'}) \
  413. or (dialect_name == 'postgresql' and dialect_driver in {
  414. 'asyncpg', 'pg8000', 'psycopg2', 'psycopg2cffi'}):
  415. engine = sa.create_engine(url, isolation_level='AUTOCOMMIT')
  416. else:
  417. engine = sa.create_engine(url)
  418. if dialect_name == 'postgresql':
  419. if not template:
  420. template = 'template1'
  421. text = "CREATE DATABASE {0} ENCODING '{1}' TEMPLATE {2}".format(
  422. quote(engine, database),
  423. encoding,
  424. quote(engine, template)
  425. )
  426. with engine.connect() as connection:
  427. connection.execute(text)
  428. elif dialect_name == 'mysql':
  429. text = "CREATE DATABASE {0} CHARACTER SET = '{1}'".format(
  430. quote(engine, database),
  431. encoding
  432. )
  433. with engine.connect() as connection:
  434. connection.execute(text)
  435. elif dialect_name == 'sqlite' and database != ':memory:':
  436. if database:
  437. with engine.connect() as connection:
  438. connection.execute("CREATE TABLE DB(id int);")
  439. connection.execute("DROP TABLE DB;")
  440. else:
  441. text = 'CREATE DATABASE {0}'.format(quote(engine, database))
  442. with engine.connect() as connection:
  443. connection.execute(text)
  444. engine.dispose()
  445. def drop_database(url):
  446. """Issue the appropriate DROP DATABASE statement.
  447. :param url: A SQLAlchemy engine URL.
  448. Works similar to the :ref:`create_database` method in that both url text
  449. and a constructed url are accepted. ::
  450. drop_database('postgresql://postgres@localhost/name')
  451. drop_database(engine.url)
  452. """
  453. url = copy(make_url(url))
  454. database = url.database
  455. dialect_name = url.get_dialect().name
  456. dialect_driver = url.get_dialect().driver
  457. if dialect_name == 'postgresql':
  458. url = _set_url_database(url, database="postgres")
  459. elif dialect_name == 'mssql':
  460. url = _set_url_database(url, database="master")
  461. elif not dialect_name == 'sqlite':
  462. url = _set_url_database(url, database=None)
  463. if dialect_name == 'mssql' and dialect_driver in {'pymssql', 'pyodbc'}:
  464. engine = sa.create_engine(url, connect_args={'autocommit': True})
  465. elif dialect_name == 'postgresql' and dialect_driver in {
  466. 'asyncpg', 'pg8000', 'psycopg2', 'psycopg2cffi'}:
  467. engine = sa.create_engine(url, isolation_level='AUTOCOMMIT')
  468. else:
  469. engine = sa.create_engine(url)
  470. if dialect_name == 'sqlite' and database != ':memory:':
  471. if database:
  472. os.remove(database)
  473. elif dialect_name == 'postgresql':
  474. with engine.connect() as connection:
  475. # Disconnect all users from the database we are dropping.
  476. version = connection.dialect.server_version_info
  477. pid_column = (
  478. 'pid' if (version >= (9, 2)) else 'procpid'
  479. )
  480. text = '''
  481. SELECT pg_terminate_backend(pg_stat_activity.%(pid_column)s)
  482. FROM pg_stat_activity
  483. WHERE pg_stat_activity.datname = '%(database)s'
  484. AND %(pid_column)s <> pg_backend_pid();
  485. ''' % {'pid_column': pid_column, 'database': database}
  486. connection.execute(text)
  487. # Drop the database.
  488. text = 'DROP DATABASE {0}'.format(quote(connection, database))
  489. connection.execute(text)
  490. else:
  491. text = 'DROP DATABASE {0}'.format(quote(engine, database))
  492. with engine.connect() as connection:
  493. connection.execute(text)
  494. engine.dispose()