How to validate column name in dynamic made sql?

Oracle db, jdbc, web app with struts2/spring.
Example table could be this:
CREATE TABLE album
album_id number(10)  not null,
  artist  varchar2(50) not null,
title  varchar2(50) not null,
  released  DATE,  
  CONSTRAINT album_pk PRIMARY KEY (album_id)
);In may app the user MAY search, MAY sort, and the result from an select might return 10.000 rows.
The basic sql usually look like this.
String sql = "select album_id, artist, title, released from album";Then in the html page the user can add search criteria for each column. Like type "iron maiden" in artist field, put "1982" in released field. And you all know what the exceptionally result should be from that :)
Now I need to modify the sql a bit:
if( artist search field contains stuff )
   sql = sql + " where nvl( artist,' ') like ?"
}we try use prepared statements right? So we use ? as placeholders, and then add "iron maiden" into this statement later on.
Nice, no big fuzz right, and pretty safe from sql injections i guess.
But now I have to have an if/else for every single field in the table. Boring. In my app I got like 25 tables like this, with 20 columns minimum. Copy/Paste have never been so boring.
I also might have to add "order by" with user selected columns and their order. I have to count the query to get total result in case i got to split it up in pages. So there is alot of if/else and sql = sql + "more stuff", and sticking to ? and pure prepared statements is impossible.
But doing this is not good either:
for( each element in a map)
  sql = sql + " and nvl( " + key + ",' ') like ?"
}Where key is "artist".
In struts and other tag libs its easy to make kode like:
<s:textfield name="model.addSearch( 'artist' )" value="%{model.getSearch( 'artist' )}" size="30" />
Silly example maybe, but just to make a point.
Inputed values in an html form, can very easily be a part of a dynamic created sql - which becomes a security problem later on.
Artist is an column name. Key should be validated if it contained an valid column name.
I could make a list of strings, containing valid column names to check against.
My question is if there is possible to get this type of information from the database, so I don't have to hand-make these lists?
But I also want to keep the number of heavy and slowing queries down.
My app have like 25 tables now, and I could easily get away with hand-make everything, copy/paste around etc. But I have more projects and this question will be here next time too. And after there again...

Etharo wrote:
Metadata. Then I have to query the database, take the result and use it for validating of input. If my sql only query 1 table, then this is ok. In this case I could do with that. But if the sql query mutliple tables, with sub-selects, unions etc. Then I might have to query all tables first, and even then I might not have what I want.
The best way is of course to run the query, then get the metadata from that query - cause then im 100% sure what columns will be returned, and then I can validate with that.... 1 query is often not that slow. But I might query once to find total number of rows the query return in order to decide if we need to page the result. then query to get the metadata for validating input, then query to get the result... Maybe this is ok -but my head don't like it as an general ok thing to do, but I can't really say why...If you have a gui screen then it needs to correspond to some specific query. It can't be all possible combinations.
So once you know the query you can obtain the meta data using a query that returns no results. Like the following.
select * from mytable wheren 1 = 0
>
Jschell:
I agree to what you say. I don't understood everything you said tho.
Im not sure if you talk about having 1 search field (like google), and you input stuff there that might be in any columns.
I have several search fields in one-to-one relasionship with view column/sql query column.
Then you already know what the field represents. So validate it in the gui and not via the database.
The first is way more advanced since you have to cover any input, any column, any case etc. Pluss add ranking. Lots of work for someone who have done little searchengines.
Latter is simpler, but might also be limiting.Huh?
As an example if you have a call center then the operators are not going to be doing unrestricted searches to find customers. They are going to look using a very limited set of data like the customer name and telephone number.
>
My job is very much like an consulent. They got an app, I shall add a new feature. The app is old and ugly coded. My boss ask how long it takes to make this, I say 2months, he decide 1 month. My dev time for features is rarely above 1 month, and I don't make much new apps.
So I don't have the time to make advanced codegenerator, or spend time to evaluate various frameworks. Bringing an framework into the existing code is actually difficult. But I do want to improve the code, and add good code into the existing app that can be extended without evil pain.
That doesn't jive with your OP. You made the following statement "My app have like 25 tables now, and I could easily get away with hand-make everything,...".
That suggests that you are doing much more than simply updating an existing application.
If you only need to add one new field then you should do only that. You shouldn't be attempting to add a system spanning validation system.
On the other hand if you are in fact adding a validation system, then code generation makes it likely that it would take less time or no more than the same. And it is less likely to introduce bugs.
Learn how to make an code generator? Well I guess thats what I asked help for - point me in the right direction if you could pls. Putting strings together to become code in an logic way is usually manageable, at least for simple querys. Evaluating that the generated code is good/safe - got no good clues...
Learn about frameworks? Got no time. Hope I will get the time, but I won't. The customer must want to spend the money so I can get the time, that won't happen cause an framework does not add features, its only cost saving in terms of dev time, and maintenance time. The customer have no such focus/interest. They got a bit money to spend now and then regularily. i.e. government.
I just want to try code as good as possible so I save myself from errors, painfull rewrites, and dev-time that gets out of proportions because of stupid code. So the question is actually about me trying to improve myself, its just that i don't know how right now.There are two goals.
1. Implement a specific feature in an existing application.
2. Learn a new way to solve problems.
Nothing says that the second will help with the first. They should be addressed separately and your post doesn't make it clear what the first is so it is hard to say how it should be down.
As for the second I already made a suggestion which provides two new ways to solve problems.

Similar Messages

  • How to pass column name at run time in function.

    how to pass column name at run time in function as parameter.
    thank in advance
    pramod patel

    Hello,
    Using dynamic sql you can pass column name to function. well I am not getting what you really want to do ? Please write in more detail. By the way I am providing one example here. see it uses dynamic sql.
    Create or replace function fun_updtest (p_columnname_varchar2 in varchar2,
    p_value_number in number)
    return number is
    v_stmt varchar2(500);
    begin
    v_stmt := 'update emp
    set '||p_columnname_varchar2||' = '||to_char(p_value_number)||'
              where empno = 7369';
    execute immediate v_stmt;
    return 0;
    commit;
    end;
    call to this function can be like this..
    declare
    v_number               number;
    begin
    v_number := fun_updtest('SAL',5000);
    end;
    Adinath Kamode

  • Regular Expression TO validate column name

    Hi All
    I want to write a regular expression to validate column names.i.e enterted name should follow the valid column name convention
    contain only A–Z, a–z, 0–9, _, $, and #
    Please someone help me to do this.
    Padma

    Hi,
    I would write it that way :SQL> with t as (
      2          select 'ABC$DEF1' cname from dual
      3          union all select 'ABC#DEF2' from dual
      4          union all select 'ABC_DEF3' from dual
      5          union all select 'ABC_#$x4' from dual
      6          union all select 'abc_def5' from dual
      7          union all select 'ABCDEFG%' from dual
      8          union all select 'ABC*DEFG' from dual
      9  )
    10  select cname
    11  from t
    12  where not regexp_like(cname,'^[_#$[:alnum:]]+$') ;
    CNAME
    ABCDEFG%
    ABC*DEFG
    2 rows selected.You could also add some length condition in the regexp if your convention is supposed to enforce any.
    Just my 2 cents :
    DBMS_ASSERT.SIMPLE_SQL_NAME looks good +(I didn't know that package)+ but it would allow double quoted names with "unwanted" characters inside. Even if valid for the RDBMS maybe it's not ok regards to the OP's naming convention :SQL> l
      1  with t as (
      2     select '"Name with blank spaces"' cname from dual
      3     union all select '"Name with @ stuff"' from dual
      4     union all select '"Name with ~ stuff"' from dual
      5  )
      6  select DBMS_ASSERT.SIMPLE_SQL_NAME(cname) checked
      7* from t
    SQL> /
    CHECKED
    "Name with blank spaces"
    "Name with @ stuff"
    "Name with ~ stuff"
    3 rows selected.I guess this procedures lacks some option parameter to specify what is valid or not.
    +(I hate to see column names with blank spaces in it)+
    (^_^)
    More seriously, if the point is to follow a chosen namig convention, I guess it would make more sense to have it explicitly written by the owner.
    (You can't say how the DBMS_ASSERT package will evolve in futures RDBMS releases).

  • How to get column names for a specific view in the scheme?

    how to get column names for a specific view in the scheme?
    TIA
    Don't have DD on the wall anymore....

    or this?
    SQL> select text from ALL_VIEWS
      2  where VIEW_NAME
      3  ='EMP_VIEW';
    TEXT
    SELECT empno,ename FROM EMP
    WHERE empno=10

  • How to pass column name as a   values from one page  to another

    hi
    i have created a report(pivot) from a table
    SQL> SELECT * FROM T;
    C1  C2          C3 D                SEQ
    A   AA           2                    1
    A   AB           3                    2
    A   AC           2                    3
    B   AB           5                    4
    B   AC           6                    5
    SQL> SELECT C1
      2  ,NVL(MAX(CASE WHEN C2='AA' THEN C3 END),'') AA
      3  ,NVL(MAX(CASE WHEN C2='AB' THEN C3 END),'') AB
      4  ,NVL(MAX(CASE WHEN C2='AC' THEN C3 END),'') AC
      5  ,SUM(C3) FROM T GROUP BY C1;
    C1          AA         AB         AC    SUM(C3)
    A            2          3          2          7
    B                       5          6         11
    SQL>
    my requirement in Apex is like this(reverse)
    eg-
    when i click on cell values '2' then,it should return
    C1  C2          C3 D                SEQ
    A   AA           2                    1
    {quote}how to pass column name as a  values from one page to another
    for example i have to pass 'c2' as a value to next page{quote}for report pivot you can reffer below link
    Report
    Amu

    thanks for your reply
    i 'm doing what exactly you mention here .
    my problem here is
    i have 15 columns
    i am executing a query based on the values of the column(column name)  in the target page
    1)here i am passing(all) the column values to the next page-but  i want to pass only one column values(column name)
    when i click on any cell of that  column
    OR
    2)i can pass all column name to target page -there(in the target page) i can filter out
    i think option 1 would good if you filter out the unwanted columns
    Regards
    Amul

  • How to get column names in table maintenance dialog?

    I created a new Z table and created a maintanance dialog so that I can maintain the table through sm30. i don't see columns names on maintenance screen, just a "+" sign for each column! Could someone please tell me how to display column name?
    Thanks.
    Mithun

    Hello Mithun
    The column texts are taken from the field descriptions of the data elements used in your z-table. A "+" sign usually indicates that none of the field descriptions of the data element has been maintained.
    Regards
      Uwe

  • How to rename column name of table?

    Hello...
    How to rename column name of table?
    The column have data.
    Thanks.
    Martonio.

    The following should work in 9i release 2 and above.
    SQL> create table mytable(col1 varchar2(2),
      2  col2 date);
    Table created.
    SQL> insert into mytable values('t1',sysdate);
    1 row created.
    SQL> select * from mytable;
    CO COL2
    t1 30-NOV-04
    1 row selected.
    SQL> desc mytable
    Name                                      Null?    Type
    COL1                                               VARCHAR2(2)
    COL2                                               DATE
    SQL> alter table mytable rename column col2 to mydate;
    Table altered.
    SQL> desc mytable
    Name                                      Null?    Type
    COL1                                               VARCHAR2(2)
    MYDATE                                             DATE
    SQL> select * from mytable;
    CO MYDATE
    t1 30-NOV-04
    1 row selected.
    SQL> disconnect
    Disconnected from Oracle9i Enterprise Edition Release 9.2.0.3.0 - 64bit Production
    With the Partitioning option
    JServer Release 9.2.0.3.0 - Productionhttp://download-west.oracle.com/docs/cd/B10501_01/server.920/a96540/wnsql.htm#972698

  • How to validate user name and password in webdynpro.

    Dear All,
    Actually i have created login name and password in view, webdynpro and want to validate the user name and password but  i am not finding proper code to  how to validate user name and password.
    Pl do the needful help.
    Regards.
    Tazeer.
    Moderator Message: There is a seperate forum for WebDynpro. Please ask your question there.
    Edited by: kishan P on Oct 5, 2010 1:08 PM

    Hello, I don´t get you question. User authentication is ready out of the box in webdypro...
    Regards Otto

  • How to replace part of column name with dynamic value

    I have the following construction in an update transaction:
    $upd_blg_user_usr->addColumn("report_1_user", "NUMERIC_TYPE", "VALUE", "{rsCatReport.id_report}");
    The dynamic value, {rsCatReport.id_report}, gets a url variable.
    I want this variable to replace the "1" in the column name "report_1_user". Something like this:
    $upd_blg_user_usr->addColumn("report_{rsCatReport.id_report}_user", "NUMERIC_TYPE", "VALUE", "{rsCatReport.id_report}");
    That construction, however, does not work. Prevents the page from loading. I've tried different constructions but have not hit one one that works.
    First, I'm not sure anything will work and second, if some different construction will work, I don't know what it is.
    Can anyone answer these questions. Thanks in advance for your help.

    What? Are you some kind of genius?
    Yes that works perfectly. Thanks as always!
    Here's the rationale. The same basic form appears on many different pages. The only difference among the forms is the outcome of submitting the form. The form on different pages takes you to a different download page and a database column is marked to signify that the user downloaded that form. For instance:
    report_1_usr
    report_2_usr
    report_3_usr
    And so forth...
    Up to now each form has had to include the url variable so the submit would take the user to the right download page and it has had to include a unique reference to the correct database column.
    Now I can echo or insert that url variable all over the place, including the reference to the column name in the transaction, so I can use a single instance of the form and include it on all pages.
    Thanks for helping me figure out the last step.

  • Setting Column Names in Dynamic Pivot Query

    Hi all,
    I'm having trouble setting column names in a dynamic pivot query and was wondering if someone could please help me figure out what I need to do.
    To help you help me, I've setup an example scenario in my hosted account. Here's the login info for my hosted site at [http://apex.oracle.com]
    Workspace: MYHOSTACCT
    Username : DEVUSER1
    Password : MYDEVACCTAnd, here is my test application info:
    ID     : 42804
    Name   : dynamic query test
    Page   : 1
    Table 1: PROJECT_LIST         (Alias = PL...  Listing of Projects)
    Table 2: FISCAL_YEAR          (Alias = FY...  Lookup table for Fiscal Years)
    Table 3: PROJECT_FY           (Alias = PF...  Intersection table containing project fiscal years)
    Table 4: PROJECT_FY_HEADCOUNT (Alias = PFH... Intersection table containing headcount per project and fiscal year)Please forgive the excessive normalization for this example, as I wanted to keep the table structure similar to my real application, which has much more going on.
    In my sample, I have the "Select Criteria" region, where the user specifies the project and fiscal year range that he or she would like to report. Click the Search button, and the report returns the project headcount in a pivoted fashion for the fiscal year range specified.
    I've got it working using a hard-coded query, which is displayed in the "Hardcoded Query" region. In this query, I basically return all years, and set conditions on each column which determines whether that column should be displayed or not based on the range selected by the user. While this works, it is not ideal, as there could be many more fiscal years to account for, and this is not very dynamic at all. Anytime a fiscal year is added to the FISCAL_YEAR table, I'd have to update this page.
    So, after reading all of the OTN SQL pivot forums and "Ask Tom" pivot thread, I've been able to create a second region labeled "Dynamic Query" in which I've created a dynamic query to return the same results. This is a much more savvy solution and works great; however, the column names are generic in the report.
    I had to set the query to parse at runtime since the column selection list is dynamic, which violates SQL rules. Can anyone please help me figure out how I can specify my column names in the dynamic query region to get the same column values I'm getting in the hardcoded region?
    Please let me know if you need anymore information, and many thanks in advance!
    Mark

    Hi Tony,
    Thanks so much for your response. I've had to study up on the dbms_sql package to understand your function... first time I've used it. I've fed my dynamic query to your function and see that it returns a colon delimited list of the column names; however, I think I need a little more schooling on how and where exactly to apply the function to actually set the column names in APEX.
    From my test app, here is the code for my dynamic query. I've got it in a "PL/SQL function body returning sql query" region:
    DECLARE 
      v_query      VARCHAR2(4000);
      v_as         VARCHAR2(4);
      v_range_from NUMBER;
      v_range_to   NUMBER;         
    BEGIN
      v_range_from := :P1_FY_FROM;
      v_range_to   := :P1_FY_TO;
      v_query      := 'SELECT ';
      -- build the dynamic column selections by looping through the fiscal year range.
      -- v_as is meant to specify the column name as (FY10, FY11, etc.), but it's not working.
      FOR i IN v_range_from.. v_range_to  LOOP
        v_as    := 'FY' || SUBSTR(i, 3, 4);
        v_query := v_query || 'MAX(DECODE(FY_NB,' || i || ',PFH_HEADCOUNT,0)) '
          || v_as || ',';
      END LOOP;
      -- add the rest of the query to the dynamic column selection
      v_query := rtrim(v_query,',') || ' FROM ('
        || 'SELECT FY_NB, PFH_HEADCOUNT FROM ('
        || 'SELECT FY_ID, FY_NB FROM FISCAL_YEAR) A '
        || 'LEFT OUTER JOIN ('
        || 'SELECT FY_ID, PFH_HEADCOUNT '
        || 'FROM PROJECT_FY_HEADCOUNT '
        || 'JOIN PROJECT_FY USING (PF_ID) '
        || 'WHERE PL_ID = ' || :P1_PROJECT || ') B '
        || 'ON A.FY_ID = B.FY_ID)';
      RETURN v_query;
    END;I need to invoke GET_QUERY_COLS(v_query) somewhere to get the column names, but I'm not sure where I need to call it and how to actually set the column names after getting the returned colon-delimited list.
    Can you (or anyone else) please help me get a little further? Once again, feel free to login to my host account to see it first hand.
    Thanks again!
    Mark

  • Not displaying column names in dynamic pages?

    I'd like to use a dynamic page as a detail page. In doing this I need a bit more freedom of design than what I now know is possible. Most important - I only need to print out the values returned by the SQL, not the column names as well. And I need to define the colors and fonts of the html table tags surrounding the returned values. How?
    It seems a bit strange that I am allowed to change the look and feel of the surrounding page elements through defining my own templates, and then have Oracle define how the elements placed in the templates are to appear.

    Hi,
    It is not possible to change the format the output coming from the <oracle> tags.
    Thanks,
    Sharmila

  • How to find column names in a table

    Am learning the basics of SQL Plus.
    Have entered the following query:
    SELECT * FROM t_ebb_session;
    This gives me the following output.
    USER_ID SESSION_ID LAST_ACCE
    However LAST_ACCE is not the full name of the column as I get 'Invalid column name when I use it in a select statement.
    How do I display the full name?

    By default, SQL*Plus will set the column display width of a character column to its size in the database, and the heading will be the column name in uppercase, truncated to fit that width if necessary. (There is a different rule for numeric columns.)
    You can override this with the COLUMN command, e.g:
    COLUMN some_column_name FORMAT a30 HEADING "Alternative Name"
    Check out the SQL*Plus documentation for all the COLUMN options.

  • How to use column name as variable in select statement

    hi,
    i want to make a sql query where in select statement using variable as a column name. but its not working plz guide me how can i do this.
    select :m1 from table1;
    regards

    Hi,
    Is this what you want..
    SQL> select &m1 from dept;
    Enter value for m1: deptno
    old   1: select &m1 from dept
    new   1: select deptno from dept
        DEPTNO
            10
            20
            30
            40
    SQL> select &m1 from dept;
    Enter value for m1: dname
    old   1: select &m1 from dept
    new   1: select dname from dept
    DNAME
    ACCOUNTING
    RESEARCH
    SALES
    OPERATIONS
    SQL> select &&m1 from dept;
    Enter value for m1: loc
    old   1: select &&m1 from dept
    new   1: select loc from dept
    LOC
    NEW YORK
    DALLAS
    CHICAGO
    BOSTON
    SQL> select &&m1 from dept;
    old   1: select &&m1 from dept
    new   1: select loc from dept
    LOC
    NEW YORK
    DALLAS
    CHICAGO
    BOSTONIf you use single '&' then each time you fire the query, It will ask for the new value..
    But if you will use double '&&' the value of m1 will be persistent across the session..
    Twinkle

  • How to pass column name in slect statement in query

    hi,
    i want to make a report where in query select statement using variable as a column name. but its not working plz guide me how can i do this.
    i have created a function which return column name through variable & that variable i want to to use in select statement
    select :m1 from table1;
    regards

    Hi,
    Create a user parameter (say P_field), and assign a valid field name as initial value (say NAME), And In the Query, write
    SELECT CODE, &P_field FN_FIELD FROM <table_name> WHERE <condition>And in the BEFORE PARAMETER FORM Trigger under the Report Triggers, write,
    function BeforePForm return boolean is
    begin
      :P_field := <your_function_call>;
      return (TRUE);
    end;And use that FN_FIELD field in the report.
    Hope this will clear your issue.
    Regards,
    Manu.

  • How to know column name (not an expression) used by function-based index?

    Hi guys,
    Is there any way to know exact column name used by FBI? If I correct, there is SYS.ICOLDEP$ table that has mapping between index/table columns, but I don't see how it could be uniquely joined with the rest. I know about USER_IND_EXPRESSIONS, but the task is to know exact column name, not it's expression.
    This required by our so-called SQL preprocessing of DB schema update utility, which parses stmt (INSERT in our case) and should check against PK/UNIQUE key values.
    Thanks!

    I don't think this is possible in 10g or 11g because :
    1. dictionary keeps track of column number in index and not in table
    2. the expression used in CREATE INDEX is a system generated column
    You would have to parse the expression from USER_IND_EXPRESSIONS:
    SQL> create table t(x int, y int);
    Table created.
    SQL> create index fbi on t(y+1);
    Index created.
    SQL> column index_name format a10
    SQL> column column_name format a20
    SQL> column column_expression format a10
    SQL> select i.index_name, ic.column_name, ic.column_position as iccn, ie.column_position as iecn, ie.column_expression
      2  from user_indexes i , user_ind_columns ic, user_ind_expressions ie
      3  where i.index_name = ic.index_name
      4  and i.index_name = ie.index_name
      5  and i.index_name =  'FBI';
    INDEX_NAME COLUMN_NAME                ICCN       IECN COLUMN_EXP
    FBI        SYS_NC00003$                  1          1 "Y"+1

Maybe you are looking for