Python sqlalchemy.sql.func.now() Examples

The following are 30 code examples of sqlalchemy.sql.func.now(). 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.func , or try the search function .
Example #1
Source File: ops.py    From android_universal with MIT License 6 votes vote down vote up
def rename_table(
            cls, operations, old_table_name, new_table_name, schema=None):
        """Emit an ALTER TABLE to rename a table.

        :param old_table_name: old name.
        :param new_table_name: new name.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        """
        op = cls(old_table_name, new_table_name, schema=schema)
        return operations.invoke(op) 
Example #2
Source File: ops.py    From jbox with MIT License 6 votes vote down vote up
def rename_table(
            cls, operations, old_table_name, new_table_name, schema=None):
        """Emit an ALTER TABLE to rename a table.

        :param old_table_name: old name.
        :param new_table_name: new name.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        """
        op = cls(old_table_name, new_table_name, schema=schema)
        return operations.invoke(op) 
Example #3
Source File: ops.py    From alembic with MIT License 6 votes vote down vote up
def rename_table(
        cls, operations, old_table_name, new_table_name, schema=None
    ):
        """Emit an ALTER TABLE to rename a table.

        :param old_table_name: old name.
        :param new_table_name: new name.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        """
        op = cls(old_table_name, new_table_name, schema=schema)
        return operations.invoke(op) 
Example #4
Source File: pwnpass.py    From password_pwncheck with MIT License 5 votes vote down vote up
def verifyPasswordGood(self,user,password,ip=None,reserve=True,always_true=False):
        score = 0
        reasons = []
        token = self.tokendb.tokenizePassword(password)
        tokenhash = self.tokendb.hashToken(token) 

        for Test in self.Tests:
            (code,ctx) = Test.test(user,password,token)
            reasons.append(Test.report(code,ctx))
            score += code
        
        reasons = list(filter(lambda x: len(x),reasons))
        if score == 0:
            if reserve == True:
                self.tokendb.addToken(user,tokenhash,ip)
                reasons.append( "Password is valid and now reserved" )
                if self.debug:
                    print(" \- + Password is a valid entry and is now reserved")
            else:
                reasons.append( "Password is tested as valid" )
                if self.debug:
                    print(" \- + Password is tested as valid entry")
            retval = True
        else:
            if self.debug:
                print(" \- - Password is invalid and unacceptable")
            retval = False

        if always_true == True and retval == False:
            print(" \- - OVERRIDING invalid with Valid (yesman enabled)!!!")
            reasons.append( "Invalid Password Approved due to Yesman mode" )
            retval = True
        return (retval,score,'\n'.join(reasons)) 
Example #5
Source File: ops.py    From android_universal with MIT License 5 votes vote down vote up
def drop_index(cls, operations, index_name,
                   table_name=None, schema=None, **kw):
        r"""Issue a "drop index" instruction using the current
        migration context.

        e.g.::

            drop_index("accounts")

        :param index_name: name of the index.
        :param table_name: name of the owning table.  Some
         backends such as Microsoft SQL Server require this.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        :param \**kw: Additional keyword arguments not mentioned above are
            dialect specific, and passed in the form
            ``<dialectname>_<argname>``.
            See the documentation regarding an individual dialect at
            :ref:`dialect_toplevel` for detail on documented arguments.

            .. versionadded:: 0.9.5 Support for dialect-specific keyword
               arguments for DROP INDEX

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> index_name

        """
        op = cls(index_name, table_name=table_name, schema=schema, **kw)
        return operations.invoke(op) 
Example #6
Source File: ops.py    From android_universal with MIT License 5 votes vote down vote up
def drop_constraint(
            cls, operations, constraint_name, table_name,
            type_=None, schema=None):
        """Drop a constraint of the given name, typically via DROP CONSTRAINT.

        :param constraint_name: name of the constraint.
        :param table_name: table name.
        :param type_: optional, required on MySQL.  can be
         'foreignkey', 'primary', 'unique', or 'check'.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> constraint_name

        """

        op = cls(constraint_name, table_name, type_=type_, schema=schema)
        return operations.invoke(op) 
Example #7
Source File: views.py    From koschei with GNU General Public License v2.0 5 votes vote down vote up
def statistics():
    """
    Show global and per-package statistics about build times etc.
    Uses materialized views that are refreshed by backend's polling.
    """
    now = db.query(func.now()).scalar()
    scalar_stats = db.query(ScalarStats).one()
    resource_query = db.query(ResourceConsumptionStats)\
        .order_by(ResourceConsumptionStats.time.desc().nullslast())\
        .paginate(20)
    return render_template("stats.html", now=now, stats=scalar_stats,
                           packages=resource_query.items,
                           page=resource_query) 
Example #8
Source File: cache.py    From eeweather with Apache License 2.0 5 votes vote down vote up
def save_json(self, key, data):
        data = json.dumps(data, separators=(",", ":"))
        updated = func.now()
        try:
            s = self.items.insert().values(key=key, data=data, updated=updated)
            s.execute()
        except IntegrityError:
            s = (
                self.items.update()
                .where(self.items.c.key == key)
                .values(key=key, data=data, updated=updated)
            )
            s.execute() 
Example #9
Source File: dbrepository.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def init(self, auto_create=True):

        # TODO handle if user does not pass in table sqlite://path.db
        uri_splt = self.uri.split(":")
        engine_uri = ":".join(uri_splt[:-1])
        table_name = uri_splt[-1]

        metadata = MetaData()
        postref_table = Table(table_name, metadata,
                              Column('id', Integer, primary_key=True),
                              Column('created_at', DateTime, default=func.now()),
                              Column('updated_at', DateTime, default=func.now(), onupdate=func.current_timestamp()),
                              Column('uuid', String(512)),
                              Column('path', String(512)),
                              Column('revision', Integer, default=0),
                              Column('status', Integer, default=self.PostStatus.DRAFT.value),
                              Column('ref', String(512)),
                              Column('data', LargeBinary))
        self.engine = create_engine(engine_uri, pool_recycle=3600)
        self.session = scoped_session(sessionmaker(bind=self.engine))
        if auto_create:
            postref_table.create(self.engine, checkfirst=True)

        class PostRef(object):
            pass
        mapper(PostRef, postref_table)
        self.PostRef = PostRef

    # ------------- Repository actions / state ------------------------------------ 
Example #10
Source File: mixins.py    From zeus with Apache License 2.0 5 votes vote down vote up
def date_created(cls):
        return db.Column(
            db.TIMESTAMP(timezone=True),
            default=timezone.now,
            server_default=func.now(),
            nullable=False,
        )


# https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/PreFilteredQuery 
Example #11
Source File: check_music.py    From snippet with MIT License 5 votes vote down vote up
def set_url(self, id, url):
        ks = {"update_time": datetime.now(), "check": True, "url": url}
        self.get_session().query(self._model).filter_by(id=id).update(ks)
# DB End
############################################################################### 
Example #12
Source File: ops.py    From alembic with MIT License 5 votes vote down vote up
def drop_index(
        cls, operations, index_name, table_name=None, schema=None, **kw
    ):
        r"""Issue a "drop index" instruction using the current
        migration context.

        e.g.::

            drop_index("accounts")

        :param index_name: name of the index.
        :param table_name: name of the owning table.  Some
         backends such as Microsoft SQL Server require this.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        :param \**kw: Additional keyword arguments not mentioned above are
            dialect specific, and passed in the form
            ``<dialectname>_<argname>``.
            See the documentation regarding an individual dialect at
            :ref:`dialect_toplevel` for detail on documented arguments.

            .. versionadded:: 0.9.5 Support for dialect-specific keyword
               arguments for DROP INDEX

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> index_name

        """
        op = cls(index_name, table_name=table_name, schema=schema, **kw)
        return operations.invoke(op) 
Example #13
Source File: pwnpass.py    From password_pwncheck with MIT License 5 votes vote down vote up
def test(self,user,password,token):
        ### now test for bad token usage
        tokenhash = self.tokendb.hashToken(token) 
        if self.tokendb.checkToken(user,tokenhash):
            if self.debug:
                print(" \- - Password is in token library")
            return (10,None)
        else:
            if self.debug:
                print(" \- * Password is not in token library")
        return (0,None) 
Example #14
Source File: celery.py    From gitlab-tools with GNU General Public License v3.0 5 votes vote down vote up
def changed(cls):
        found = PeriodicTasks.query.filter_by(ident=1).first()
        if not found:
            found = PeriodicTasks()
        found.last_update = datetime.datetime.now()
        db.session.add(found) 
Example #15
Source File: ops.py    From jbox with MIT License 5 votes vote down vote up
def drop_constraint(
            cls, operations, constraint_name, table_name,
            type_=None, schema=None):
        """Drop a constraint of the given name, typically via DROP CONSTRAINT.

        :param constraint_name: name of the constraint.
        :param table_name: table name.
        :param type_: optional, required on MySQL.  can be
         'foreignkey', 'primary', 'unique', or 'check'.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> constraint_name

        """

        op = cls(constraint_name, table_name, type_=type_, schema=schema)
        return operations.invoke(op) 
Example #16
Source File: ops.py    From jbox with MIT License 5 votes vote down vote up
def drop_index(cls, operations, index_name, table_name=None, schema=None):
        """Issue a "drop index" instruction using the current
        migration context.

        e.g.::

            drop_index("accounts")

        :param index_name: name of the index.
        :param table_name: name of the owning table.  Some
         backends such as Microsoft SQL Server require this.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> index_name

        """
        op = cls(index_name, table_name=table_name, schema=schema)
        return operations.invoke(op) 
Example #17
Source File: ops.py    From alembic with MIT License 5 votes vote down vote up
def drop_constraint(
        cls, operations, constraint_name, table_name, type_=None, schema=None
    ):
        r"""Drop a constraint of the given name, typically via DROP CONSTRAINT.

        :param constraint_name: name of the constraint.
        :param table_name: table name.
        :param type\_: optional, required on MySQL.  can be
         'foreignkey', 'primary', 'unique', or 'check'.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> constraint_name

        """

        op = cls(constraint_name, table_name, type_=type_, schema=schema)
        return operations.invoke(op) 
Example #18
Source File: ops.py    From jbox with MIT License 4 votes vote down vote up
def create_check_constraint(
            cls, operations,
            constraint_name, table_name, condition,
            schema=None, **kw):
        """Issue a "create check constraint" instruction using the
        current migration context.

        e.g.::

            from alembic import op
            from sqlalchemy.sql import column, func

            op.create_check_constraint(
                "ck_user_name_len",
                "user",
                func.len(column('name')) > 5
            )

        CHECK constraints are usually against a SQL expression, so ad-hoc
        table metadata is usually needed.   The function will convert the given
        arguments into a :class:`sqlalchemy.schema.CheckConstraint` bound
        to an anonymous table in order to emit the CREATE statement.

        :param name: Name of the check constraint.  The name is necessary
         so that an ALTER statement can be emitted.  For setups that
         use an automated naming scheme such as that described at
         :ref:`sqla:constraint_naming_conventions`,
         ``name`` here can be ``None``, as the event listener will
         apply the name to the constraint object when it is associated
         with the table.
        :param table_name: String name of the source table.
        :param condition: SQL expression that's the condition of the
         constraint. Can be a string or SQLAlchemy expression language
         structure.
        :param deferrable: optional bool. If set, emit DEFERRABLE or
         NOT DEFERRABLE when issuing DDL for this constraint.
        :param initially: optional string. If set, emit INITIALLY <value>
         when issuing DDL for this constraint.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> constraint_name
           * source -> table_name

        """
        op = cls(constraint_name, table_name, condition, schema=schema, **kw)
        return operations.invoke(op) 
Example #19
Source File: ops.py    From android_universal with MIT License 4 votes vote down vote up
def drop_column(
            cls, operations, table_name, column_name, schema=None, **kw):
        """Issue a "drop column" instruction using the current
        migration context.

        e.g.::

            drop_column('organization', 'account_id')

        :param table_name: name of table
        :param column_name: name of column
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        :param mssql_drop_check: Optional boolean.  When ``True``, on
         Microsoft SQL Server only, first
         drop the CHECK constraint on the column using a
         SQL-script-compatible
         block that selects into a @variable from sys.check_constraints,
         then exec's a separate DROP CONSTRAINT for that constraint.
        :param mssql_drop_default: Optional boolean.  When ``True``, on
         Microsoft SQL Server only, first
         drop the DEFAULT constraint on the column using a
         SQL-script-compatible
         block that selects into a @variable from sys.default_constraints,
         then exec's a separate DROP CONSTRAINT for that default.
        :param mssql_drop_foreign_key: Optional boolean.  When ``True``, on
         Microsoft SQL Server only, first
         drop a single FOREIGN KEY constraint on the column using a
         SQL-script-compatible
         block that selects into a @variable from
         sys.foreign_keys/sys.foreign_key_columns,
         then exec's a separate DROP CONSTRAINT for that default.  Only
         works if the column has exactly one FK constraint which refers to
         it, at the moment.

         .. versionadded:: 0.6.2

        """

        op = cls(table_name, column_name, schema=schema, **kw)
        return operations.invoke(op) 
Example #20
Source File: ops.py    From android_universal with MIT License 4 votes vote down vote up
def add_column(cls, operations, table_name, column, schema=None):
        """Issue an "add column" instruction using the current
        migration context.

        e.g.::

            from alembic import op
            from sqlalchemy import Column, String

            op.add_column('organization',
                Column('name', String())
            )

        The provided :class:`~sqlalchemy.schema.Column` object can also
        specify a :class:`~sqlalchemy.schema.ForeignKey`, referencing
        a remote table name.  Alembic will automatically generate a stub
        "referenced" table and emit a second ALTER statement in order
        to add the constraint separately::

            from alembic import op
            from sqlalchemy import Column, INTEGER, ForeignKey

            op.add_column('organization',
                Column('account_id', INTEGER, ForeignKey('accounts.id'))
            )

        Note that this statement uses the :class:`~sqlalchemy.schema.Column`
        construct as is from the SQLAlchemy library.  In particular,
        default values to be created on the database side are
        specified using the ``server_default`` parameter, and not
        ``default`` which only specifies Python-side defaults::

            from alembic import op
            from sqlalchemy import Column, TIMESTAMP, func

            # specify "DEFAULT NOW" along with the column add
            op.add_column('account',
                Column('timestamp', TIMESTAMP, server_default=func.now())
            )

        :param table_name: String name of the parent table.
        :param column: a :class:`sqlalchemy.schema.Column` object
         representing the new column.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.


        """

        op = cls(table_name, column, schema=schema)
        return operations.invoke(op) 
Example #21
Source File: ops.py    From android_universal with MIT License 4 votes vote down vote up
def create_check_constraint(
            cls, operations,
            constraint_name, table_name, condition,
            schema=None, **kw):
        """Issue a "create check constraint" instruction using the
        current migration context.

        e.g.::

            from alembic import op
            from sqlalchemy.sql import column, func

            op.create_check_constraint(
                "ck_user_name_len",
                "user",
                func.len(column('name')) > 5
            )

        CHECK constraints are usually against a SQL expression, so ad-hoc
        table metadata is usually needed.   The function will convert the given
        arguments into a :class:`sqlalchemy.schema.CheckConstraint` bound
        to an anonymous table in order to emit the CREATE statement.

        :param name: Name of the check constraint.  The name is necessary
         so that an ALTER statement can be emitted.  For setups that
         use an automated naming scheme such as that described at
         :ref:`sqla:constraint_naming_conventions`,
         ``name`` here can be ``None``, as the event listener will
         apply the name to the constraint object when it is associated
         with the table.
        :param table_name: String name of the source table.
        :param condition: SQL expression that's the condition of the
         constraint. Can be a string or SQLAlchemy expression language
         structure.
        :param deferrable: optional bool. If set, emit DEFERRABLE or
         NOT DEFERRABLE when issuing DDL for this constraint.
        :param initially: optional string. If set, emit INITIALLY <value>
         when issuing DDL for this constraint.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> constraint_name
           * source -> table_name

        """
        op = cls(constraint_name, table_name, condition, schema=schema, **kw)
        return operations.invoke(op) 
Example #22
Source File: ops.py    From android_universal with MIT License 4 votes vote down vote up
def create_unique_constraint(
            cls, operations, constraint_name, table_name, columns,
            schema=None, **kw):
        """Issue a "create unique constraint" instruction using the
        current migration context.

        e.g.::

            from alembic import op
            op.create_unique_constraint("uq_user_name", "user", ["name"])

        This internally generates a :class:`~sqlalchemy.schema.Table` object
        containing the necessary columns, then generates a new
        :class:`~sqlalchemy.schema.UniqueConstraint`
        object which it then associates with the
        :class:`~sqlalchemy.schema.Table`.
        Any event listeners associated with this action will be fired
        off normally.   The :class:`~sqlalchemy.schema.AddConstraint`
        construct is ultimately used to generate the ALTER statement.

        :param name: Name of the unique constraint.  The name is necessary
         so that an ALTER statement can be emitted.  For setups that
         use an automated naming scheme such as that described at
         :ref:`sqla:constraint_naming_conventions`,
         ``name`` here can be ``None``, as the event listener will
         apply the name to the constraint object when it is associated
         with the table.
        :param table_name: String name of the source table.
        :param columns: a list of string column names in the
         source table.
        :param deferrable: optional bool. If set, emit DEFERRABLE or
         NOT DEFERRABLE when issuing DDL for this constraint.
        :param initially: optional string. If set, emit INITIALLY <value>
         when issuing DDL for this constraint.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> constraint_name
           * source -> table_name
           * local_cols -> columns

        """

        op = cls(
            constraint_name, table_name, columns,
            schema=schema, **kw
        )
        return operations.invoke(op) 
Example #23
Source File: ops.py    From android_universal with MIT License 4 votes vote down vote up
def create_primary_key(
            cls, operations,
            constraint_name, table_name, columns, schema=None):
        """Issue a "create primary key" instruction using the current
        migration context.

        e.g.::

            from alembic import op
            op.create_primary_key(
                        "pk_my_table", "my_table",
                        ["id", "version"]
                    )

        This internally generates a :class:`~sqlalchemy.schema.Table` object
        containing the necessary columns, then generates a new
        :class:`~sqlalchemy.schema.PrimaryKeyConstraint`
        object which it then associates with the
        :class:`~sqlalchemy.schema.Table`.
        Any event listeners associated with this action will be fired
        off normally.   The :class:`~sqlalchemy.schema.AddConstraint`
        construct is ultimately used to generate the ALTER statement.

        :param name: Name of the primary key constraint.  The name is necessary
         so that an ALTER statement can be emitted.  For setups that
         use an automated naming scheme such as that described at
         :ref:`sqla:constraint_naming_conventions`
         ``name`` here can be ``None``, as the event listener will
         apply the name to the constraint object when it is associated
         with the table.
        :param table_name: String name of the target table.
        :param columns: a list of string column names to be applied to the
         primary key constraint.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> constraint_name
           * cols -> columns

        """
        op = cls(constraint_name, table_name, columns, schema)
        return operations.invoke(op) 
Example #24
Source File: ops.py    From jbox with MIT License 4 votes vote down vote up
def create_primary_key(
            cls, operations,
            constraint_name, table_name, columns, schema=None):
        """Issue a "create primary key" instruction using the current
        migration context.

        e.g.::

            from alembic import op
            op.create_primary_key(
                        "pk_my_table", "my_table",
                        ["id", "version"]
                    )

        This internally generates a :class:`~sqlalchemy.schema.Table` object
        containing the necessary columns, then generates a new
        :class:`~sqlalchemy.schema.PrimaryKeyConstraint`
        object which it then associates with the
        :class:`~sqlalchemy.schema.Table`.
        Any event listeners associated with this action will be fired
        off normally.   The :class:`~sqlalchemy.schema.AddConstraint`
        construct is ultimately used to generate the ALTER statement.

        :param name: Name of the primary key constraint.  The name is necessary
         so that an ALTER statement can be emitted.  For setups that
         use an automated naming scheme such as that described at
         :ref:`sqla:constraint_naming_conventions`
         ``name`` here can be ``None``, as the event listener will
         apply the name to the constraint object when it is associated
         with the table.
        :param table_name: String name of the target table.
        :param columns: a list of string column names to be applied to the
         primary key constraint.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> constraint_name
           * cols -> columns

        """
        op = cls(constraint_name, table_name, columns, schema)
        return operations.invoke(op) 
Example #25
Source File: ops.py    From jbox with MIT License 4 votes vote down vote up
def create_unique_constraint(
            cls, operations, constraint_name, table_name, columns,
            schema=None, **kw):
        """Issue a "create unique constraint" instruction using the
        current migration context.

        e.g.::

            from alembic import op
            op.create_unique_constraint("uq_user_name", "user", ["name"])

        This internally generates a :class:`~sqlalchemy.schema.Table` object
        containing the necessary columns, then generates a new
        :class:`~sqlalchemy.schema.UniqueConstraint`
        object which it then associates with the
        :class:`~sqlalchemy.schema.Table`.
        Any event listeners associated with this action will be fired
        off normally.   The :class:`~sqlalchemy.schema.AddConstraint`
        construct is ultimately used to generate the ALTER statement.

        :param name: Name of the unique constraint.  The name is necessary
         so that an ALTER statement can be emitted.  For setups that
         use an automated naming scheme such as that described at
         :ref:`sqla:constraint_naming_conventions`,
         ``name`` here can be ``None``, as the event listener will
         apply the name to the constraint object when it is associated
         with the table.
        :param table_name: String name of the source table.
        :param columns: a list of string column names in the
         source table.
        :param deferrable: optional bool. If set, emit DEFERRABLE or
         NOT DEFERRABLE when issuing DDL for this constraint.
        :param initially: optional string. If set, emit INITIALLY <value>
         when issuing DDL for this constraint.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        .. versionchanged:: 0.8.0 The following positional argument names
           have been changed:

           * name -> constraint_name
           * source -> table_name
           * local_cols -> columns

        """

        op = cls(
            constraint_name, table_name, columns,
            schema=schema, **kw
        )
        return operations.invoke(op) 
Example #26
Source File: ops.py    From jbox with MIT License 4 votes vote down vote up
def add_column(cls, operations, table_name, column, schema=None):
        """Issue an "add column" instruction using the current
        migration context.

        e.g.::

            from alembic import op
            from sqlalchemy import Column, String

            op.add_column('organization',
                Column('name', String())
            )

        The provided :class:`~sqlalchemy.schema.Column` object can also
        specify a :class:`~sqlalchemy.schema.ForeignKey`, referencing
        a remote table name.  Alembic will automatically generate a stub
        "referenced" table and emit a second ALTER statement in order
        to add the constraint separately::

            from alembic import op
            from sqlalchemy import Column, INTEGER, ForeignKey

            op.add_column('organization',
                Column('account_id', INTEGER, ForeignKey('accounts.id'))
            )

        Note that this statement uses the :class:`~sqlalchemy.schema.Column`
        construct as is from the SQLAlchemy library.  In particular,
        default values to be created on the database side are
        specified using the ``server_default`` parameter, and not
        ``default`` which only specifies Python-side defaults::

            from alembic import op
            from sqlalchemy import Column, TIMESTAMP, func

            # specify "DEFAULT NOW" along with the column add
            op.add_column('account',
                Column('timestamp', TIMESTAMP, server_default=func.now())
            )

        :param table_name: String name of the parent table.
        :param column: a :class:`sqlalchemy.schema.Column` object
         representing the new column.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.


        """

        op = cls(table_name, column, schema=schema)
        return operations.invoke(op) 
Example #27
Source File: ops.py    From alembic with MIT License 4 votes vote down vote up
def drop_column(
        cls, operations, table_name, column_name, schema=None, **kw
    ):
        """Issue a "drop column" instruction using the current
        migration context.

        e.g.::

            drop_column('organization', 'account_id')

        :param table_name: name of table
        :param column_name: name of column
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        :param mssql_drop_check: Optional boolean.  When ``True``, on
         Microsoft SQL Server only, first
         drop the CHECK constraint on the column using a
         SQL-script-compatible
         block that selects into a @variable from sys.check_constraints,
         then exec's a separate DROP CONSTRAINT for that constraint.
        :param mssql_drop_default: Optional boolean.  When ``True``, on
         Microsoft SQL Server only, first
         drop the DEFAULT constraint on the column using a
         SQL-script-compatible
         block that selects into a @variable from sys.default_constraints,
         then exec's a separate DROP CONSTRAINT for that default.
        :param mssql_drop_foreign_key: Optional boolean.  When ``True``, on
         Microsoft SQL Server only, first
         drop a single FOREIGN KEY constraint on the column using a
         SQL-script-compatible
         block that selects into a @variable from
         sys.foreign_keys/sys.foreign_key_columns,
         then exec's a separate DROP CONSTRAINT for that default.  Only
         works if the column has exactly one FK constraint which refers to
         it, at the moment.

         .. versionadded:: 0.6.2

        """

        op = cls(table_name, column_name, schema=schema, **kw)
        return operations.invoke(op) 
Example #28
Source File: ops.py    From alembic with MIT License 4 votes vote down vote up
def add_column(cls, operations, table_name, column, schema=None):
        """Issue an "add column" instruction using the current
        migration context.

        e.g.::

            from alembic import op
            from sqlalchemy import Column, String

            op.add_column('organization',
                Column('name', String())
            )

        The provided :class:`~sqlalchemy.schema.Column` object can also
        specify a :class:`~sqlalchemy.schema.ForeignKey`, referencing
        a remote table name.  Alembic will automatically generate a stub
        "referenced" table and emit a second ALTER statement in order
        to add the constraint separately::

            from alembic import op
            from sqlalchemy import Column, INTEGER, ForeignKey

            op.add_column('organization',
                Column('account_id', INTEGER, ForeignKey('accounts.id'))
            )

        Note that this statement uses the :class:`~sqlalchemy.schema.Column`
        construct as is from the SQLAlchemy library.  In particular,
        default values to be created on the database side are
        specified using the ``server_default`` parameter, and not
        ``default`` which only specifies Python-side defaults::

            from alembic import op
            from sqlalchemy import Column, TIMESTAMP, func

            # specify "DEFAULT NOW" along with the column add
            op.add_column('account',
                Column('timestamp', TIMESTAMP, server_default=func.now())
            )

        :param table_name: String name of the parent table.
        :param column: a :class:`sqlalchemy.schema.Column` object
         representing the new column.
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.


        """

        op = cls(table_name, column, schema=schema)
        return operations.invoke(op) 
Example #29
Source File: ops.py    From jbox with MIT License 4 votes vote down vote up
def drop_column(
            cls, operations, table_name, column_name, schema=None, **kw):
        """Issue a "drop column" instruction using the current
        migration context.

        e.g.::

            drop_column('organization', 'account_id')

        :param table_name: name of table
        :param column_name: name of column
        :param schema: Optional schema name to operate within.  To control
         quoting of the schema outside of the default behavior, use
         the SQLAlchemy construct
         :class:`~sqlalchemy.sql.elements.quoted_name`.

         .. versionadded:: 0.7.0 'schema' can now accept a
            :class:`~sqlalchemy.sql.elements.quoted_name` construct.

        :param mssql_drop_check: Optional boolean.  When ``True``, on
         Microsoft SQL Server only, first
         drop the CHECK constraint on the column using a
         SQL-script-compatible
         block that selects into a @variable from sys.check_constraints,
         then exec's a separate DROP CONSTRAINT for that constraint.
        :param mssql_drop_default: Optional boolean.  When ``True``, on
         Microsoft SQL Server only, first
         drop the DEFAULT constraint on the column using a
         SQL-script-compatible
         block that selects into a @variable from sys.default_constraints,
         then exec's a separate DROP CONSTRAINT for that default.
        :param mssql_drop_foreign_key: Optional boolean.  When ``True``, on
         Microsoft SQL Server only, first
         drop a single FOREIGN KEY constraint on the column using a
         SQL-script-compatible
         block that selects into a @variable from
         sys.foreign_keys/sys.foreign_key_columns,
         then exec's a separate DROP CONSTRAINT for that default.  Only
         works if the column has exactly one FK constraint which refers to
         it, at the moment.

         .. versionadded:: 0.6.2

        """

        op = cls(table_name, column_name, schema=schema, **kw)
        return operations.invoke(op) 
Example #30
Source File: notification.py    From verejne.digital with Apache License 2.0 4 votes vote down vote up
def GenerateNotifications():
    global ico_lat_lng
    ico_lat_lng = utils.IcoToLatLngMap()

    with Session() as session:

        # Get the highest id that has been already processed
        last_update = session.query(LastNotificationUpdate).first()
        min_id = last_update.last_id if last_update is not None else 0
        print "Last processed id", min_id
 
        # compute id's of companies with <= max_won already won
        cnts = session.query(func.count(Obstaravanie.winner_id), Obstaravanie.winner_id).\
                group_by(Obstaravanie.winner_id)
        eligible_companies = set()
        for cnt, company_id in cnts:
            if (cnt <= max_won): eligible_companies.add(company_id)

        # keep track of already generated candidates, so that a notification is not
        # generated twice
        generated_notifications = set(e[0] for e in session.query(Notification.candidate_id).all())

        gens = 0
        max_id = None
        for obst in session.query(Obstaravanie).\
                            filter(Obstaravanie.id >= min_id).\
                            order_by(-Obstaravanie.id).limit(1000):
            if (max_id is None): max_id = obst.id
            if (obst.winner_id is not None): continue
            if (obst.finished): continue
            good_candidates = 0
            for candidate in obst.candidates:
                if (IsGoodCandidate(obst, candidate)):
                    good_candidates += 1
                    if (good_candidates > max_good_candidates_per_obst): break
                    # Process only candidates, for which we know the address
                    if utils.getAddressForIco(candidate.company.ico) == "": continue
                    if ((candidate.company_id in eligible_companies) and
                        not (candidate.id in generated_notifications) and
                        (candidate.reason.customer.ico != obst.customer.ico)):
                        notification = Notification(
                            candidate_id=candidate.id,
                            status=NotificationStatus.GENERATED,
                            date_generated=func.now(),
                            date_modified=func.now())
                        gens += 1
                        session.add(notification)
        print "Generated #notifications:", gens

        # Update the highest synced obstaravanie.id
        session.query(LastNotificationUpdate).delete(synchronize_session=False)
        last_update = LastNotificationUpdate(last_id=max_id)
        session.add(last_update)

        session.commit()
        session.close()