Python sqlalchemy.sql.exists() Examples

The following are 11 code examples of sqlalchemy.sql.exists(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.sql , or try the search function .
Example #1
Source File: serialized_dag.py    From airflow with Apache License 2.0 7 votes vote down vote up
def write_dag(cls, dag: DAG, min_update_interval: Optional[int] = None, session=None):
        """Serializes a DAG and writes it into database.

        :param dag: a DAG to be written into database
        :param min_update_interval: minimal interval in seconds to update serialized DAG
        :param session: ORM Session
        """
        # Checks if (Current Time - Time when the DAG was written to DB) < min_update_interval
        # If Yes, does nothing
        # If No or the DAG does not exists, updates / writes Serialized DAG to DB
        if min_update_interval is not None:
            if session.query(exists().where(
                and_(cls.dag_id == dag.dag_id,
                     (timezone.utcnow() - timedelta(seconds=min_update_interval)) < cls.last_updated))
            ).scalar():
                return
        log.debug("Writing DAG: %s to the DB", dag.dag_id)
        session.merge(cls(dag))
        log.debug("DAG: %s written to the DB", dag.dag_id) 
Example #2
Source File: debug.py    From dokomoforms with GNU General Public License v3.0 6 votes vote down vote up
def get(self, email='test@test_email.com'):
        """Log in for any user (creating one if necessary)."""
        email_exists = (
            self.session
            .query(exists().where(Email.address == email))
            .scalar()
        )
        created = False
        if not email_exists:
            with self.session.begin():
                creator = Administrator(
                    name='debug_user',
                    emails=[Email(address=email)],
                )
                self.session.add(creator)
            self.set_status(201)
            created = True
        DebugLoginHandler.get(self, email, created=created) 
Example #3
Source File: verbs.py    From siuba with MIT License 6 votes vote down vote up
def _anti_join(left, right = None, on = None, *args, sql_on = None):
    _raise_if_args(args)

    left_sel = left.last_op.alias()
    right_sel = right.last_op.alias()

    # handle arguments ----
    on  = _validate_join_arg_on(on, sql_on)
    
    # create join conditions ----
    bool_clause = _create_join_conds(left_sel, right_sel, on)

    # create inner join ----
    not_exists = ~sql.exists([1], from_obj = right_sel).where(bool_clause)
    sel = sql.select(left_sel.columns, from_obj = left_sel).where(not_exists)
    return left.append_op(sel) 
Example #4
Source File: RawEngine.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_dir_ignoring_files(fqpath, dir_suffix = "_d"):

	dirPath, fName = os.path.split(fqpath)

	full_split = splitall(dirPath)

	root_segment = full_split[:len(RESOURCE_SPLIT)]

	for x in range(len(RESOURCE_SPLIT), len(full_split)):

		inc_path = os.path.join(*(root_segment + [full_split[x], ]))
		if os.path.exists(inc_path) and os.path.isdir(inc_path):
			root_segment.append(full_split[x])
		elif os.path.exists(inc_path) and os.path.isfile(inc_path):
			root_segment.append(full_split[x] + dir_suffix)
		else:
			# This could probably short-circuit since the first non
			# existent item means the rest of the path is safe, but w/e
			root_segment.append(full_split[x])


	dirPath = os.path.join(*root_segment)
	os.makedirs(dirPath, exist_ok=True)

	fqpath = os.path.join(dirPath, fName)

	return fqpath 
Example #5
Source File: RawEngine.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def checkHaveHistory(self, sess, url):
		# Only do version fiddling if versioning is enabled.
		if not settings.DO_VERSIONING:
			return 99

		ctbl = version_table(self.db.RawWebPages.__table__)
		query = sess.query(exists().where(ctbl.c.url == url))
		return query.scalar() 
Example #6
Source File: bgp_dragent_scheduler.py    From neutron-dynamic-routing with Apache License 2.0 5 votes vote down vote up
def _get_unscheduled_bgp_speakers(self, context):
        """BGP speakers that needs to be scheduled.
        """

        no_agent_binding = ~sql.exists().where(
            bgp_db.BgpSpeaker.id ==
            bgp_dras_db.BgpSpeakerDrAgentBinding.bgp_speaker_id)
        query = context.session.query(bgp_db.BgpSpeaker.id).filter(
            no_agent_binding)
        return [bgp_speaker_id_[0] for bgp_speaker_id_ in query] 
Example #7
Source File: serialized_dag.py    From airflow with Apache License 2.0 5 votes vote down vote up
def has_dag(cls, dag_id: str, session=None) -> bool:
        """Checks a DAG exist in serialized_dag table.

        :param dag_id: the DAG to check
        :param session: ORM Session
        """
        return session.query(exists().where(cls.dag_id == dag_id)).scalar() 
Example #8
Source File: views.py    From koschei with GNU General Public License v2.0 5 votes vote down vote up
def can_edit_group(group):
    """
    Whether the group is editable by the current user.

    Available as `editable` property of PackageGroup.
    """
    # TODO move to model_additions where it belongs
    return g.user and (g.user.admin or
                       db.query(exists()
                                .where((GroupACL.user_id == g.user.id) &
                                       (GroupACL.group_id == group.id)))
                       .scalar()) 
Example #9
Source File: verbs.py    From siuba with MIT License 5 votes vote down vote up
def _semi_join(left, right = None, on = None, *args, sql_on = None):
    _raise_if_args(args)

    left_sel = left.last_op.alias()
    right_sel = right.last_op.alias()

    # handle arguments ----
    on  = _validate_join_arg_on(on, sql_on)
    
    # create join conditions ----
    bool_clause = _create_join_conds(left_sel, right_sel, on)

    # create inner join ----
    exists_clause = sql.select(
            [sql.literal(1)],
            from_obj = right_sel,
            whereclause = bool_clause
            )

    # only keep left hand select's columns ----
    sel = sql.select(
            left_sel.columns,
            from_obj = left_sel,
            whereclause = sql.exists(exists_clause)
            )

    return left.append_op(sel) 
Example #10
Source File: test_cte.py    From sqlalchemy with MIT License 4 votes vote down vote up
def test_upsert_from_select(self):
        orders = table(
            "orders",
            column("region"),
            column("amount"),
            column("product"),
            column("quantity"),
        )

        upsert = (
            orders.update()
            .where(orders.c.region == "Region1")
            .values(amount=1.0, product="Product1", quantity=1)
            .returning(*(orders.c._all_columns))
            .cte("upsert")
        )

        insert = orders.insert().from_select(
            orders.c.keys(),
            select(
                [
                    literal("Region1"),
                    literal(1.0),
                    literal("Product1"),
                    literal(1),
                ]
            ).where(~exists(upsert.select())),
        )

        self.assert_compile(
            insert,
            "WITH upsert AS (UPDATE orders SET amount=:amount, "
            "product=:product, quantity=:quantity "
            "WHERE orders.region = :region_1 "
            "RETURNING orders.region, orders.amount, "
            "orders.product, orders.quantity) "
            "INSERT INTO orders (region, amount, product, quantity) "
            "SELECT :param_1 AS anon_1, :param_2 AS anon_2, "
            ":param_3 AS anon_3, :param_4 AS anon_4 WHERE NOT (EXISTS "
            "(SELECT upsert.region, upsert.amount, upsert.product, "
            "upsert.quantity FROM upsert))",
        )

        eq_(insert.compile().isinsert, True) 
Example #11
Source File: views.py    From koschei with GNU General Public License v2.0 4 votes vote down vote up
def process_group_form(group=None):
    """
    Validate and process submitted group form.
    :param group:
    :return:
    """
    if request.method == 'GET':
        # construct new form
        if group:
            # edit form
            obj = dict(name=group.name, owners=[u.name for u in group.owners],
                       packages=[p.name for p in group.packages])
            form = forms.GroupForm(**obj)
        else:
            # creation form
            form = forms.GroupForm(owners=[g.user.name])
        return render_template('edit-group.html', group=group, form=form)
    form = forms.GroupForm()
    # check permissions
    if group and not group.editable:
        flash_nak("You don't have permission to edit this group")
        return redirect(url_for('group_detail', name=group.name,
                                namespace=group.namespace))
    # check form validity
    if not form.validate_or_flash():
        return render_template('edit-group.html', group=group, form=form)

    # existing group being edited or None - to be sent into template
    existing_group = group

    if not group:
        group = PackageGroup(namespace=g.user.name)
        db.add(group)
    group.name = form.name.data
    try:
        db.flush()
    except IntegrityError:
        db.rollback()
        flash_nak("Group already exists")
        return render_template('edit-group.html', group=existing_group, form=form)
    try:
        data.set_group_content(session, group, form.packages.data)
        data.set_group_maintainers(session, group, form.owners.data)
    except data.PackagesDontExist as e:
        db.rollback()
        flash_nak(str(e))
        return render_template('edit-group.html', group=existing_group, form=form)
    db.commit()
    flash_ack("Group created" if not existing_group else "Group modified")
    return redirect(url_for('group_detail', name=group.name,
                            namespace=group.namespace))