signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@preserve_cwd<EOL>def downgrade_database(<EOL>alembic_config_filename: str,<EOL>destination_revision: str,<EOL>alembic_base_dir: str = None,<EOL>starting_revision: str = None,<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 downgrade(rev, context):<EOL><INDENT>return script._downgrade_revs(destination_revision, rev)<EOL><DEDENT>log.info("<STR_LIT>",<EOL>destination_revision)<EOL>with EnvironmentContext(config,<EOL>script,<EOL>fn=downgrade,<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 downgrade our database. USE WITH EXTREME CAUTION. "revision" is the destination revision. 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 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:m4
@preserve_cwd<EOL>def create_database_migration_numbered_style(<EOL>alembic_ini_file: str,<EOL>alembic_versions_dir: str,<EOL>message: str,<EOL>n_sequence_chars: int = <NUM_LIT:4>) -> None:
<EOL><INDENT>existing_version_filenames = next(os.walk(alembic_versions_dir),<EOL>(None, None, []))<EOL><DEDENT>ing_version_filenames = [<EOL>for x in existing_version_filenames if x != "<STR_LIT>"]<EOL>ebug("<STR_LIT>",<EOL>existing_version_filenames)<EOL>nt_seq_strs = [x[:n_sequence_chars]<EOL>for x in existing_version_filenames]<EOL>nt_seq_strs.sort()<EOL>t current_seq_strs:<EOL>urrent_seq_str = None<EOL>ew_seq_no = <NUM_LIT:1><EOL>urrent_seq_str = current_seq_strs[-<NUM_LIT:1>]<EOL>ew_seq_no = max(int(x) for x in current_seq_strs) + <NUM_LIT:1><EOL>eq_str = str(new_seq_no).zfill(n_sequence_chars)<EOL>nfo(<EOL>"<STR_LIT>"<EOL>g new revision with Alembic...<EOL>revision was: {}<EOL>evision will be: {}<EOL>t fails with "<STR_LIT>", you might need<EOL>OP the Alembic version table (by default named '<STR_LIT>', but<EOL>ay have elected to change that in your env.py.]<EOL>"<STR_LIT>",<EOL>urrent_seq_str,<EOL>ew_seq_str<EOL>ic_ini_dir = os.path.dirname(alembic_ini_file)<EOL>dir(alembic_ini_dir)<EOL>gs = ['<STR_LIT>',<EOL>'<STR_LIT:-c>', alembic_ini_file,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>', message,<EOL>'<STR_LIT>', new_seq_str]<EOL>nfo("<STR_LIT>", alembic_ini_dir, cmdargs)<EOL>ocess.call(cmdargs)<EOL>
Create a new Alembic migration script. Alembic compares the **state of the database** to the **state of the metadata**, and generates a migration that brings the former up to the latter. (It does **not** compare the most recent revision to the current metadata, so make sure your database is up to date with the most recent revision before running this!) You **must check** that the autogenerated revisions are sensible. How does it know where to look for the database? 1. This function changes into the directory of the Alembic ``.ini`` file and calls the external program .. code-block:: bash alembic -c ALEMBIC_INI_FILE revision --autogenerate -m MESSAGE --rev-id REVISION_ID 2. The Alembic ``.ini`` file points (via the ``script_location`` variable) to a directory containing your ``env.py``. Alembic loads this script. 3. That script typically works out the database URL and calls further into the Alembic code. See http://alembic.zzzcomputing.com/en/latest/autogenerate.html. Regarding filenames: the default ``n_sequence_chars`` of 4 is like Django and gives files with names like .. code-block:: none 0001_x.py, 0002_y.py, ... NOTE THAT TO USE A NON-STANDARD ALEMBIC VERSION TABLE, YOU MUST SPECIFY THAT IN YOUR ``env.py`` (see e.g. CamCOPS). Args: alembic_ini_file: filename of Alembic ``alembic.ini`` file alembic_versions_dir: directory in which you keep your Python scripts, one per Alembic revision message: message to be associated with this revision n_sequence_chars: number of numerical sequence characters to use in the filename/revision (see above).
f14635:m5
def stamp_allowing_unusual_version_table(<EOL>config: Config,<EOL>revision: str,<EOL>sql: bool = False,<EOL>tag: str = None,<EOL>version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> None:
<EOL>t = ScriptDirectory.from_config(config)<EOL>ing_rev = None<EOL>" in revision:<EOL>f not sql:<EOL><INDENT>raise CommandError("<STR_LIT>")<EOL><DEDENT>tarting_rev, revision = revision.split('<STR_LIT::>', <NUM_LIT:2>)<EOL>nspection PyUnusedLocal<EOL>o_stamp(rev: str, context):<EOL><INDENT>noinspection PyProtectedMember<EOL><DEDENT>eturn script._stamp_revs(revision, rev)<EOL>EnvironmentContext(config,<EOL>script,<EOL>fn=do_stamp,<EOL>as_sql=sql,<EOL>destination_rev=revision,<EOL>starting_rev=starting_rev,<EOL>tag=tag,<EOL>version_table=version_table):<EOL>cript.run_env()<EOL>
Stamps the Alembic version table with the given revision; don't run any migrations. This function is a clone of ``alembic.command.stamp()``, but allowing ``version_table`` to change. See http://alembic.zzzcomputing.com/en/latest/api/commands.html#alembic.command.stamp
f14635:m6
@Operations.implementation_for(CreateViewOp)<EOL>def create_view(operations, operation):
operations.execute("<STR_LIT>" % (<EOL>operation.target.name,<EOL>operation.target.sqltext<EOL>))<EOL>
Implements ``CREATE VIEW``. Args: operations: instance of ``alembic.operations.base.Operations`` operation: instance of :class:`.ReversibleOp` Returns: ``None``
f14636:m0
@Operations.implementation_for(DropViewOp)<EOL>def drop_view(operations, operation):
operations.execute("<STR_LIT>" % operation.target.name)<EOL>
Implements ``DROP VIEW``. Args: operations: instance of ``alembic.operations.base.Operations`` operation: instance of :class:`.ReversibleOp` Returns: ``None``
f14636:m1
@Operations.implementation_for(CreateSPOp)<EOL>def create_sp(operations, operation):
operations.execute(<EOL>"<STR_LIT>" % (<EOL>operation.target.name, operation.target.sqltext<EOL>)<EOL>)<EOL>
Implements ``CREATE FUNCTION``. Args: operations: instance of ``alembic.operations.base.Operations`` operation: instance of :class:`.ReversibleOp` Returns: ``None``
f14636:m2
@Operations.implementation_for(DropSPOp)<EOL>def drop_sp(operations, operation):
operations.execute("<STR_LIT>" % operation.target.name)<EOL>
Implements ``DROP FUNCTION``. Args: operations: instance of ``alembic.operations.base.Operations`` operation: instance of :class:`.ReversibleOp` Returns: ``None``
f14636:m3
def __init__(self, name, sqltext):
<EOL>self.name = name<EOL>self.sqltext = sqltext<EOL>
Object that can be passed to the ``create_view()`` and similar functions that we will register within the ``alembic.op`` namespace. See http://alembic.zzzcomputing.com/en/latest/cookbook.html#replaceable-objects Args: name: e.g. name of a view, such as ``subject_session_view`` sqltext: e.g. SQL to create the view, such as .. code-block:: sql SELECT C.subject, S.* FROM config C INNER JOIN session S ON S.config_id = C.config_id
f14636:c0:m0
def __init__(self, target):
self.target = target<EOL>
Args: target: instance of :class:`.ReplaceableObject`
f14636:c1:m0
@classmethod<EOL><INDENT>def invoke_for_target(cls, operations, target):<DEDENT>
op = cls(target)<EOL>return operations.invoke(op)<EOL>
Invokes the operation. Args: operations: instance of ``alembic.operations.base.Operations`` target: instance of :class:`.ReplaceableObject` Returns: result of ``alembic.operations.base.Operations.invoke`` performed upon an instance of this class initialized with ``target``
f14636:c1:m1
def reverse(self):
raise NotImplementedError()<EOL>
Returns: the ``MigrateOperation`` representing the reverse of this operation
f14636:c1:m2
@classmethod<EOL><INDENT>def _get_object_from_version(cls, operations, ident):<DEDENT>
version, objname = ident.split("<STR_LIT:.>")<EOL>module_ = operations.get_context().script.get_revision(version).module<EOL>obj = getattr(module_, objname)<EOL>return obj<EOL>
Returns a Python object from an Alembic migration module (script). Args: operations: instance of ``alembic.operations.base.Operations`` ident: string of the format ``version.objname`` Returns: the object whose name is ``objname`` within the Alembic migration script identified by ``version``
f14636:c1:m3
def process_bind_param(self, value: Optional[List[str]],<EOL>dialect: Dialect) -> str:
retval = self._strlist_to_dbstr(value)<EOL>return retval<EOL>
Convert things on the way from Python to the database.
f14637:c0:m3
def process_literal_param(self, value: Optional[List[str]],<EOL>dialect: Dialect) -> str:
retval = self._strlist_to_dbstr(value)<EOL>return retval<EOL>
Convert things on the way from Python to the database.
f14637:c0:m4
def process_result_value(self, value: Optional[str],<EOL>dialect: Dialect) -> List[str]:
retval = self._dbstr_to_strlist(value)<EOL>return retval<EOL>
Convert things on the way from the database to Python.
f14637:c0:m5
def process_bind_param(self, value: Optional[List[int]],<EOL>dialect: Dialect) -> str:
retval = self._intlist_to_dbstr(value)<EOL>return retval<EOL>
Convert things on the way from Python to the database.
f14637:c1:m3
def process_literal_param(self, value: Optional[List[int]],<EOL>dialect: Dialect) -> str:
retval = self._intlist_to_dbstr(value)<EOL>return retval<EOL>
Convert things on the way from Python to the database.
f14637:c1:m4
def process_result_value(self, value: Optional[str],<EOL>dialect: Dialect) -> List[int]:
retval = self._dbstr_to_intlist(value)<EOL>return retval<EOL>
Convert things on the way from the database to Python.
f14637:c1:m5
def is_sqlserver(engine: "<STR_LIT>") -> bool:
dialect_name = get_dialect_name(engine)<EOL>return dialect_name == SqlaDialectName.SQLSERVER<EOL>
Is the SQLAlchemy :class:`Engine` a Microsoft SQL Server database?
f14638:m0
def get_sqlserver_product_version(engine: "<STR_LIT>") -> Tuple[int]:
assert is_sqlserver(engine), (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>sql = "<STR_LIT>"<EOL>rp = engine.execute(sql) <EOL>row = rp.fetchone()<EOL>dotted_version = row[<NUM_LIT:0>] <EOL>return tuple(int(x) for x in dotted_version.split("<STR_LIT:.>"))<EOL>
Gets SQL Server version information. Attempted to use ``dialect.server_version_info``: .. code-block:: python from sqlalchemy import create_engine url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME" engine = create_engine(url) dialect = engine.dialect vi = dialect.server_version_info Unfortunately, ``vi == ()`` for an SQL Server 2014 instance via ``mssql+pyodbc``. It's also ``None`` for a ``mysql+pymysql`` connection. So this seems ``server_version_info`` is a badly supported feature. So the only other way is to ask the database directly. The problem is that this requires an :class:`Engine` or similar. (The initial hope was to be able to use this from within SQL compilation hooks, to vary the SQL based on the engine version. Still, this isn't so bad.) We could use either .. code-block:: sql SELECT @@version; -- returns a human-readable string SELECT SERVERPROPERTY('ProductVersion'); -- better The ``pyodbc`` interface will fall over with ``ODBC SQL type -150 is not yet supported`` with that last call, though, meaning that a ``VARIANT`` is coming back, so we ``CAST`` as per the source below.
f14638:m1
def is_sqlserver_2008_or_later(engine: "<STR_LIT>") -> bool:
if not is_sqlserver(engine):<EOL><INDENT>return False<EOL><DEDENT>version_tuple = get_sqlserver_product_version(engine)<EOL>return version_tuple >= (SQLSERVER_MAJOR_VERSION_2008, )<EOL>
Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server, version 2008 or later?
f14638:m2
def pre_disable_sqlalchemy_extra_echo_log() -> None:
log = logging.getLogger("<STR_LIT>")<EOL>log.addHandler(logging.NullHandler())<EOL>
Adds a null handler to the log named ``sqlalchemy.engine.base.Engine``, which prevents a duplicated log stream being created later. Why is this necessary? If you create an SQLAlchemy :class:`Engine` with ``echo=True``, it creates an additional log to ``stdout``, via .. code-block:: python sqlalchemy.engine.base.Engine.__init__() sqlalchemy.log.instance_logger() sqlalchemy.log.InstanceLogger.__init__() # ... which checks that the logger has no handlers and if not calls: sqlalchemy.log._add_default_handler() # ... which adds a handler to sys.stdout
f14641:m0
def dump_connection_info(engine: Engine, fileobj: TextIO = sys.stdout) -> None:
meta = MetaData(bind=engine)<EOL>writeline_nl(fileobj, sql_comment('<STR_LIT>'.format(meta)))<EOL>
Dumps some connection info, as an SQL comment. Obscures passwords. Args: engine: the SQLAlchemy :class:`Engine` to dump metadata information from fileobj: the file-like object (default ``sys.stdout``) to write information to
f14643:m0
def dump_ddl(metadata: MetaData,<EOL>dialect_name: str,<EOL>fileobj: TextIO = sys.stdout,<EOL>checkfirst: bool = True) -> None:
<EOL>def dump(querysql, *multiparams, **params):<EOL><INDENT>compsql = querysql.compile(dialect=engine.dialect)<EOL>writeline_nl(fileobj, "<STR_LIT>".format(sql=compsql))<EOL><DEDENT>writeline_nl(fileobj,<EOL>sql_comment("<STR_LIT>".format(dialect_name)))<EOL>engine = create_engine('<STR_LIT>'.format(dialect=dialect_name),<EOL>strategy='<STR_LIT>', executor=dump)<EOL>metadata.create_all(engine, checkfirst=checkfirst)<EOL>
Sends schema-creating DDL from the metadata to the dump engine. This makes ``CREATE TABLE`` statements. Args: metadata: SQLAlchemy :class:`MetaData` dialect_name: string name of SQL dialect to generate DDL in fileobj: file-like object to send DDL to checkfirst: if ``True``, use ``CREATE TABLE IF NOT EXISTS`` or equivalent.
f14643:m1
def quick_mapper(table: Table) -> Type[DeclarativeMeta]:
<EOL>nspection PyPep8Naming<EOL>= declarative_base()<EOL><INDENT>GenericMapper(Base):<EOL><DEDENT>_table__ = table<EOL>nspection PyTypeChecker<EOL>n GenericMapper<EOL>
Makes a new SQLAlchemy mapper for an existing table. See http://www.tylerlesmann.com/2009/apr/27/copying-databases-across-platforms-sqlalchemy/ Args: table: SQLAlchemy :class:`Table` object Returns: a :class:`DeclarativeMeta` class
f14643:m2
def get_literal_query(statement: Union[Query, Executable],<EOL>bind: Connectable = None) -> str:
<EOL>.debug("<STR_LIT>", statement)<EOL>.debug("<STR_LIT>", statement.bind)<EOL>instance(statement, Query):<EOL>f bind is None:<EOL><INDENT>bind = statement.session.get_bind(statement._mapper_zero_or_none())<EOL><DEDENT>tatement = statement.statement<EOL>bind is None:<EOL>ind = statement.bind<EOL>nd is None: <EOL>aise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>nspection PyUnresolvedReferences<EOL>ct = bind.dialect<EOL>ler = statement._compiler(dialect)<EOL><INDENT>LiteralCompiler(compiler.__class__):<EOL>noinspection PyMethodMayBeStatic<EOL><DEDENT>ef visit_bindparam(self,<EOL>bindparam: BindParameter,<EOL>within_columns_clause: bool = False,<EOL>literal_binds: bool = False,<EOL>**kwargs) -> str:<EOL><INDENT>return super().render_literal_bindparam(<EOL>bindparam,<EOL>within_columns_clause=within_columns_clause,<EOL>literal_binds=literal_binds,<EOL>**kwargs<EOL>)<EOL>
Takes an SQLAlchemy statement and produces a literal SQL version, with values filled in. As per http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query Notes: - for debugging purposes *only* - insecure; you should always separate queries from their values - please also note that this function is quite slow Args: statement: the SQL statement (a SQLAlchemy object) to use bind: if the statement is unbound, you will need to specify an object here that supports SQL execution Returns: a string literal version of the query.
f14643:m4
def dump_table_as_insert_sql(engine: Engine,<EOL>table_name: str,<EOL>fileobj: TextIO,<EOL>wheredict: Dict[str, Any] = None,<EOL>include_ddl: bool = False,<EOL>multirow: bool = False) -> None:
<EOL>log.info("<STR_LIT>", table_name)<EOL>writelines_nl(fileobj, [<EOL>SEP1,<EOL>sql_comment("<STR_LIT>".format(table_name)),<EOL>SEP2,<EOL>sql_comment("<STR_LIT>".format(wheredict)),<EOL>])<EOL>dialect = engine.dialect<EOL>if not dialect.supports_multivalues_insert:<EOL><INDENT>multirow = False<EOL><DEDENT>if multirow:<EOL><INDENT>log.warning("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>multirow = False<EOL><DEDENT>meta = MetaData(bind=engine)<EOL>log.debug("<STR_LIT>")<EOL>table = Table(table_name, meta, autoload=True)<EOL>if include_ddl:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>dump_ddl(table.metadata, dialect_name=engine.dialect.name,<EOL>fileobj=fileobj)<EOL><DEDENT>log.debug("<STR_LIT>")<EOL>query = select(table.columns)<EOL>if wheredict:<EOL><INDENT>for k, v in wheredict.items():<EOL><INDENT>col = table.columns.get(k)<EOL>query = query.where(col == v)<EOL><DEDENT><DEDENT>cursor = engine.execute(query)<EOL>if multirow:<EOL><INDENT>row_dict_list = []<EOL>for r in cursor:<EOL><INDENT>row_dict_list.append(dict(r))<EOL><DEDENT>if row_dict_list:<EOL><INDENT>statement = table.insert().values(row_dict_list)<EOL>insert_str = get_literal_query(statement, bind=engine)<EOL>writeline_nl(fileobj, insert_str)<EOL><DEDENT>else:<EOL><INDENT>writeline_nl(fileobj, sql_comment("<STR_LIT>"))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>found_one = False<EOL>for r in cursor:<EOL><INDENT>found_one = True<EOL>row_dict = dict(r)<EOL>statement = table.insert(values=row_dict)<EOL>insert_str = get_literal_query(statement, bind=engine)<EOL>writeline_nl(fileobj, insert_str)<EOL><DEDENT>if not found_one:<EOL><INDENT>writeline_nl(fileobj, sql_comment("<STR_LIT>"))<EOL><DEDENT><DEDENT>writeline_nl(fileobj, SEP2)<EOL>log.debug("<STR_LIT>")<EOL>
Reads a table from the database, and writes SQL to replicate the table's data to the output ``fileobj``. Args: engine: SQLAlchemy :class:`Engine` table_name: name of the table fileobj: file-like object to write to wheredict: optional dictionary of ``{column_name: value}`` to use as ``WHERE`` filters include_ddl: if ``True``, include the DDL to create the table as well multirow: write multi-row ``INSERT`` statements
f14643:m5
def dump_database_as_insert_sql(engine: Engine,<EOL>fileobj: TextIO = sys.stdout,<EOL>include_ddl: bool = False,<EOL>multirow: bool = False) -> None:
for tablename in get_table_names(engine):<EOL><INDENT>dump_table_as_insert_sql(<EOL>engine=engine,<EOL>table_name=tablename,<EOL>fileobj=fileobj,<EOL>include_ddl=include_ddl,<EOL>multirow=multirow<EOL>)<EOL><DEDENT>
Reads an entire database and writes SQL to replicate it to the output file-like object. Args: engine: SQLAlchemy :class:`Engine` fileobj: file-like object to write to include_ddl: if ``True``, include the DDL to create the table as well multirow: write multi-row ``INSERT`` statements
f14643:m6
def dump_orm_object_as_insert_sql(engine: Engine,<EOL>obj: object,<EOL>fileobj: TextIO) -> None:
<EOL>insp = inspect(obj)<EOL>meta = MetaData(bind=engine)<EOL>table_name = insp.mapper.mapped_table.name<EOL>table = Table(table_name, meta, autoload=True)<EOL>query = select(table.columns)<EOL>for orm_pkcol in insp.mapper.primary_key:<EOL><INDENT>core_pkcol = table.columns.get(orm_pkcol.name)<EOL>pkval = getattr(obj, orm_pkcol.name)<EOL>query = query.where(core_pkcol == pkval)<EOL><DEDENT>cursor = engine.execute(query)<EOL>row = cursor.fetchone() <EOL>row_dict = dict(row)<EOL>statement = table.insert(values=row_dict)<EOL>insert_str = get_literal_query(statement, bind=engine)<EOL>writeline_nl(fileobj, insert_str)<EOL>
Takes a SQLAlchemy ORM object, and writes ``INSERT`` SQL to replicate it to the output file-like object. Args: engine: SQLAlchemy :class:`Engine` obj: SQLAlchemy ORM object to write fileobj: file-like object to write to
f14643:m7
def bulk_insert_extras(dialect_name: str,<EOL>fileobj: TextIO,<EOL>start: bool) -> None:
lines = []<EOL>if dialect_name == SqlaDialectName.MYSQL:<EOL><INDENT>if start:<EOL><INDENT>lines = [<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>]<EOL><DEDENT>else:<EOL><INDENT>lines = [<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>]<EOL><DEDENT><DEDENT>writelines_nl(fileobj, lines)<EOL>
Writes bulk ``INSERT`` preamble (start=True) or end (start=False). For MySQL, this temporarily switches off autocommit behaviour and index/FK checks, for speed, then re-enables them at the end and commits. Args: dialect_name: SQLAlchemy dialect name (see :class:`SqlaDialectName`) fileobj: file-like object to write to start: if ``True``, write preamble; if ``False``, write end
f14643:m8
def dump_orm_tree_as_insert_sql(engine: Engine,<EOL>baseobj: object,<EOL>fileobj: TextIO) -> None:
<EOL>line_nl(<EOL>ileobj,<EOL>ql_comment("<STR_LIT>"))<EOL>insert_extras(engine.dialect.name, fileobj, start=True)<EOL>art in walk_orm_tree(baseobj):<EOL>ump_orm_object_as_insert_sql(engine, part, fileobj)<EOL>insert_extras(engine.dialect.name, fileobj, start=False)<EOL>
Sends an object, and all its relations (discovered via "relationship" links) as ``INSERT`` commands in SQL, to ``fileobj``. Args: engine: SQLAlchemy :class:`Engine` baseobj: starting SQLAlchemy ORM object fileobj: file-like object to write to Problem: foreign key constraints. - MySQL/InnoDB doesn't wait to the end of a transaction to check FK integrity (which it should): http://stackoverflow.com/questions/5014700/in-mysql-can-i-defer-referential-integrity-checks-until-commit # noqa - PostgreSQL can. - Anyway, slightly ugly hacks... https://dev.mysql.com/doc/refman/5.5/en/optimizing-innodb-bulk-data-loading.html - Not so obvious how we can iterate through the list of ORM objects and guarantee correct insertion order with respect to all FKs.
f14643:m9
def insert_on_duplicate(tablename: str,<EOL>values: Any = None,<EOL>inline: bool = False,<EOL>**kwargs):
<EOL>n InsertOnDuplicate(tablename, values, inline=inline, **kwargs)<EOL>
Command to produce an :class:`InsertOnDuplicate` object. Args: tablename: name of the table values: values to ``INSERT`` inline: as per http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.insert kwargs: additional parameters Returns: an :class:`InsertOnDuplicate` object
f14644:m0
def monkeypatch_TableClause() -> None:
log.debug("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>TableClause.insert_on_duplicate = insert_on_duplicate<EOL>
Modifies :class:`sqlalchemy.sql.expression.TableClause` to insert a ``insert_on_duplicate`` member that is our :func:`insert_on_duplicate` function as above.
f14644:m1
def unmonkeypatch_TableClause() -> None:
del TableClause.insert_on_duplicate<EOL>
Reverses the action of :func:`monkeypatch_TableClause`.
f14644:m2
@compiles(InsertOnDuplicate, SqlaDialectName.MYSQL)<EOL>def compile_insert_on_duplicate_key_update(insert: Insert,<EOL>compiler: SQLCompiler,<EOL>**kw) -> str:
<EOL>.critical(compiler.__dict__)<EOL>.critical(compiler.dialect.__dict__)<EOL>.critical(insert.__dict__)<EOL>ompiler.visit_insert(insert, **kw)<EOL>.critical(s)<EOL>E_INSERT_FIELDNAMES.match(s)<EOL>is None:<EOL>aise ValueError("<STR_LIT>")<EOL>ns = [c.strip() for c in m.group('<STR_LIT>').split("<STR_LIT:U+002C>")]<EOL>.critical(columns)<EOL>es = "<STR_LIT:U+002CU+0020>".join(<EOL>"<STR_LIT>".format(c=c) for c in columns])<EOL>'<STR_LIT>'.format(updates)<EOL>.critical(s)<EOL>n s<EOL>
Hooks into the use of the :class:`InsertOnDuplicate` class for the MySQL dialect. Compiles the relevant SQL for an ``INSERT... ON DUPLICATE KEY UPDATE`` statement. Notes: - We can't get the fieldnames directly from ``insert`` or ``compiler``. - We could rewrite the innards of the visit_insert statement (https://github.com/bedwards/sqlalchemy_mysql_ext/blob/master/duplicate.py)... but, like that, it will get outdated. - We could use a hack-in-by-hand method (http://stackoverflow.com/questions/6611563/sqlalchemy-on-duplicate-key-update) ... but a little automation would be nice. - So, regex to the rescue. - NOTE THAT COLUMNS ARE ALREADY QUOTED by this stage; no need to repeat.
f14644:m3
def coltype_as_typeengine(coltype: Union[VisitableType,<EOL>TypeEngine]) -> TypeEngine:
if isinstance(coltype, TypeEngine):<EOL><INDENT>return coltype<EOL><DEDENT>return coltype()<EOL>
Instances of SQLAlchemy column types are subclasses of ``TypeEngine``. It's possible to specify column types either as such instances, or as the class type. This function ensures that such classes are converted to instances. To explain: you can specify columns like .. code-block:: python a = Column("a", Integer) b = Column("b", Integer()) c = Column("c", String(length=50)) isinstance(Integer, TypeEngine) # False isinstance(Integer(), TypeEngine) # True isinstance(String(length=50), TypeEngine) # True type(Integer) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(Integer()) # <class 'sqlalchemy.sql.sqltypes.Integer'> type(String) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(String(length=50)) # <class 'sqlalchemy.sql.sqltypes.String'> This function coerces things to a :class:`TypeEngine`.
f14645:m0
def walk_orm_tree(obj,<EOL>debug: bool = False,<EOL>seen: Set = None,<EOL>skip_relationships_always: List[str] = None,<EOL>skip_relationships_by_tablename: Dict[str, List[str]] = None,<EOL>skip_all_relationships_for_tablenames: List[str] = None,<EOL>skip_all_objects_for_tablenames: List[str] = None)-> Generator[object, None, None]:
<EOL>skip_relationships_always = skip_relationships_always or [] <EOL>skip_relationships_by_tablename = skip_relationships_by_tablename or {} <EOL>skip_all_relationships_for_tablenames = skip_all_relationships_for_tablenames or [] <EOL>skip_all_objects_for_tablenames = skip_all_objects_for_tablenames or [] <EOL>stack = [obj]<EOL>if seen is None:<EOL><INDENT>seen = set()<EOL><DEDENT>while stack:<EOL><INDENT>obj = stack.pop(<NUM_LIT:0>)<EOL>if obj in seen:<EOL><INDENT>continue<EOL><DEDENT>tablename = obj.__tablename__<EOL>if tablename in skip_all_objects_for_tablenames:<EOL><INDENT>continue<EOL><DEDENT>seen.add(obj)<EOL>if debug:<EOL><INDENT>log.debug("<STR_LIT>", obj)<EOL><DEDENT>yield obj<EOL>insp = inspect(obj) <EOL>for relationship in insp.mapper.relationships: <EOL><INDENT>attrname = relationship.key<EOL>if attrname in skip_relationships_always:<EOL><INDENT>continue<EOL><DEDENT>if tablename in skip_all_relationships_for_tablenames:<EOL><INDENT>continue<EOL><DEDENT>if (tablename in skip_relationships_by_tablename and<EOL>attrname in skip_relationships_by_tablename[tablename]):<EOL><INDENT>continue<EOL><DEDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>", relationship)<EOL><DEDENT>related = getattr(obj, attrname)<EOL>if debug and related:<EOL><INDENT>log.debug("<STR_LIT>", related)<EOL><DEDENT>if relationship.uselist:<EOL><INDENT>stack.extend(related)<EOL><DEDENT>elif related is not None:<EOL><INDENT>stack.append(related)<EOL><DEDENT><DEDENT><DEDENT>
Starting with a SQLAlchemy ORM object, this function walks a relationship tree, yielding each of the objects once. To skip attributes by name, put the attribute name(s) in ``skip_attrs_always``. To skip by table name, pass ``skip_attrs_by_tablename`` as e.g. .. code-block:: python {'sometable': ['attr1_to_skip', 'attr2_to_skip']} Args: obj: the SQLAlchemy ORM object to walk debug: be verbose seen: usually ``None``, but can be a set of objects marked as "already seen"; if an object is in this set, it is skipped skip_relationships_always: relationships are skipped if the relationship has a name in this (optional) list skip_relationships_by_tablename: optional dictionary mapping table names (keys) to relationship attribute names (values); if the "related table"/"relationship attribute" pair are in this dictionary, the relationship is skipped skip_all_relationships_for_tablenames: relationships are skipped if the the related table has a name in this (optional) list skip_all_objects_for_tablenames: if the object belongs to a table whose name is in this (optional) list, the object is skipped Yields: SQLAlchemy ORM objects (including the starting object)
f14645:m1
def copy_sqla_object(obj: object,<EOL>omit_fk: bool = True,<EOL>omit_pk: bool = True,<EOL>omit_attrs: List[str] = None,<EOL>debug: bool = False) -> object:
omit_attrs = omit_attrs or [] <EOL>cls = type(obj)<EOL>mapper = class_mapper(cls)<EOL>newobj = cls() <EOL>rel_keys = set([c.key for c in mapper.relationships])<EOL>prohibited = rel_keys<EOL>if omit_pk:<EOL><INDENT>pk_keys = set([c.key for c in mapper.primary_key])<EOL>prohibited |= pk_keys<EOL><DEDENT>if omit_fk:<EOL><INDENT>fk_keys = set([c.key for c in mapper.columns if c.foreign_keys])<EOL>prohibited |= fk_keys<EOL><DEDENT>prohibited |= set(omit_attrs)<EOL>if debug:<EOL><INDENT>log.debug("<STR_LIT>", prohibited)<EOL><DEDENT>for k in [p.key for p in mapper.iterate_properties<EOL>if p.key not in prohibited]:<EOL><INDENT>try:<EOL><INDENT>value = getattr(obj, k)<EOL>if debug:<EOL><INDENT>log.debug("<STR_LIT>",<EOL>k, value)<EOL><DEDENT>setattr(newobj, k, value)<EOL><DEDENT>except AttributeError:<EOL><INDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>", k)<EOL><DEDENT>pass<EOL><DEDENT><DEDENT>return newobj<EOL>
Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT MUST SUPPORT CREATION USING ``__init__()`` WITH NO PARAMETERS), and copies across all attributes, omitting PKs (by default), FKs (by default), and relationship attributes (always omitted). Args: obj: the object to copy omit_fk: omit foreign keys (FKs)? omit_pk: omit primary keys (PKs)? omit_attrs: attributes (by name) not to copy debug: be verbose Returns: a new copy of the object
f14645:m2
def rewrite_relationships(oldobj: object,<EOL>newobj: object,<EOL>objmap: Dict[object, object],<EOL>debug: bool = False,<EOL>skip_table_names: List[str] = None) -> None:
skip_table_names = skip_table_names or [] <EOL>insp = inspect(oldobj) <EOL>for attrname_rel in insp.mapper.relationships.items(): <EOL><INDENT>attrname = attrname_rel[<NUM_LIT:0>]<EOL>rel_prop = attrname_rel[<NUM_LIT:1>]<EOL>if rel_prop.viewonly:<EOL><INDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>continue <EOL><DEDENT>related_class = rel_prop.mapper.class_<EOL>related_table_name = related_class.__tablename__ <EOL>if related_table_name in skip_table_names:<EOL><INDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>",<EOL>related_table_name)<EOL><DEDENT>continue<EOL><DEDENT>related_old = getattr(oldobj, attrname)<EOL>if rel_prop.uselist:<EOL><INDENT>related_new = [objmap[r] for r in related_old]<EOL><DEDENT>elif related_old is not None:<EOL><INDENT>related_new = objmap[related_old]<EOL><DEDENT>else:<EOL><INDENT>related_new = None<EOL><DEDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>",<EOL>attrname, related_new)<EOL><DEDENT>setattr(newobj, attrname, related_new)<EOL><DEDENT>
A utility function only. Used in copying objects between SQLAlchemy sessions. Both ``oldobj`` and ``newobj`` are SQLAlchemy instances. The instance ``newobj`` is already a copy of ``oldobj`` but we wish to rewrite its relationships, according to the map ``objmap``, which maps old to new objects. For example: - Suppose a source session has a Customer record and a Sale record containing ``sale.customer_id``, a foreign key to Customer. - We may have corresponding Python SQLAlchemy ORM objects ``customer_1_src`` and ``sale_1_src``. - We copy them into a destination database, where their Python ORM objects are ``customer_1_dest`` and ``sale_1_dest``. - In the process we set up an object map looking like: .. code-block:: none Old session New session ------------------------------- customer_1_src customer_1_dest sale_1_src sale_1_dest - Now, we wish to make ``sale_1_dest`` have a relationship to ``customer_1_dest``, in the same way that ``sale_1_src`` has a relationship to ``customer_1_src``. This function will modify ``sale_1_dest`` accordingly, given this object map. It will observe that ``sale_1_src`` (here ``oldobj``) has a relationship to ``customer_1_src``; it will note that ``objmap`` maps ``customer_1_src`` to ``customer_1_dest``; it will create the relationship from ``sale_1_dest`` (here ``newobj``) to ``customer_1_dest``. Args: oldobj: SQLAlchemy ORM object to read from newobj: SQLAlchemy ORM object to write to objmap: dictionary mapping "source" objects to their corresponding "destination" object. debug: be verbose skip_table_names: if a related table's name is in this (optional) list, that relationship is skipped
f14645:m3
def deepcopy_sqla_objects(<EOL>startobjs: List[object],<EOL>session: Session,<EOL>flush: bool = True,<EOL>debug: bool = False,<EOL>debug_walk: bool = True,<EOL>debug_rewrite_rel: bool = False,<EOL>objmap: Dict[object, object] = None) -> None:
if objmap is None:<EOL><INDENT>objmap = {} <EOL><DEDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>seen = set()<EOL>for startobj in startobjs:<EOL><INDENT>for oldobj in walk_orm_tree(startobj, seen=seen, debug=debug_walk):<EOL><INDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>", oldobj)<EOL><DEDENT>newobj = copy_sqla_object(oldobj, omit_pk=True, omit_fk=True)<EOL>objmap[oldobj] = newobj<EOL><DEDENT><DEDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>for oldobj, newobj in objmap.items():<EOL><INDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>", newobj)<EOL><DEDENT>rewrite_relationships(oldobj, newobj, objmap, debug=debug_rewrite_rel)<EOL><DEDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>for newobj in objmap.values():<EOL><INDENT>session.add(newobj)<EOL><DEDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>if flush:<EOL><INDENT>session.flush()<EOL><DEDENT>
Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a new session. This function operates in several passes: 1. Walk the ORM tree through all objects and their relationships, copying every object thus found (via :func:`copy_sqla_object`, without their relationships), and building a map from each source-session object to its equivalent destination-session object. 2. Work through all the destination objects, rewriting their relationships (via :func:`rewrite_relationships`) so they relate to each other (rather than their source-session brethren). 3. Insert all the destination-session objects into the destination session. For this to succeed, every object must take an ``__init__`` call with no arguments (see :func:`copy_sqla_object`). (We can't specify the required ``args``/``kwargs``, since we are copying a tree of arbitrary objects.) Args: startobjs: SQLAlchemy ORM objects to copy session: destination SQLAlchemy :class:`Session` into which to insert the copies flush: flush the session when we've finished? debug: be verbose? debug_walk: be extra verbose when walking the ORM tree? debug_rewrite_rel: be extra verbose when rewriting relationships? objmap: starting object map from source-session to destination-session objects (see :func:`rewrite_relationships` for more detail); usually ``None`` to begin with.
f14645:m4
def deepcopy_sqla_object(startobj: object,<EOL>session: Session,<EOL>flush: bool = True,<EOL>debug: bool = False,<EOL>debug_walk: bool = False,<EOL>debug_rewrite_rel: bool = False,<EOL>objmap: Dict[object, object] = None) -> object:
if objmap is None:<EOL><INDENT>objmap = {} <EOL><DEDENT>deepcopy_sqla_objects(<EOL>startobjs=[startobj],<EOL>session=session,<EOL>flush=flush,<EOL>debug=debug,<EOL>debug_walk=debug_walk,<EOL>debug_rewrite_rel=debug_rewrite_rel,<EOL>objmap=objmap<EOL>)<EOL>return objmap[startobj]<EOL>
Makes a copy of the object, inserting it into ``session``. Uses :func:`deepcopy_sqla_objects` (q.v.). A problem is the creation of duplicate dependency objects if you call it repeatedly. Optionally, if you pass the objmap in (which maps old to new objects), you can call this function repeatedly to clone a related set of objects... ... no, that doesn't really work, as it doesn't visit parents before children. The :func:`cardinal_pythonlib.sqlalchemy.merge_db.merge_db` function does that properly. Args: startobj: SQLAlchemy ORM object to deep-copy session: see :func:`deepcopy_sqla_objects` flush: see :func:`deepcopy_sqla_objects` debug: see :func:`deepcopy_sqla_objects` debug_walk: see :func:`deepcopy_sqla_objects` debug_rewrite_rel: see :func:`deepcopy_sqla_objects` objmap: see :func:`deepcopy_sqla_objects` Returns: the copied object matching ``startobj``
f14645:m5
def gen_columns(obj) -> Generator[Tuple[str, Column], None, None]:
mapper = obj.__mapper__ <EOL>assert mapper, "<STR_LIT>""<STR_LIT>".format(obj)<EOL>colmap = mapper.columns <EOL>if not colmap:<EOL><INDENT>return<EOL><DEDENT>for attrname, column in colmap.items():<EOL><INDENT>yield attrname, column<EOL><DEDENT>
Asks a SQLAlchemy ORM object: "what are your SQLAlchemy columns?" Yields tuples of ``(attr_name, Column)`` from an SQLAlchemy ORM object instance. Also works with the corresponding SQLAlchemy ORM class. Examples: .. code-block:: python from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.sql.schema import Column from sqlalchemy.sql.sqltypes import Integer Base = declarative_base() class MyClass(Base): __tablename__ = "mytable" pk = Column("pk", Integer, primary_key=True, autoincrement=True) a = Column("a", Integer) x = MyClass() list(gen_columns(x)) list(gen_columns(MyClass))
f14645:m6
def get_pk_attrnames(obj) -> List[str]:
return [attrname<EOL>for attrname, column in gen_columns(obj)<EOL>if column.primary_key]<EOL>
Asks an SQLAlchemy ORM object: "what are your primary key(s)?" Args: obj: SQLAlchemy ORM object Returns: list of attribute names of primary-key columns
f14645:m7
def gen_columns_for_uninstrumented_class(cls: Type)-> Generator[Tuple[str, Column], None, None]:
<EOL>ttrname in dir(cls):<EOL>otential_column = getattr(cls, attrname)<EOL>f isinstance(potential_column, Column):<EOL><INDENT>yield attrname, potential_column<EOL><DEDENT>
Generate ``(attr_name, Column)`` tuples from an UNINSTRUMENTED class, i.e. one that does not inherit from ``declarative_base()``. Use this for mixins of that kind. SUBOPTIMAL. May produce warnings like: .. code-block:: none SAWarning: Unmanaged access of declarative attribute id from non-mapped class GenericTabletRecordMixin Try to use :func:`gen_columns` instead.
f14645:m8
def attrname_to_colname_dict(cls) -> Dict[str, str]:
attr_col = {} <EOL>for attrname, column in gen_columns(cls):<EOL><INDENT>attr_col[attrname] = column.name<EOL><DEDENT>return attr_col<EOL>
Asks an SQLAlchemy class how its attribute names correspond to database column names. Args: cls: SQLAlchemy ORM class Returns: a dictionary mapping attribute names to database column names
f14645:m9
def gen_relationships(obj) -> Generator[Tuple[str, RelationshipProperty, Type],<EOL>None, None]:
insp = inspect(obj) <EOL>for attrname, rel_prop in insp.mapper.relationships.items(): <EOL><INDENT>related_class = rel_prop.mapper.class_<EOL>yield attrname, rel_prop, related_class<EOL><DEDENT>
Yields tuples of ``(attrname, RelationshipProperty, related_class)`` for all relationships of an ORM object. The object 'obj' can be EITHER an instance OR a class.
f14645:m11
def get_orm_columns(cls: Type) -> List[Column]:
mapper = inspect(cls) <EOL>colmap = mapper.columns <EOL>return colmap.values()<EOL>
Gets :class:`Column` objects from an SQLAlchemy ORM class. Does not provide their attribute names.
f14645:m12
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]:
colnames = [col.name for col in get_orm_columns(cls)]<EOL>return sorted(colnames) if sort else colnames<EOL>
Gets column names (that is, database column names) from an SQLAlchemy ORM class.
f14645:m13
def get_table_names_from_metadata(metadata: MetaData) -> List[str]:
return [table.name for table in metadata.tables.values()]<EOL>
Returns all database table names found in an SQLAlchemy :class:`MetaData` object.
f14645:m14
def get_metadata_from_orm_class_or_object(cls: Type) -> MetaData:
<EOL>table = cls.__table__ <EOL>return table.metadata<EOL>
Returns the :class:`MetaData` object from an SQLAlchemy ORM class or instance.
f14645:m15
def gen_orm_classes_from_base(base: Type) -> Generator[Type, None, None]:
for cls in gen_all_subclasses(base):<EOL><INDENT>if _get_immediate_cls_attr(cls, '<STR_LIT>', strict=True):<EOL><INDENT>continue <EOL><DEDENT>yield cls<EOL><DEDENT>
From an SQLAlchemy ORM base class, yield all the subclasses (except those that are abstract). If you begin with the proper :class`Base` class, then this should give all ORM classes in use.
f14645:m16
def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]:
<EOL>return {cls.__tablename__: cls for cls in gen_orm_classes_from_base(base)}<EOL>
Given an SQLAlchemy ORM base class, returns a dictionary whose keys are table names and whose values are ORM classes. If you begin with the proper :class`Base` class, then this should give all tables and ORM classes in use.
f14645:m17
def get_attrdict(self) -> OrderedNamespace:
<EOL>columns = self.__table__.columns.keys()<EOL>values = (getattr(self, x) for x in columns)<EOL>zipped = zip(columns, values)<EOL>return OrderedNamespace(zipped)<EOL>
Returns what looks like a plain object with the values of the SQLAlchemy ORM object.
f14645:c0:m0
@classmethod<EOL><INDENT>def from_attrdict(cls, attrdict: OrderedNamespace) -> object:<DEDENT>
dictionary = attrdict.__dict__<EOL>return cls(**dictionary)<EOL>
Builds a new instance of the ORM object from values in an attrdict.
f14645:c0:m2
def fail_unknown_dialect(compiler: "<STR_LIT>", task: str) -> None:
raise NotImplementedError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>task=task,<EOL>dialect=compiler.dialect<EOL>)<EOL>)<EOL>
Raise :exc:`NotImplementedError` in relation to a dialect for which a function hasn't been implemented (with a helpful error message).
f14646:m0
def fetch_processed_single_clause(element: "<STR_LIT>",<EOL>compiler: "<STR_LIT>") -> str:
if len(element.clauses) != <NUM_LIT:1>:<EOL><INDENT>raise TypeError("<STR_LIT>".format(<EOL>len(element.clauses)))<EOL><DEDENT>clauselist = element.clauses <EOL>first = clauselist.get_children()[<NUM_LIT:0>]<EOL>return compiler.process(first)<EOL>
Takes a clause element that must have a single clause, and converts it to raw SQL text.
f14646:m1
@compiles(extract_year)<EOL>def extract_year_default(element: "<STR_LIT>",<EOL>compiler: "<STR_LIT>", **kw) -> None:
fail_unknown_dialect(compiler, "<STR_LIT>")<EOL>
Default implementation of :func:, which raises :exc:`NotImplementedError`.
f14646:m2
@contextmanager<EOL>def if_sqlserver_disable_constraints(session: SqlASession,<EOL>tablename: str) -> None:
<EOL>e = get_engine_from_session(session)<EOL>_sqlserver(engine):<EOL>uoted_tablename = quote_identifier(tablename, engine)<EOL>ession.execute(<EOL>"<STR_LIT>".format(<EOL>quoted_tablename))<EOL>ield<EOL>ession.execute(<EOL>"<STR_LIT>".format(<EOL>quoted_tablename))<EOL>ield<EOL>
If we're running under SQL Server, disable constraint checking for the specified table while the resource is held. Args: session: SQLAlchemy :class:`Session` tablename: table name See https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger
f14647:m0
@contextmanager<EOL>def if_sqlserver_disable_triggers(session: SqlASession,<EOL>tablename: str) -> None:
<EOL>e = get_engine_from_session(session)<EOL>_sqlserver(engine):<EOL>uoted_tablename = quote_identifier(tablename, engine)<EOL>ession.execute(<EOL>"<STR_LIT>".format(quoted_tablename))<EOL>ield<EOL>ession.execute(<EOL>"<STR_LIT>".format(quoted_tablename))<EOL>ield<EOL>
If we're running under SQL Server, disable triggers for the specified table while the resource is held. Args: session: SQLAlchemy :class:`Session` tablename: table name See https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger
f14647:m1
@contextmanager<EOL>def if_sqlserver_disable_constraints_triggers(session: SqlASession,<EOL>tablename: str) -> None:
with if_sqlserver_disable_constraints(session, tablename):<EOL><INDENT>with if_sqlserver_disable_triggers(session, tablename):<EOL><INDENT>yield<EOL><DEDENT><DEDENT>
If we're running under SQL Server, disable triggers AND constraints for the specified table while the resource is held. Args: session: SQLAlchemy :class:`Session` tablename: table name
f14647:m2
def make_mysql_url(username: str, password: str, dbname: str,<EOL>driver: str = "<STR_LIT>", host: str = "<STR_LIT:localhost>",<EOL>port: int = <NUM_LIT>, charset: str = "<STR_LIT:utf8>") -> str:
return "<STR_LIT>".format(<EOL>driver=driver,<EOL>host=host,<EOL>port=port,<EOL>db=dbname,<EOL>u=username,<EOL>p=password,<EOL>cs=charset,<EOL>)<EOL>
Makes an SQLAlchemy URL for a MySQL database.
f14648:m0
def make_sqlite_url(filename: str) -> str:
absfile = os.path.abspath(filename)<EOL>return "<STR_LIT>".format(host="<STR_LIT>", path=absfile)<EOL>
Makes an SQLAlchemy URL for a SQLite database.
f14648:m1
def get_engine_from_session(dbsession: Session) -> Engine:
engine = dbsession.bind<EOL>assert isinstance(engine, Engine)<EOL>return engine<EOL>
Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`.
f14648:m2
def get_safe_url_from_engine(engine: Engine) -> str:
raw_url = engine.url <EOL>url_obj = make_url(raw_url) <EOL>return repr(url_obj)<EOL>
Gets a URL from an :class:`Engine`, obscuring the password.
f14648:m3
def get_safe_url_from_session(dbsession: Session) -> str:
return get_safe_url_from_engine(get_engine_from_session(dbsession))<EOL>
Gets a URL from a :class:`Session`, obscuring the password.
f14648:m4
def get_safe_url_from_url(url: str) -> str:
engine = create_engine(url)<EOL>return get_safe_url_from_engine(engine)<EOL>
Converts an SQLAlchemy URL into a safe version that obscures the password.
f14648:m5
def get_rows_fieldnames_from_raw_sql(<EOL>session: Union[Session, Engine, Connection],<EOL>sql: str) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]:
result = session.execute(sql) <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 sql: raw SQL to execure Returns: ``(rows, fieldnames)`` where ``rows`` is the usual set of results and ``fieldnames`` are the name of the result columns/fields.
f14649:m0
def count_star(session: Union[Session, Engine, Connection],<EOL>tablename: str,<EOL>*criteria: Any) -> int:
<EOL>query = select([func.count()]).select_from(table(tablename))<EOL>for criterion in criteria:<EOL><INDENT>query = query.where(criterion)<EOL><DEDENT>return session.execute(query).scalar()<EOL>
Returns the result of ``COUNT(*)`` from the specified table (with additional ``WHERE`` criteria if desired). Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object tablename: name of the table criteria: optional SQLAlchemy "where" criteria Returns: a scalar
f14649:m1
def count_star_and_max(session: Union[Session, Engine, Connection],<EOL>tablename: str,<EOL>maxfield: str,<EOL>*criteria: Any) -> Tuple[int, Optional[int]]:
query = select([<EOL>func.count(),<EOL>func.max(column(maxfield))<EOL>]).select_from(table(tablename))<EOL>for criterion in criteria:<EOL><INDENT>query = query.where(criterion)<EOL><DEDENT>result = session.execute(query)<EOL>return result.fetchone()<EOL>
Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object tablename: name of the table maxfield: name of column (field) to take the ``MAX()`` of criteria: optional SQLAlchemy "where" criteria Returns: a tuple: ``(count, maximum)``
f14649:m2
def exists_in_table(session: Session, table_: Table, *criteria: Any) -> bool:
exists_clause = exists().select_from(table_)<EOL>for criterion in criteria:<EOL><INDENT>exists_clause = exists_clause.where(criterion)<EOL><DEDENT>if session.get_bind().dialect.name == SqlaDialectName.MSSQL:<EOL><INDENT>query = select([literal(True)]).where(exists_clause)<EOL><DEDENT>else:<EOL><INDENT>query = select([exists_clause])<EOL><DEDENT>result = session.execute(query).scalar()<EOL>return bool(result)<EOL>
Implements an efficient way of detecting if a record or records exist; should be faster than ``COUNT(*)`` in some circumstances. Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object table_: SQLAlchemy :class:`Table` object criteria: optional SQLAlchemy "where" criteria Returns: a boolean Prototypical use: .. code-block:: python return exists_in_table(session, table, column(fieldname1) == value2, column(fieldname2) == value2)
f14649:m3
def exists_plain(session: Session, tablename: str, *criteria: Any) -> bool:
return exists_in_table(session, table(tablename), *criteria)<EOL>
Implements an efficient way of detecting if a record or records exist; should be faster than COUNT(*) in some circumstances. Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object tablename: name of the table criteria: optional SQLAlchemy "where" criteria Returns: a boolean Prototypical use: .. code-block:: python return exists_plain(config.destdb.session, dest_table_name, column(fieldname1) == value2, column(fieldname2) == value2)
f14649:m4
def fetch_all_first_values(session: Session,<EOL>select_statement: Select) -> List[Any]:
rows = session.execute(select_statement) <EOL>try:<EOL><INDENT>return [row[<NUM_LIT:0>] for row in rows]<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise MultipleResultsFound(str(e))<EOL><DEDENT>
Returns a list of the first values in each row returned by a ``SELECT`` query. A Core version of this sort of thing: http://xion.io/post/code/sqlalchemy-query-values.html Args: session: SQLAlchemy :class:`Session` object select_statement: SQLAlchemy :class:`Select` object Returns: a list of the first value of each result row
f14649:m5
def main() -> None:
<EOL>log.info("<STR_LIT>")<EOL>test_base_elements()<EOL>log.info("<STR_LIT>")<EOL>
Command-line entry point to run tests.
f14653:m18
@classmethod<EOL><INDENT>def quote_identifier_if_required(cls, identifier: str,<EOL>debug_force_quote: bool = False) -> str:<DEDENT>
if debug_force_quote:<EOL><INDENT>return cls.quote_identifier(identifier)<EOL><DEDENT>if cls.is_quoted(identifier):<EOL><INDENT>return identifier<EOL><DEDENT>if cls.requires_quoting(identifier):<EOL><INDENT>return cls.quote_identifier(identifier)<EOL><DEDENT>return identifier<EOL>
Transforms a SQL identifier (such as a column name) into a version that is quoted if required (or, with ``debug_force_quote=True``, is quoted regardless).
f14653:c0:m1
@classmethod<EOL><INDENT>def quote_identifier(cls, identifier: str) -> str:<DEDENT>
raise NotImplementedError()<EOL>
Quotes an SQL identifier (e.g. table or column name); e.g. some databases use ``[name]``, some use ```name```).
f14653:c0:m2
@classmethod<EOL><INDENT>def is_quoted(cls, identifier: str) -> bool:<DEDENT>
raise NotImplementedError()<EOL>
Determines whether an SQL identifier (e.g. table or column name) is already quoted.
f14653:c0:m3
@classmethod<EOL><INDENT>def requires_quoting(cls, identifier: str) -> bool:<DEDENT>
raise NotImplementedError()<EOL>
Determines whether an SQL identifier (e.g. table or column name) requires to be quoted.
f14653:c0:m4
@classmethod<EOL><INDENT>def get_grammar(cls) -> ParserElement:<DEDENT>
raise NotImplementedError()<EOL>
Returns the full SQL grammar parser.
f14653:c0:m5
@classmethod<EOL><INDENT>def get_column_spec(cls) -> ParserElement:<DEDENT>
raise NotImplementedError()<EOL>
Returns a parser element representing an SQL column name, such as .. code-block:: sql somecol sometable.somecol somedb.sometable.somecol
f14653:c0:m6
@classmethod<EOL><INDENT>def get_result_column(cls) -> ParserElement:<DEDENT>
raise NotImplementedError()<EOL>
Returns a parser element representing an SQL result column, such as .. code-block:: sql somecol somecol AS somealias COUNT(*) AS total 3
f14653:c0:m7
@classmethod<EOL><INDENT>def get_join_op(cls) -> ParserElement:<DEDENT>
raise NotImplementedError()<EOL>
Returns a parser element representing an SQL JOIN operation, such as .. code-block:: sql JOIN INNER JOIN LEFT OUTER JOIN
f14653:c0:m8
@classmethod<EOL><INDENT>def get_table_spec(cls) -> ParserElement:<DEDENT>
raise NotImplementedError()<EOL>
Returns a parser element representing an SQL table name, such as .. code-block:: sql sometable somedb.sometable
f14653:c0:m9
@classmethod<EOL><INDENT>def get_join_constraint(cls) -> ParserElement:<DEDENT>
raise NotImplementedError()<EOL>
Returns a parser element representing an SQL join constraint, such as .. code-block:: sql ON customer.id = sale.customer_id
f14653:c0:m10
@classmethod<EOL><INDENT>def get_select_statement(cls) -> ParserElement:<DEDENT>
raise NotImplementedError()<EOL>
Returns a parser element representing an SQL SELECT statement, such as .. code-block:: sql SELECT a, b FROM sometable WHERE c = 5; SELECT a, COUNT(*) FROM sometable INNER JOIN othertable ON sometable.c = othertable.c GROUP BY a;
f14653:c0:m11
@classmethod<EOL><INDENT>def get_expr(cls) -> ParserElement:<DEDENT>
raise NotImplementedError()<EOL>
Returns a parser element representing an SQL expression, such as .. code-block:: sql somecol 17 NOT(LENGTH(LEFT(somecol, 5)) + 3 < othercol % 4)
f14653:c0:m12
@classmethod<EOL><INDENT>def get_where_clause(cls) -> ParserElement:<DEDENT>
raise NotImplementedError()<EOL>
Returns a parser element representing an SQL WHERE clause (the ``WHERE`` keyword followed by a WHERE expression), such as .. code-block:: sql WHERE a > 3 WHERE LENGTH(a) < c + 2
f14653:c0:m13
@classmethod<EOL><INDENT>def get_where_expr(cls) -> ParserElement:<DEDENT>
raise NotImplementedError()<EOL>
Returns a parser element representing an SQL WHERE expression (the condition without the ``WHERE`` keyword itself), such as .. code-block:: sql a > 3 LENGTH(a) < c + 2
f14653:c0:m14
def sql_string_literal(text: str) -> str:
<EOL>return SQUOTE + text.replace(SQUOTE, DOUBLE_SQUOTE) + SQUOTE<EOL>
Transforms text into its ANSI SQL-quoted version, e.g. (in Python ``repr()`` format): .. code-block:: none "some string" -> "'some string'" "Jack's dog" -> "'Jack''s dog'"
f14654:m0
def sql_date_literal(dt: DateLikeType) -> str:
<EOL>return dt.strftime("<STR_LIT>")<EOL>
Transforms a Python object that is of duck type ``datetime.date`` into an ANSI SQL literal string, like '2000-12-31'.
f14654:m1
def sql_datetime_literal(dt: DateTimeLikeType,<EOL>subsecond: bool = False) -> str:
<EOL>fmt = "<STR_LIT>".format("<STR_LIT>" if subsecond else "<STR_LIT>")<EOL>return dt.strftime(fmt)<EOL>
Transforms a Python object that is of duck type ``datetime.datetime`` into an ANSI SQL literal string, like ``'2000-12-31 23:59:59'``, or if ``subsecond=True``, into the (non-ANSI) format ``'2000-12-31 23:59:59.123456'`` or similar.
f14654:m2
def sql_comment(comment: str) -> str:
"""<STR_LIT>"""<EOL>if not comment:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>return "<STR_LIT:\n>".join("<STR_LIT>".format(x) for x in comment.splitlines())<EOL>
Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``.
f14654:m3
def sql_dequote_string(s: str) -> str:
if len(s) < <NUM_LIT:2> or s[<NUM_LIT:0>] != SQUOTE or s[-<NUM_LIT:1>] != SQUOTE:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>s = s[<NUM_LIT:1>:-<NUM_LIT:1>] <EOL>return s.replace(DOUBLE_SQUOTE, SQUOTE)<EOL>
Reverses :func:`sql_quote_string`.
f14654:m4
def gen_items_from_sql_csv(s: str) -> Generator[str, None, None]:
<EOL>if not s:<EOL><INDENT>return<EOL><DEDENT>n = len(s)<EOL>startpos = <NUM_LIT:0><EOL>pos = <NUM_LIT:0><EOL>in_quotes = False<EOL>while pos < n:<EOL><INDENT>if not in_quotes:<EOL><INDENT>if s[pos] == COMMA:<EOL><INDENT>chunk = s[startpos:pos] <EOL>result = chunk.strip()<EOL>yield result<EOL>startpos = pos + <NUM_LIT:1><EOL><DEDENT>elif s[pos] == SQUOTE:<EOL><INDENT>in_quotes = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if pos < n - <NUM_LIT:1> and s[pos] == SQUOTE and s[pos + <NUM_LIT:1>] == SQUOTE:<EOL><INDENT>pos += <NUM_LIT:1> <EOL><DEDENT>elif s[pos] == SQUOTE:<EOL><INDENT>in_quotes = False<EOL><DEDENT><DEDENT>pos += <NUM_LIT:1><EOL><DEDENT>result = s[startpos:].strip()<EOL>yield result<EOL>
Splits a comma-separated list of quoted SQL values, with ``'`` as the quote character. Allows escaping of the quote character by doubling it. Returns the quotes (and escaped quotes) as part of the result. Allows newlines etc. within the string passed.
f14654:m5
def make_grammar(dialect: str) -> SqlGrammar:
if dialect == SqlaDialectName.MYSQL:<EOL><INDENT>return mysql_grammar<EOL><DEDENT>elif dialect == SqlaDialectName.MSSQL:<EOL><INDENT>return mssql_grammar<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>".format(repr(dialect)))<EOL><DEDENT>
Factory to make an :class:`.SqlGrammar` from the name of an SQL dialect, where the name is one of the members of :class:`.SqlaDialectName`.
f14655:m0
def rst_underline(heading: str, underline_char: str) -> str:
assert "<STR_LIT:\n>" not in heading<EOL>assert len(underline_char) == <NUM_LIT:1><EOL>return heading + "<STR_LIT:\n>" + (underline_char * len(heading))<EOL>
Underlines a heading for RST files. Args: heading: text to underline underline_char: character to use Returns: underlined heading, over two lines (without a final terminating newline)
f14657:m0
def write_if_allowed(filename: str,<EOL>content: str,<EOL>overwrite: bool = False,<EOL>mock: bool = False) -> None:
<EOL>if not overwrite and exists(filename):<EOL><INDENT>fail("<STR_LIT>".format(filename))<EOL><DEDENT>directory = dirname(filename)<EOL>if not mock:<EOL><INDENT>mkdir_p(directory)<EOL><DEDENT>log.info("<STR_LIT>", filename)<EOL>if mock:<EOL><INDENT>log.warning("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>with open(filename, "<STR_LIT>") as outfile:<EOL><INDENT>outfile.write(content)<EOL><DEDENT><DEDENT>
Writes the contents to a file, if permitted. Args: filename: filename to write content: contents to write overwrite: permit overwrites? mock: pretend to write, but don't Raises: RuntimeError: if file exists but overwriting not permitted
f14657:m2
def __init__(self,<EOL>source_filename: str,<EOL>project_root_dir: str,<EOL>target_rst_filename: str,<EOL>method: AutodocMethod = AutodocMethod.BEST,<EOL>python_package_root_dir: str = None,<EOL>source_rst_title_style_python: bool = True,<EOL>pygments_language_override: Dict[str, str] = None) -> None:
self.source_filename = abspath(expanduser(source_filename))<EOL>self.project_root_dir = abspath(expanduser(project_root_dir))<EOL>self.target_rst_filename = abspath(expanduser(target_rst_filename))<EOL>self.method = method<EOL>self.source_rst_title_style_python = source_rst_title_style_python<EOL>self.python_package_root_dir = (<EOL>abspath(expanduser(python_package_root_dir))<EOL>if python_package_root_dir else self.project_root_dir<EOL>)<EOL>self.pygments_language_override = pygments_language_override or {} <EOL>assert isfile(self.source_filename), (<EOL>"<STR_LIT>".format(self.source_filename))<EOL>assert isdir(self.project_root_dir), (<EOL>"<STR_LIT>".format(<EOL>self.project_root_dir))<EOL>assert relative_filename_within_dir(<EOL>filename=self.source_filename,<EOL>directory=self.project_root_dir<EOL>), (<EOL>"<STR_LIT>".format(<EOL>self.source_filename, self.project_root_dir)<EOL>)<EOL>assert relative_filename_within_dir(<EOL>filename=self.python_package_root_dir,<EOL>directory=self.project_root_dir<EOL>), (<EOL>"<STR_LIT>".format(<EOL>self.python_package_root_dir, self.project_root_dir)<EOL>)<EOL>assert isinstance(method, AutodocMethod)<EOL>
Args: source_filename: source file (e.g. Python, C++, XML file) to document project_root_dir: root directory of the whole project target_rst_filename: filenamd of an RST file to write that will document the source file method: instance of :class:`AutodocMethod`; for example, should we ask Sphinx's ``autodoc`` to read docstrings and build us a pretty page, or just include the contents with syntax highlighting? python_package_root_dir: if your Python modules live in a directory other than ``project_root_dir``, specify it here source_rst_title_style_python: if ``True`` and the file is a Python file and ``method == AutodocMethod.AUTOMODULE``, the heading used will be in the style of a Python module, ``x.y.z``. Otherwise, it will be a path (``x/y/z``). pygments_language_override: if specified, a dictionary mapping file extensions to Pygments languages (for example: a ``.pro`` file will be autodetected as Prolog, but you might want to map that to ``none`` for Qt project files).
f14657:c1:m0
@property<EOL><INDENT>def source_extension(self) -> str:<DEDENT>
return splitext(self.source_filename)[<NUM_LIT:1>]<EOL>
Returns the extension of the source filename.
f14657:c1:m2
@property<EOL><INDENT>def is_python(self) -> bool:<DEDENT>
return self.source_extension == EXT_PYTHON<EOL>
Is the source file a Python file?
f14657:c1:m3
@property<EOL><INDENT>def source_filename_rel_project_root(self) -> str:<DEDENT>
return relpath(self.source_filename, start=self.project_root_dir)<EOL>
Returns the name of the source filename, relative to the project root. Used to calculate file titles.
f14657:c1:m4