In this post we are going to cover XML in Snowflake: PARSE_XML to turn text into a document, CHECK_XML to find out whether it will, and XMLGET to read inside it.
XML works the way JSON did in this level. The text sits in an ordinary VARCHAR column, a function parses it, and from then on you reach into it with accessors. The functions have different names and there is one fewer of them than you expect.
This is the last post of Level 8. It is also the one the author got wrong the first time round, on the belief that PARSE_XML returns NULL for a bad document. It does not. That mistake is in here too, because what actually happens is more useful than the guess.
We will start with four documents in a text column and build it up step by step.
Episode 96 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's parse all four documents
- So what exactly does PARSE_XML refuse?
- Is there a CHECK_XML?
- Now let's look for TRY_PARSE_XML
- One warning about CHECK_XML first
- Now let's write the guard, and watch where we put it
- Let's parse the good ones and read the root tag
- Now let's reach inside with XMLGET
- Now let's read the attributes
- What happens if we use the wrong accessor?
- Now the one that will actually bite you: no index means index 0
- And the other half: an empty element is not a missing one
- Let's flatten the children into rows
- Now let's load it properly, keeping the bad row
- So how does XML compare with JSON?
- One last thing: what Level 8 leaves behind
Let's create some sample data
We need a few documents to work on, and one of them has to be broken, because half of this post is about what Snowflake does with a broken one.
Copy this into a Snowflake worksheet and run it once.
-- Sample data for this post. Four XML documents in an ordinary text column.
-- Three of them are well formed. The fourth closes the wrong tag, and it is
-- there on purpose.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE DOCS_XML (
DOC_ID INT,
WHAT_IT_IS VARCHAR,
RAW_XML VARCHAR
);
INSERT INTO DOCS_XML VALUES
(1, 'two children',
'<order id="1001"><customer>Northwind Traders</customer>'
|| '<item sku="A-100"><qty>8</qty></item>'
|| '<item sku="B-220"><qty>4</qty></item></order>'),
(2, 'attributes and text',
'<order id="1002" status="SHIPPED">'
|| '<customer country="USA">Blue Ridge Supply</customer>'
|| '<item sku="C-310"><qty>3</qty></item></order>'),
(3, 'repeated and empty tags',
'<order id="1003"><customer>Kestrel Analytics</customer>'
|| '<note/><tag>priority</tag><tag>repeat</tag></order>'),
(4, 'not well formed',
'<order id="1004"><customer>Harbour Foods</order>');Now let's look at what we just created.
SELECT * FROM DOCS_XML ORDER BY DOC_ID;| DOC_ID | WHAT_IT_IS | RAW_XML |
|---|---|---|
| 1 | two children | <order id="1001"><customer>Northwind Traders</customer><item sku="A-100"><qty>8</qty></item><item sku="B-220"><qty>4</qty></item></order> |
| 2 | attributes and text | <order id="1002" status="SHIPPED"><customer country="USA">Blue Ridge Supply</customer><item sku="C-310"><qty>3</qty></item></order> |
| 3 | repeated and empty tags | <order id="1003"><customer>Kestrel Analytics</customer><note/><tag>priority</tag><tag>repeat</tag></order> |
| 4 | not well formed | <order id="1004"><customer>Harbour Foods</order> |
Four documents. The first has two children of the same name. The second has attributes on the root and on a child, and some text. The third has a repeated tag and an empty one. The fourth opens a customer element and then closes order, so it is not well formed.
And let's be clear that the column really is text, not some XML type that has done work for us already.
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'DOCS_XML'
ORDER BY ORDINAL_POSITION;| COLUMN_NAME | DATA_TYPE |
|---|---|
| DOC_ID | NUMBER |
| WHAT_IT_IS | TEXT |
| RAW_XML | TEXT |
NUMBER and then two TEXT columns. Nothing has been parsed yet.
Let's parse all four documents
The obvious first query. Parse the column over the whole table.
SELECT DOC_ID, PARSE_XML(RAW_XML) AS SHOULD_NOT_GET_THIS_FAR
FROM DOCS_XML
ORDER BY DOC_ID;100100 (22P02): Error parsing XML: missing closing tags: </customer>, pos 48
Error parsing XML: missing closing tags: </customer>, pos 48.
This is the bit worth slowing down for. We did not get three documents and a NULL. We got no rows at all. One bad document in the column, and the whole statement failed.
PARSE_XML raises, exactly like PARSE_JSON in Episode 87. Here is PARSE_JSON on a broken piece of JSON for comparison, so you can see the same shape of refusal.
SELECT PARSE_JSON('{"a":') AS SHOULD_NOT_GET_THIS_FAR;100069 (22P02): Error parsing JSON: incomplete object value, pos 6
That capture's name says the opposite of what this post has just shown you, and the reason is in the introduction: the demo script was written on the belief that PARSE_XML returns NULL. The query under the name only runs PARSE_JSON, which does raise, so that is all it is being used for here.
Let's count what the failure cost us.
SELECT COUNT(*) AS ROWS_IN_TABLE,
COUNT_IF(CHECK_XML(RAW_XML) IS NULL) AS WELL_FORMED,
COUNT_IF(CHECK_XML(RAW_XML) IS NOT NULL) AS NOT_WELL_FORMED,
COUNT_IF(CHECK_XML(RAW_XML) IS NULL) AS ROWS_YOU_COULD_HAVE_HAD
FROM DOCS_XML;| ROWS_IN_TABLE | WELL_FORMED | NOT_WELL_FORMED | ROWS_YOU_COULD_HAVE_HAD |
|---|---|---|---|
| 4 | 3 | 1 | 3 |
Four rows in the table, three of them well formed. Three rows we could have had, and we got none of them.
So what exactly does PARSE_XML refuse?
Three faults, three different messages. First an unclosed tag.
SELECT PARSE_XML('<a><b>unclosed</a>') AS SHOULD_NOT_GET_THIS_FAR;100100 (22P02): Error parsing XML: missing closing tags: </b>, pos 18
It names the tag it wanted and the position it gave up at.
Now text with no root element at all.
SELECT PARSE_XML('just some text') AS SHOULD_NOT_GET_THIS_FAR;100100 (22P02): Error parsing XML: not an XML element, pos 1
Not an XML element, pos 1. It did not get as far as the first character being useful.
And now two root elements in one string.
SELECT PARSE_XML('<a>1</a><b>2</b>') AS SHOULD_NOT_GET_THIS_FAR;100100 (22P02): Error parsing XML: more than one document in the input
More than one document in the input. One string, one document. Good messages, all three of them, which raises the obvious question.
Is there a CHECK_XML?
JSON had three functions: PARSE_JSON, TRY_PARSE_JSON and CHECK_JSON. Let's find out which of those XML has, starting with the checker.
SELECT CHECK_XML('<a><b>unclosed</a>') AS SHOULD_NOT_GET_THIS_FAR;| SHOULD_NOT_GET_THIS_FAR |
|---|
| missing closing tags: </b>, pos 18 |
It exists, and it hands back the complaint as a string rather than raising. Same message as the error pane above, only now it is a value we can use.
The column heading on that grid says SHOULD_NOT_GET_THIS_FAR, which is left over from the first version of the demo script, where every probe was expected to fail. This one does not fail. Read the heading as the author's old guess and the value under it as the answer.
Let's put it over every row of the table, which is the way you would actually use it.
SELECT DOC_ID, WHAT_IT_IS,
CHECK_XML(RAW_XML) AS THE_COMPLAINT,
CHECK_XML(RAW_XML) IS NULL AS IT_IS_WELL_FORMED,
LENGTH(RAW_XML) AS TEXT_LENGTH
FROM DOCS_XML
ORDER BY DOC_ID;| DOC_ID | WHAT_IT_IS | THE_COMPLAINT | IT_IS_WELL_FORMED | TEXT_LENGTH |
|---|---|---|---|---|
| 1 | two children | NULL | TRUE | 137 |
| 2 | attributes and text | NULL | TRUE | 131 |
| 3 | repeated and empty tags | NULL | TRUE | 106 |
| 4 | not well formed | missing closing tags: </customer>, pos 48 | FALSE | 48 |
One complaint in four documents. IT_IS_WELL_FORMED is TRUE, TRUE, TRUE, FALSE, and the bad row carries its position. Have a look at the last column while you are there: the position the parser gave up at is the whole length of document 4, because the document ends before the tag it was waiting for.
Notice the shape of the answer. CHECK_XML returns NULL when the document is fine. No news is good news, so the test for a good document is IS NULL.
Now let's look for TRY_PARSE_XML
CHECK_XML tells us whether a document is parseable. What we actually want is the one that parses it or gives us a NULL, the way TRY_PARSE_JSON does.
SELECT TRY_PARSE_XML('<a><b>unclosed</a>') AS SHOULD_NOT_GET_THIS_FAR;002139 (02000): SQL compilation error: Unknown function TRY_PARSE_XML.
Unknown function TRY_PARSE_XML. It does not exist. So let's try the other way of asking, a TRY_CAST.
SELECT TRY_CAST('<a><b>unclosed</a>' AS XML) AS SHOULD_NOT_GET_THIS_FAR;002040 (42601): SQL compilation error: Unsupported data type 'XML'.
Unsupported data type 'XML'. Also no. There is no parse-or-NULL form of this function anywhere.
Let's see the two families side by side, because this is the fact to take away from the post.
SELECT CHECK_JSON('{"a":') AS CHECK_JSON_DESCRIBES,
TRY_PARSE_JSON('{"a":') IS NULL AS TRY_PARSE_JSON_GIVES_NULL,
CHECK_XML('<a><b>1</a>') AS CHECK_XML_DESCRIBES,
CHECK_XML('<a><b>1</a>') IS NOT NULL AS XML_FAULT_IS_DESCRIBABLE,
CHECK_JSON('{"a":1}') IS NULL AS GOOD_JSON_IS_QUIET,
CHECK_XML('<a>1</a>') IS NULL AS GOOD_XML_IS_QUIET;| CHECK_JSON_DESCRIBES | TRY_PARSE_JSON_GIVES_NULL | CHECK_XML_DESCRIBES | XML_FAULT_IS_DESCRIBABLE | GOOD_JSON_IS_QUIET | GOOD_XML_IS_QUIET |
|---|---|---|---|---|---|
| incomplete object value, pos 6 | TRUE | missing closing tags: </b>, pos 11 | TRUE | TRUE | TRUE |
Both checkers describe their fault with a position. Both are quiet on good input. The difference is the middle column: TRY_PARSE_JSON gives a NULL, and XML has no equivalent at all.
| What you want | JSON | XML |
|---|---|---|
| Parse it, raise on bad input | PARSE_JSON | PARSE_XML |
Parse it, NULL on bad input | TRY_PARSE_JSON | nothing |
| Describe the fault | CHECK_JSON | CHECK_XML |
JSON has three tools and XML has two. The guard in the middle row is yours to write.
Here is what writing it yourself looks like next to the one-expression JSON version.
SELECT TRY_PARSE_JSON('{"a":1}') AS JSON_ONE_EXPRESSION,
TRY_PARSE_JSON('{"a":') AS JSON_BAD_IS_NULL,
CASE WHEN CHECK_XML('<a>1</a>') IS NULL
THEN PARSE_XML('<a>1</a>') END AS XML_TWO_EXPRESSIONS,
CASE WHEN CHECK_XML('<a><b>1</a>') IS NULL
THEN PARSE_XML('<a><b>1</a>') END AS XML_BAD_IS_NULL;| JSON_ONE_EXPRESSION | JSON_BAD_IS_NULL | XML_TWO_EXPRESSIONS | XML_BAD_IS_NULL |
|---|---|---|---|
| { "a": 1 } | NULL | <a>1</a> | NULL |
One expression on the JSON side, two on the XML side, and the bad input ends as a NULL either way. The XML version has to name the document twice, once in the check and once in the parse.
One warning about CHECK_XML first
Before we build the guard on it, we should find out what CHECK_XML says about input that is not really a document at all.
SELECT CHECK_XML('') IS NULL AS EMPTY_CALLED_VALID,
CHECK_XML('') AS EMPTY_COMPLAINT,
CHECK_XML(NULL::VARCHAR) IS NULL AS NULL_CALLED_VALID,
CHECK_XML(' ') IS NULL AS SPACES_CALLED_VALID,
CHECK_XML(' ') AS SPACES_COMPLAINT,
CHECK_JSON('') IS NULL AS JSON_SAYS_EMPTY_IS_VALID;| EMPTY_CALLED_VALID | EMPTY_COMPLAINT | NULL_CALLED_VALID | SPACES_CALLED_VALID | SPACES_COMPLAINT | JSON_SAYS_EMPTY_IS_VALID |
|---|---|---|---|---|---|
| TRUE | NULL | TRUE | TRUE | NULL | TRUE |
An empty string is called valid. A SQL NULL is called valid. A string of spaces is called valid. And the last column says CHECK_JSON does the same thing with an empty string.
CHECK_XML answers is this well formed, not is there a document here. Those are two different questions and only one of them is being asked. If a blank row has to be a problem in your pipeline, test for it yourself.
Now let's write the guard, and watch where we put it
The guard is CHECK_XML(RAW_XML) IS NULL. The obvious place for it is the WHERE clause, so let's start there.
SELECT DOC_ID, WHAT_IT_IS,
PARSE_XML(RAW_XML) AS PARSED,
TYPEOF(PARSE_XML(RAW_XML)) AS ITS_TYPE
FROM DOCS_XML
WHERE CHECK_XML(RAW_XML) IS NULL
ORDER BY DOC_ID;| DOC_ID | WHAT_IT_IS | PARSED | ITS_TYPE |
|---|---|---|---|
| 1 | two children | <order id="1001"> <customer>Northwind Traders</customer> <item sku="A-100"> <qty>8</qty> </item> <item sku="B-220"> <qty>4</qty> </item> </order> | XML |
| 2 | attributes and text | <order id="1002" status="SHIPPED"> <customer country="USA">Blue Ridge Supply</customer> <item sku="C-310"> <qty>3</qty> </item> </order> | XML |
| 3 | repeated and empty tags | <order id="1003"> <customer>Kestrel Analytics</customer> <note></note> <tag>priority</tag> <tag>repeat</tag> </order> | XML |
Three rows, all parsed, all of type XML. The statement runs now. But look at what we have: the broken document is gone, and nothing on this result says it ever existed.
Now the same guard written as a CASE expression in the select list instead.
SELECT DOC_ID, WHAT_IT_IS,
CASE WHEN CHECK_XML(RAW_XML) IS NULL THEN PARSE_XML(RAW_XML) END
AS PARSED_OR_NULL,
CASE WHEN CHECK_XML(RAW_XML) IS NULL THEN 'parsed'
ELSE 'REJECTED: ' || CHECK_XML(RAW_XML) END AS WHAT_HAPPENED
FROM DOCS_XML
ORDER BY DOC_ID;| DOC_ID | WHAT_IT_IS | PARSED_OR_NULL | WHAT_HAPPENED |
|---|---|---|---|
| 1 | two children | <order id="1001"> <customer>Northwind Traders</customer> <item sku="A-100"> <qty>8</qty> </item> <item sku="B-220"> <qty>4</qty> </item> </order> | parsed |
| 2 | attributes and text | <order id="1002" status="SHIPPED"> <customer country="USA">Blue Ridge Supply</customer> <item sku="C-310"> <qty>3</qty> </item> </order> | parsed |
| 3 | repeated and empty tags | <order id="1003"> <customer>Kestrel Analytics</customer> <note></note> <tag>priority</tag> <tag>repeat</tag> </order> | parsed |
| 4 | not well formed | NULL | REJECTED: missing closing tags: </customer>, pos 48 |
Four rows. The broken one is still here, its parsed value is NULL, and the last column carries the reason why. That is the only form that lets you report on what failed.
Let's count the difference rather than eyeball it.
SELECT (SELECT COUNT(*) FROM DOCS_XML) AS DOCUMENTS_IN,
(SELECT COUNT(*) FROM DOCS_XML WHERE CHECK_XML(RAW_XML) IS NULL)
AS WHERE_FORM_KEEPS,
(SELECT COUNT(*) FROM DOCS_XML) AS CASE_FORM_KEEPS,
(SELECT COUNT(*) FROM DOCS_XML)
- (SELECT COUNT(*) FROM DOCS_XML WHERE CHECK_XML(RAW_XML) IS NULL)
AS WHAT_THE_WHERE_DROPPED;| DOCUMENTS_IN | WHERE_FORM_KEEPS | CASE_FORM_KEEPS | WHAT_THE_WHERE_DROPPED |
|---|---|---|---|
| 4 | 3 | 4 | 1 |
Four documents in. The WHERE form keeps three and the CASE form keeps four, so the WHERE form dropped one. On four rows that is easy to spot. On a load of four million it is a silent shortfall.
Write the guard as a CASE, not a WHERE, and keep CHECK_XML's complaint in a column beside it. Then a bad document is a row you can report on rather than a row that was never there.
Let's parse the good ones and read the root tag
With the guard in place we can parse safely. Let's do that and ask what the parsed value actually is.
SELECT DOC_ID, WHAT_IT_IS,
PARSE_XML(RAW_XML) AS PARSED,
TYPEOF(PARSE_XML(RAW_XML)) AS ITS_TYPE,
PARSE_XML(RAW_XML):"@"::VARCHAR AS THE_ROOT_TAG
FROM DOCS_XML
WHERE CHECK_XML(RAW_XML) IS NULL
ORDER BY DOC_ID;| DOC_ID | WHAT_IT_IS | PARSED | ITS_TYPE | THE_ROOT_TAG |
|---|---|---|---|---|
| 1 | two children | <order id="1001"> <customer>Northwind Traders</customer> <item sku="A-100"> <qty>8</qty> </item> <item sku="B-220"> <qty>4</qty> </item> </order> | XML | order |
| 2 | attributes and text | <order id="1002" status="SHIPPED"> <customer country="USA">Blue Ridge Supply</customer> <item sku="C-310"> <qty>3</qty> </item> </order> | XML | order |
| 3 | repeated and empty tags | <order id="1003"> <customer>Kestrel Analytics</customer> <note></note> <tag>priority</tag> <tag>repeat</tag> </order> | XML | order |
TYPEOF says XML. Not OBJECT, not ARRAY. XML gets its own type name, unlike everything else in this level.
And the last column is the first accessor: :"@" on its own gives the name of the root tag. order, three times.
Now let's reach inside with XMLGET
XMLGET takes a parsed document and the name of a child element. Let's ask for the customer.
SELECT DOC_ID,
XMLGET(PARSE_XML(RAW_XML), 'customer') AS THE_ELEMENT,
TYPEOF(XMLGET(PARSE_XML(RAW_XML), 'customer')) AS ELEMENT_TYPE,
XMLGET(PARSE_XML(RAW_XML), 'customer'):"$" AS THE_CONTENT,
XMLGET(PARSE_XML(RAW_XML), 'customer'):"$"::VARCHAR AS AS_TEXT
FROM DOCS_XML
WHERE DOC_ID IN (1, 2)
ORDER BY DOC_ID;| DOC_ID | THE_ELEMENT | ELEMENT_TYPE | THE_CONTENT | AS_TEXT |
|---|---|---|---|---|
| 1 | <customer>Northwind Traders</customer> | XML | "Northwind Traders" | Northwind Traders |
| 2 | <customer country="USA">Blue Ridge Supply</customer> | XML | "Blue Ridge Supply" | Blue Ridge Supply |
Look carefully at the second column. We did not get Northwind Traders. We got <customer>Northwind Traders</customer>, tags and all, and TYPEOF on it says XML. XMLGET returns an element, not its text.
To get the text inside, add :"$". The third column does that and the fourth casts the result to VARCHAR.
Let's measure the difference, because this is the accessor people leave out.
SELECT XMLGET(PARSE_XML(RAW_XML), 'customer')::VARCHAR AS ELEMENT_AS_VARCHAR,
XMLGET(PARSE_XML(RAW_XML), 'customer'):"$"::VARCHAR AS CONTENT_AS_VARCHAR,
LENGTH(XMLGET(PARSE_XML(RAW_XML), 'customer')::VARCHAR) AS ELEMENT_LENGTH,
LENGTH(XMLGET(PARSE_XML(RAW_XML), 'customer'):"$"::VARCHAR) AS CONTENT_LENGTH
FROM DOCS_XML
WHERE DOC_ID = 1;| ELEMENT_AS_VARCHAR | CONTENT_AS_VARCHAR | ELEMENT_LENGTH | CONTENT_LENGTH |
|---|---|---|---|
| <customer>Northwind Traders</customer> | Northwind Traders | 38 | 17 |
The element is thirty-eight characters and the content is seventeen. That is twenty-one characters of tags you would be carrying around in a report column. :"$" is not optional.
Now let's read the attributes
An attribute is :"@" with the name after it, inside the quotes. Let's read the id and the status off the root, the tag name, and one attribute from inside a child.
SELECT DOC_ID,
PARSE_XML(RAW_XML):"@id"::VARCHAR AS THE_ID_ATTRIBUTE,
PARSE_XML(RAW_XML):"@status"::VARCHAR AS THE_STATUS_ATTRIBUTE,
PARSE_XML(RAW_XML):"@"::VARCHAR AS THE_TAG_NAME,
XMLGET(PARSE_XML(RAW_XML), 'customer'):"@country"::VARCHAR AS A_NESTED_ATTRIBUTE
FROM DOCS_XML
WHERE CHECK_XML(RAW_XML) IS NULL
ORDER BY DOC_ID;| DOC_ID | THE_ID_ATTRIBUTE | THE_STATUS_ATTRIBUTE | THE_TAG_NAME | A_NESTED_ATTRIBUTE |
|---|---|---|---|---|
| 1 | 1001 | NULL | order | NULL |
| 2 | 1002 | SHIPPED | order | USA |
| 3 | 1003 | NULL | order | NULL |
Every document has an id, so that column is filled in. Only document 2 has a status, so the other two rows are NULL there. The tag name is order on all three.
The last column is the one to notice. XMLGET(..., 'customer'):"@country" is an attribute on a child element, and it works the same way. Attributes nest.
So there are three accessors, and they do three different jobs.
| Accessor | What it gives you |
|---|---|
:"$" | The content inside the element |
:"@" | The name of the element's tag |
:"@name" | The attribute called name |
What happens if we use the wrong accessor?
That table is three things that look very alike, so the next question is what Snowflake does when we pick the wrong one. Let's ask for an attribute as if it were a child, and a child as if it were an attribute.
SELECT PARSE_XML(RAW_XML):"@id"::VARCHAR AS ATTRIBUTE_CORRECTLY,
XMLGET(PARSE_XML(RAW_XML), 'id') AS ATTRIBUTE_AS_A_CHILD,
XMLGET(PARSE_XML(RAW_XML), 'id') IS NULL AS THAT_IS_NULL,
PARSE_XML(RAW_XML):"@customer"::VARCHAR AS CHILD_AS_AN_ATTRIBUTE,
PARSE_XML(RAW_XML):"@customer" IS NULL AS THAT_IS_NULL_TOO
FROM DOCS_XML
WHERE DOC_ID = 2;| ATTRIBUTE_CORRECTLY | ATTRIBUTE_AS_A_CHILD | THAT_IS_NULL | CHILD_AS_AN_ATTRIBUTE | THAT_IS_NULL_TOO |
|---|---|---|---|---|
| 1002 | NULL | TRUE | NULL | TRUE |
The first column reads the id correctly. Then XMLGET(..., 'id') looks for a child element called id, and there is no such child, so it is NULL. And :"@customer" looks for an attribute called customer, and there is no such attribute, so that is NULL too.
No error either time. Let's count it over all three good documents, so the scale of it is clear.
SELECT COUNT(*) AS GOOD_DOCUMENTS,
COUNT(PARSE_XML(RAW_XML):"@id") AS ID_AS_ATTRIBUTE,
COUNT(XMLGET(PARSE_XML(RAW_XML), 'id')) AS ID_AS_CHILD,
COUNT(XMLGET(PARSE_XML(RAW_XML), 'customer')) AS CUSTOMER_AS_CHILD,
COUNT(PARSE_XML(RAW_XML):"@customer") AS CUSTOMER_AS_ATTRIBUTE
FROM DOCS_XML
WHERE CHECK_XML(RAW_XML) IS NULL;| GOOD_DOCUMENTS | ID_AS_ATTRIBUTE | ID_AS_CHILD | CUSTOMER_AS_CHILD | CUSTOMER_AS_ATTRIBUTE |
|---|---|---|---|---|
| 3 | 3 | 0 | 3 | 0 |
The id as an attribute is found on all three. The id as a child is found on none of them. The customer as a child is found on all three, and as an attribute on none.
Those two zero columns are the Level 8 problem one last time. A wrong accessor gives you NULL on every row, and a NULL on every row looks exactly like a column that was never populated. That is the same silent failure as the capital letter in Episode 88.
Now the one that will actually bite you: no index means index 0
Document 1 has two item elements in it, with the same tag name. Let's ask for the item, singular, the way you would write it without thinking.
SELECT DOC_ID,
XMLGET(PARSE_XML(RAW_XML), 'item') AS FIRST_ITEM,
XMLGET(PARSE_XML(RAW_XML), 'item'):"@sku"::VARCHAR AS ITS_SKU,
XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item'), 'qty'):"$"::VARCHAR AS ITS_QTY
FROM DOCS_XML
WHERE DOC_ID = 1;| DOC_ID | FIRST_ITEM | ITS_SKU | ITS_QTY |
|---|---|---|---|
| 1 | <item sku="A-100"> <qty>8</qty> </item> | A-100 | 8 |
We got one of them: sku A-100, quantity 8. Which one is that, and where did the other one go?
XMLGET has a third argument, an index. Let's use it.
SELECT XMLGET(PARSE_XML(RAW_XML), 'item', 0):"@sku"::VARCHAR AS ITEM_0_SKU,
XMLGET(PARSE_XML(RAW_XML), 'item', 1):"@sku"::VARCHAR AS ITEM_1_SKU,
XMLGET(PARSE_XML(RAW_XML), 'item', 2):"@sku"::VARCHAR AS ITEM_2_PAST_THE_END,
XMLGET(PARSE_XML(RAW_XML), 'item', 2) IS NULL AS PAST_THE_END_IS_NULL,
XMLGET(PARSE_XML(RAW_XML), 'item', 0):"@sku"
= XMLGET(PARSE_XML(RAW_XML), 'item'):"@sku" AS NO_INDEX_MEANS_ZERO
FROM DOCS_XML
WHERE DOC_ID = 1;| ITEM_0_SKU | ITEM_1_SKU | ITEM_2_PAST_THE_END | PAST_THE_END_IS_NULL | NO_INDEX_MEANS_ZERO |
|---|---|---|---|---|
| A-100 | B-220 | NULL | TRUE | TRUE |
Index 0 is A-100 and index 1 is B-220. Index 2 is past the end, and it is NULL rather than an error. The last column answers the question we just asked: with no index at all we get the same value as index 0.
Now let's total the quantities on that document, written the obvious way, and put the right answer beside it.
SELECT DOC_ID,
XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item', 0), 'qty'):"$"::INT AS QTY_0,
XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item', 1), 'qty'):"$"::INT AS QTY_1,
XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item'), 'qty'):"$"::INT AS WHAT_NO_INDEX_GIVES,
COALESCE(XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item', 0), 'qty'):"$"::INT, 0)
+ COALESCE(XMLGET(XMLGET(PARSE_XML(RAW_XML), 'item', 1), 'qty'):"$"::INT, 0)
AS THE_REAL_TOTAL
FROM DOCS_XML
WHERE DOC_ID = 1;| DOC_ID | QTY_0 | QTY_1 | WHAT_NO_INDEX_GIVES | THE_REAL_TOTAL |
|---|---|---|---|---|
| 1 | 8 | 4 | 8 | 12 |
Quantity at index 0 is 8 and at index 1 is 4. Written with no index the answer is 8, and the real total is 12.
8 where the answer is 12, with no error and nothing missing from the output. The second item is not wrong, it is simply not in the expression. That is the same shape as the silently doubled total in Episode 91, running in the other direction.
If a tag can repeat, XMLGET on its own will read the first one and tell you nothing about the rest. Use FLATTEN to get them all as rows, which we do further down this page, and keep XMLGET for the tags you know appear once.
And the other half: an empty element is not a missing one
Document 3 has an empty note tag and a tag element that appears twice. Let's look at the empty one.
SELECT XMLGET(PARSE_XML(RAW_XML), 'note') AS THE_EMPTY_ELEMENT,
XMLGET(PARSE_XML(RAW_XML), 'note') IS NULL AS EMPTY_ELEMENT_IS_NULL,
XMLGET(PARSE_XML(RAW_XML), 'note'):"$" AS ITS_CONTENT,
XMLGET(PARSE_XML(RAW_XML), 'note'):"$" IS NULL AS CONTENT_IS_NULL,
XMLGET(PARSE_XML(RAW_XML), 'tag', 0):"$"::VARCHAR AS TAG_0,
XMLGET(PARSE_XML(RAW_XML), 'tag', 1):"$"::VARCHAR AS TAG_1
FROM DOCS_XML
WHERE DOC_ID = 3;| THE_EMPTY_ELEMENT | EMPTY_ELEMENT_IS_NULL | ITS_CONTENT | CONTENT_IS_NULL | TAG_0 | TAG_1 |
|---|---|---|---|---|---|
| <note></note> | FALSE | "" | FALSE | priority | repeat |
The element came back as <note></note> and EMPTY_ELEMENT_IS_NULL is FALSE. Its content is an empty string, printed as two quote characters, and that is not NULL either.
Now let's put that next to a tag that is not in the document at all.
SELECT XMLGET(PARSE_XML(RAW_XML), 'note') IS NOT NULL AS NOTE_EXISTS,
XMLGET(PARSE_XML(RAW_XML), 'note'):"$" IS NULL AS NOTE_HAS_NO_CONTENT,
XMLGET(PARSE_XML(RAW_XML), 'nothing') IS NULL AS NOTHING_DOES_NOT_EXIST,
XMLGET(PARSE_XML(RAW_XML), 'nothing'):"$" IS NULL AS AND_HAS_NO_CONTENT
FROM DOCS_XML
WHERE DOC_ID = 3;| NOTE_EXISTS | NOTE_HAS_NO_CONTENT | NOTHING_DOES_NOT_EXIST | AND_HAS_NO_CONTENT |
|---|---|---|---|
| TRUE | FALSE | TRUE | TRUE |
The note exists and has content that is not NULL. The tag called nothing does not exist, and both its columns are NULL. Present-but-empty and absent are two different states, and IS NULL is how you tell them apart.
Over all three good documents it looks like this.
SELECT DOC_ID,
XMLGET(PARSE_XML(RAW_XML), 'customer'):"$"::VARCHAR AS CUSTOMER_,
XMLGET(PARSE_XML(RAW_XML), 'note') AS NOTE_,
XMLGET(PARSE_XML(RAW_XML), 'never_existed') AS ABSENT_,
XMLGET(PARSE_XML(RAW_XML), 'never_existed') IS NULL AS ABSENT_IS_NULL
FROM DOCS_XML
WHERE CHECK_XML(RAW_XML) IS NULL
ORDER BY DOC_ID;| DOC_ID | CUSTOMER_ | NOTE_ | ABSENT_ | ABSENT_IS_NULL |
|---|---|---|---|---|
| 1 | Northwind Traders | NULL | NULL | TRUE |
| 2 | Blue Ridge Supply | NULL | NULL | TRUE |
| 3 | Kestrel Analytics | <note></note> | NULL | TRUE |
The customer is on every document. The note is on document 3 only, and on the other two it is NULL, because there is no such element there at all. The tag that never existed is NULL everywhere.
Look at how those two states are printed, because they are easy to read past. The note's content is the two characters "", which is how Snowflake prints an empty string sitting inside a document. The absent element is the grey NULL the grids on this page use for a real SQL NULL. One is a value and the other is the absence of one.
Let's flatten the children into rows
FLATTEN works on XML too, and it is the answer to the repeated tag. The input is the content of the document, which is :"$".
SELECT D.DOC_ID,
F.INDEX AS CHILD_INDEX,
F.VALUE:"@"::VARCHAR AS TAG_NAME,
F.VALUE:"$" AS ITS_CONTENT
FROM DOCS_XML D,
LATERAL FLATTEN(INPUT => PARSE_XML(D.RAW_XML):"$") F
WHERE D.DOC_ID = 1
ORDER BY F.INDEX;| DOC_ID | CHILD_INDEX | TAG_NAME | ITS_CONTENT |
|---|---|---|---|
| 1 | 0 | customer | "Northwind Traders" |
| 1 | 1 | item | <qty>8</qty> |
| 1 | 2 | item | <qty>4</qty> |
One row per child, in document order. Index 0 is the customer, and index 1 and index 2 are the two items we lost earlier. The tag name of each one comes from :"@" on the flattened value, which means we can group by it.
Let's do that over every good document.
SELECT D.DOC_ID, D.WHAT_IT_IS,
COUNT(*) AS CHILDREN,
ARRAY_AGG(F.VALUE:"@"::VARCHAR) AS TAG_NAMES
FROM DOCS_XML D,
LATERAL FLATTEN(INPUT => PARSE_XML(D.RAW_XML):"$") F
WHERE CHECK_XML(D.RAW_XML) IS NULL
GROUP BY D.DOC_ID, D.WHAT_IT_IS
ORDER BY D.DOC_ID;| DOC_ID | WHAT_IT_IS | CHILDREN | TAG_NAMES |
|---|---|---|---|
| 1 | two children | 3 | [ "customer", "item", "item" ] |
| 2 | attributes and text | 2 | [ "customer", "item" ] |
| 3 | repeated and empty tags | 4 | [ "customer", "note", "tag", "tag" ] |
Three children on document 1, two on document 2 and four on document 3, with the tag names collected into an array beside them. Document 3's array shows the empty note sitting between the customer and the two tags.
And let's account for every row before we move on.
SELECT (SELECT COUNT(*) FROM DOCS_XML) AS DOCUMENTS_IN,
(SELECT COUNT(*) FROM DOCS_XML WHERE CHECK_XML(RAW_XML) IS NULL)
AS SURVIVED_THE_GUARD,
COUNT(DISTINCT D.DOC_ID) AS SURVIVED_THE_FLATTEN,
COUNT(*) AS CHILD_ROWS
FROM DOCS_XML D,
LATERAL FLATTEN(INPUT => PARSE_XML(D.RAW_XML):"$") F
WHERE CHECK_XML(D.RAW_XML) IS NULL;| DOCUMENTS_IN | SURVIVED_THE_GUARD | SURVIVED_THE_FLATTEN | CHILD_ROWS |
|---|---|---|---|
| 4 | 3 | 3 | 9 |
Four documents in, three survived the guard, three survived the flatten, and nine child rows came out. Nothing unexplained.
Now let's load it properly, keeping the bad row
This is the shape we loaded JSON in, back in Episode 87: the raw text, the parsed document, the complaint, and a flag. Let's build the table.
CREATE OR REPLACE TABLE XML_LOADED AS
SELECT DOC_ID,
WHAT_IT_IS,
RAW_XML,
CASE WHEN CHECK_XML(RAW_XML) IS NULL THEN PARSE_XML(RAW_XML) END AS DOC,
CHECK_XML(RAW_XML) AS PARSE_COMPLAINT,
CHECK_XML(RAW_XML) IS NULL AS IS_WELL_FORMED
FROM DOCS_XML;| status |
|---|
| Table XML_LOADED successfully created. |
The CASE guard is doing the work there, which is why the broken document can come along. Let's read it back.
SELECT DOC_ID, WHAT_IT_IS, IS_WELL_FORMED, PARSE_COMPLAINT,
TYPEOF(DOC) AS DOC_TYPE,
XMLGET(DOC, 'customer'):"$"::VARCHAR AS CUSTOMER_
FROM XML_LOADED
ORDER BY DOC_ID;| DOC_ID | WHAT_IT_IS | IS_WELL_FORMED | PARSE_COMPLAINT | DOC_TYPE | CUSTOMER_ |
|---|---|---|---|---|---|
| 1 | two children | TRUE | NULL | XML | Northwind Traders |
| 2 | attributes and text | TRUE | NULL | XML | Blue Ridge Supply |
| 3 | repeated and empty tags | TRUE | NULL | XML | Kestrel Analytics |
| 4 | not well formed | FALSE | missing closing tags: </customer>, pos 48 | NULL | NULL |
Four rows. Three parsed, with DOC_TYPE of XML and the customer read straight out of them. One with a NULL document and the reason it is NULL in the column beside it.
That last row is the whole argument for the CASE form. It is a row somebody can go and fix.
SELECT (SELECT COUNT(*) FROM DOCS_XML) AS ROWS_IN,
(SELECT COUNT(*) FROM XML_LOADED) AS ROWS_OUT,
(SELECT COUNT_IF(IS_WELL_FORMED) FROM XML_LOADED) AS GOOD_ROWS,
(SELECT COUNT_IF(NOT IS_WELL_FORMED) FROM XML_LOADED) AS BAD_ROWS,
(SELECT COUNT(*) FROM DOCS_XML)
= (SELECT COUNT(*) FROM XML_LOADED) AS NOTHING_LOST;| ROWS_IN | ROWS_OUT | GOOD_ROWS | BAD_ROWS | NOTHING_LOST |
|---|---|---|---|---|
| 4 | 4 | 3 | 1 | TRUE |
Four in, four out, three good, one bad, and NOTHING_LOST is TRUE.
So how does XML compare with JSON?
We have met both now, so let's put the same data in both shapes side by side.
SELECT PARSE_XML('<order id="1"><customer>Northwind</customer></order>')
AS AS_XML,
PARSE_JSON('{"id":1,"customer":"Northwind"}')
AS AS_JSON,
TYPEOF(PARSE_XML('<order id="1"><customer>Northwind</customer></order>'))
AS XML_TYPE,
TYPEOF(PARSE_JSON('{"id":1,"customer":"Northwind"}'))
AS JSON_TYPE,
XMLGET(PARSE_XML('<order id="1"><customer>Northwind</customer></order>'),
'customer'):"$"::VARCHAR AS XML_READ,
PARSE_JSON('{"id":1,"customer":"Northwind"}'):customer::VARCHAR AS JSON_READ;| AS_XML | AS_JSON | XML_TYPE | JSON_TYPE | XML_READ | JSON_READ |
|---|---|---|---|---|---|
| <order id="1"> <customer>Northwind</customer> </order> | { "customer": "Northwind", "id": 1 } | XML | OBJECT | Northwind | Northwind |
Two different types, XML and OBJECT. Both read back Northwind. The XML side needed XMLGET and a :"$" to get there, and the JSON side needed a colon and the key name.
And a few differences worth having in one place.
SELECT PARSE_XML('<a>1</a>') IS NULL AS XML_BAD_GIVES_NULL_NOT_ERROR,
TYPEOF(PARSE_XML('<a>1</a>')) AS XML_IS_ALWAYS_ONE_TYPE,
XMLGET(PARSE_XML('<a><b>1</b></a>'), 'b'):"$"::INT AS XML_NEEDS_A_DOLLAR,
PARSE_JSON('{"b":1}'):b::INT AS JSON_DOES_NOT,
TYPEOF(PARSE_JSON('{"b":1}'):b) AS JSON_REMEMBERS_THE_TYPE,
TYPEOF(XMLGET(PARSE_XML('<a><b>1</b></a>'), 'b'):"$") AS XML_CONTENT_TYPE;| XML_BAD_GIVES_NULL_NOT_ERROR | XML_IS_ALWAYS_ONE_TYPE | XML_NEEDS_A_DOLLAR | JSON_DOES_NOT | JSON_REMEMBERS_THE_TYPE | XML_CONTENT_TYPE |
|---|---|---|---|---|---|
| FALSE | XML | 1 | 1 | INTEGER | INTEGER |
Reading across: XML is always one type, XML, where a parsed JSON value takes the type of what it holds. Getting a number out of XML needs the :"$" and out of JSON does not. And on this example both report the content as an INTEGER.
The first column of that grid is headed XML_BAD_GIVES_NULL_NOT_ERROR and it is FALSE, which is the third leftover from the first version of the script. The document in that expression is <a>1</a>, which is perfectly well formed, so all the FALSE means is that a good document does not parse to NULL. For what a bad one does, the error panes near the top of this page are the answer.
One last thing: what Level 8 leaves behind
That closes Level 8. Let's count the tables it built, because every one of them turns up again later in the course.
SELECT (SELECT COUNT(*) FROM EVENTS_JSON) AS EVENTS_JSON,
(SELECT COUNT(*) FROM JSON_TEXT_RAW) AS JSON_TEXT_RAW,
(SELECT COUNT(*) FROM DOCS_XML) AS DOCS_XML,
(SELECT COUNT(*) FROM TYPED_SHAPES) AS TYPED_SHAPES;| EVENTS_JSON | JSON_TEXT_RAW | DOCS_XML | TYPED_SHAPES |
|---|---|---|---|
| 4 | 11 | 4 | 2 |
The JSON documents from Episode 86 onwards, the raw text table the validator ran over, these four XML documents, and the typed shapes from Episode 95.
And with the loaded XML table added, which we built two sections ago.
SELECT (SELECT COUNT(*) FROM EVENTS_JSON) AS EVENTS_JSON,
(SELECT COUNT(*) FROM JSON_TEXT_RAW) AS JSON_TEXT_RAW,
(SELECT COUNT(*) FROM DOCS_XML) AS DOCS_XML,
(SELECT COUNT(*) FROM XML_LOADED) AS XML_LOADED,
(SELECT COUNT(*) FROM TYPED_SHAPES) AS TYPED_SHAPES;| EVENTS_JSON | JSON_TEXT_RAW | DOCS_XML | XML_LOADED | TYPED_SHAPES |
|---|---|---|---|---|
| 4 | 11 | 4 | 4 | 2 |
That is semi-structured data, from VARIANT to XML, in eleven posts.
Key points
PARSE_XMLraises on a malformed document. It does not returnNULL. One bad row in the column and the whole statement returns nothing.- It refuses three things with three clear messages: an unclosed tag, text with no root element, and two roots in one string.
CHECK_XMLexists andTRY_PARSE_XMLdoes not, and neither doesTRY_CAST(... AS XML). JSON has three tools and XML has two.CHECK_XMLreturnsNULLwhen the document is fine, so the test for a good document isIS NULL.- It calls an empty string, a SQL
NULLand a string of spaces all valid. It means well formed, not present. - Write the guard as a
CASE, not aWHERE. TheWHEREform silently deletes the document you most need to report on. TYPEOFof a parsed document isXML, which is its own type.XMLGETreturns the whole element, tags included.:"$"is the content,:"@"is the tag name, and:"@name"is an attribute.- Use the wrong accessor and you get
NULLon every row, which looks exactly like missing data. XMLGETwith no index means index 0. On a repeated tag your total is quietly short and nothing says so. UseFLATTENinstead.- An empty element is present:
XMLGETreturns it and its content is an empty string. An absent element isNULL. Those are different states. FLATTENover:"$"gives one row per child, with:"@"as the tag name, so you can group XML the way you group JSON.
Episode 97 — data types, and which of their names are lies. That is Level 9, which is DDL: building the things our queries have been running against for ninety-six posts.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode, and that includes the seven refusals. Three column and capture headings on this page date from an earlier version of the demo script, written before the author found out that PARSE_XML raises rather than returning NULL, and the page says so at each one rather than letting the heading stand. The DOCS_XML documents are invented demo data and the fourth one is malformed on purpose. Every count in the text above is read off one of the grids on this page. Nothing is timed and no performance claims are made anywhere in this series. Function behaviour follows the Snowflake PARSE_XML documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.