Changes

Jump to navigation Jump to search
257 bytes removed ,  13:31, 2 July 2020
This [[Module Library|XQuery Module]] contains functions to access relational databases from XQuery using SQL. With this module, you can execute query, update and prepared statements, and the result sets are returned as sequences of XML elements representing tuples. Each element has children representing the columns returned by the SQL statement.
 
This module uses JDBC to connect to a SQL server. Hence, your JDBC driver will need to be added to the classpath, too. If you work with the full distributions of BaseX, you can copy the driver into the {{Code|lib}} directory. To connect to MySQL, for example, download the [https://dev.mysql.com/downloads/connector/j/ Connector/J Driver] and extract the archive into this directory.
=Conventions=
All functions and errors in this module are assigned to the {{Code|<code><nowiki>http://basex.org/modules/sql}} </nowiki></code> namespace, which is statically bound to the {{Code|sql}} prefix.<br/>All errors are assigned to the {{Code|http://basex.org/errors}} namespace, which is statically bound to the {{Code|bxerr}} prefix.
=Functions=
==sql:init==
 
{| width='100%'
|-
|-
| '''Errors'''
|{{Error|BXSQ0007init|XQuery Errors#SQL Functions Errors}} the specified driver class is not found.
|}
==sql:connect==
 
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|sql:connect|$url as xs:string|xs:integeranyURI}}<br/ >{{Func|sql:connect|$url as xs:string, $user as xs:string, $password as xs:string|xs:integeranyURI}}<br/ >{{Func|sql:connect|$url as xs:string, $user as xs:string, $password as xs:string, $options as itemmap(*)?|xs:integeranyURI}}<br/ >
|-
| '''Summary'''
|This function establishes a connection to a relational database. As a result and returns a connection handle is returnedid. The parameter {{Code|$url}} is the URL of the database and shall be of the form: {{Code|jdbc:<driver name>:[//<server>[/<database>]]}}. If the parameters {{Code|$user}} and {{Code|$password}} are specified, they are used as credentials for connecting to the database. The {{Code|$options}} parameter can be used to set connection options, which can either be specified<br/>* as children of an {{Code|&lt;sql:options/&gt;}} element, e.g.:<pre class="brush:xml"><sql:options> <sql:autocommit value='true'/> ...</sql:options></pre>* as map, which contains all key/value pairs:<pre class="brush:xml">map { "autocommit" := "true", ... }</pre>
|-
| '''Errors'''
|{{Error|BXSQ0001error|XQuery Errors#SQL Functions Errors}} an SQL exception occursoccurred when connecting to the database.|-| '''Examples'''|Connects to an SQL Server and sets autocommit to {{Code|true}}:<syntaxhighlight lang="xquery">sql:connect('dbc:sqlserver://DBServer', e.g. missing JDBC driver or not existing relation.map { 'autocommit': true() })</syntaxhighlight>
|}
==sql:execute==
 
Once a connection is established, the returned connection handle can be used to execute queries on the database. Our SQL module supports both direct queries and prepared statements.
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|sql:execute|$connection id as xs:integeranyURI, $query statement as xs:string|elementitem()*}}<br/>{{Func|sql:execute|$id as xs:anyURI, $statement as xs:string, $options as map(*)?|item()*}}
|-
| '''Summary'''
| This function executes a query or an SQL {{Code|$statement}}, using the connection with the specified {{Code|$id}}. The returned result depends on the kind of statement:* If an update statementwas executed, the number of updated rows will be returned as integer. The parameter * Otherwise, an XML representation of all results will be returned.With {{Code|$connectionoptions}} specifies a connection handle. The , the following parameter can be set:* {{Code|$querytimeout}} is a string representing an SQL statement: query execution will be interrupted after the specified number of seconds.
|-
| '''Errors'''
|{{Error|BXSQ0001error|XQuery Errors#SQL Functions Errors}} an error occurred while executing SQL exception occurs, e.g. <br/ >{{Error|id|#Errors}} the specified connection does not existing relation is retrievedexist.<br/ >{{Error|BXSQ0002timeout|XQuery Errors#SQL Functions Errors}} a wrong connection handle is passedquery execution exceeded timeout.<br/ >
|}
|-
| width='120' | '''Signatures'''
|{{Func|sql:execute-prepared|$id as xs:integeranyURI, $params as element(sql:parameters)|item()*}}<br/>{{Func|sql:execute-prepared|$id as xs:anyURI, $params as element(sql:parameters), $options as map(*)?|item()*}}
|-
| '''Summary'''
| This function executes a prepared statement. The parameter with the specified {{Code|$id}} specifies a prepared statement handle. The output format is identical to [[#sql:execute|sql:execute]]. The optional parameter {{Code|$params}} is an element {{Code|<sql:parameters/>}} representing the parameters for a prepared statement along with their types and values. The following schema shall be used:<br/ ><pre classsyntaxhighlight lang="brush:xmlxquery">
element sql:parameters {
element sql:parameter { attribute type { "int"|"string"|"boolean"|"date"|"double"| "float"|"short"|"time"|"timestamp" | "sqlxml" }, attribute null { "true"|"false" }?, text text }+ }?</presyntaxhighlight>With {{Code|$options}}, the following parameter can be set:* {{Code|timeout}}: query execution will be interrupted after the specified number of seconds.
|-
| '''Errors'''
|{{Error|BXSQ0001attribute|XQuery Errors#SQL Functions Errors}} an SQL exception occurs, e.g. not existing relation is retrieved.<br/ >attribute different from {{ErrorCode|BXSQ0002|XQuery Errors#SQL Functions Errorstype}} a wrong prepared statement handle is passed.<br/ >and {{ErrorCode|BXSQ0003|XQuery Errors#SQL Functions Errorsnull}} the number of is set for a {{Code|<sql:parameter/>}} elements in element.<br/ >{{CodeError|error|<sql:parameters/>#Errors}} differs from the number of placeholders in the prepared statementan error occurred while executing SQL.<br/ >{{Error|BXSQ0004id|XQuery Errors#SQL Functions Errors}} the type of a parameter for a prepared statement is specified connection does not specifiedexist.<br/ >{{Error|BXSQ0005parameters|XQuery Errors#SQL Functions Errors}} an attribute different from {{Code|no parameter type}} and specified.<br/>{{CodeError|null}} is set for a {{Codetimeout|<sql:parameter/>#Errors}} elementquery execution exceeded timeout.<br/ >{{Error|BXSQ0006type|XQuery Errors#SQL Functions Errors}} the value of a parameter is from type date, time or timestamp and its value is in an invalid cannot be converted to the specified format.<br/ >
|}
==sql:prepare==
 
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|sql:prepare|$connection id as xs:integeranyURI, $statement as xs:string|xs:integeranyURI}}
|-
| '''Summary'''
|This function prepares a statement and returns a handle to it. The parameter an SQL {{Code|$connectionstatement}} indicates , using the specified connection handle to be used. The parameter {{Code|$statementid}} , and returns the id reference to this statement. The statement is a string representing an SQL statement with one or more '?' placeholders. If the value of a field has to be set to {{Code|NULL}}, then the attribute {{Code|null}} of the element {{Code|<sql:parameter/>}} has to element must be {{Code|true}}.
|-
| '''Errors'''
|{{Error|BXSQ0001error|XQuery Errors#SQL Functions Errors}} an error occurred while executing SQL exception occurs.<br/ >{{Error|BXSQ0002id|XQuery Errors#SQL Functions Errors}} a wrong the specified connection handle is passeddoes not exist.<br/ >
|}
==sql:commit==
 
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|sql:commit|$connection id as xs:integeranyURI|empty-sequence()}}
|-
| '''Summary'''
| This function commits the changes made to a relational database. , using the specified connection {{Code|$connectionid}} specifies the connection handle.
|-
| '''Errors'''
|{{Error|BXSQ0001error|XQuery Errors#SQL Functions Errors}} an error occurred while executing SQL exception occurs.<br/ >{{Error|BXSQ0002id|XQuery Errors#SQL Functions Errors}} a wrong the specified connection handle is passeddoes not exist.<br/ >
|}
==sql:rollback==
 
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|sql:rollback|$connection id as xs:integeranyURI|empty-sequence()}}
|-
| '''Summary'''
| This function rolls back the changes made to a relational database. , using the specified connection {{Code|$connectionid}} specifies the connection handle.
|-
| '''Errors'''
|{{Error|BXSQ0001error|XQuery Errors#SQL Functions Errors}} an error occurred while executing SQL exception occurs.<br/ >{{Error|BXSQ0002id|XQuery Errors#SQL Functions Errors}} a wrong the specified connection handle is passeddoes not exist.<br/ >
|}
==sql:close==
 
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|sql:close|$connection id as xs:integeranyURI|empty-sequence()}}
|-
| '''Summary'''
| This function closes a database connection to a relational database. with the specified {{Code|$connectionid}} specifies .<br/>Opened connections will automatically be closed after the connection handleXQuery expression has been evaluated, but in order to save memory, it is always recommendable to close connections that are not used anymore.
|-
| '''Errors'''
|{{Error|BXSQ0001error|XQuery Errors#SQL Functions Errors}} an error occurred while executing SQL exception occurs.<br/ >{{Error|BXSQ0002id|XQuery Errors#SQL Functions Errors}} a wrong the specified connection handle is passeddoes not exist.<br/ >
|}
==Direct queries==
A simple select statement can be executed on the following way:
A simple select statement can be executed as follows: <pre classsyntaxhighlight lang="brush:xquery">let $conn id := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")return sql:execute($connid, "SELECT * FROM coffees WHERE price < 10")</presyntaxhighlight>
The result will may look like:
<pre classsyntaxhighlight lang="brush:xml">
<sql:row xmlns:sql="http://basex.org/modules/sql">
<sql:column name="cof_name">French_Roast</sql:column>
<sql:column name="total">14</sql:column>
</sql:row>
<sql:row xmlns:sql="http://basex.org/modules/sql"> <sql:column name="cof_name">Colombian_Decaf</sql:column> <sql:column name="sup_id">101</sql:column> <sql:column name="price">8.75</sql:column> <sql:column name="sales">6</sql:column> <sql:column name="total">12</sql:column> <sql:column name="date">2010-10-10 13:56:11.0</sql:column></sql:row></presyntaxhighlight>
==Prepared Statements==
 
A prepared select statement can be executed in the following way:
<pre classsyntaxhighlight lang="brush:xquery">
(: Establish a connection :)
let $conn := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")
(: Values and types of prepared statement parameters :)
let $params := <sql:parameters>
<sql:parameter type='double'>10</sql:parameter> <sql:parameter type='string'>French_Roast</sql:parameter>
</sql:parameters>
(: Execute prepared statement :)
return sql:execute-prepared($prep, $params)
</presyntaxhighlight>
==SQLite==
The following expression demonstrates how SQLite can be addressed using with the [https://www.xerialbitbucket.org/trac/Xerialxerial/wikisqlite-jdbc/SQLiteJDBC#Download Xerial SQLite JDBC driver]:
<pre classsyntaxhighlight lang="brush:xquery">
(: Initialize driver :)
sql:init("org.sqlite.JDBC"),
return sql:execute($conn, $q),
(: Return table contents :)
sql:execute($conn, "select * from person"), sql:close($conn)
)
</presyntaxhighlight>
=Errors=
|Description
|-
|{{Code|BXSQ0001attribute}}|An SQL exception occurred (e.g.attribute different from {{Code|type}} and {{Code|null}} is set for a {{Code|&lt;sql: a non-existing relation is retrieved)parameter/&gt;}} element.
|-
|{{Code|BXSQ0002error}}|A wrong connection handle or prepared statement handle is passedAn SQL exception occurred.
|-
|{{Code|BXSQ0003id}}|The number of {{Code|&lt;sql:parameter/&gt;}} elements in {{Code|&lt;sql:parameters/&gt;}} differs from the number of placeholders in the prepared statementA connection does not exist.
|-
|{{Code|BXSQ0004init}}|The type of a parameter for a prepared statement A database driver is not specifiedfound.
|-
|{{Code|BXSQ0005parameters}}|An attribute different from {{Code|No parameter type}} and {{Code|null}} is set for a {{Code|&lt;sql:parameter/&gt;}} elementspecified.
|-
|{{Code|BXSQ0006timeout}}|A parameter is from type date, time or timestamp and its value is in an invalid formatQuery execution exceeded timeout.
|-
|{{Code|BXSQ0007type}}|A The value of a parameter cannot be converted to the specified database driver class is not foundformat.
|}
=Changelog=
 
;Version 9.0
 
* Updated: [[#sql:execute|sql:execute]], [[#sql:execute-prepared|sql:execute-prepared]]: Return update count for updating statements. {{Code|$options}} argument added.
* Updated: Connection ids are URIs now.
* Updated: error codes updated; errors now use the module namespace
;Version 7.5
 
* Updated: prepared statements are now executed via [[#sql:execute-prepared|sql:execute-prepared]]
The module was introduced with Version 7.0.
 
[[Category:XQuery]]
Bureaucrats, editor, reviewer, Administrators
13,550

edits

Navigation menu