NitZRobotKoder
NitZRobotKoder

Reputation: 1086

Marklogic : Insert and retrieve document using xquery in the same run

Need something like this in Marklogic by using xquery. Get a document present in a location, if not present create a document using xdmp:document-insert() and then retrieve document using fn:doc().

In the first run, document is not present. So it creates the document but does not fetch anything. In the second run, document created in the first run is retrieved. But, I want to do both in the same run.

I know that I am missing something simple here. Is it the case with single transaction? Both the statements are in separate lines, so not sure wether it is a single transaction case.

    declare function lk:createXmlIfNotPresent(){
       let $xml_dir := "app/test"
       let $xml_full_path := "app/test/test.xml"
       let $dir_uri := cts:uri-match($xml_dir)
       let $dir_creation :=
       if(fn:empty($xml_dir)) then (
            xdmp:directory-create($xml_dir)
        )else()
       let $exists := fn:doc-available($xml_full_path)
       let $xml_creation :=
       if($exists eq fn:false()) then (
        xdmp:document-insert($xml_full_path,<root></root>,xdmp:default-  permissions())
       )else()
       return fn:doc($xml_full_path)
  };

Upvotes: 0

Views: 1270

Answers (3)

ehennum
ehennum

Reputation: 7335

While the advice about transactions is true for the general case, this case can be handled simply.

You already have the document in memory (<root/> in the example) as the second parameter to xdmp:document-insert().

You can assign the document to a variable. Pass the document to xdmp:document-insert(), and also return the document.

Upvotes: 1

DALDEI
DALDEI

Reputation: 3732

Yes, this has to do with transactions. The entire body of an XQuery program, by default, it's running in a single transaction. Unlike RDBMS transactions, in ML a transaction hides what it does. Your view of the database remains unchanged through the life of the transaction. Only when the program is complete, the changes are committed and visible.

You can work around/with this in various ways, I suggest this tutorial.

https://docs.marklogic.com/guide/app-dev/transactions

Upvotes: 3

Navin Rawat
Navin Rawat

Reputation: 3138

If you want to do both in the same run use xdmp:eval() function to create your document.

Upvotes: 0

Related Questions