我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sqlalchemy.sql.func.now()。
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)
def notify(user, source_id, source_type, source_action, link, author): # check if there is already a notification from the same source (id, type) and action notif = Notification.query.filter_by(user=user).filter_by(source_id=source_id).\ filter_by(source_type=source_type).filter_by(source_action=source_action).first() if notif: # update the existing notification: notif.authors.append(author) notif.date = func.now() notif.seen = False else: # if not, a new notification is needed: notif = Notification(user=user, user_id=user.id, source_id=source_id, source_type=source_type, source_action=source_action, link=link, date=func.now(), seen=False) notif.authors.append(author) db.session.add(notif) db.session.commit() # anyway, send an email to the interested user cronmail.send_notif_message(notif)
def submit(content, groups, proposed, poster): law = Law(content=content, date=func.now()) db.session.add(law) db.session.flush() # set topic tpc = Topic.retrieve("law-" + str(law.id)) law.topic = tpc law.topic_id = tpc.id # set groups for group_name in groups: # new laws cannot be in the Base group if group_name != 'Base': group = LawGroup.query.filter_by(name=group_name).first() if group: # group must already exist law.group.append(group) # set the law status as proposed law.status.append(proposed) # subscribe the poster law.subscribed.append(poster) # finally return the law return law
def rename_table(self, 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. """ self.impl.rename_table( old_table_name, new_table_name, schema=schema )
def drop_index(self, name, table_name=None, schema=None): """Issue a "drop index" instruction using the current migration context. e.g.:: drop_index("accounts") :param 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. """ # need a dummy column name here since SQLAlchemy # 0.7.6 and further raises on Index with no columns self.impl.drop_index( self._index(name, table_name, ['x'], schema=schema) )
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)
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)
def create_index(self, name, table_name, columns, schema=None, **kw): """Issue a "create index" instruction using the current migration context. e.g.:: from alembic import op op.create_index('ik_test', 't1', ['foo', 'bar']) :param name: name of the index. :param table_name: name of the owning table. .. versionchanged:: 0.5.0 The ``tablename`` parameter is now named ``table_name``. As this is a positional argument, the old name is no longer present. :param columns: a list of string column names in the table. :param schema: Optional schema name to operate within. .. versionadded:: 0.4.0 """ self.impl.create_index( self._index(name, table_name, columns, schema=schema, **kw) )
def drop_index(self, name, table_name=None, schema=None): """Issue a "drop index" instruction using the current migration context. e.g.:: drop_index("accounts") :param name: name of the index. :param table_name: name of the owning table. Some backends such as Microsoft SQL Server require this. .. versionchanged:: 0.5.0 The ``tablename`` parameter is now named ``table_name``. The old name will continue to function for backwards compatibility. :param schema: Optional schema name to operate within. .. versionadded:: 0.4.0 """ # need a dummy column name here since SQLAlchemy # 0.7.6 and further raises on Index with no columns self.impl.drop_index( self._index(name, table_name, ['x'], schema=schema) )
def save_json(self, key, data): data = json.dumps(data) if self.key_exists(key): s = self.items.update().where(self.items.c.key == key).values( key=key, data=data, dt=func.now()) else: s = self.items.insert().values(key=key, data=data, dt=func.now()) s.execute()
def submit(content, poster, parent_id): post = Post(content=content, poster=poster, poster_id=poster.id, date=func.now()) if parent_id: post.parent_id = parent_id # gather mentions, topics, linked laws and proposal mentions = [] topic_names = [] for word in content.split(): if word.startswith('@'): mentions.append(word[1:]) elif word.startswith('#'): topic_names.append(word) # set the topics lnkd_laws, lnkd_prop = post.set_topics(topic_names) # add the post to the database db.session.add(post) post.last_edit_date = post.date post.subscribed.append(poster) db.session.commit() # notify a user only once notified = set() # do not notify the author of the post notified.add(poster) # notify parent(s) of the new comment if post.parent: notified = post.parent.notify_comment(poster, post.date, notified) # notify subscribers to law and proposals: notified = Law.notify_post(lnkd_laws, poster, notified) notified = Proposal.notify_post(lnkd_prop, poster, notified) # notify mentions post.notify_mentions(poster, mentions, notified) return post
def edit(self, content): self.content = content self.set_topics([word for word in content.split() if word.startswith('#')]) self.last_edit_date = func.now() db.session.commit()
def wipe(self): self.content = '--DELETED--' self.topics = [] self.last_edit_date = func.now() db.session.commit()
def __init__(self, user_id, event_time=datetime.now(), event_type=None, event_severity=None, event_duration=None, event_tracking_status_name='CREATED'): self.user_id = user_id self.event_time = event_time self.event_type = event_type self.event_severity = event_severity self.event_duration = event_duration self.event_tracking_status_name = event_tracking_status_name
def add_ebook(self, ebook, user, note=None, order=None): ebook_id = ebook.id if isinstance(ebook, Ebook) else ebook if not self.items.filter(BookshelfItem.ebook_id == ebook_id).all(): item = BookshelfItem(type='EBOOK', ebook_id=ebook_id, note=note, order=order,bookshelf=self, created_by=user, modified_by=user) app.db.session.add(item) self.modified = datetime.datetime.now()
def add_series(self, series, user, note=None, order=None): series_id = series.id if isinstance(series, Series) else series if not self.items.filter(BookshelfItem.series_id == series_id).all(): item = BookshelfItem(type='SERIES', series_id=series_id, note=note, order=order,bookshelf=self, created_by=user, modified_by=user) app.db.session.add(item) self.modified = datetime.datetime.now()
def drop_constraint(self, name, table_name, type_=None, schema=None): """Drop a constraint of the given name, typically via DROP CONSTRAINT. :param 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. """ t = self._table(table_name, schema=schema) types = { 'foreignkey': lambda name: sa_schema.ForeignKeyConstraint( [], [], name=name), 'primary': sa_schema.PrimaryKeyConstraint, 'unique': sa_schema.UniqueConstraint, 'check': lambda name: sa_schema.CheckConstraint("", name=name), None: sa_schema.Constraint } try: const = types[type_] except KeyError: raise TypeError("'type' can be one of %s" % ", ".join(sorted(repr(x) for x in types))) const = const(name=name) t.append_constraint(const) self.impl.drop_constraint(const)
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 = u":".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 ------------------------------------
def _deactivate_expired_organizations(self): orgs_to_deactivate = Organization.query\ .filter_by(active=True)\ .filter( and_( or_( Organization.paid_until == None, Organization.paid_until < func.now() ), func.timestampdiff( sqltext("SECOND"), Organization.created_at, func.now(), ) > (Organization.trial_days * constants.SECONDS_PER_DAY), ) ) for org in orgs_to_deactivate: manager_url = url_for( 'manager.manager_app', org_id=org.id, _external=True) + "#settings" # alert admins of deactivation for admin in org.admins: alert_email( admin, "[Action Required] %s scheduling is on hold" % org.name, "In order to continue scheduling, please set up billing at:<br><a href='%s'>%s</a>" % (manager_url, manager_url)) org.active = False current_app.logger.info( "Deactivated org %s because it is unpaid and the trial is over" % org.id) db.session.commit()
def _get_schedule_range(self, role): """ given a Role object, determines the start/stop of its next schedule return: (tuple) start, stop """ org = Organization.query.join(Location)\ .join(Role).filter(Role.id == role.id).first() default_tz = get_default_tz() local_tz = role.location.timezone_pytz last_schedule = Schedule2.query \ .filter_by(role_id=role.id) \ .order_by(desc(Schedule2.start)) \ .first() # schedule exists if last_schedule: start = default_tz.localize(last_schedule.stop) # need to create a start for the 1st schedule else: now = local_tz.localize(normalize_to_midnight(datetime.utcnow())) now_utc = now.astimezone(default_tz) week_start_index = constants.DAYS_OF_WEEK.index( org.day_week_starts) adjust_days = ( (6 - week_start_index + now.weekday()) % constants.WEEK_LENGTH) start = normalize_to_midnight( (now_utc - timedelta(days=adjust_days, hours=23) ).astimezone(local_tz)).astimezone(default_tz) stop = normalize_to_midnight((start + timedelta(days=constants.WEEK_LENGTH, hours=1)).astimezone(local_tz)) \ .astimezone(default_tz) return start, stop
def _enqueue_schedules_mobius(self): """ find and then queue all schedules that are due for mobius processing """ schedules_to_queue = Schedule2.query \ .join(Role) \ .join(Location) \ .join(Organization) \ .filter( Schedule2.state.in_(["initial", "unpublished"]), Organization.plan.in_(boss_plans), Organization.active, Role.archived == False, func.timestampdiff( sqltext("SECOND"), func.now(), Schedule2.start, ) < Organization.shifts_assigned_days_before_start * constants.SECONDS_PER_DAY, ).all() for s in schedules_to_queue: if s.state == "initial": s.transition_to_unpublished() s.transition_to_mobius_queue() return len(schedules_to_queue) # For monitoring
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
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)
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)