Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force SQLAlchemy to include duplicate columns?

Tags:

sql

sqlalchemy

I'm learning the SQLAlchemy Expression Language, and I'm trying to execute a trivial query that returns a single duplicated column via select([users.c.id, users.c.id]):

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, insert, select
engine = create_engine('sqlite:///:memory:', echo=True)
conn = engine.connect()
metadata = MetaData()
users = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
Column('fullname', String),
)
metadata.create_all(engine)
conn.execute(users.insert(), [
{'id': 1, 'name' : 'jack', 'fullname': 'Jack Jones'},
{'id': 2, 'name' : 'wendy', 'fullname': 'Wendy Williams'},
])
print(list(conn.execute(select([users.c.id, users.c.id]))))

Which outputs:

[(1,), (2,)]

I.e., only one of the two requested columns. I expected:

[(1, 2), (2, 2)]

To double-check that my expectations are correct, I ran the equivalent queries directly in sqlite3 and PostgreSQL 9.2 ([1] and [2] below), both of which correctly returned the duplicated ids. I'm using SQLAlchemy version 0.8.0b2, Python 3.2.3, sqlite3 3.6.12, and Mac OS X 10.6 and 10.7.

Thanks in advance!

[1] sqlite3

$ sqlite3 temp.db
CREATE TABLE users(id INTEGER, name TEXT, fullname TEXT);
INSERT INTO users VALUES(1, 'jack', 'Jack Jones');
INSERT INTO users VALUES(2, 'wendy', 'Wendy Williams');
SELECT id, id FROM users;
->
1|1
2|2

[2] PostgreSQL

$ /Library/PostgreSQL/9.2/bin/psql -U postgres
CREATE DATABASE temp;
CREATE TABLE users(id INTEGER, name TEXT, fullname TEXT);
INSERT INTO users VALUES(1, 'jack', 'Jack Jones');
INSERT INTO users VALUES(2, 'wendy', 'Wendy Williams');
SELECT id, id FROM users;
->
1 |  1
2 |  2
like image 591
Matthew Cornell Avatar asked Dec 09 '25 20:12

Matthew Cornell


1 Answers

At least one of your columns needs a label to create a distinction between the two.

print(list(conn.execute(select([users.c.id, users.c.id.label('id2')]))))
like image 132
jd. Avatar answered Dec 12 '25 10:12

jd.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!