database.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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 parameter 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(f"'{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(f"'{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(url, '_replace'):
  310. # Cannot use URL.set() as database may need to be set to None.
  311. ret = url._replace(database=database)
  312. else: # SQLAlchemy <1.4
  313. url = copy(url)
  314. url.database = database
  315. ret = url
  316. assert ret.database == database, ret
  317. return ret
  318. def _get_scalar_result(engine, sql):
  319. with engine.connect() as conn:
  320. return conn.scalar(sql)
  321. def _sqlite_file_exists(database):
  322. if not os.path.isfile(database) or os.path.getsize(database) < 100:
  323. return False
  324. with open(database, 'rb') as f:
  325. header = f.read(100)
  326. return header[:16] == b'SQLite format 3\x00'
  327. def database_exists(url):
  328. """Check if a database exists.
  329. :param url: A SQLAlchemy engine URL.
  330. Performs backend-specific testing to quickly determine if a database
  331. exists on the server. ::
  332. database_exists('postgresql://postgres@localhost/name') #=> False
  333. create_database('postgresql://postgres@localhost/name')
  334. database_exists('postgresql://postgres@localhost/name') #=> True
  335. Supports checking against a constructed URL as well. ::
  336. engine = create_engine('postgresql://postgres@localhost/name')
  337. database_exists(engine.url) #=> False
  338. create_database(engine.url)
  339. database_exists(engine.url) #=> True
  340. """
  341. url = make_url(url)
  342. database = url.database
  343. dialect_name = url.get_dialect().name
  344. engine = None
  345. try:
  346. if dialect_name == 'postgresql':
  347. text = "SELECT 1 FROM pg_database WHERE datname='%s'" % database
  348. for db in (database, 'postgres', 'template1', 'template0', None):
  349. url = _set_url_database(url, database=db)
  350. engine = sa.create_engine(url)
  351. try:
  352. return bool(_get_scalar_result(engine, sa.text(text)))
  353. except (ProgrammingError, OperationalError):
  354. pass
  355. return False
  356. elif dialect_name == 'mysql':
  357. url = _set_url_database(url, database=None)
  358. engine = sa.create_engine(url)
  359. text = ("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA "
  360. "WHERE SCHEMA_NAME = '%s'" % database)
  361. return bool(_get_scalar_result(engine, sa.text(text)))
  362. elif dialect_name == 'sqlite':
  363. url = _set_url_database(url, database=None)
  364. engine = sa.create_engine(url)
  365. if database:
  366. return database == ':memory:' or _sqlite_file_exists(database)
  367. else:
  368. # The default SQLAlchemy database is in memory, and :memory: is
  369. # not required, thus we should support that use case.
  370. return True
  371. else:
  372. text = 'SELECT 1'
  373. try:
  374. engine = sa.create_engine(url)
  375. return bool(_get_scalar_result(engine, sa.text(text)))
  376. except (ProgrammingError, OperationalError):
  377. return False
  378. finally:
  379. if engine:
  380. engine.dispose()
  381. def create_database(url, encoding='utf8', template=None):
  382. """Issue the appropriate CREATE DATABASE statement.
  383. :param url: A SQLAlchemy engine URL.
  384. :param encoding: The encoding to create the database as.
  385. :param template:
  386. The name of the template from which to create the new database. At the
  387. moment only supported by PostgreSQL driver.
  388. To create a database, you can pass a simple URL that would have
  389. been passed to ``create_engine``. ::
  390. create_database('postgresql://postgres@localhost/name')
  391. You may also pass the url from an existing engine. ::
  392. create_database(engine.url)
  393. Has full support for mysql, postgres, and sqlite. In theory,
  394. other database engines should be supported.
  395. """
  396. url = make_url(url)
  397. database = url.database
  398. dialect_name = url.get_dialect().name
  399. dialect_driver = url.get_dialect().driver
  400. if dialect_name == 'postgresql':
  401. url = _set_url_database(url, database="postgres")
  402. elif dialect_name == 'mssql':
  403. url = _set_url_database(url, database="master")
  404. elif dialect_name == 'cockroachdb':
  405. url = _set_url_database(url, database="defaultdb")
  406. elif not dialect_name == 'sqlite':
  407. url = _set_url_database(url, database=None)
  408. if (dialect_name == 'mssql' and dialect_driver in {'pymssql', 'pyodbc'}) \
  409. or (dialect_name == 'postgresql' and dialect_driver in {
  410. 'asyncpg', 'pg8000', 'psycopg', 'psycopg2', 'psycopg2cffi'}):
  411. engine = sa.create_engine(url, isolation_level='AUTOCOMMIT')
  412. else:
  413. engine = sa.create_engine(url)
  414. if dialect_name == 'postgresql':
  415. if not template:
  416. template = 'template1'
  417. with engine.begin() as conn:
  418. text = "CREATE DATABASE {} ENCODING '{}' TEMPLATE {}".format(
  419. quote(conn, database),
  420. encoding,
  421. quote(conn, template)
  422. )
  423. conn.execute(sa.text(text))
  424. elif dialect_name == 'mysql':
  425. with engine.begin() as conn:
  426. text = "CREATE DATABASE {} CHARACTER SET = '{}'".format(
  427. quote(conn, database),
  428. encoding
  429. )
  430. conn.execute(sa.text(text))
  431. elif dialect_name == 'sqlite' and database != ':memory:':
  432. if database:
  433. with engine.begin() as conn:
  434. conn.execute(sa.text('CREATE TABLE DB(id int)'))
  435. conn.execute(sa.text('DROP TABLE DB'))
  436. else:
  437. with engine.begin() as conn:
  438. text = f'CREATE DATABASE {quote(conn, database)}'
  439. conn.execute(sa.text(text))
  440. engine.dispose()
  441. def drop_database(url):
  442. """Issue the appropriate DROP DATABASE statement.
  443. :param url: A SQLAlchemy engine URL.
  444. Works similar to the :ref:`create_database` method in that both url text
  445. and a constructed url are accepted. ::
  446. drop_database('postgresql://postgres@localhost/name')
  447. drop_database(engine.url)
  448. """
  449. url = make_url(url)
  450. database = url.database
  451. dialect_name = url.get_dialect().name
  452. dialect_driver = url.get_dialect().driver
  453. if dialect_name == 'postgresql':
  454. url = _set_url_database(url, database="postgres")
  455. elif dialect_name == 'mssql':
  456. url = _set_url_database(url, database="master")
  457. elif dialect_name == 'cockroachdb':
  458. url = _set_url_database(url, database="defaultdb")
  459. elif not dialect_name == 'sqlite':
  460. url = _set_url_database(url, database=None)
  461. if dialect_name == 'mssql' and dialect_driver in {'pymssql', 'pyodbc'}:
  462. engine = sa.create_engine(url, connect_args={'autocommit': True})
  463. elif dialect_name == 'postgresql' and dialect_driver in {
  464. 'asyncpg', 'pg8000', 'psycopg', 'psycopg2', 'psycopg2cffi'}:
  465. engine = sa.create_engine(url, isolation_level='AUTOCOMMIT')
  466. else:
  467. engine = sa.create_engine(url)
  468. if dialect_name == 'sqlite' and database != ':memory:':
  469. if database:
  470. os.remove(database)
  471. elif dialect_name == 'postgresql':
  472. with engine.begin() as conn:
  473. # Disconnect all users from the database we are dropping.
  474. version = conn.dialect.server_version_info
  475. pid_column = (
  476. 'pid' if (version >= (9, 2)) else 'procpid'
  477. )
  478. text = '''
  479. SELECT pg_terminate_backend(pg_stat_activity.{pid_column})
  480. FROM pg_stat_activity
  481. WHERE pg_stat_activity.datname = '{database}'
  482. AND {pid_column} <> pg_backend_pid();
  483. '''.format(pid_column=pid_column, database=database)
  484. conn.execute(sa.text(text))
  485. # Drop the database.
  486. text = f'DROP DATABASE {quote(conn, database)}'
  487. conn.execute(sa.text(text))
  488. else:
  489. with engine.begin() as conn:
  490. text = f'DROP DATABASE {quote(conn, database)}'
  491. conn.execute(sa.text(text))
  492. engine.dispose()