Translation

The oldest posts, are written in Italian. If you are interested and you want read the post in English, please use Google Translator. You can find it on the right side. If the translation is wrong, please email me: I'll try to translate for you.

lunedì, settembre 11, 2017

Using XML 09: SELECT, Part 3b/3

In the previous post I saw that the XQuery_string '/alertlog' return just one row. So my question is "what if I change the row-pattern from '/alertlog' to /alertlog/msg or /alertlog/msg/txt"?

Here the answere

XQuery_string: /alertlog/msg


As you can see, in this case there will be 6 rows: one for each element. And this is exactly what I want

SQL> SELECT rownum, t.*, tx.* from mytab t, 
  2> XMLTable('/alertlog/msg' PASSING t.XML_COLUMN) tx








XQuery_string: /alertlog/msg/txt


Also in this case I have 6 rows. But here I have only the <txt> element (it was my request)

SQL> SELECT rownum, t.*, tx.* from mytab t, 
  2> XMLTable('/alertlog/msg/txt' PASSING t.XML_COLUMN) tx


I skip the output between line 2 and 5.



XQuery_string: more examples


Here other two example: similar to the previous posts

SQL> SELECT rownum, t.*, tx.* from mytab t, 
  2> XMLTable('/alertlog/msg/[@pid="65370"]' PASSING t.XML_COLUMN) tx



SQL> SELECT rownum, t.*, tx.* from mytab t, 
  2> XMLTable('/alertlog/msg/[@pid="65263"]' PASSING t.XML_COLUMN) tx





and if I modify the search

SQL> SELECT rownum, t.*, tx.* from mytab t, 
  2> XMLTable('/alertlog/msg/[@pid="65370"]/txt' PASSING t.XML_COLUMN) tx



Part08 Index Part10

Using XML 08: SELECT, Part 3a/3

Continune from previous post

XMLTable [4]

XMLTable decompose the result of an XQuery evaluation into relational rows and columns. Or: the XMLTABLE operator allows us to split the XML data into rows and project columns on to it [13]. You can query the result returned by the function as a virtual relational table using SQL.

XMLTABLE (<XQuery_string> <XMLTABLE_options>)
  |- <XMLTABLE_options>   => <XML_passing_clause> [COLUMNS <XML_table_colums>]
  |- <XML_passing_clause> => PASSING <expr> [AS <identifier>]
  |- <XML_table_colums>   => <column> [<datatype>|XMLTYPE] [PATH <string>] [DEFAULT <expr>]

where [4][5]
  • <XQuery_string> is a literal string. XQuery_string is sometimes called the row pattern of the XMLTable call. It is a complete XQuery expression. The value of XQuery_string serves as input to the XMLTable function; it is this XQuery result that is decomposed and stored as relational data.
  • The <expr> in the XML_passing_clause is an expression returning an XMLType or an instance of a SQL scalar data type (that is, not an object or collection data type) that is used as the context for evaluating the XQuery expression. You can specify only one expr in the PASSING clause without an identifier. Each expression expr can be a table or view column value, a PL/SQL variable, or a bind variables with proper casting. The result of evaluating each expr is bound to the corresponding identifier in the XQuery_string. If any expr that is not followed by an AS clause, then the result of evaluating that expression is used as the context item for evaluating the XQuery_string
  • The optional COLUMNS clause defines the columns of the virtual table to be created by XMLTable. If you omit the COLUMNS clause, then XMLTable returns a row with a single XMLType pseudocolumn named COLUMN_VALUE. For each resulting column you must specify the column data type, which can be XMLType or any other data type. If the column data type is XMLType, then specify the XMLTYPE clause.
  • If you omit PATH, then the XQuery expression column is assumed. For example:
          XMLTable(... COLUMNS xyz)
              is equivalent to
                XMLTable(... COLUMNS xyz PATH 'XYZ')
                  You can use different PATH clauses to split the XQuery result into different virtual-table columns.


        In a more simple way

        XMLTABLE (<row-pattern> 
                  PASSING <XMLType>
                  COLUMNS <column_name> <datatype> PATH <string>) 


        Ok. Let's start

        The row-pattern is '/alertlog'; the PASSING clause is......well, I try "SELECT * FROM MYTAB" (because Each expression expr can be a table or view column value)

        SQL> SELECT * FROM XMLTable('/alertlog' PASSING (select * from mytab))



        SQL> SELECT * FROM XMLTable('/alertlog' PASSING (select KEY_COLUMN, XML_COLUMN from mytab))

        De

        Ok. <exp> can be a table or view column name, but it must return an XML or an instance of a SQL scalar data type. So I have to try something simple. Because MYTAB table is


        I specify just the MYTAB.XML_COLUMN column

        SQL> SELECT * FROM XMLTable('/alertlog' PASSING (select XML_COLUMN from mytab))



        Remember that if you omit the COLUMNS clause, then XMLTable returns a row with a single XMLType pseudocolumn named COLUMN_VALUE.

        I want to know how many rows are returned, so I use thr ROWNUM pseudo column

        SQL> col COLUMN_VALUE for a60
        SQL> SELECT rownum, t.*
        SQL> FROM XMLTable('/alertlog' PASSING (select XML_COLUMN from mytab)) t



        Perfect. Now because I want all columns of MYTAB, the only way I have in my mind is to join the XMLTable with MYTAB, but I'not  not sure: I try

        SQL> SELECT tk.key_column, tx.*
        SQL> FROM XMLTable('/alertlog' PASSING (select XML_COULMN from mytab)) tx, mytab t;



        I tried to use the the new syntax in Oracle: the "JOIN" clause. See the Appendix section at the end of this post.

        In the previous SELECT, I specified "tk.key_column" and "tx.xml_column". I would like not specify the columns, so I change previous statement just aa little

        SQL> SELECT * FROM XMLTable('/alertlog' PASSING t.XML_COLUMN) tx, mytab t



        I want to try a stupid thing: I want to change the order between XMLTable and MYTAB. Why? Because in the exception ORA-00904, Oracle told me that the "T.XML_COLUMN" is an invalid identifier. It's strange, because I specified the "T" table just after the comma in the FROM clause.

         SQL> SELECT * FROM mytab t, XMLTable('/alertlog' PASSING t.XML_COLUMN) tx 


        Great, but I want to show also the row numebr

         SQL> SELECT rownum, t.*, tx.*
         SQL> FROM mytab t, XMLTable('/alertlog' PASSING t.XML_COLUMN) tx 



        As usual, one row is returned.

        What if I change the XQuery_string/row-pattern, from /alertlog to /alertlog/msg?

        (to be continued)




        Appendix

        If I use the JOIN syntax I had following error


        It's new for me. The problem is the absence of ON clause. In fact if I use it with the condition "1=1", then it works



        It non depend on the join that include the XMLTable: the ON condition is mandatory for the syntax. Well, as I told before, it's the first time I incurred in the errore. This is because I always used the ON.

        Update

        2017/Sep/11 - Update the Reference section adding [13] and [14]

        References

        [1] https://docs.oracle.com/database/122/SQLRF/EXTRACT-XML.htm#SQLRF00640
        [2] https://docs.oracle.com/database/122/SQLRF/EXTRACTVALUE.htm#SQLRF06173
        [3] https://docs.oracle.com/database/122/SQLRF/XMLQUERY.htm#SQLRF06209
        [4] https://docs.oracle.com/database/122/SQLRF/XMLTABLE.htm#SQLRF06232
        [5] https://docs.oracle.com/cd/E11882_01/appdev.112/e23094/xdb_xquery.htm#ADXDB5121
        [6] http://allthingsoracle.com/xquery-for-absolute-beginners-part-1-xpath/
        [7] http://allthingsoracle.com/xquery-for-absolute-beginners-part-2-xquery-and-the-oracle-database/
        [8] https://www.youtube.com/watch?v=n_dEb6myFH4
        [9] https://www.youtube.com/watch?v=5d4fZVxFx20
        [10] Pro Oracle SQL, pag 481 written by Morton, Osborne, Shamsudeen [Apress]
        [11] http://www.ateam-oracle.com/using-xmltable-and-xmltype-to-extract-html-clob-data/
        [12] http://www.oradev.com/xml_functions.html
        [13] https://oracle-base.com/articles/misc/xmltable-convert-xml-data-into-rows-and-columns-using-sql
        [14] XMLTable (PDF)


        Part07 Index Part09

        giovedì, agosto 31, 2017

        Using XML 07: SELECT, Part 2/3

        Because the EXTRACT [1] and EXTRACTVALUE [2] functions are deprecated in 11gR2 [10], you have to use the XMLQuery [3] and XMLTable [4] (respectively).

        XMLQuery [1]

        XMLQUERY lets you query XML data in SQL statements. It takes an XQuery expression as a string literal, an optional context item, and other bind variables and returns the result of evaluating the XQuery expression.

        The more simple syntax is

        XMLQuery(XQuery_string PASSING expr RETURNING CONTENT)

        where [1]

        • XQuery_string is a complete XQuery expression, including prolog
        • The expr is an expression returning an XMLType or an instance of a SQL scalar data type that is used as the context for evaluating the XQuery expression. 
        • RETURNING CONTENT indicates that the result from the XQuery evaluation is either an XML 1.0 document or a document fragment conforming to the XML 1.0 semantics.
        or in simple words
        • XMLQueryis the search path
        • "expr" is the XML column of the table 
        Here there are 3 examples, so you can compare the output, with the one of EXTRACT function provided in the previous post

        SQL> SELECT rownum, t.*, 
          2> XMLQuery('/alertlog' PASSING t.XML_COLUMN  RETURNING CONTENT) extract FROM mytab t



        SQL> SELECT rownum, t.*, 
          2> XMLQuery('/alertlog/msg' PASSING t.XML_COLUMN  RETURNING CONTENT) extract FROM mytab t



        SQL> SELECT rownum, t.*,
          2> XMLQuery('/alertlog/msg/txt' PASSING t.XML_COLUMN  RETURNING CONTENT) extract FROM mytab t



        Here other two examples



        As you can see, also if there is a little difference in the syntax between XMLQuery and EXTRACT function, the outptu is the same. The XMLQuery function returns the TAGs. The same thing of the EXTRACT function.

        In the next post XMLTable


        References
        [1] https://docs.oracle.com/database/122/SQLRF/EXTRACT-XML.htm#SQLRF00640
        [2] https://docs.oracle.com/database/122/SQLRF/EXTRACTVALUE.htm#SQLRF06173
        [3] https://docs.oracle.com/database/122/SQLRF/XMLQUERY.htm#SQLRF06209
        [4] https://docs.oracle.com/database/122/SQLRF/XMLTABLE.htm#SQLRF06232
        [5] http://allthingsoracle.com/xquery-for-absolute-beginners-part-1-xpath/
        [6] http://allthingsoracle.com/xquery-for-absolute-beginners-part-2-xquery-and-the-oracle-database/
        [7] https://www.youtube.com/watch?v=n_dEb6myFH4
        [8] https://www.youtube.com/watch?v=5d4fZVxFx20
        [9] Pro Oracle SQL, pag 481 written by Morton, Osborne, Shamsudeen [Apress]
        [10] http://www.oracle.com/technetwork/database/features/xmldb/xmlqueryoptimize11gr2-168036.pdf (PDF)

        mercoledì, agosto 30, 2017

        Using XML 06: SELECT, Part 1/3

        In the last two posts [3][4], I was shown how to insert a record (an XML document) in an XML column. Here I want to show how to select data inside an XML column

        In order to SELECT data, you have to use some functions. Two of these are EXTRACT [1] and EXTRACTVALUE [2]

        EXTRACT [1]

        It applies to a VARCHAR2 XPath string and returns an XMLType instance containing an XML fragment. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial slash, the context of the relative path defaults to the root node.

        EXTRACT (<XMLType_instance>, <XPATH_string>)

        I start using just EXTRACT(XML_COLUMN, '/alertlog')


        The result is the entire XML content. This is because I chosen the root node. So, what I expect if I use EXTRACT(XML_COLUMN, '/alertlog/msg') is the EXTRACT column without the root node. And in fact:


        A similar things I expect if I use EXTRACT(XML_COLUMN, '/alertlog/msg/txt'). I mean, the output should be only the "txt" element.


        In all cases, only one row is returned (yes there is one row in the table).


        EXTRACTVALUE [2]

        The EXTRACTVALUE function takes as arguments an XMLType instance and an XPath expression and returns a scalar value of the resultant node. The result must be a single node and be either a text node, attribute, or element. If the result is an element, then the element must have a single text node as its child, and it is this value that the function returns. You can specify an absolute XPath_string with an initial slash or a relative XPath_string by omitting the initial slash. If you omit the initial slash, the context of the relative path defaults to the root node.

        EXTRACTVALUE (<XMLType_instance>, <XPATH_string>)


        I have to follow the manual above: The result must be a single node and be either a text node, attribute, or element. If the result is an element, then the element must have a single text node as its child, and it is this value that the function returns. This is why I had previous exception. If I specify just an element, then...


        Also this, is a valid statement


        As you see in this case, only onw row is returned. Anyway, the documentation says:

        The EXTRACT (XML) function is deprecated. It is still supported for backward compatibility. However, Oracle recommends that you use the XMLQUERY function instead. See XMLQUERY for more information [1]

        The EXTRACTVALUE function is deprecated. It is still supported for backward compatibility. However, Oracle recommends that you use the XMLTABLE function, or the XMLCAST and XMLQUERY functions instead. See XMLTABLE, XMLCAST, and XMLQUERY for more information [2]

        In the next post. we see how to use the XMLQuery function in order to obtain the same result

        References

        [1] https://docs.oracle.com/database/122/SQLRF/EXTRACT-XML.htm#SQLRF00640
        [2] https://docs.oracle.com/database/122/SQLRF/EXTRACTVALUE.htm#SQLRF06173
        [3] https://orasal.blogspot.it/2017/08/using-xml-04-insert-into-table.html
        [4] https://orasal.blogspot.it/2017/08/using-xml-04-insert-into-table-part-22.html

        Part05 Index Part07

        martedì, agosto 29, 2017

        Using XML 05: INSERT into table, Part 2/2

        In the last post, I tried to insert an extract of the alertlog.xml into an XML column

        INSERT INTO mytab VALUES (1, XMLType(bfilename('MYXMLDIR', 'mylog.xml'), nls_charset_id('AL32UTF8')));

        and I had the following exception

        ERROR at line 1:
        ORA-31061: XDB error: XML event error
        ORA-19202: Error occurred in XML processing
        In line 1 of orastream:
        LPX-00225: end-element tag "txt" does not match start-element tag ""

        Really I aspected this error, because I'm not sure if my "tail" command created a "well formed" XML alert log file. So I have to check it.


        Here you see that the extract of the alertlog.xml begin with two closed TAG "</txt>" and "</msg>", so I have to remove those first two lines and then reinsert my log file. This is how the file starts after the modifications:


        Now I can do a new insert


        Ouch! Another error: LPX-00245. If I check the contents of the log.xml....


        ...there is a TAG </msg>", but it appears more times, so it isn't a root node. I have to add a root TAG as the first and last line. I choose "<alertlog></alertlog>" TAG


        At this point, I expect that my log.xml file is well formed and that the new insert should be OK.


        Yessss. I inserted my first XML row. Now I want to see what there is in this column


        Only the first character are shown. This is because the XML is managed by SQL*Plus as a LONG type, so I have to modify the "long" settings


        (Some output was deleted)



        Conclusions (until now)

        1. The insert of an XML document into an XML column will insert just one row.
        2. The XML type check automatically if the XML document is well formed [1]

        References

        [1] https://docs.oracle.com/cd/B19306_01/appdev.102/b14259/xdb01int.htm#BABCCCJI

        Part 04 Index Part06

        lunedì, agosto 28, 2017

        Using XML 04: INSERT into table, Part 1/2

        What I want to do in this post is to try to insert an XML document into a table. Because in Oracle 11g+ there is an XML version of the alert.log, I take just some lines from it and save the output in a file. I save the new file in the /tmp/mylog.xml file.


        Now I create a table with just two columns. One will be the primary key, the other one will be an XML column type


         I run a very simple insert, trying to put the "this-is-a-test" string in the XML column.


        The exception LPX-00210 is what exactly I expect: if you remember, a "well formed" XML document, must begin with angular parentheses (<).

        In order to insert the XML content of the "mylog.log" file into MYTAB table, what I have really to do, is to run the following statement:

        INSERT INTO mytab
        VALUES (1, XMLType(bfilename('MYXMLDIR', 'mylog.xml'), nls_charset_id('AL32UTF8')));

        Because of this, I have to introduce "XMLType" and "bfilename" first.

        BFILENAME [1]

        BFILENAME ('<oracle_directory>', '<filename>')

        BFILENAME returns a BFILE locator that is associated with a physical LOB binary file on the server file system.
        'oracle_directory' is a database object that serves as an alias for a full path name on the server file system where the files are actually located. 'filename' is the name of the file in the server file system.

        You must create the directory object and associate a BFILE value with a physical file before you can use them as arguments to BFILENAME in a SQL or PL/SQL statement.

        Defining XMLType Tables and Columns [2][3][5]

        You can use a simple INSERT operation in SQL or PL/SQL to load an XML document into the database. Before the document can be stored as an XMLType column or table, you must convert it into an XMLType instance using one of the XMLType constructors.

        XMLType constructors allow an XMLType instance to be created from different sources, including VARCHAR, CLOB, and BFILE values.

        You can use XMLType as you would any other SQL data type. For example, you can create an XMLType table or view, or an XMLType column in a relational table.

        You can use XMLType in PL/SQL stored procedures for parameters, return values, and variables. XMLType is an Oracle Database object type, so you can also create a table of XMLType object instances.

        By default, an XMLType table or column can contain any well-formed XML document XMLType is an abstract data type that provides different storage models to best fit your data and your use of it. 

        XMLType tables and columns can be stored in these ways (there are two possibilities):

        • The table is relational, with an XMLType column and a non-XMLType column.
        • The table is of data type XMLType.

        http://docs.oracle.com/database/122/ADXDB/how-to-use-XML-DB.htm#ADXDB6338

        This section describe an XMLType constructor [4]:

        constructor function XMLType(
           xmlData    IN clob
         , schema     IN varchar2 := NULL
         , validated  IN number   := 0
         , wellformed IN number   := 0
        )
        return self as result deterministic;

        constructor function XMLType(
           xmlData    IN varchar2
         , schema     IN varchar2 := NULL
         , validated  IN number   := 0
         , wellformed IN number   := 0
        )
        return self as result deterministic;

        constructor function XMLType(
           xmlData    IN blob
         , csid       IN number   /* The character set id of input XML data */
         , schema     IN varchar2 := NULL
         , validated  IN number   := 0
         , wellformed IN number   := 0
        )
        return self as result deterministic;

        constructor function XMLType(
           xmlData    IN bfile
         , csid       IN number   /* The character set id of input XML data */
         , schema     IN varchar2 := NULL
         , validated  IN number   := 0
         , wellformed IN number   := 0
        )
        return self as result deterministic;

        How you can see, XMLType constructor accept as the first parameter a CLOB, a VARCHAR2, a BinaryLOB or BinaryFILE. This is why you read above.

        XMLType constructors allow an XMLType instance to be created from different sources, including VARCHAR, CLOB, and BFILE values.

        Also, if you pass to the constructor a BLOB or a BFILE, you must specify the CHARACTER_SET (csid value). But if you are using a CLOB or VARCHAR2, you haven't specify this. I suppose that this is because in case of "CHARACTER", the right set is derived directly from da database NLS_CHARCTER_SET parameter.

        So I can write (in the more simple form, that is, passing the first two parameters):

        XMLType (xmlData IN blob, csid IN number)

        where (I'm using the AL32UTF8 CHARACTER_SET in my DBs)

        xmlData ::= BFILENAME ('<oracle_directory>', '<filename>') (see BFILENAME above)
        csid    ::= NLS_CHARSET_ID('AL32UTF8')

        I can rewrite the XMLType like this

        XMLType (BFILENAME ('<oracle_directory>', '<filename>'), NLS_CHARSET_ID ('AL32UTF8'))

        At this point, I'm ready to insert my alert log file in MYTAB table. First I create the Oracle directory


        then I populate the table


        Should I expect the LPX-00225 exception? Maybe yes.

        (To be continued)

        References
        [1] https://docs.oracle.com/database/122/SQLRF/BFILENAME.htm#SQLRF00610
        [2] http://docs.oracle.com/database/122/ADXDB/how-to-use-XML-DB.htm#ADXDB4049
        [3] http://docs.oracle.com/database/122/ADXDB/how-to-use-XML-DB.htm#ADXDB6338
        [4] https://docs.oracle.com/database/122/ARPLS/XMLTYPE.htm#ARPLS71992
        [5] https://docs.oracle.com/cd/B19306_01/appdev.102/b14259/xdb01int.htm#BABCCCJI

        Part03 Index Part05