2

SQLite 3 で Python を使用しています。ユーザーが SQL クエリを入力しており、それらの結果をテンプレート言語用にフォーマットする必要があります。

したがって、基本的には、DB API カーソル (PEP 249) の .description を使用する必要がありますが、ユーザーは頻繁に結合を行うため、列名テーブル名の両方を取得する必要があります。

明白な答え、つまりテーブル定義を読み取ることは不可能です。テーブルの多くは同じ列名を持っています。

また、avg(field) などの集計関数の列/テーブル名にインテリジェントな動作が必要です...

私が思いつく唯一の解決策は、SQL パーサーを使用して SELECT ステートメントを分析することです (ため息)。

ドキュメントや同じ問題を抱えている他の人には何も見つかりませんでした。

編集:明確にするために-問題は、SQL選択の結果を見つけることです。選択ステートメントは、ユーザーインターフェイスでユーザーによって提供されます。私はそれを制御できません。上で述べたように、テーブル定義を読んでも役に立ちません。

4

1 に答える 1

1

Python's DB API only specifies column names for the cursor.description (and none of the RDBMS implementations of this API will return table names for queries...I'll show you why).

What you're asking for is very hard, and only even approachable with an SQL parser...and even then there are many situations where even the concept of which "Table" a column is from may not make much sense.

Consider these SQL statements:

  1. Which table is today from?

    SELECT DATE('now') AS today FROM TableA FULL JOIN TableB 
    ON TableA.col1 = TableB.col1;
    
  2. Which table is myConst from?

    SELECT 1 AS myConst;
    
  3. Which table is myCalc from?

    SELECT a+b AS myCalc FROM (select t1.col1 AS a, t2.col2 AS b 
    FROM table1 AS t1
    LEFT OUTER JOIN table2 AS t2 on t1.col2 = t2.col2);
    
  4. Which table is myCol from?

    SELECT SUM(a) as myCol FROM (SELECT a FROM table1 UNION SELECT b FROM table2);
    

The above were very simple SQL statements for which you either have to make up a "table", or arbitrarily pick one...even if you had an SQL parser!

What SQL gives you is a set of data back as results. The elements in this set can not necessarily be attributed to specific database tables. You probably need to rethink your approach to this problem.

于 2012-06-02T03:11:18.033 に答える