Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's not exactly ORM, but to create the table initially, I'd clone the table structure (see <code>cloneTable</code> in the example below). For copying the data, I then would use the <a href="http://docs.sqlalchemy.org/en/latest/core/compiler.html#compiling-sub-elements-of-a-custom-expression-construct">InsertFromSelect example</a>. </p> <p><strong>Edit:</strong> <em>Since version 0.8.3, SqlAlchemy supports <a href="http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.Insert.from_select">Insert.from_select()</a> out of the box. Hence the InsertFromSelect class and the respective visitor in the example below can be directly replaced and are no longer needed. I leave the original example unchanged for historic reasons.</em></p> <p>Here is a working example</p> <pre><code>from sqlalchemy import Table from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql.expression import UpdateBase class InsertFromSelect(UpdateBase): def __init__(self, table, select): self.table = table self.select = select @compiles(InsertFromSelect) def visit_insert_from_select(element, compiler, **kw): return "INSERT INTO %s %s" % ( compiler.process(element.table, asfrom=True), compiler.process(element.select) ) def cloneTable(name, table, metadata): cols = [c.copy() for c in table.columns] constraints = [c.copy() for c in table.constraints] return Table(name, metadata, *(cols + constraints)) # test data from sqlalchemy import MetaData, Column, Integer from sqlalchemy.engine import create_engine e = create_engine('sqlite://') m = MetaData(e) t = Table('t', m, Column('id', Integer, primary_key=True), Column('number', Integer)) t.create() e.execute(t.insert().values(id=1, number=3)) e.execute(t.insert().values(id=9, number=-3)) # create temp table temp = cloneTable('temp', t, m) temp.create() # copy data ins = InsertFromSelect(temp, t.select().where(t.c.id&gt;5)) e.execute(ins) # print result for r in e.execute(temp.select()): print r </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload