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 fieldname...
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><INDE...
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:...
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>...
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 ...
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', ...
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 Not...
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>"...
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>...
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("<...
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: .. co...
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 (...
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: ...
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 sqlalch...
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...
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'...
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)...
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 ``TIMES...
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 wil...
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>', '<ST...
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><D...
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_c...
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,...
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 == tab...
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:`TableDepe...
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,...
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...
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...
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><DED...
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.ci...
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 co...
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...
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...
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 ...
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):<EO...
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=ve...
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 ...
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_r...
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 wo...
f14635:m3