遗留的oracle sql语法转换python

时间:2018-03-31 18:13:23

标签: python sql-parser

我正在将传统的oracle sql join语法转换为与postgres兼容的ANSI sql代码。我正在使用python为此目的创建实用程序。从我的研究到目前为止,我发现使用sqlparser python库。

示例sql语法:

  SELECT i.product_id
,      d.language_id
,      CASE WHEN d.language_id IS NOT NULL
            THEN d.translated_name
            ELSE TRANSLATE(i.product_name USING NCHAR_CS)
       END    AS product_name
,      i.category_id
,      CASE WHEN d.language_id IS NOT NULL
            THEN d.translated_description
            ELSE TRANSLATE(i.product_description USING NCHAR_CS)
       END    AS product_description
,      i.weight_class
,      i.warranty_period
,      i.supplier_id
,      i.product_status
,      i.list_price
,      i.min_price
,      i.catalog_url
FROM   product_information  i
,      product_descriptions d
WHERE  d.product_id  (+) = i.product_id
AND    d.language_id (+) = sys_context('USERENV','LANG');

预期产出:

  SELECT i.product_id
,      d.language_id
,      CASE WHEN d.language_id IS NOT NULL
            THEN d.translated_name
            ELSE TRANSLATE(i.product_name USING NCHAR_CS)
       END    AS product_name
,      i.category_id
,      CASE WHEN d.language_id IS NOT NULL
            THEN d.translated_description
            ELSE TRANSLATE(i.product_description USING NCHAR_CS)
       END    AS product_description
,      i.weight_class
,      i.warranty_period
,      i.supplier_id
,      i.product_status
,      i.list_price
,      i.min_price
,      i.catalog_url
FROM   product_information  i right outer join product_descriptions d

on 
d.product_id   = i.product_id 
and    d.language_id = sys_context('USERENV','LANG');

到目前为止,我试过这样的事。我有令牌但不确定如何在传统Oracle连接语法的情况下交换位置。如果有人能提供一些见解。我对python很新。

import sqlparse

query= '''
    SELECT i.product_id
,      d.language_id
,      CASE WHEN d.language_id IS NOT NULL
            THEN d.translated_name
            ELSE TRANSLATE(i.product_name USING NCHAR_CS)
       END    AS product_name
,      i.category_id
,      CASE WHEN d.language_id IS NOT NULL
            THEN d.translated_description
            ELSE TRANSLATE(i.product_description USING NCHAR_CS)
       END    AS product_description
,      i.weight_class
,      i.warranty_period
,      i.supplier_id
,      i.product_status
,      i.list_price
,      i.min_price
,      i.catalog_url
FROM   product_information  i
,      product_descriptions d
WHERE  d.product_id  (+) = i.product_id
AND    d.language_id (+) = sys_context('USERENV','LANG')'''


res=sqlparse.parse(query)
stmt = res[0]
print (stmt.tokens[-1])

我得到了输出 where子句加入

WHERE  d.product_id  (+) = i.product_id
AND    d.language_id (+) = sys_context('USERENV','LANG');

我被困在这里,如何将其重写为

FROM   product_information  i right outer join product_descriptions d    
on  d.product_id   = i.product_id 
and    d.language_id = sys_context('USERENV','LANG');

0 个答案:

没有答案