Динамический SQL с идентификатором в psycopg2? - PullRequest
2 голосов
/ 28 октября 2019
int1 = "first"
int2 = "second"
column1 = ['height', 'test1', 'test2']
column2 = ['height', 'width']

int1_attr = [sql.Identifier(int1,s) for s in column1]
int2_attr = [sql.Identifier(int2,s)for s in column2]

qry_str = sql.SQL("CREATE TABLE IF NOT EXISTS {} as (Select {},{}, st_intersection({},{}) from {},{} )").format(
sql.Identifier('Intersection'),
sql.SQL(', ').join(int1_attr),
sql.SQL(', ').join(int2_attr),
sql.Identifier(int1+".geom"),
sql.Identifier(int2+".geom"),
sql.Identifier(int1),
sql.Identifier(int2)
)
print(qry_str.as_string(con))

>> CREATE TABLE IF NOT EXISTS "Intersection" as (Select "first"."height", "first"."test1", "first"."test2","second"."height", "second"."width", st_intersection("first.geom","second.geom") from "first","second" )

Эй, мне нужно, например, "first". "Height" как "first.height" в выбранной части, но для всех атрибутов. Этот код - то, что я мог сделать. Я не могу добиться никакого прогресса от этого. Есть ли способ к этому?

В конце sql должен выглядеть так:

>> CREATE TABLE IF NOT EXISTS "Intersection" as (Select "first"."height" as "first.height", "first"."test1" as "first.test1", "first"."test2" as "first.test2" ,"second"."height" as "second.height", "second"."width" as "second.with", st_intersection("first.geom","second.geom") from "first","second")

Ответы [ 2 ]

0 голосов
/ 29 октября 2019

В int1_attr вы просто указываете столбцы с "table"."column". Что вам нужно сделать, это построить int1_attr как "table"."column" AS "table.column". Это можно сделать с помощью:

int1_attr = [
    sql.SQL("{} AS {}").format(
        sql.Identifier(int1, s),
        sql.Identifier("{}.{}".format(int1, s))
    ) for s in column1
]
int2_attr = [
    sql.SQL("{} AS {}").format(
        sql.Identifier(int2, s),
        sql.Identifier("{}.{}".format(int2, s))
    ) for s in column2
]
0 голосов
/ 29 октября 2019

Вы можете использовать Identifier для создания квалифицированного имени столбца:

NAMED_EXPRESSION = '%s as %s'
QUALIFIED_NAME = '%s.%s'
int1_attr = [
    NAMED_EXPRESSION % (
      sql.Identifier(int1, s),
      sql.Identifier(QUALIFIED_NAME % (int1, s))
    ) for s in column1
]
...