signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def wipe_table(self, table: str) -> int: | sql = "<STR_LIT>" + self.delimit(table)<EOL>return self.db_exec(sql)<EOL> | Delete all records from a table. Use caution! | f14623:c6:m78 |
def create_or_replace_primary_key(self,<EOL>table: str,<EOL>fieldnames: Sequence[str]) -> int: | <EOL>sql = """<STR_LIT>""".format(self.get_current_schema_expr())<EOL>row = self.fetchone(sql, table)<EOL>has_pk_already = True if row[<NUM_LIT:0>] >= <NUM_LIT:1> else False<EOL>drop_pk_if_exists = "<STR_LIT>" if has_pk_already else "<STR_LIT>"<EOL>fieldlist = "<STR_LIT:U+002C>".join([self.delimit(f) for f in fieldnames])<EOL>sql = ("<STR_LIT>" + self.delimit(table) +<EOL>drop_pk_if_exists +<EOL>"<STR_LIT>" + fieldlist + "<STR_LIT:)>")<EOL>return self.db_exec(sql)<EOL> | Make a primary key, or replace it if it exists. | f14623:c6:m79 |
def is_read_only(self) -> bool: | return self.flavour.is_read_only(self, logger=log)<EOL> | Does the user have read-only access to the database?
This is a safety check, but should NOT be the only safety check! | f14623:c6:m90 |
def escape_newlines(s: str) -> str: | if not s:<EOL><INDENT>return s<EOL><DEDENT>s = s.replace("<STR_LIT:\\>", r"<STR_LIT:\\>") <EOL>s = s.replace("<STR_LIT:\n>", r"<STR_LIT:\n>") <EOL>s = s.replace("<STR_LIT:\r>", r"<STR_LIT:\r>") <EOL>return s<EOL> | Escapes CR, LF, and backslashes.
Its counterpart is :func:`unescape_newlines`.
``s.encode("string_escape")`` and ``s.encode("unicode_escape")`` are
alternatives, but they mess around with quotes, too (specifically,
backslash-escaping single quotes). | f14624:m0 |
def unescape_newlines(s: str) -> str: | <EOL>if not s:<EOL><INDENT>return s<EOL><DEDENT>d = "<STR_LIT>" <EOL>in_escape = False<EOL>for i in range(len(s)):<EOL><INDENT>c = s[i] <EOL>if in_escape:<EOL><INDENT>if c == "<STR_LIT:r>":<EOL><INDENT>d += "<STR_LIT:\r>"<EOL><DEDENT>elif c == "<STR_LIT:n>":<EOL><INDENT>d += "<STR_LIT:\n>"<EOL><DEDENT>else:<EOL><INDENT>d += c<EOL><DEDENT>in_escape = False<EOL><DEDENT>else:<EOL><INDENT>if c == "<STR_LIT:\\>":<EOL><INDENT>in_escape = True<EOL><DEDENT>else:<EOL><INDENT>d += c<EOL><DEDENT><DEDENT><DEDENT>return d<EOL> | Reverses :func:`escape_newlines`. | f14624:m1 |
def escape_tabs_newlines(s: str) -> str: | if not s:<EOL><INDENT>return s<EOL><DEDENT>s = s.replace("<STR_LIT:\\>", r"<STR_LIT:\\>") <EOL>s = s.replace("<STR_LIT:\n>", r"<STR_LIT:\n>") <EOL>s = s.replace("<STR_LIT:\r>", r"<STR_LIT:\r>") <EOL>s = s.replace("<STR_LIT:\t>", r"<STR_LIT:\t>") <EOL>return s<EOL> | Escapes CR, LF, tab, and backslashes.
Its counterpart is :func:`unescape_tabs_newlines`. | f14624:m2 |
def unescape_tabs_newlines(s: str) -> str: | if not s:<EOL><INDENT>return s<EOL><DEDENT>d = "<STR_LIT>" <EOL>in_escape = False<EOL>for i in range(len(s)):<EOL><INDENT>c = s[i] <EOL>if in_escape:<EOL><INDENT>if c == "<STR_LIT:r>":<EOL><INDENT>d += "<STR_LIT:\r>"<EOL><DEDENT>elif c == "<STR_LIT:n>":<EOL><INDENT>d += "<STR_LIT:\n>"<EOL><DEDENT>elif c == "<STR_LIT:t>":<EOL><INDENT>d += "<STR_LIT:\t>"<EOL><DEDENT>else:<EOL><INDENT>d += c<EOL><DEDENT>in_escape = False<EOL><DEDENT>else:<EOL><INDENT>if c == "<STR_LIT:\\>":<EOL><INDENT>in_escape = True<EOL><DEDENT>else:<EOL><INDENT>d += c<EOL><DEDENT><DEDENT><DEDENT>return d<EOL> | Reverses :func:`escape_tabs_newlines`.
See also http://stackoverflow.com/questions/4020539. | f14624:m3 |
def _unicode_def_src_to_str(srclist: List[Union[str, int]]) -> str: | charlist = [] <EOL>for src in srclist:<EOL><INDENT>if isinstance(src, int):<EOL><INDENT>charlist.append(chr(src))<EOL><DEDENT>else:<EOL><INDENT>first, last = [int(x, <NUM_LIT:16>) for x in src.split("<STR_LIT:->")]<EOL>charlist += [chr(x) for x in range(first, last + <NUM_LIT:1>)]<EOL><DEDENT><DEDENT>return "<STR_LIT>".join(charlist)<EOL> | Used to create :data:`UNICODE_CATEGORY_STRINGS`.
Args:
srclist: list of integers or hex range strings like ``"0061-007A"``
Returns:
a string with all characters described by ``srclist``: either the
character corresponding to the integer Unicode character number, or
all characters corresponding to the inclusive range described | f14624:m4 |
def __new__(mcs, cls, bases, oldclassdict): | newclassdict = _EnumDict()<EOL>for k, v in oldclassdict.items():<EOL><INDENT>if v == ():<EOL><INDENT>v = k<EOL><DEDENT>newclassdict[k] = v<EOL><DEDENT>return super().__new__(mcs, cls, bases, newclassdict)<EOL> | Scan through ``oldclassdict`` and convert any value that is a plain
tuple into a ``str`` of the name instead. | f14626:c1:m0 |
def __new__(mcs, cls, bases, oldclassdict): | newclassdict = _EnumDict()<EOL>for k, v in oldclassdict.items():<EOL><INDENT>if v == ():<EOL><INDENT>v = k.lower()<EOL><DEDENT>if v in newclassdict.keys():<EOL><INDENT>raise ValueError("<STR_LIT>".format(k))<EOL><DEDENT>newclassdict[k] = v<EOL><DEDENT>return super().__new__(mcs, cls, bases, newclassdict)<EOL> | Scan through ``oldclassdict`` and convert any value that is a plain
tuple into a ``str`` of the name instead. | f14626:c3:m0 |
@classmethod<EOL><INDENT>def __prepare__(mcs, name, bases): <DEDENT> | <EOL>return collections.defaultdict(itertools.count().__next__)<EOL> | Called when AutoEnum (below) is defined, prior to ``__new__``, with:
.. code-block:: python
name = 'AutoEnum'
bases = () | f14626:c6:m0 |
def __new__(mcs, name, bases, classdict): | <EOL>cls = type.__new__(mcs, name, bases, dict(classdict))<EOL>return cls<EOL> | Called when AutoEnum (below) is defined, with:
.. code-block:: python
name = 'AutoEnum'
bases = ()
classdict = defaultdict(<method-wrapper '__next__' of itertools.count
object at 0x7f7d8fc5f648>,
{
'__doc__': '... a docstring... ',
'__qualname__': 'AutoEnum',
'__name__': 0,
'__module__': 0
}
) | f14626:c6:m1 |
def derived_class_implements_method(derived: Type[T1],<EOL>base: Type[T2],<EOL>method_name: str) -> bool: | derived_method = getattr(derived, method_name, None)<EOL>if derived_method is None:<EOL><INDENT>return False<EOL><DEDENT>base_method = getattr(base, method_name, None)<EOL>return derived_method is not base_method<EOL> | Does a derived class implement a method (and not just inherit a base
class's version)?
Args:
derived: a derived class
base: a base class
method_name: the name of a method
Returns:
whether the derived class method is (a) present, and (b) different to
the base class's version of the same method
Note: if C derives from B derives from A, then a check on C versus A will
succeed if C implements the method, or if C inherits it from B but B has
re-implemented it compared to A. | f14627:m0 |
def gen_all_subclasses(cls: Type) -> Generator[Type, None, None]: | for s1 in cls.__subclasses__():<EOL><INDENT>yield s1<EOL>for s2 in gen_all_subclasses(s1):<EOL><INDENT>yield s2<EOL><DEDENT><DEDENT> | Generates all subclasses of a class.
Args:
cls: a class
Yields:
all subclasses | f14627:m1 |
def all_subclasses(cls: Type) -> List[Type]: | return list(gen_all_subclasses(cls))<EOL> | Returns all subclasses of a class.
Args:
cls: a class
Returns:
a list of all subclasses | f14627:m2 |
def excel_to_bytes(wb: Workbook) -> bytes: | memfile = io.BytesIO()<EOL>wb.save(memfile)<EOL>return memfile.getvalue()<EOL> | Obtain a binary version of an :class:`openpyxl.Workbook` representation of
an Excel file. | f14628:m0 |
def __init__(self,<EOL>tablename: str = None,<EOL>table: Table = None,<EOL>metadata: MetaData = None) -> None: | assert table is not None or tablename, "<STR_LIT>"<EOL>assert not (tablename and table is not None), (<EOL>"<STR_LIT>")<EOL>self._table = table<EOL>self._tablename = tablename<EOL>self._metadata = metadata<EOL> | Initialize with either ``tablename`` or ``table``, not both.
Args:
tablename: string name of the table
table: SQLAlchemy :class:`Table` object
metadata: optional :class:`MetaData` object | f14629:c0:m0 |
@property<EOL><INDENT>def table(self) -> Table:<DEDENT> | if self._table is not None:<EOL><INDENT>return self._table<EOL><DEDENT>assert self._metadata, (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>for table in self._metadata.tables.values(): <EOL><INDENT>if table.name == self._tablename:<EOL><INDENT>return table<EOL><DEDENT><DEDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(self._tablename))<EOL> | Returns a SQLAlchemy :class:`Table` object. This is either the
:class:`Table` object that was used for initialization, or one that
was constructed from the ``tablename`` plus the ``metadata``. | f14629:c0:m3 |
@property<EOL><INDENT>def tablename(self) -> str:<DEDENT> | if self._tablename:<EOL><INDENT>return self._tablename<EOL><DEDENT>return self.table.name<EOL> | Returns the string name of the table. | f14629:c0:m4 |
def set_metadata(self, metadata: MetaData) -> None: | self._metadata = metadata<EOL> | Sets the :class:`MetaData`. | f14629:c0:m5 |
def set_metadata_if_none(self, metadata: MetaData) -> None: | if self._metadata is None:<EOL><INDENT>self._metadata = metadata<EOL><DEDENT> | Sets the :class:`MetaData` unless it was set already. | f14629:c0:m6 |
def get_table_names(engine: Engine) -> List[str]: | insp = Inspector.from_engine(engine)<EOL>return insp.get_table_names()<EOL> | Returns a list of database table names from the :class:`Engine`. | f14630:m0 |
def get_view_names(engine: Engine) -> List[str]: | insp = Inspector.from_engine(engine)<EOL>return insp.get_view_names()<EOL> | Returns a list of database view names from the :class:`Engine`. | f14630:m1 |
def table_exists(engine: Engine, tablename: str) -> bool: | return tablename in get_table_names(engine)<EOL> | Does the named table exist in the database? | f14630:m2 |
def view_exists(engine: Engine, viewname: str) -> bool: | return viewname in get_view_names(engine)<EOL> | Does the named view exist in the database? | f14630:m3 |
def table_or_view_exists(engine: Engine, table_or_view_name: str) -> bool: | tables_and_views = get_table_names(engine) + get_view_names(engine)<EOL>return table_or_view_name in tables_and_views<EOL> | Does the named table/view exist (either as a table or as a view) in the
database? | f14630:m4 |
def gen_columns_info(engine: Engine,<EOL>tablename: str) -> Generator[SqlaColumnInspectionInfo,<EOL>None, None]: | <EOL>insp = Inspector.from_engine(engine)<EOL>for d in insp.get_columns(tablename):<EOL><INDENT>yield SqlaColumnInspectionInfo(d)<EOL><DEDENT> | For the specified table, generate column information as
:class:`SqlaColumnInspectionInfo` objects. | f14630:m5 |
def get_column_info(engine: Engine, tablename: str,<EOL>columnname: str) -> Optional[SqlaColumnInspectionInfo]: | for info in gen_columns_info(engine, tablename):<EOL><INDENT>if info.name == columnname:<EOL><INDENT>return info<EOL><DEDENT><DEDENT>return None<EOL> | For the specified column in the specified table, get column information
as a :class:`SqlaColumnInspectionInfo` object (or ``None`` if such a
column can't be found). | f14630:m6 |
def get_column_type(engine: Engine, tablename: str,<EOL>columnname: str) -> Optional[TypeEngine]: | for info in gen_columns_info(engine, tablename):<EOL><INDENT>if info.name == columnname:<EOL><INDENT>return info.type<EOL><DEDENT><DEDENT>return None<EOL> | For the specified column in the specified table, get its type as an
instance of an SQLAlchemy column type class (or ``None`` if such a column
can't be found).
For more on :class:`TypeEngine`, see
:func:`cardinal_pythonlib.orm_inspect.coltype_as_typeengine`. | f14630:m7 |
def get_column_names(engine: Engine, tablename: str) -> List[str]: | return [info.name for info in gen_columns_info(engine, tablename)]<EOL> | Get all the database column names for the specified table. | f14630:m8 |
def get_pk_colnames(table_: Table) -> List[str]: | pk_names = [] <EOL>for col in table_.columns:<EOL><INDENT>if col.primary_key:<EOL><INDENT>pk_names.append(col.name)<EOL><DEDENT><DEDENT>return pk_names<EOL> | If a table has a PK, this will return its database column name(s);
otherwise, ``None``. | f14630:m9 |
def get_single_int_pk_colname(table_: Table) -> Optional[str]: | n_pks = <NUM_LIT:0><EOL>int_pk_names = []<EOL>for col in table_.columns:<EOL><INDENT>if col.primary_key:<EOL><INDENT>n_pks += <NUM_LIT:1><EOL>if is_sqlatype_integer(col.type):<EOL><INDENT>int_pk_names.append(col.name)<EOL><DEDENT><DEDENT><DEDENT>if n_pks == <NUM_LIT:1> and len(int_pk_names) == <NUM_LIT:1>:<EOL><INDENT>return int_pk_names[<NUM_LIT:0>]<EOL><DEDENT>return None<EOL> | If a table has a single-field (non-composite) integer PK, this will
return its database column name; otherwise, None.
Note that it is legitimate for a database table to have both a composite
primary key and a separate ``IDENTITY`` (``AUTOINCREMENT``) integer field.
This function won't find such columns. | f14630:m10 |
def get_single_int_autoincrement_colname(table_: Table) -> Optional[str]: | n_autoinc = <NUM_LIT:0><EOL>int_autoinc_names = []<EOL>for col in table_.columns:<EOL><INDENT>if col.autoincrement:<EOL><INDENT>n_autoinc += <NUM_LIT:1><EOL>if is_sqlatype_integer(col.type):<EOL><INDENT>int_autoinc_names.append(col.name)<EOL><DEDENT><DEDENT><DEDENT>if n_autoinc > <NUM_LIT:1>:<EOL><INDENT>log.warning("<STR_LIT>",<EOL>table_.name, n_autoinc)<EOL><DEDENT>if n_autoinc == <NUM_LIT:1> and len(int_autoinc_names) == <NUM_LIT:1>:<EOL><INDENT>return int_autoinc_names[<NUM_LIT:0>]<EOL><DEDENT>return None<EOL> | If a table has a single integer ``AUTOINCREMENT`` column, this will
return its name; otherwise, ``None``.
- It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but
we should check.
- SQL Server's ``IDENTITY`` keyword is equivalent to MySQL's
``AUTOINCREMENT``.
- Verify against SQL Server:
.. code-block:: sql
SELECT table_name, column_name
FROM information_schema.columns
WHERE COLUMNPROPERTY(OBJECT_ID(table_schema + '.' + table_name),
column_name,
'IsIdentity') = 1
ORDER BY table_name;
... http://stackoverflow.com/questions/87747
- Also:
.. code-block:: sql
sp_columns 'tablename';
... which is what SQLAlchemy does (``dialects/mssql/base.py``, in
:func:`get_columns`). | f14630:m11 |
def get_effective_int_pk_col(table_: Table) -> Optional[str]: | return (<EOL>get_single_int_pk_colname(table_) or<EOL>get_single_int_autoincrement_colname(table_) or<EOL>None<EOL>)<EOL> | If a table has a single integer primary key, or a single integer
``AUTOINCREMENT`` column, return its column name; otherwise, ``None``. | f14630:m12 |
def index_exists(engine: Engine, tablename: str, indexname: str) -> bool: | insp = Inspector.from_engine(engine)<EOL>return any(i['<STR_LIT:name>'] == indexname for i in insp.get_indexes(tablename))<EOL> | Does the specified index exist for the specified table? | f14630:m13 |
def mssql_get_pk_index_name(engine: Engine,<EOL>tablename: str,<EOL>schemaname: str = MSSQL_DEFAULT_SCHEMA) -> str: | <EOL>query = text("""<STR_LIT>""").bindparams(<EOL>tablename=tablename,<EOL>schemaname=schemaname,<EOL>)<EOL>with contextlib.closing(<EOL>engine.execute(query)) as result: <EOL><INDENT>row = result.fetchone()<EOL>return row[<NUM_LIT:0>] if row else '<STR_LIT>'<EOL><DEDENT> | For Microsoft SQL Server specifically: fetch the name of the PK index
for the specified table (in the specified schema), or ``''`` if none is
found. | f14630:m14 |
def mssql_table_has_ft_index(engine: Engine,<EOL>tablename: str,<EOL>schemaname: str = MSSQL_DEFAULT_SCHEMA) -> bool: | query = text("""<STR_LIT>""").bindparams(<EOL>tablename=tablename,<EOL>schemaname=schemaname,<EOL>)<EOL>with contextlib.closing(<EOL>engine.execute(query)) as result: <EOL><INDENT>row = result.fetchone()<EOL>return row[<NUM_LIT:0>] > <NUM_LIT:0><EOL><DEDENT> | For Microsoft SQL Server specifically: does the specified table (in the
specified schema) have at least one full-text index? | f14630:m15 |
def mssql_transaction_count(engine_or_conn: Union[Connection, Engine]) -> int: | sql = "<STR_LIT>"<EOL>with contextlib.closing(<EOL>engine_or_conn.execute(sql)) as result: <EOL><INDENT>row = result.fetchone()<EOL>return row[<NUM_LIT:0>] if row else None<EOL><DEDENT> | For Microsoft SQL Server specifically: fetch the value of the ``TRANCOUNT``
variable (see e.g.
https://docs.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017).
Returns ``None`` if it can't be found (unlikely?). | f14630:m16 |
def add_index(engine: Engine,<EOL>sqla_column: Column = None,<EOL>multiple_sqla_columns: List[Column] = None,<EOL>unique: bool = False,<EOL>fulltext: bool = False,<EOL>length: int = None) -> None: | <EOL>def quote(identifier: str) -> str:<EOL><INDENT>return quote_identifier(identifier, engine)<EOL><DEDENT>is_mssql = engine.dialect.name == SqlaDialectName.MSSQL<EOL>is_mysql = engine.dialect.name == SqlaDialectName.MYSQL<EOL>multiple_sqla_columns = multiple_sqla_columns or [] <EOL>if multiple_sqla_columns and not (fulltext and is_mssql):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if bool(multiple_sqla_columns) == (sqla_column is not None):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>repr(sqla_column), repr(multiple_sqla_columns)))<EOL><DEDENT>if sqla_column is not None:<EOL><INDENT>colnames = [sqla_column.name]<EOL>sqla_table = sqla_column.table<EOL>tablename = sqla_table.name<EOL><DEDENT>else:<EOL><INDENT>colnames = [c.name for c in multiple_sqla_columns]<EOL>sqla_table = multiple_sqla_columns[<NUM_LIT:0>].table<EOL>tablename = sqla_table.name<EOL>if any(c.table.name != tablename for c in multiple_sqla_columns[<NUM_LIT:1>:]):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>repr(multiple_sqla_columns)))<EOL><DEDENT><DEDENT>if fulltext:<EOL><INDENT>if is_mssql:<EOL><INDENT>idxname = '<STR_LIT>' <EOL><DEDENT>else:<EOL><INDENT>idxname = "<STR_LIT>".format("<STR_LIT:_>".join(colnames))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>idxname = "<STR_LIT>".format("<STR_LIT:_>".join(colnames))<EOL><DEDENT>if idxname and index_exists(engine, tablename, idxname):<EOL><INDENT>log.info("<STR_LIT>"<EOL>"<STR_LIT>".format(idxname, tablename))<EOL>return<EOL><DEDENT>log.info(<EOL>"<STR_LIT>",<EOL>ft="<STR_LIT>" if fulltext else "<STR_LIT>",<EOL>i=idxname or "<STR_LIT>",<EOL>t=tablename,<EOL>c="<STR_LIT:U+002CU+0020>".join(colnames),<EOL>)<EOL>if fulltext:<EOL><INDENT>if is_mysql:<EOL><INDENT>log.info('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>sql = (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>tablename=quote(tablename),<EOL>idxname=quote(idxname),<EOL>colnames="<STR_LIT:U+002CU+0020>".join(quote(c) for c in colnames),<EOL>)<EOL>)<EOL>DDL(sql, bind=engine).execute()<EOL><DEDENT>elif is_mssql: <EOL><INDENT>schemaname = engine.schema_for_object(<EOL>sqla_table) or MSSQL_DEFAULT_SCHEMA <EOL>if mssql_table_has_ft_index(engine=engine,<EOL>tablename=tablename,<EOL>schemaname=schemaname):<EOL><INDENT>log.info(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(tablename))<EOL>return<EOL><DEDENT>pk_index_name = mssql_get_pk_index_name(<EOL>engine=engine, tablename=tablename, schemaname=schemaname)<EOL>if not pk_index_name:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>repr(tablename)))<EOL><DEDENT>sql = (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>tablename=quote(tablename),<EOL>keyidxname=quote(pk_index_name),<EOL>colnames="<STR_LIT:U+002CU+0020>".join(quote(c) for c in colnames),<EOL>)<EOL>)<EOL>transaction_count = mssql_transaction_count(engine)<EOL>if transaction_count != <NUM_LIT:0>:<EOL><INDENT>log.critical("<STR_LIT>"<EOL>"<STR_LIT:{}>".format(transaction_count))<EOL><DEDENT>DDL(sql, bind=engine).execute()<EOL><DEDENT>else:<EOL><INDENT>log.error("<STR_LIT>"<EOL>"<STR_LIT:{}>".format(engine.dialect.name))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>index = Index(idxname, sqla_column, unique=unique, mysql_length=length)<EOL>index.create(engine)<EOL><DEDENT> | Adds an index to a database column (or, in restricted circumstances,
several columns).
The table name is worked out from the :class:`Column` object.
Args:
engine: SQLAlchemy :class:`Engine` object
sqla_column: single column to index
multiple_sqla_columns: multiple columns to index (see below)
unique: make a ``UNIQUE`` index?
fulltext: make a ``FULLTEXT`` index?
length: index length to use (default ``None``)
Restrictions:
- Specify either ``sqla_column`` or ``multiple_sqla_columns``, not both.
- The normal method is ``sqla_column``.
- ``multiple_sqla_columns`` is only used for Microsoft SQL Server full-text
indexing (as this database permits only one full-text index per table,
though that index can be on multiple columns). | f14630:m17 |
def make_bigint_autoincrement_column(column_name: str,<EOL>dialect: Dialect) -> Column: | <EOL>if dialect.name == SqlaDialectName.MSSQL:<EOL><INDENT>return Column(column_name, BigInteger,<EOL>Sequence('<STR_LIT>', start=<NUM_LIT:1>, increment=<NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(repr(dialect.name)))<EOL><DEDENT> | Returns an instance of :class:`Column` representing a :class:`BigInteger`
``AUTOINCREMENT`` column in the specified :class:`Dialect`. | f14630:m18 |
def column_creation_ddl(sqla_column: Column, dialect: Dialect) -> str: | <EOL>n str(CreateColumn(sqla_column).compile(dialect=dialect))<EOL> | Returns DDL to create a column, using the specified dialect.
The column should already be bound to a table (because e.g. the SQL Server
dialect requires this for DDL generation).
Manual testing:
.. code-block:: python
from sqlalchemy.schema import Column, CreateColumn, MetaData, Sequence, Table
from sqlalchemy.sql.sqltypes import BigInteger
from sqlalchemy.dialects.mssql.base import MSDialect
dialect = MSDialect()
col1 = Column('hello', BigInteger, nullable=True)
col2 = Column('world', BigInteger, autoincrement=True) # does NOT generate IDENTITY
col3 = Column('you', BigInteger, Sequence('dummy_name', start=1, increment=1))
metadata = MetaData()
t = Table('mytable', metadata)
t.append_column(col1)
t.append_column(col2)
t.append_column(col3)
print(str(CreateColumn(col1).compile(dialect=dialect))) # hello BIGINT NULL
print(str(CreateColumn(col2).compile(dialect=dialect))) # world BIGINT NULL
print(str(CreateColumn(col3).compile(dialect=dialect))) # you BIGINT NOT NULL IDENTITY(1,1)
If you don't append the column to a Table object, the DDL generation step
gives:
.. code-block:: none
sqlalchemy.exc.CompileError: mssql requires Table-bound columns in order to generate DDL | f14630:m19 |
def giant_text_sqltype(dialect: Dialect) -> str: | if dialect.name == SqlaDialectName.SQLSERVER:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>elif dialect.name == SqlaDialectName.MYSQL:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(dialect.name))<EOL><DEDENT> | Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVARCHAR(MAX)' for SQL Server. | f14630:m20 |
def _get_sqla_coltype_class_from_str(coltype: str,<EOL>dialect: Dialect) -> Type[TypeEngine]: | <EOL>ischema_names = dialect.ischema_names<EOL>try:<EOL><INDENT>return ischema_names[coltype.upper()]<EOL><DEDENT>except KeyError:<EOL><INDENT>return ischema_names[coltype.lower()]<EOL><DEDENT> | Returns the SQLAlchemy class corresponding to a particular SQL column
type in a given dialect.
Performs an upper- and lower-case search.
For example, the SQLite dialect uses upper case, and the
MySQL dialect uses lower case. | f14630:m21 |
def get_list_of_sql_string_literals_from_quoted_csv(x: str) -> List[str]: | f = io.StringIO(x)<EOL>reader = csv.reader(f, delimiter='<STR_LIT:U+002C>', quotechar="<STR_LIT:'>", quoting=csv.QUOTE_ALL,<EOL>skipinitialspace=True)<EOL>for line in reader: <EOL><INDENT>return [x for x in line]<EOL><DEDENT> | Used to extract SQL column type parameters. For example, MySQL has column
types that look like ``ENUM('a', 'b', 'c', 'd')``. This function takes the
``"'a', 'b', 'c', 'd'"`` and converts it to ``['a', 'b', 'c', 'd']``. | f14630:m22 |
@lru_cache(maxsize=None)<EOL>def get_sqla_coltype_from_dialect_str(coltype: str,<EOL>dialect: Dialect) -> TypeEngine: | size = None <EOL>dp = None <EOL>args = [] <EOL>kwargs = {} <EOL>basetype = '<STR_LIT>'<EOL>try:<EOL><INDENT>m = RE_COLTYPE_WITH_COLLATE.match(coltype)<EOL>if m is not None:<EOL><INDENT>coltype = m.group('<STR_LIT>')<EOL><DEDENT>found = False<EOL>if not found:<EOL><INDENT>m = RE_MYSQL_ENUM_COLTYPE.match(coltype)<EOL>if m is not None:<EOL><INDENT>basetype = '<STR_LIT>'<EOL>values = get_list_of_sql_string_literals_from_quoted_csv(<EOL>m.group('<STR_LIT>'))<EOL>length = max(len(x) for x in values)<EOL>kwargs = {'<STR_LIT>': length}<EOL>found = True<EOL><DEDENT><DEDENT>if not found:<EOL><INDENT>m = RE_COLTYPE_WITH_TWO_PARAMS.match(coltype)<EOL>if m is not None:<EOL><INDENT>basetype = m.group('<STR_LIT:type>').upper()<EOL>size = ast.literal_eval(m.group('<STR_LIT:size>'))<EOL>dp = ast.literal_eval(m.group('<STR_LIT>'))<EOL>found = True<EOL><DEDENT><DEDENT>if not found:<EOL><INDENT>m = RE_COLTYPE_WITH_ONE_PARAM.match(coltype)<EOL>if m is not None:<EOL><INDENT>basetype = m.group('<STR_LIT:type>').upper()<EOL>size_text = m.group('<STR_LIT:size>').strip().upper()<EOL>if size_text != '<STR_LIT>':<EOL><INDENT>size = ast.literal_eval(size_text)<EOL><DEDENT>found = True<EOL><DEDENT><DEDENT>if not found:<EOL><INDENT>basetype = coltype.upper()<EOL><DEDENT>if (dialect.name == SqlaDialectName.MSSQL and<EOL>basetype.lower() == '<STR_LIT>'):<EOL><INDENT>basetype = '<STR_LIT:int>'<EOL><DEDENT>cls = _get_sqla_coltype_class_from_str(basetype, dialect)<EOL>if basetype == '<STR_LIT>' and size:<EOL><INDENT>if dialect.name == SqlaDialectName.MYSQL:<EOL><INDENT>kwargs = {'<STR_LIT>': size}<EOL><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>args = [x for x in (size, dp) if x is not None]<EOL><DEDENT>try:<EOL><INDENT>return cls(*args, **kwargs)<EOL><DEDENT>except TypeError:<EOL><INDENT>return cls()<EOL><DEDENT><DEDENT>except:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(repr(coltype),<EOL>repr(dialect.name)))<EOL><DEDENT> | Returns an SQLAlchemy column type, given a column type name (a string) and
an SQLAlchemy dialect. For example, this might convert the string
``INTEGER(11)`` to an SQLAlchemy ``Integer(length=11)``.
Args:
dialect: a SQLAlchemy :class:`Dialect` class
coltype: a ``str()`` representation, e.g. from ``str(c['type'])`` where
``c`` is an instance of :class:`sqlalchemy.sql.schema.Column`.
Returns:
a Python object that is a subclass of
:class:`sqlalchemy.types.TypeEngine`
Example:
.. code-block:: python
get_sqla_coltype_from_string('INTEGER(11)', engine.dialect)
# gives: Integer(length=11)
Notes:
- :class:`sqlalchemy.engine.default.DefaultDialect` is the dialect base
class
- a dialect contains these things of interest:
- ``ischema_names``: string-to-class dictionary
- ``type_compiler``: instance of e.g.
:class:`sqlalchemy.sql.compiler.GenericTypeCompiler`. This has a
``process()`` method, but that operates on :class:`TypeEngine` objects.
- ``get_columns``: takes a table name, inspects the database
- example of the dangers of ``eval``:
http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
- An example of a function doing the reflection/inspection within
SQLAlchemy is
:func:`sqlalchemy.dialects.mssql.base.MSDialect.get_columns`,
which has this lookup: ``coltype = self.ischema_names.get(type, None)``
Caveats:
- the parameters, e.g. ``DATETIME(6)``, do NOT necessarily either work at
all or work correctly. For example, SQLAlchemy will happily spit out
``'INTEGER(11)'`` but its :class:`sqlalchemy.sql.sqltypes.INTEGER` class
takes no parameters, so you get the error ``TypeError: object() takes no
parameters``. Similarly, MySQL's ``DATETIME(6)`` uses the 6 to refer to
precision, but the ``DATETIME`` class in SQLAlchemy takes only a boolean
parameter (timezone).
- However, sometimes we have to have parameters, e.g. ``VARCHAR`` length.
- Thus, this is a bit useless.
- Fixed, with a few special cases. | f14630:m23 |
def remove_collation(coltype: TypeEngine) -> TypeEngine: | if not getattr(coltype, '<STR_LIT>', None):<EOL><INDENT>return coltype<EOL><DEDENT>newcoltype = copy.copy(coltype)<EOL>newcoltype.collation = None<EOL>return newcoltype<EOL> | Returns a copy of the specific column type with any ``COLLATION`` removed. | f14630:m24 |
@lru_cache(maxsize=None)<EOL>def convert_sqla_type_for_dialect(<EOL>coltype: TypeEngine,<EOL>dialect: Dialect,<EOL>strip_collation: bool = True,<EOL>convert_mssql_timestamp: bool = True,<EOL>expand_for_scrubbing: bool = False) -> TypeEngine: | assert coltype is not None<EOL>to_mysql = dialect.name == SqlaDialectName.MYSQL<EOL>to_mssql = dialect.name == SqlaDialectName.MSSQL<EOL>typeclass = type(coltype)<EOL>if isinstance(coltype, sqltypes.Enum):<EOL><INDENT>return sqltypes.String(length=coltype.length)<EOL><DEDENT>if isinstance(coltype, sqltypes.UnicodeText):<EOL><INDENT>return sqltypes.UnicodeText()<EOL><DEDENT>if isinstance(coltype, sqltypes.Text):<EOL><INDENT>return sqltypes.Text()<EOL><DEDENT>if isinstance(coltype, sqltypes.Unicode):<EOL><INDENT>if (coltype.length is None and to_mysql) or expand_for_scrubbing:<EOL><INDENT>return sqltypes.UnicodeText()<EOL><DEDENT><DEDENT>if isinstance(coltype, sqltypes.String):<EOL><INDENT>if (coltype.length is None and to_mysql) or expand_for_scrubbing:<EOL><INDENT>return sqltypes.Text()<EOL><DEDENT>if strip_collation:<EOL><INDENT>return remove_collation(coltype)<EOL><DEDENT>return coltype<EOL><DEDENT>if typeclass == mssql.base.BIT and to_mysql:<EOL><INDENT>return mysql.base.BIT()<EOL><DEDENT>is_mssql_timestamp = isinstance(coltype, MSSQL_TIMESTAMP)<EOL>if is_mssql_timestamp and to_mssql and convert_mssql_timestamp:<EOL><INDENT>return mssql.base.BINARY(<NUM_LIT:8>)<EOL><DEDENT>return coltype<EOL> | Converts an SQLAlchemy column type from one SQL dialect to another.
Args:
coltype: SQLAlchemy column type in the source dialect
dialect: destination :class:`Dialect`
strip_collation: remove any ``COLLATION`` information?
convert_mssql_timestamp:
since you cannot write to a SQL Server ``TIMESTAMP`` field, setting
this option to ``True`` (the default) converts such types to
something equivalent but writable.
expand_for_scrubbing:
The purpose of expand_for_scrubbing is that, for example, a
``VARCHAR(200)`` field containing one or more instances of
``Jones``, where ``Jones`` is to be replaced with ``[XXXXXX]``,
will get longer (by an unpredictable amount). So, better to expand
to unlimited length.
Returns:
an SQLAlchemy column type instance, in the destination dialect | f14630:m25 |
def _coltype_to_typeengine(coltype: Union[TypeEngine,<EOL>VisitableType]) -> TypeEngine: | if isinstance(coltype, VisitableType):<EOL><INDENT>coltype = coltype()<EOL><DEDENT>assert isinstance(coltype, TypeEngine)<EOL>return coltype<EOL> | An example is simplest: if you pass in ``Integer()`` (an instance of
:class:`TypeEngine`), you'll get ``Integer()`` back. If you pass in
``Integer`` (an instance of :class:`VisitableType`), you'll also get
``Integer()`` back. The function asserts that its return type is an
instance of :class:`TypeEngine`. | f14630:m26 |
def is_sqlatype_binary(coltype: Union[TypeEngine, VisitableType]) -> bool: | <EOL>coltype = _coltype_to_typeengine(coltype)<EOL>return isinstance(coltype, sqltypes._Binary)<EOL> | Is the SQLAlchemy column type a binary type? | f14630:m27 |
def is_sqlatype_date(coltype: TypeEngine) -> bool: | coltype = _coltype_to_typeengine(coltype)<EOL>return (<EOL>isinstance(coltype, sqltypes.DateTime) or<EOL>isinstance(coltype, sqltypes.Date)<EOL>)<EOL> | Is the SQLAlchemy column type a date type? | f14630:m28 |
def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool: | coltype = _coltype_to_typeengine(coltype)<EOL>return isinstance(coltype, sqltypes.Integer)<EOL> | Is the SQLAlchemy column type an integer type? | f14630:m29 |
def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool: | coltype = _coltype_to_typeengine(coltype)<EOL>return isinstance(coltype, sqltypes.Numeric)<EOL> | Is the SQLAlchemy column type one that inherits from :class:`Numeric`,
such as :class:`Float`, :class:`Decimal`? | f14630:m30 |
def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool: | coltype = _coltype_to_typeengine(coltype)<EOL>return isinstance(coltype, sqltypes.String)<EOL> | Is the SQLAlchemy column type a string type? | f14630:m31 |
def is_sqlatype_text_of_length_at_least(<EOL>coltype: Union[TypeEngine, VisitableType],<EOL>min_length: int = <NUM_LIT:1000>) -> bool: | coltype = _coltype_to_typeengine(coltype)<EOL>if not isinstance(coltype, sqltypes.String):<EOL><INDENT>return False <EOL><DEDENT>if coltype.length is None:<EOL><INDENT>return True <EOL><DEDENT>return coltype.length >= min_length<EOL> | Is the SQLAlchemy column type a string type that's at least the specified
length? | f14630:m32 |
def is_sqlatype_text_over_one_char(<EOL>coltype: Union[TypeEngine, VisitableType]) -> bool: | coltype = _coltype_to_typeengine(coltype)<EOL>return is_sqlatype_text_of_length_at_least(coltype, <NUM_LIT:2>)<EOL> | Is the SQLAlchemy column type a string type that's more than one character
long? | f14630:m33 |
def does_sqlatype_merit_fulltext_index(<EOL>coltype: Union[TypeEngine, VisitableType],<EOL>min_length: int = <NUM_LIT:1000>) -> bool: | coltype = _coltype_to_typeengine(coltype)<EOL>return is_sqlatype_text_of_length_at_least(coltype, min_length)<EOL> | Is the SQLAlchemy column type a type that might merit a ``FULLTEXT``
index (meaning a string type of at least ``min_length``)? | f14630:m34 |
def does_sqlatype_require_index_len(<EOL>coltype: Union[TypeEngine, VisitableType]) -> bool: | coltype = _coltype_to_typeengine(coltype)<EOL>if isinstance(coltype, sqltypes.Text):<EOL><INDENT>return True<EOL><DEDENT>if isinstance(coltype, sqltypes.LargeBinary):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL> | Is the SQLAlchemy column type one that requires its indexes to have a
length specified?
(MySQL, at least, requires index length to be specified for ``BLOB`` and
``TEXT`` columns:
http://dev.mysql.com/doc/refman/5.7/en/create-index.html.) | f14630:m35 |
def hack_in_mssql_xml_type(): | <EOL>ebug("<STR_LIT>")<EOL>.base.ischema_names['<STR_LIT>'] = mssql.base.TEXT<EOL>p://stackoverflow.com/questions/<NUM_LIT>/sqlalchemy-making-schema-reflection-find-use-a-custom-type-for-all-instances <EOL>nt(repr(mssql.base.ischema_names.keys()))<EOL>nt(repr(mssql.base.ischema_names))<EOL> | r"""
Modifies SQLAlchemy's type map for Microsoft SQL Server to support XML.
SQLAlchemy does not support the XML type in SQL Server (mssql).
Upon reflection, we get:
.. code-block:: none
sqlalchemy\dialects\mssql\base.py:1921: SAWarning: Did not recognize type 'xml' of column '...'
We will convert anything of type ``XML`` into type ``TEXT``. | f14630:m36 |
def column_types_equal(a_coltype: TypeEngine, b_coltype: TypeEngine) -> bool: | <EOL>n str(a_coltype) == str(b_coltype)<EOL> | Checks that two SQLAlchemy column types are equal (by comparing ``str()``
versions of them).
See http://stackoverflow.com/questions/34787794/sqlalchemy-column-type-comparison.
IMPERFECT. | f14630:m37 |
def columns_equal(a: Column, b: Column) -> bool: | return (<EOL>a.name == b.name and<EOL>column_types_equal(a.type, b.type) and<EOL>a.nullable == b.nullable<EOL>)<EOL> | Are two SQLAlchemy columns are equal? Checks based on:
- column ``name``
- column ``type`` (see :func:`column_types_equal`)
- ``nullable`` | f14630:m38 |
def column_lists_equal(a: List[Column], b: List[Column]) -> bool: | n = len(a)<EOL>if len(b) != n:<EOL><INDENT>return False<EOL><DEDENT>for i in range(n):<EOL><INDENT>if not columns_equal(a[i], b[i]):<EOL><INDENT>log.debug("<STR_LIT>", a[i], b[i])<EOL>return False<EOL><DEDENT><DEDENT>return True<EOL> | Are all columns in list ``a`` equal to their counterparts in list ``b``,
as per :func:`columns_equal`? | f14630:m39 |
def indexes_equal(a: Index, b: Index) -> bool: | return str(a) == str(b)<EOL> | Are two indexes equal? Checks by comparing ``str()`` versions of them.
(AM UNSURE IF THIS IS ENOUGH.) | f14630:m40 |
def index_lists_equal(a: List[Index], b: List[Index]) -> bool: | n = len(a)<EOL>if len(b) != n:<EOL><INDENT>return False<EOL><DEDENT>for i in range(n):<EOL><INDENT>if not indexes_equal(a[i], b[i]):<EOL><INDENT>log.debug("<STR_LIT>", a[i], b[i])<EOL>return False<EOL><DEDENT><DEDENT>return True<EOL> | Are all indexes in list ``a`` equal to their counterparts in list ``b``,
as per :func:`indexes_equal`? | f14630:m41 |
def __init__(self, sqla_info_dict: Dict[str, Any]) -> None: | <EOL>self.name = sqla_info_dict['<STR_LIT:name>'] <EOL>self.type = sqla_info_dict['<STR_LIT:type>'] <EOL>self.nullable = sqla_info_dict['<STR_LIT>'] <EOL>self.default = sqla_info_dict['<STR_LIT:default>'] <EOL>self.attrs = sqla_info_dict.get('<STR_LIT>', {}) <EOL>self.comment = sqla_info_dict.get('<STR_LIT>', '<STR_LIT>')<EOL> | Args:
sqla_info_dict:
see
- http://docs.sqlalchemy.org/en/latest/core/reflection.html#sqlalchemy.engine.reflection.Inspector.get_columns
- https://bitbucket.org/zzzeek/sqlalchemy/issues/4051/sqlalchemyenginereflectioninspectorget_col | f14630:c0:m0 |
def create_table_from_orm_class(engine: Engine,<EOL>ormclass: DeclarativeMeta,<EOL>without_constraints: bool = False) -> None: | table = ormclass.__table__ <EOL>log.info("<STR_LIT>",<EOL>table.name,<EOL>get_safe_url_from_engine(engine),<EOL>"<STR_LIT>" if without_constraints else "<STR_LIT>")<EOL>if without_constraints:<EOL><INDENT>include_foreign_key_constraints = []<EOL><DEDENT>else:<EOL><INDENT>include_foreign_key_constraints = None <EOL><DEDENT>creator = CreateTable(<EOL>table,<EOL>include_foreign_key_constraints=include_foreign_key_constraints<EOL>)<EOL>creator.execute(bind=engine)<EOL> | From an SQLAlchemy ORM class, creates the database table via the specified
engine, using a ``CREATE TABLE`` SQL (DDL) statement.
Args:
engine: SQLAlchemy :class:`Engine` object
ormclass: SQLAlchemy ORM class
without_constraints: don't add foreign key constraints | f14631:m0 |
def get_dialect(mixed: Union[SQLCompiler, Engine, Dialect]) -> Dialect: | if isinstance(mixed, Dialect):<EOL><INDENT>return mixed<EOL><DEDENT>elif isinstance(mixed, Engine):<EOL><INDENT>return mixed.dialect<EOL><DEDENT>elif isinstance(mixed, SQLCompiler):<EOL><INDENT>return mixed.dialect<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT> | Finds the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy :class:`Dialect` being used | f14632:m0 |
def get_dialect_name(mixed: Union[SQLCompiler, Engine, Dialect]) -> str: | dialect = get_dialect(mixed)<EOL>return dialect.name<EOL> | Finds the name of the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy dialect name being used | f14632:m1 |
def get_preparer(mixed: Union[SQLCompiler, Engine,<EOL>Dialect]) -> IdentifierPreparer: | dialect = get_dialect(mixed)<EOL>return dialect.preparer(dialect)<EOL> | Returns the SQLAlchemy :class:`IdentifierPreparer` in use for the dialect
being used.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: an :class:`IdentifierPreparer` | f14632:m2 |
def quote_identifier(identifier: str,<EOL>mixed: Union[SQLCompiler, Engine, Dialect]) -> str: | <EOL>return get_preparer(mixed).quote(identifier)<EOL> | Converts an SQL identifier to a quoted version, via the SQL dialect in
use.
Args:
identifier: the identifier to be quoted
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns:
the quoted identifier | f14632:m3 |
def get_all_dependencies(metadata: MetaData,<EOL>extra_dependencies: List[TableDependency] = None,<EOL>sort: bool = True)-> List[TableDependency]: | extra_dependencies = extra_dependencies or [] <EOL>for td in extra_dependencies:<EOL><INDENT>td.set_metadata_if_none(metadata)<EOL><DEDENT>dependencies = set([td.sqla_tuple() for td in extra_dependencies])<EOL>tables = list(metadata.tables.values()) <EOL>for table in tables:<EOL><INDENT>for fkc in table.foreign_key_constraints:<EOL><INDENT>if fkc.use_alter is True:<EOL><INDENT>continue<EOL><DEDENT>dependent_on = fkc.referred_table<EOL>if dependent_on is not table:<EOL><INDENT>dependencies.add((dependent_on, table))<EOL><DEDENT><DEDENT>if hasattr(table, "<STR_LIT>"):<EOL><INDENT>dependencies.update(<EOL>(parent, table) for parent in table._extra_dependencies<EOL>)<EOL><DEDENT><DEDENT>dependencies = [<EOL>TableDependency(parent_table=parent, child_table=child)<EOL>for parent, child in dependencies<EOL>]<EOL>if sort:<EOL><INDENT>dependencies.sort(key=lambda td_: (td_.parent_tablename,<EOL>td_.child_tablename))<EOL><DEDENT>return dependencies<EOL> | Describes how the tables found in the metadata depend on each other.
(If table B contains a foreign key to table A, for example, then B depends
on A.)
Args:
metadata: the metadata to inspect
extra_dependencies: additional table dependencies to specify manually
sort: sort into alphabetical order of (parent, child) table names?
Returns:
a list of :class:`TableDependency` objects
See :func:`sort_tables_and_constraints` for method. | f14633:m0 |
def classify_tables_by_dependency_type(<EOL>metadata: MetaData,<EOL>extra_dependencies: List[TableDependency] = None,<EOL>sort: bool = True)-> List[TableDependencyClassification]: | tables = list(metadata.tables.values()) <EOL>all_deps = get_all_dependencies(metadata, extra_dependencies)<EOL>tdcmap = {} <EOL>for table in tables:<EOL><INDENT>parents = [td.parent_table for td in all_deps<EOL>if td.child_table == table]<EOL>children = [td.child_table for td in all_deps<EOL>if td.parent_table == table]<EOL>tdcmap[table] = TableDependencyClassification(<EOL>table, parents=parents, children=children<EOL>)<EOL><DEDENT>def parents_contain(start: Table,<EOL>probe: Table) -> Tuple[bool, List[Table]]:<EOL><INDENT>tdc_ = tdcmap[start]<EOL>if probe in tdc_.parents:<EOL><INDENT>return True, [start, probe]<EOL><DEDENT>for parent in tdc_.parents:<EOL><INDENT>contains_, chain_ = parents_contain(start=parent, probe=probe)<EOL>if contains_:<EOL><INDENT>return True, [start] + chain_<EOL><DEDENT><DEDENT>return False, []<EOL><DEDENT>def children_contain(start: Table,<EOL>probe: Table) -> Tuple[bool, List[Table]]:<EOL><INDENT>tdc_ = tdcmap[start]<EOL>if probe in tdc_.children:<EOL><INDENT>return True, [start, probe]<EOL><DEDENT>for child in tdc_.children:<EOL><INDENT>contains_, chain_ = children_contain(start=child, probe=probe)<EOL>if contains_:<EOL><INDENT>return True, [start] + chain_<EOL><DEDENT><DEDENT>return False, []<EOL><DEDENT>for table in tables:<EOL><INDENT>tdc = tdcmap[table]<EOL>contains, chain = parents_contain(start=table, probe=table)<EOL>if contains:<EOL><INDENT>tdc.set_circular(contains, chain)<EOL><DEDENT>else:<EOL><INDENT>contains, chain = children_contain(start=table, probe=table)<EOL>if contains:<EOL><INDENT>tdc.set_circular(contains, chain)<EOL><DEDENT>else:<EOL><INDENT>tdc.set_circular(False)<EOL><DEDENT><DEDENT><DEDENT>classifications = list(tdcmap.values())<EOL>if sort:<EOL><INDENT>classifications.sort(key=lambda c: c.tablename)<EOL><DEDENT>return classifications<EOL> | Inspects a metadata object (optionally adding other specified dependencies)
and returns a list of objects describing their dependencies.
Args:
metadata: the :class:`MetaData` to inspect
extra_dependencies: additional dependencies
sort: sort the results by table name?
Returns:
list of :class:`TableDependencyClassification` objects, one for each
table | f14633:m1 |
def merge_db(base_class: Type,<EOL>src_engine: Engine,<EOL>dst_session: Session,<EOL>allow_missing_src_tables: bool = True,<EOL>allow_missing_src_columns: bool = True,<EOL>translate_fn: Callable[[TranslationContext], None] = None,<EOL>skip_tables: List[TableIdentity] = None,<EOL>only_tables: List[TableIdentity] = None,<EOL>tables_to_keep_pks_for: List[TableIdentity] = None,<EOL>extra_table_dependencies: List[TableDependency] = None,<EOL>dummy_run: bool = False,<EOL>info_only: bool = False,<EOL>report_every: int = <NUM_LIT:1000>,<EOL>flush_per_table: bool = True,<EOL>flush_per_record: bool = False,<EOL>commit_with_flush: bool = False,<EOL>commit_at_end: bool = True,<EOL>prevent_eager_load: bool = True,<EOL>trcon_info: Dict[str, Any] = None) -> None: | log.info("<STR_LIT>")<EOL>if dummy_run:<EOL><INDENT>log.warning("<STR_LIT>")<EOL><DEDENT>if only_tables is not None and not only_tables:<EOL><INDENT>log.warning("<STR_LIT>")<EOL>return<EOL><DEDENT>skip_tables = skip_tables or [] <EOL>only_tables = only_tables or [] <EOL>tables_to_keep_pks_for = tables_to_keep_pks_for or [] <EOL>extra_table_dependencies = extra_table_dependencies or [] <EOL>trcon_info = trcon_info or {} <EOL>metadata = base_class.metadata <EOL>src_session = sessionmaker(bind=src_engine)() <EOL>dst_engine = get_engine_from_session(dst_session)<EOL>tablename_to_ormclass = get_orm_classes_by_table_name_from_base(base_class)<EOL>for tilist in [skip_tables, only_tables, tables_to_keep_pks_for]:<EOL><INDENT>for ti in tilist:<EOL><INDENT>ti.set_metadata_if_none(metadata)<EOL><DEDENT><DEDENT>for td in extra_table_dependencies:<EOL><INDENT>td.set_metadata_if_none(metadata)<EOL><DEDENT>skip_table_names = [ti.tablename for ti in skip_tables]<EOL>only_table_names = [ti.tablename for ti in only_tables]<EOL>tables_to_keep_pks_for = [ti.tablename for ti in tables_to_keep_pks_for] <EOL>_src_url = get_safe_url_from_engine(src_engine)<EOL>_dst_url = get_safe_url_from_session(dst_session)<EOL>assert _src_url != _dst_url or _src_url == SQLITE_MEMORY_URL, (<EOL>"<STR_LIT>"<EOL>)<EOL>src_tables = sorted(get_table_names(src_engine))<EOL>dst_tables = sorted(list(tablename_to_ormclass.keys()))<EOL>log.debug("<STR_LIT>", src_tables)<EOL>log.debug("<STR_LIT>", dst_tables)<EOL>if not allow_missing_src_tables:<EOL><INDENT>missing_tables = sorted(<EOL>d for d in dst_tables<EOL>if d not in src_tables and d not in skip_table_names<EOL>)<EOL>if missing_tables:<EOL><INDENT>raise RuntimeError("<STR_LIT>"<EOL>"<STR_LIT>" + repr(missing_tables))<EOL><DEDENT><DEDENT>table_num = <NUM_LIT:0><EOL>overall_record_num = <NUM_LIT:0><EOL>tables = list(metadata.tables.values()) <EOL>ordered_tables = sort_tables(<EOL>tables,<EOL>extra_dependencies=[td.sqla_tuple() for td in extra_table_dependencies]<EOL>)<EOL>all_dependencies = get_all_dependencies(metadata, extra_table_dependencies)<EOL>dep_classifications = classify_tables_by_dependency_type(<EOL>metadata, extra_table_dependencies)<EOL>circular = [tdc for tdc in dep_classifications if tdc.circular]<EOL>assert not circular, "<STR_LIT>".format(circular)<EOL>log.debug("<STR_LIT>",<EOL>"<STR_LIT>".join(str(td) for td in all_dependencies))<EOL>log.debug("<STR_LIT>",<EOL>"<STR_LIT>".join(str(c) for c in dep_classifications))<EOL>log.info("<STR_LIT>",<EOL>[table.name for table in ordered_tables])<EOL>objmap = {}<EOL>def flush() -> None:<EOL><INDENT>if not dummy_run:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>dst_session.flush()<EOL>if commit_with_flush:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>dst_session.commit()<EOL><DEDENT><DEDENT><DEDENT>def translate(oldobj_: object, newobj_: object) -> object:<EOL><INDENT>if translate_fn is None:<EOL><INDENT>return newobj_<EOL><DEDENT>tc = TranslationContext(oldobj=oldobj_,<EOL>newobj=newobj_,<EOL>objmap=objmap,<EOL>table=table,<EOL>tablename=tablename,<EOL>src_session=src_session,<EOL>dst_session=dst_session,<EOL>src_engine=src_engine,<EOL>dst_engine=dst_engine,<EOL>missing_src_columns=missing_columns,<EOL>src_table_names=src_tables,<EOL>info=trcon_info)<EOL>translate_fn(tc)<EOL>if tc.newobj is None:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>return tc.newobj<EOL><DEDENT>for table in ordered_tables:<EOL><INDENT>tablename = table.name<EOL>if tablename in skip_table_names:<EOL><INDENT>log.info("<STR_LIT>", tablename)<EOL>continue<EOL><DEDENT>if only_table_names and tablename not in only_table_names:<EOL><INDENT>log.info("<STR_LIT>", tablename)<EOL>continue<EOL><DEDENT>if allow_missing_src_tables and tablename not in src_tables:<EOL><INDENT>log.info("<STR_LIT>",<EOL>tablename)<EOL>continue<EOL><DEDENT>table_num += <NUM_LIT:1><EOL>table_record_num = <NUM_LIT:0><EOL>src_columns = sorted(get_column_names(src_engine, tablename))<EOL>dst_columns = sorted([column.name for column in table.columns])<EOL>missing_columns = sorted(list(set(dst_columns) - set(src_columns)))<EOL>if not allow_missing_src_columns:<EOL><INDENT>if missing_columns:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(tablename, missing_columns))<EOL><DEDENT><DEDENT>orm_class = tablename_to_ormclass[tablename]<EOL>pk_attrs = get_pk_attrnames(orm_class)<EOL>c2a = colname_to_attrname_dict(orm_class)<EOL>missing_attrs = map_keys_to_values(missing_columns, c2a)<EOL>tdc = [tdc for tdc in dep_classifications if tdc.table == table][<NUM_LIT:0>]<EOL>log.info("<STR_LIT>",<EOL>tablename, orm_class)<EOL>log.debug("<STR_LIT>", pk_attrs)<EOL>log.debug("<STR_LIT>", table)<EOL>log.debug("<STR_LIT>",<EOL>tdc.parent_names, tdc.child_names)<EOL>if info_only:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>continue<EOL><DEDENT>def wipe_primary_key(inst: object) -> None:<EOL><INDENT>for attrname in pk_attrs:<EOL><INDENT>setattr(inst, attrname, None)<EOL><DEDENT><DEDENT>query = src_session.query(orm_class)<EOL>if allow_missing_src_columns and missing_columns:<EOL><INDENT>src_attrs = map_keys_to_values(src_columns, c2a)<EOL>log.info("<STR_LIT>",<EOL>tablename, missing_columns)<EOL>log.debug("<STR_LIT>",<EOL>src_columns, src_attrs)<EOL>query = query.options(load_only(*src_attrs))<EOL><DEDENT>if prevent_eager_load:<EOL><INDENT>query = query.options(lazyload("<STR_LIT:*>"))<EOL><DEDENT>wipe_pk = tablename not in tables_to_keep_pks_for<EOL>for instance in query.all():<EOL><INDENT>table_record_num += <NUM_LIT:1><EOL>overall_record_num += <NUM_LIT:1><EOL>if table_record_num % report_every == <NUM_LIT:0>:<EOL><INDENT>log.info("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>"<STR_LIT>" if dummy_run else "<STR_LIT>",<EOL>table_num, tablename,<EOL>table_record_num, overall_record_num)<EOL><DEDENT>if tdc.standalone:<EOL><INDENT>src_session.expunge(instance)<EOL>make_transient(instance)<EOL>if wipe_pk:<EOL><INDENT>wipe_primary_key(instance)<EOL><DEDENT>instance = translate(instance, instance)<EOL>if not instance:<EOL><INDENT>continue <EOL><DEDENT>if not dummy_run:<EOL><INDENT>dst_session.add(instance)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>oldobj = instance <EOL>newobj = copy_sqla_object(<EOL>oldobj, omit_pk=wipe_pk, omit_fk=True,<EOL>omit_attrs=missing_attrs, debug=False<EOL>)<EOL>rewrite_relationships(oldobj, newobj, objmap, debug=False,<EOL>skip_table_names=skip_table_names)<EOL>newobj = translate(oldobj, newobj)<EOL>if not newobj:<EOL><INDENT>continue <EOL><DEDENT>if not dummy_run:<EOL><INDENT>dst_session.add(newobj)<EOL><DEDENT>if tdc.is_parent:<EOL><INDENT>objmap[oldobj] = newobj <EOL><DEDENT><DEDENT>if flush_per_record:<EOL><INDENT>flush()<EOL><DEDENT><DEDENT>if flush_per_table:<EOL><INDENT>flush()<EOL><DEDENT><DEDENT>flush()<EOL>if commit_at_end:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>dst_session.commit()<EOL><DEDENT>log.info("<STR_LIT>")<EOL> | Copies an entire database as far as it is described by ``metadata`` and
``base_class``, from SQLAlchemy ORM session ``src_session`` to
``dst_session``, and in the process:
- creates new primary keys at the destination, or raises an error if it
doesn't know how (typically something like: ``Field 'name' doesn't have a
default value``)
- maintains relationships, or raises an error if it doesn't know how
Basic method:
- Examines the metadata for the SQLAlchemy ORM base class you provide.
- Assumes that the tables exist (in the destination).
- For each table/ORM class found in the metadata:
- Queries (via the ORM) from the source.
- For each ORM instance retrieved:
- Writes information to the destination SQLAlchemy session.
- If that ORM object has relationships, process them too.
If a table is missing in the source, then that's OK if and only if
``allow_missing_src_tables`` is set. (Similarly with columns and
``allow_missing_src_columns``; we ask the ORM to perform a partial load,
of a subset of attributes only.)
Args:
base_class:
your ORM base class, e.g. from ``Base = declarative_base()``
src_engine:
SQLALchemy :class:`Engine` for the source database
dst_session:
SQLAlchemy :class:`Session` for the destination database
allow_missing_src_tables:
proceed if tables are missing from the source (allowing you to
import from older, incomplete databases)
allow_missing_src_columns:
proceed if columns are missing from the source (allowing you to
import from older, incomplete databases)
translate_fn:
optional function called with each instance, so you can modify
instances in the pipeline. Signature:
.. code-block:: python
def my_translate_fn(trcon: TranslationContext) -> None:
# We can modify trcon.newobj, or replace it (including
# setting trcon.newobj = None to omit this object).
pass
skip_tables:
tables to skip (specified as a list of :class:`TableIdentity`)
only_tables:
tables to restrict the processor to (specified as a list of
:class:`TableIdentity`)
tables_to_keep_pks_for:
tables for which PKs are guaranteed to be safe to insert into the
destination database, without modification (specified as a list of
:class:`TableIdentity`)
extra_table_dependencies:
optional list of :class:`TableDependency` objects (q.v.)
dummy_run:
don't alter the destination database
info_only:
show info, then stop
report_every:
provide a progress report every *n* records
flush_per_table:
flush the session after every table (reasonable)
flush_per_record:
flush the session after every instance (AVOID this if tables may
refer to themselves)
commit_with_flush:
``COMMIT`` with each flush?
commit_at_end:
``COMMIT`` when finished?
prevent_eager_load:
disable any eager loading (use lazy loading instead)
trcon_info:
additional dictionary passed to ``TranslationContext.info``
(see :class:`.TranslationContext`) | f14633:m2 |
def __init__(self,<EOL>parent_table_id: TableIdentity = None,<EOL>child_table_id: TableIdentity = None,<EOL>parent_table: Table = None,<EOL>child_table: Table = None,<EOL>parent_tablename: str = None,<EOL>child_tablename: str = None,<EOL>metadata: MetaData = None) -> None: | overspecified = "<STR_LIT>""<STR_LIT>"<EOL>if parent_table_id:<EOL><INDENT>self._parent = parent_table_id<EOL>assert parent_table is None and not parent_tablename, overspecified<EOL><DEDENT>else:<EOL><INDENT>self._parent = TableIdentity(table=parent_table,<EOL>tablename=parent_tablename,<EOL>metadata=metadata)<EOL><DEDENT>if child_table_id:<EOL><INDENT>self._child = child_table_id<EOL>assert child_table is None and not child_tablename, overspecified<EOL><DEDENT>else:<EOL><INDENT>self._child = TableIdentity(table=child_table,<EOL>tablename=child_tablename,<EOL>metadata=metadata)<EOL><DEDENT> | The parent and child tables can be specified by name, :class:`Table`
object, or our :class:`TableIdentity` descriptor class. | f14633:c0:m0 |
def set_metadata(self, metadata: MetaData) -> None: | self._parent.set_metadata(metadata)<EOL>self._child.set_metadata(metadata)<EOL> | Sets the metadata for the parent and child tables. | f14633:c0:m3 |
def set_metadata_if_none(self, metadata: MetaData) -> None: | self._parent.set_metadata_if_none(metadata)<EOL>self._child.set_metadata_if_none(metadata)<EOL> | Sets the metadata for the parent and child tables, unless they were
set already. | f14633:c0:m4 |
@property<EOL><INDENT>def parent_table(self) -> Table:<DEDENT> | return self._parent.table<EOL> | Returns the parent table as a :class:`Table`. | f14633:c0:m5 |
@property<EOL><INDENT>def child_table(self) -> Table:<DEDENT> | return self._child.table<EOL> | Returns the child table as a :class:`Table`. | f14633:c0:m6 |
@property<EOL><INDENT>def parent_tablename(self) -> str:<DEDENT> | return self._parent.tablename<EOL> | Returns the parent table's string name. | f14633:c0:m7 |
@property<EOL><INDENT>def child_tablename(self) -> str:<DEDENT> | return self._child.tablename<EOL> | Returns the child table's string name. | f14633:c0:m8 |
def sqla_tuple(self) -> Tuple[Table, Table]: | return self.parent_table, self.child_table<EOL> | Returns the tuple ``(parent_table, child_table)``, both as
:class:`Table` objects. | f14633:c0:m9 |
def __init__(self,<EOL>table: Table,<EOL>children: List[Table] = None,<EOL>parents: List[Table] = None) -> None: | self.table = table<EOL>self.children = children or [] <EOL>self.parents = parents or [] <EOL>self.circular = False<EOL>self.circular_chain = []<EOL> | Args:
table: the table in question
children: its children (things that depend on it)
parents: its parents (things that it depends on) | f14633:c1:m0 |
@property<EOL><INDENT>def is_child(self) -> bool:<DEDENT> | return bool(self.parents)<EOL> | Is this table a child? | f14633:c1:m1 |
@property<EOL><INDENT>def is_parent(self) -> bool:<DEDENT> | return bool(self.children)<EOL> | Is this table a parent? | f14633:c1:m2 |
@property<EOL><INDENT>def standalone(self) -> bool:<DEDENT> | return not self.is_child and not self.is_parent<EOL> | Is this table standalone (neither a child nor a parent)? | f14633:c1:m3 |
@property<EOL><INDENT>def tablename(self) -> str:<DEDENT> | return self.table.name<EOL> | Returns the table's name. | f14633:c1:m4 |
@property<EOL><INDENT>def parent_names(self) -> List[str]:<DEDENT> | return [t.name for t in self.parents]<EOL> | Returns the names of this table's parents. | f14633:c1:m5 |
@property<EOL><INDENT>def child_names(self) -> List[str]:<DEDENT> | return [t.name for t in self.children]<EOL> | Returns the names of this table's children. | f14633:c1:m6 |
def set_circular(self, circular: bool, chain: List[Table] = None) -> None: | self.circular = circular<EOL>self.circular_chain = chain or []<EOL> | Mark this table as circular (or not).
Args:
circular: is it circular?
chain: if it's circular, this should be the list of tables
participating in the circular chain | f14633:c1:m7 |
@property<EOL><INDENT>def circular_description(self) -> str:<DEDENT> | return "<STR_LIT>".join(t.name for t in self.circular_chain)<EOL> | Description of the circular chain. | f14633:c1:m8 |
@property<EOL><INDENT>def description(self) -> str:<DEDENT> | if self.is_parent and self.is_child:<EOL><INDENT>desc = "<STR_LIT>"<EOL><DEDENT>elif self.is_parent:<EOL><INDENT>desc = "<STR_LIT>"<EOL><DEDENT>elif self.is_child:<EOL><INDENT>desc = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>desc = "<STR_LIT>"<EOL><DEDENT>if self.circular:<EOL><INDENT>desc += "<STR_LIT>".format(self.circular_description)<EOL><DEDENT>return desc<EOL> | Short description. | f14633:c1:m9 |
def get_rows_fieldnames_from_query(<EOL>session: Union[Session, Engine, Connection],<EOL>query: Query) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]: | <EOL>result = session.execute(query) <EOL>fieldnames = result.keys()<EOL>rows = result.fetchall()<EOL>return rows, fieldnames<EOL> | Returns results and column names from a query.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
query: SQLAlchemy :class:`Query`
Returns:
``(rows, fieldnames)`` where ``rows`` is the usual set of results and
``fieldnames`` are the name of the result columns/fields. | f14634:m0 |
def bool_from_exists_clause(session: Session,<EOL>exists_clause: Exists) -> bool: | <EOL>ssion.get_bind().dialect.name == SqlaDialectName.MSSQL:<EOL><INDENT>SQL Server<EOL><DEDENT>esult = session.query(literal(True)).filter(exists_clause).scalar()<EOL><INDENT>MySQL, etc.<EOL><DEDENT>esult = session.query(exists_clause).scalar()<EOL>n bool(result)<EOL> | Database dialects are not consistent in how ``EXISTS`` clauses can be
converted to a boolean answer. This function manages the inconsistencies.
See:
- https://bitbucket.org/zzzeek/sqlalchemy/issues/3212/misleading-documentation-for-queryexists
- http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.exists
Specifically, we want this:
*SQL Server*
.. code-block:: sql
SELECT 1 WHERE EXISTS (SELECT 1 FROM table WHERE ...)
-- ... giving 1 or None (no rows)
-- ... fine for SQL Server, but invalid for MySQL (no FROM clause)
*Others, including MySQL*
.. code-block:: sql
SELECT EXISTS (SELECT 1 FROM table WHERE ...)
-- ... giving 1 or 0
-- ... fine for MySQL, but invalid syntax for SQL Server | f14634:m1 |
def exists_orm(session: Session,<EOL>ormclass: DeclarativeMeta,<EOL>*criteria: Any) -> bool: | <EOL>q = session.query(ormclass)<EOL>for criterion in criteria:<EOL><INDENT>q = q.filter(criterion)<EOL><DEDENT>exists_clause = q.exists()<EOL>return bool_from_exists_clause(session=session,<EOL>exists_clause=exists_clause)<EOL> | Detects whether a database record exists for the specified ``ormclass``
and ``criteria``.
Example usage:
.. code-block:: python
bool_exists = exists_orm(session, MyClass, MyClass.myfield == value) | f14634:m2 |
def get_or_create(session: Session,<EOL>model: DeclarativeMeta,<EOL>defaults: Dict[str, Any] = None,<EOL>**kwargs: Any) -> Tuple[Any, bool]: | instance = session.query(model).filter_by(**kwargs).first()<EOL>if instance:<EOL><INDENT>return instance, False<EOL><DEDENT>else:<EOL><INDENT>params = dict((k, v) for k, v in kwargs.items()<EOL>if not isinstance(v, ClauseElement))<EOL>params.update(defaults or {})<EOL>instance = model(**params)<EOL>session.add(instance)<EOL>return instance, True<EOL><DEDENT> | Fetches an ORM object from the database, or creates one if none existed.
Args:
session: an SQLAlchemy :class:`Session`
model: an SQLAlchemy ORM class
defaults: default initialization arguments (in addition to relevant
filter criteria) if we have to create a new instance
kwargs: optional filter criteria
Returns:
a tuple ``(instance, newly_created)``
See http://stackoverflow.com/questions/2546207 (this function is a
composite of several suggestions). | f14634:m3 |
def __init__(self, *args, **kwargs) -> None: | <EOL>super().__init__(*args, **kwargs)<EOL> | Optimizes ``COUNT(*)`` queries.
See
https://stackoverflow.com/questions/12941416/how-to-count-rows-with-select-count-with-sqlalchemy
Example use:
.. code-block:: python
q = CountStarSpecializedQuery([cls], session=dbsession)\
.filter(cls.username == username)
return q.count_star() | f14634:c0:m0 |
def count_star(self) -> int: | count_query = (self.statement.with_only_columns([func.count()])<EOL>.order_by(None))<EOL>return self.session.execute(count_query).scalar()<EOL> | Implements the ``COUNT(*)`` specialization. | f14634:c0:m1 |
def get_head_revision_from_alembic(<EOL>alembic_config_filename: str,<EOL>alembic_base_dir: str = None,<EOL>version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str: | if alembic_base_dir is None:<EOL><INDENT>alembic_base_dir = os.path.dirname(alembic_config_filename)<EOL><DEDENT>os.chdir(alembic_base_dir) <EOL>config = Config(alembic_config_filename)<EOL>script = ScriptDirectory.from_config(config)<EOL>with EnvironmentContext(config,<EOL>script,<EOL>version_table=version_table):<EOL><INDENT>return script.get_current_head()<EOL><DEDENT> | Ask Alembic what its head revision is (i.e. where the Python code would
like the database to be at).
Arguments:
alembic_config_filename: config filename
alembic_base_dir: directory to start in, so relative paths in the
config file work.
version_table: table name for Alembic versions | f14635:m0 |
def get_current_revision(<EOL>database_url: str,<EOL>version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str: | engine = create_engine(database_url)<EOL>conn = engine.connect()<EOL>opts = {'<STR_LIT>': version_table}<EOL>mig_context = MigrationContext.configure(conn, opts=opts)<EOL>return mig_context.get_current_revision()<EOL> | Ask the database what its current revision is.
Arguments:
database_url: SQLAlchemy URL for the database
version_table: table name for Alembic versions | f14635:m1 |
def get_current_and_head_revision(<EOL>database_url: str,<EOL>alembic_config_filename: str,<EOL>alembic_base_dir: str = None,<EOL>version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> Tuple[str, str]: | <EOL>head_revision = get_head_revision_from_alembic(<EOL>alembic_config_filename=alembic_config_filename,<EOL>alembic_base_dir=alembic_base_dir,<EOL>version_table=version_table<EOL>)<EOL>log.info("<STR_LIT>", head_revision)<EOL>current_revision = get_current_revision(<EOL>database_url=database_url,<EOL>version_table=version_table<EOL>)<EOL>log.info("<STR_LIT>", current_revision)<EOL>return current_revision, head_revision<EOL> | Returns a tuple of ``(current_revision, head_revision)``; see
:func:`get_current_revision` and :func:`get_head_revision_from_alembic`.
Arguments:
database_url: SQLAlchemy URL for the database
alembic_config_filename: config filename
alembic_base_dir: directory to start in, so relative paths in the
config file work.
version_table: table name for Alembic versions | f14635:m2 |
@preserve_cwd<EOL>def upgrade_database(<EOL>alembic_config_filename: str,<EOL>alembic_base_dir: str = None,<EOL>starting_revision: str = None,<EOL>destination_revision: str = "<STR_LIT>",<EOL>version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE,<EOL>as_sql: bool = False) -> None: | if alembic_base_dir is None:<EOL><INDENT>alembic_base_dir = os.path.dirname(alembic_config_filename)<EOL><DEDENT>os.chdir(alembic_base_dir) <EOL>config = Config(alembic_config_filename)<EOL>script = ScriptDirectory.from_config(config)<EOL>def upgrade(rev, context):<EOL><INDENT>return script._upgrade_revs(destination_revision, rev)<EOL><DEDENT>log.info("<STR_LIT>",<EOL>destination_revision)<EOL>with EnvironmentContext(config,<EOL>script,<EOL>fn=upgrade,<EOL>as_sql=as_sql,<EOL>starting_rev=starting_revision,<EOL>destination_rev=destination_revision,<EOL>tag=None,<EOL>version_table=version_table):<EOL><INDENT>script.run_env()<EOL><DEDENT>log.info("<STR_LIT>")<EOL> | Use Alembic to upgrade our database.
See http://alembic.readthedocs.org/en/latest/api/runtime.html
but also, in particular, ``site-packages/alembic/command.py``
Arguments:
alembic_config_filename:
config filename
alembic_base_dir:
directory to start in, so relative paths in the config file work
starting_revision:
revision to start at (typically ``None`` to ask the database)
destination_revision:
revision to aim for (typically ``"head"`` to migrate to the latest
structure)
version_table: table name for Alembic versions
as_sql:
run in "offline" mode: print the migration SQL, rather than
modifying the database. See
http://alembic.zzzcomputing.com/en/latest/offline.html | f14635:m3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.