The db_postgres returns queried values, but not the column names.
echo conn.get_all_rows(sql("select name, age from test_users"))
# ==> @[@["Jim", "30"]]
Is there a way to get also the column names for the query? The @["name", "age"]?
Full example:
import postgres, db_postgres, strutils, sequtils
let conn = open("localhost:5432", "postgres", "", "nim_test")
let batch = """
drop table if exists test_users;
create table test_users(
name varchar(100) not null,
age integer not null
);
insert into test_users (name, age) values ('Jim', 30)
"""
for part in batch.split(";"): conn.exec(sql(part))
echo conn.get_all_rows(sql("select name, age from test_users"))
# ==> @[@["Jim", "30"]]
instantRows should provide access to the columns: iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery; args: varargs[string, `$]): InstantRow {...}`
Here is the example from the db_sqlite
var columns: DbColumns
for row in db.instantRows(columns, sql"SELECT * FROM my_table"):
discard
echo columns[0]
# Output:
# (name: "id", tableName: "my_table", typ: (kind: dbNull,
# notNull: false, name: "INTEGER", size: 0, maxReprLen: 0, precision: 0,
# scale: 0, min: 0, max: 0, validValues: @[]), primaryKey: false,
# foreignKey: false)
It works, thanks!
One more question, does querying column names has overhead? Like would the driver returns both column names and results in single query, or it does two queries, one to get column names and another to get results?
If anyone else needs this:
import postgres, db_postgres, strutils, sequtils
let conn = open("localhost:5432", "postgres", "", "nim_test")
let batch = """
drop table if exists test_users;
create table test_users(
name varchar(100) not null,
age integer not null
);
insert into test_users (name, age) values ('Jim', 30)
"""
for part in batch.split(";"): conn.exec(sql(part))
var columns: DbColumns
for row in conn.instantRows(columns, sql("select name, age from test_users")):
echo columns.len
echo columns[0].name
echo columns[1].name
echo row[0]
echo typeof row[1]