sqlalchemy.text

Here are the examples of the python api sqlalchemy.text taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

160 Examples 7

Example 1

Project: asyncpgsa Source File: test_pool.py
async def test_use_sqlalchemy_with_escaped_params(pool):
    """
    Use sqlalchemy with escaped params
    Make sure that the escaped parameters get used in the right order
    :return:
    """
    query = sa.select('*') \
        .select_from(sa.text('sqrt(:num) as a')) \
        .select_from(sa.text('sqrt(:a2) as b')) \
        .select_from(sa.text('sqrt(:z3) as c')) \
        .params(num=16, a2=36, z3=25)
    async with pool.transaction() as conn:
        result = await conn.fetch(query)

    row = next(result)
    assert row.a == 4.0
    assert row.b == 6.0
    assert row.c == 5.0

Example 2

Project: kokoropy Source File: impl.py
Function: exec
    def _exec(self, construct, execution_options=None,
                            multiparams=(),
                            params=util.immutabledict()):
        if isinstance(construct, string_types):
            construct = text(construct)
        if self.as_sql:
            if multiparams or params:
                # TODO: coverage
                raise Exception("Execution arguments not allowed with as_sql")
            self.static_output(text_type(
                    construct.compile(dialect=self.dialect)
                    ).replace("\t", "    ").strip() + self.command_terminator)
        else:
            conn = self.connection
            if execution_options:
                conn = conn.execution_options(**execution_options)
            conn.execute(construct, *multiparams, **params)

Example 3

Project: alembic Source File: test_postgresql.py
    def test_compare_float_no_diff1(self):
        self._compare_default_roundtrip(
            Float(),
            text("5.2"), "5.2",
            diff_expected=False
        )

Example 4

Project: sqlalchemy Source File: test_update_delete.py
    def test_update_with_bindparams(self):
        User = self.classes.User

        sess = Session()

        john, jack, jill, jane = sess.query(User).order_by(User.id).all()

        sess.query(User).filter(text('age_int > :x')).params(x=29).\
            update({'age': User.age - 10}, synchronize_session='fetch')

        eq_([john.age, jack.age, jill.age, jane.age], [25, 37, 29, 27])
        eq_(sess.query(User.age).order_by(
            User.id).all(), list(zip([25, 37, 29, 27])))

Example 5

Project: alembic Source File: test_postgresql.py
    def test_compare_float_no_diff6(self):
        self._compare_default_roundtrip(
            Float(),
            "5", text("5.0"),
            diff_expected=False
        )

Example 6

Project: alembic Source File: test_mysql.py
Function: compare_default_roundtrip
    def _compare_default_roundtrip(self, type_, txt, alternate=None):
        if alternate:
            expected = True
        else:
            alternate = txt
            expected = False
        t = Table(
            "test", self.metadata,
            Column(
                "somecol", type_,
                server_default=text(txt) if txt else None
            )
        )
        t2 = Table("test", MetaData(),
                   Column("somecol", type_, server_default=text(alternate))
                   )
        assert self._compare_default(
            t, t2, t2.c.somecol, alternate
        ) is expected

Example 7

Project: sozlukcrawler Source File: yillara_gore_girdi.py
    def get_distinct_years(self):
        log.debug('Getting distinct years')
        sql = text("SELECT DISTINCT(YEAR(datetime)) FROM girdiler WHERE source=:s AND baslik_id=:b GROUP BY datetime")

        result = session.execute(sql, params=dict(s=self.source, b=self.baslik_id)).fetchall()

        # Convert the result into ints
        return map(lambda x: int(x[0]), result)

Example 8

Project: pybossa Source File: default.py
def delete_materialized_views():
    """Delete materialized views."""
    sql = text('''SELECT relname
               FROM pg_class WHERE relname LIKE '%dashboard%';''')
    results = db.session.execute(sql)
    for row in results:
        sql = 'drop materialized view if exists %s' % row.relname
        db.session.execute(sql)
        db.session.commit()

Example 9

Project: DataGristle Source File: metadata.py
Function: get_instance_id
    def get_instance_id(self, schema_id, instance_name='default'):
        """Get instance_id if one exists, ir not doesn't exist then create it.
           Return final instance_id.

           Note that this code assumes that only a single instance exists for
           a given schema.   This is only going to be true for the short-term.
        """
        sql = """ SELECT instance_id               \
                  FROM instance                    \
                  WHERE schema_id  = :schema_id    \
              """
        select_sql = text(sql)
        result = self.engine.execute(select_sql, schema_id=schema_id)
        rows   = result.fetchall()
        try:
            return rows[0].instance_id
        except IndexError:  # No rows found
            return self.setter(schema_id=schema_id,
                                         instance_name=instance_name)

Example 10

Project: sqlalchemy-redshift Source File: dialect.py
    @reflection.cache
    def get_view_definition(self, connection, view_name, schema=None, **kw):
        """Return view definition.
        Given a :class:`.Connection`, a string `view_name`,
        and an optional string `schema`, return the view definition.

        Overrides interface
        :meth:`~sqlalchemy.engine.interfaces.Dialect.get_view_definition`.
        """
        view = self._get_redshift_relation(connection, view_name, schema, **kw)
        return sa.text(view.view_definition)

Example 11

Project: sqlalchemy Source File: test_deprecations.py
    def test_select_whereclause(self):
        """Query.select_whereclause(whereclause=None, params=None, **kwargs)


        users = session,query(User).select_whereclause(users.c.name=='ed')
        users = session.query(User).select_whereclause("name='ed'")

        """

        User = self.classes.User

        session = create_session()

        users = session.query(User).filter(User.name=='ed').all()
        assert len(users) == 1 and users[0].name == 'ed'

        users = session.query(User).filter(text("name='ed'")).all()
        assert len(users) == 1 and users[0].name == 'ed'

Example 12

Project: alembic Source File: test_postgresql.py
    def test_compare_character_text_diff(self):
        self._compare_default_roundtrip(
            String(),
            text("'hello'"),
            text("'there'")
        )

Example 13

Project: viaduct Source File: 2263218a4ee_seo_table.py
def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('custom_form', 'price',
               existing_type=mysql.FLOAT(),
               nullable=False,
               existing_server_default=sa.text("'0'"))
    op.drop_table('seo')

Example 14

Project: sqlalchemy Source File: test_constraints.py
    def test_index_against_text_inline(self):
        metadata = MetaData()
        idx = Index('y', text("some_function(q)"))
        x = Table('x', metadata,
                  Column('q', String(50)),
                  idx
                  )

        self.assert_compile(
            schema.CreateIndex(idx),
            "CREATE INDEX y ON x (some_function(q))"
        )

Example 15

Project: pybossa Source File: task_repository.py
    def delete_valid_from_project(self, project):
        """Delete only tasks that have no results associated."""
        sql = text('''
                   DELETE FROM task WHERE task.project_id=:project_id
                   AND task.id NOT IN
                   (SELECT task_id FROM result
                   WHERE result.project_id=:project_id GROUP BY result.task_id);
                   ''')
        self.db.session.execute(sql, dict(project_id=project.id))
        self.db.session.commit()
        cached_projects.clean_project(project.id)
        self._delete_zip_files_from_store(project)

Example 16

Project: glottolog3 Source File: 44501a0f88bb_orphaned_justifications.py
def upgrade():
    update_just = sa.text('UPDATE valuesetreference AS vsr SET updated = now(), '
        'source_pk = (SELECT pk FROM source WHERE id = :new) '
        'WHERE EXISTS (SELECT 1 FROM source WHERE pk = vsr.source_pk '
        'AND id = :old)')
    for old, new in OLD_NEW:
        op.execute(update_just.bindparams(old=old, new=new))

Example 17

Project: alembic Source File: test_postgresql.py
    def test_create_index_postgresql_where(self):
        context = op_fixture("postgresql")
        op.create_index(
            'geocoded',
            'locations',
            ['coordinates'],
            postgresql_where=text("locations.coordinates != Null"))
        context.assert_(
            "CREATE INDEX geocoded ON locations (coordinates) "
            "WHERE locations.coordinates != Null")

Example 18

Project: sozlukcrawler Source File: yillara_gore_girdi.py
    def entry_numbers_in_months(self):
        years = self.get_distinct_years()

        out = []
        for year in years:
            for month in xrange(1, 13):
                sql = text("SELECT COUNT(girdi_id) FROM girdiler WHERE source=:s AND baslik_id=:b AND YEAR(datetime)=:y AND MONTH(datetime)=:m")
                result = session.execute(sql, params=dict(s=self.source, b=self.baslik_id, y=year, m=month)).fetchone()

                # Highcharts ile gosterirken Date.UTF 0 indexinden basliyor. Bu
                # yuzden -1 yazmak durumundayiz. Ornegin 2012 yilinin 0. ayi
                # highchart ile cizdirildiginde 2012-1 seklinde gozukmekte
                out.append({'year': year, 'month': month-1, 'number_of_entires': int(result[0])})

        return out

Example 19

Project: pybossa Source File: jobs.py
def update_projects_week():
    """Create or update updated projects last week materialized view."""
    if _exists_materialized_view('dashboard_week_project_update'):
        return _refresh_materialized_view('dashboard_week_project_update')
    else:
        sql = text('''CREATE MATERIALIZED VIEW dashboard_week_project_update AS
                   SELECT TO_DATE(project.updated, 'YYYY-MM-DD\THH24:MI:SS.US') AS day,
                   project.id, short_name, project.name,
                   owner_id, "user".name AS u_name, "user".email_addr
                   FROM project, "user"
                   WHERE TO_DATE(project.updated,
                                'YYYY-MM-DD\THH24:MI:SS.US') >= now() -
                                ('1 week')::INTERVAL
                   AND "user".id = project.owner_id
                   GROUP BY project.id, "user".name, "user".email_addr;''')
        db.session.execute(sql)
        db.session.commit()
        return "Materialized view created"

Example 20

Project: indico Source File: 201506081244_a2dfbb4b85c_add_extra_indexes_for_user_search.py
def _create_index(table, column):
    col_func = 'indico_unaccent(lower({}))'.format(column)
    kwargs = {'postgresql_using': 'gin',
              'postgresql_ops': {col_func: 'gin_trgm_ops'}}
    op.create_index(op.f('ix_{}_{}_unaccent'.format(table, column)), table, [sa.text(col_func)], schema='users',
                    **kwargs)

Example 21

Project: alembic Source File: test_postgresql.py
    def test_compare_float_no_diff3(self):
        self._compare_default_roundtrip(
            Float(),
            text("5"), text("5.0"),
            diff_expected=False
        )

Example 22

Project: alembic Source File: test_postgresql.py
    def test_compare_float_no_diff5(self):
        self._compare_default_roundtrip(
            Float(),
            text("5"), "5.0",
            diff_expected=False
        )

Example 23

Project: pybossa Source File: jobs.py
def new_tasks_week():
    """Create or update new tasks last week materialized view."""
    if _exists_materialized_view('dashboard_week_new_task'):
        return _refresh_materialized_view('dashboard_week_new_task')
    else:
        sql = text('''CREATE MATERIALIZED VIEW dashboard_week_new_task AS
                      SELECT TO_DATE(task.created,
                                     'YYYY-MM-DD\THH24:MI:SS.US') AS day,
                      COUNT(task.id) AS day_tasks
                      FROM task WHERE TO_DATE(task.created,
                                              'YYYY-MM-DD\THH24:MI:SS.US')
                                          >= now() - ('1 week'):: INTERVAL
                      GROUP BY day ORDER BY day ASC;''')
        db.session.execute(sql)
        db.session.commit()
        return "Materialized view created"

Example 24

Project: alembic Source File: test_postgresql.py
    def test_compare_numeric_no_diff(self):
        self._compare_default_roundtrip(
            Numeric(),
            text("5"), "5.0",
            diff_expected=False
        )

Example 25

Project: tvb-framework Source File: helper.py
def change_algorithm(module, classname, new_module, new_class):
    """
    Change module and classname fields in ALGORITHM_GROUPS table.
    """
    session = SA_SESSIONMAKER()
    try:
        session.execute(text(
            """UPDATE "ALGORITHM_GROUPS"
               SET module = '""" + new_module + """', classname = '""" + new_class + """'
               WHERE module = '""" + module + """' AND classname = '""" + classname + """';"""))
        session.commit()
    except Exception, excep:
        LOGGER.exception(excep)
    finally:
        session.close()

Example 26

Project: sqlalchemy Source File: test_deprecations.py
    def test_select_text(self):
        """Query.select_text(text, **params)

        users = session.query(User).select_text('SELECT * FROM users_table')

        """

        User = self.classes.User

        session = create_session()

        users = (session.query(User).
                 from_statement(text('SELECT * FROM users_table'))).all()
        assert len(users) == 4

Example 27

Project: sqlalchemy Source File: provision.py
@_drop_db.for_db("postgresql")
def _pg_drop_db(cfg, eng, ident):
    with eng.connect().execution_options(
            isolation_level="AUTOCOMMIT") as conn:
        conn.execute(
            text(
                "select pg_terminate_backend(pid) from pg_stat_activity "
                "where usename=current_user and pid != pg_backend_pid() "
                "and datname=:dname"
            ), dname=ident)
        conn.execute("DROP DATABASE %s" % ident)

Example 28

Project: plenario Source File: redshift_ops.py
def insert_observation(foi_name, nodeid, datetime, sensor,
                       values, procedures):
    """Inserts sensor readings

          :param values: list of observed property values in order
          :param procedures: integer procedure identifier """

    op = ('INSERT INTO {} '
          'VALUES ({}, {}, {}'
          .format(foi_name.lower(), repr(nodeid), repr(datetime), repr(sensor)))
    for val in values:
        op = (op + ', {}'.format(val))
    op = (op + ', {});'.format(str(procedures)))
    print op
    op = text(op)
    redshift_engine.execute(op)

Example 29

Project: sqlalchemy Source File: test_update_delete.py
    def test_delete_with_bindparams(self):
        User = self.classes.User

        sess = Session()

        john, jack, jill, jane = sess.query(User).order_by(User.id).all()
        sess.query(User).filter(text('name = :name')).params(
            name='john').delete('fetch')
        assert john not in sess

        eq_(sess.query(User).order_by(User.id).all(), [jack, jill, jane])

Example 30

Project: pybossa Source File: jobs.py
def new_users_week():
    """Create or update new users last week materialized view."""
    if _exists_materialized_view('dashboard_week_new_users'):
        return _refresh_materialized_view('dashboard_week_new_users')
    else:
        sql = text('''CREATE MATERIALIZED VIEW dashboard_week_new_users AS
                      SELECT TO_DATE("user".created,
                                     'YYYY-MM-DD\THH24:MI:SS.US') AS day,
                      COUNT("user".id) AS day_users
                      FROM "user" WHERE TO_DATE("user".created,
                                              'YYYY-MM-DD\THH24:MI:SS.US')
                                          >= now() - ('1 week'):: INTERVAL
                      GROUP BY day;''')
        db.session.execute(sql)
        db.session.commit()
        return "Materialized view created"

Example 31

Project: sqlalchemy Source File: test_constraints.py
    def test_index_against_text_separate(self):
        metadata = MetaData()
        idx = Index('y', text("some_function(q)"))
        t = Table('x', metadata,
                  Column('q', String(50))
                  )
        t.append_constraint(idx)
        self.assert_compile(
            schema.CreateIndex(idx),
            "CREATE INDEX y ON x (some_function(q))"
        )

Example 32

Project: viaduct Source File: 391b3fa1471_add_archived_field_to_custom_form.py
def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('custom_form', 'price',
               existing_type=mysql.FLOAT(),
               nullable=False,
               existing_server_default=sa.text("'0'"))
    op.drop_column('custom_form', 'archived')

Example 33

Project: sqlalchemy Source File: test_insert.py
Function: define_tables
    @classmethod
    def define_tables(cls, metadata):
        Table('mytable', metadata,
              Column('myid', Integer),
              Column('name', String(30)),
              Column('description', String(30)))
        Table('myothertable', metadata,
              Column('otherid', Integer, primary_key=True),
              Column('othername', String(30)))
        Table('table_w_defaults', metadata,
              Column('id', Integer, primary_key=True),
              Column('x', Integer, default=10),
              Column('y', Integer, server_default=text('5')),
              Column('z', Integer, default=lambda: 10)
            )

Example 34

Project: pybossa Source File: jobs.py
def draft_projects_week():
    """Create or update new created draft projects last week materialized view."""
    if _exists_materialized_view('dashboard_week_project_draft'):
        return _refresh_materialized_view('dashboard_week_project_draft')
    else:
        sql = text('''CREATE MATERIALIZED VIEW dashboard_week_project_draft AS
                   SELECT TO_DATE(project.created, 'YYYY-MM-DD\THH24:MI:SS.US') AS day,
                   project.id, short_name, project.name,
                   owner_id, "user".name AS u_name, "user".email_addr
                   FROM project, "user"
                   WHERE TO_DATE(project.created,
                                'YYYY-MM-DD\THH24:MI:SS.US') >= now() -
                                ('1 week')::INTERVAL
                   AND "user".id = project.owner_id
                   AND project.published = false
                   GROUP BY project.id, "user".name, "user".email_addr;''')
        db.session.execute(sql)
        db.session.commit()
        return "Materialized view created"

Example 35

Project: glottolog3 Source File: 3d8925dd5250_move_retired_bookkeeping.py
def upgrade():
    move_lang = sa.text('UPDATE language AS l SET updated = now() '
        'WHERE id = :id AND EXISTS (SELECT 1 FROM languoid WHERE pk = l.pk '
        'AND father_pk IS NULL)')
    move_uoid = sa.text('UPDATE languoid AS ll '
        'SET father_pk = (SELECT pk FROM language WHERE id = :after) '
        'WHERE EXISTS (SELECT 1 FROM language WHERE pk = ll.pk AND id = :id) '
        'AND father_pk IS NULL')

    for id in MOVE:
        op.execute(move_lang.bindparams(id=id))
        op.execute(move_uoid.bindparams(id=id, after=AFTER))

    for sql in RECREATE_TREECLOSURE:
        op.execute(sql)

Example 36

Project: alembic Source File: test_postgresql.py
    @config.requirements.fail_before_sqla_080
    def test_create_index_postgresql_expressions(self):
        context = op_fixture("postgresql")
        op.create_index(
            'geocoded',
            'locations',
            [text('lower(coordinates)')],
            postgresql_where=text("locations.coordinates != Null"))
        context.assert_(
            "CREATE INDEX geocoded ON locations (lower(coordinates)) "
            "WHERE locations.coordinates != Null")

Example 37

Project: glottolog3 Source File: 44f5188c7e26_fix_pk_seqs.py
Function: upgrade
def upgrade():
    # http://wiki.postgresql.org/wiki/Fixing_Sequences
    query = sa.text("""SELECT 'SELECT setval(' ||
          quote_literal(quote_ident(s.relname)) ||
          ', coalesce(max(' ||
          quote_ident(c.attname) ||
          '), 1)) FROM ' ||
          quote_ident(t.relname)
        FROM pg_class AS s
        JOIN pg_depend AS d ON d.objid = s.oid
        JOIN pg_class AS t ON t.oid = d.refobjid
        JOIN pg_attribute AS c ON c.attrelid = d.refobjid AND c.attnum = d.refobjsubid
        WHERE s.relkind = 'S'""")
    conn = op.get_bind()
    for setval, in conn.execute(query):
        conn.execute(setval)

Example 38

Project: pybossa Source File: task_repository.py
    def delete_taskruns_from_project(self, project):
        sql = text('''
                   DELETE FROM task_run WHERE project_id=:project_id;
                   ''')
        self.db.session.execute(sql, dict(project_id=project.id))
        self.db.session.commit()
        cached_projects.clean_project(project.id)
        self._delete_zip_files_from_store(project)

Example 39

Project: sozlukcrawler Source File: yillara_gore_girdi.py
    def entry_numbers_in_years(self):
        years = self.get_distinct_years()

        out = []
        for year in years:
            sql = text("SELECT COUNT(girdi_id) FROM girdiler WHERE source=:s AND baslik_id=:b AND YEAR(datetime)=:y")
            result = session.execute(sql, params=dict(s=self.source, b=self.baslik_id, y=year)).fetchone()

            out.append({'year': year, 'month': 1, 'number_of_entires': int(result[0])})

        return out

Example 40

Project: alembic Source File: test_postgresql.py
    @config.requirements.postgresql_uuid_ossp
    def test_compare_uuid_text(self):
        self._compare_default_roundtrip(
            UUID,
            text("uuid_generate_v4()")
        )

Example 41

Project: sozlukcrawler Source File: yillara_gore_girdi.py
    def total_entries(self):
        sql = text("SELECT COUNT(*) FROM girdiler WHERE source=:s AND baslik_id=:b")
        result = session.execute(sql, params=dict(s=self.source, b=self.baslik_id)).fetchone()

        out = "// toplam girdi sayisi\n"
        out += "[%s, %s]" % (self.source, int(result[0]))

        return out

Example 42

Project: pybossa Source File: data.py
def _select_from_materialized_view(view, n_days=None):
    if n_days is None:
        sql = text("SELECT * FROM %s" % view)
        options = {}
    else:
        sql = text("""SELECT COUNT(user_id)
                   FROM %s
                   WHERE n_days=:n_days""" % view)
        options = dict(n_days=n_days)
    try:
        session = db.slave_session
        return session.execute(sql, options)
    except ProgrammingError:
        db.slave_session.rollback()
        raise

Example 43

Project: hasjob Source File: c20bd2c9b35_campaigns.py
def downgrade():
    op.drop_index(op.f('ix_userjobview_user_id'), table_name='userjobview')
    op.drop_index(op.f('ix_campaign_user_action_user_id'), table_name='campaign_user_action')
    op.drop_index(op.f('ix_campaign_user_action_action_id'), table_name='campaign_user_action')
    op.drop_table('campaign_user_action')
    op.drop_table('campaign_action')
    op.execute(sa.text('DROP TYPE campaign_action_type_enum;'))
    op.drop_index(op.f('ix_campaign_location_geonameid'), table_name='campaign_location')
    op.drop_table('campaign_location')
    op.drop_table('campaign_view')
    op.drop_index(op.f('ix_campaign_board_campaign_id'), table_name='campaign_board')
    op.drop_table('campaign_board')
    op.drop_table('campaign')

Example 44

Project: alembic Source File: test_postgresql.py
    def test_compare_float_no_diff2(self):
        self._compare_default_roundtrip(
            Float(),
            "5.2", text("5.2"),
            diff_expected=False
        )

Example 45

Project: SecPi Source File: base_webpage.py
	@cherrypy.expose
	@cherrypy.tools.json_in()
	@cherrypy.tools.json_out(handler=utils.json_handler)
	def list(self):
		if(hasattr(cherrypy.request, 'json')):
			qry = self.db.query(self.baseclass)
			
			if('filter' in cherrypy.request.json and cherrypy.request.json['filter']!=''):
				qry = qry.filter(text(cherrypy.request.json['filter']))
			
			if('sort' in cherrypy.request.json and cherrypy.request.json['sort']!=''):
				qry = qry.order_by(text(cherrypy.request.json['sort']))
			
			objects = qry.all()
			
		else:	
			objects = self.db.query(self.baseclass).all()
		
		return {'status': 'success', 'data': self.objectsToList(objects)}

Example 46

Project: pytrainer Source File: version014_test.py
    def upgradeAndAssert(self, original, expected):
        self._engine.execute(sqlalchemy.text("insert into sports (id_sports, name, weight, color, met, max_pace)"
                                             " values (:id, :name, :weight, :color, :met, :max_pace)"),
                                           id= 1,
                                           name= "Test Sport",
                                           weight= original["weight"],
                                           color= original["color"],
                                           met= original["met"],
                                           max_pace= original["max_pace"])
        version014.upgrade(self._engine)
        result = self._engine.execute(self._sports_table.select(self._sports_table.c.id_sports==1))
        (_, _, weight, color, met, max_pace) = result.fetchone()
        result.close()
        self.assertEqual(expected["weight"], weight)
        self.assertEqual(expected["color"], color)
        self.assertEqual(expected["met"], met)
        self.assertEqual(expected["max_pace"], max_pace)

Example 47

Project: pybossa Source File: jobs.py
def _exists_materialized_view(view):
    sql = text('''SELECT EXISTS (SELECT relname FROM pg_class WHERE
               relname = :view);''')
    results = db.slave_session.execute(sql, dict(view=view))
    for result in results:
        return result.exists
    return False

Example 48

Project: pybossa Source File: jobs.py
def new_task_runs_week():
    """Create or update new task_runs last week materialized view."""
    if _exists_materialized_view('dashboard_week_new_task_run'):
        return _refresh_materialized_view('dashboard_week_new_task_run')
    else:
        sql = text('''CREATE MATERIALIZED VIEW dashboard_week_new_task_run AS
                      SELECT TO_DATE(task_run.finish_time,
                                     'YYYY-MM-DD\THH24:MI:SS.US') AS day,
                      COUNT(task_run.id) AS day_task_runs
                      FROM task_run WHERE TO_DATE(task_run.finish_time,
                                              'YYYY-MM-DD\THH24:MI:SS.US')
                                          >= now() - ('1 week'):: INTERVAL
                      GROUP BY day;''')
        db.session.execute(sql)
        db.session.commit()
        return "Materialized view created"

Example 49

Project: plenario Source File: redshift_ops.py
def create_foi_table(foi_name, properties):
    """Create a new foi table

       :param foi_name: name of feature
       :param properties: list of {'name': name, 'type': type} dictionaries """

    op = ('CREATE TABLE {} ('
          '"node_id" VARCHAR NOT NULL, '
          'datetime TIMESTAMP WITHOUT TIME ZONE NOT NULL, '
          '"meta_id" DOUBLE PRECISION NOT NULL, '
          '"sensor" VARCHAR NOT NULL, ').format(foi_name)
    for prop in properties:
        op = (op + '"{}" {}, '.format(prop['name'], prop['type']))
    op = (op + ('PRIMARY KEY ("node_id", datetime)) '
          'DISTKEY(datetime) SORTKEY(datetime);'))
    print op
    redshift_engine.execute(text(op))

Example 50

Project: sqlalchemy Source File: test_dialect.py
    @testing.fails_on('+zxjdbc', 'psycopg2/pg8000 specific assertion')
    @testing.requires.psycopg2_or_pg8000_compatibility
    def test_numeric_raise(self):
        stmt = text(
            "select cast('hi' as char) as hi", typemap={'hi': Numeric})
        assert_raises(exc.InvalidRequestError, testing.db.execute, stmt)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4