Changes

Jump to navigation Jump to search
7,016 bytes removed ,  12:59, 23 November 2017
no edit summary
=Functions=
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.==xquery:eval==
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= {{Mark|Updated with Version 9.0}}: All functions and errors in this module are assigned to the <code><nowiki>http://basex.org/modules/sql</nowiki></code> namespace, which is statically bound to the {{Codecode|sqlpass}} prefixoption added.<br/> =Functions= ==sql:init==
{| width='100%'
|-
| width='120' | '''Signatures'''
|{{Func|sqlxquery:initeval|$class query as xs:string|empty-sequenceitem()*}}<br />{{Func|xquery:eval|$query as xs:string, $bindings as map(*)?|item()*}}<br />{{Func|xquery:eval|$query as xs:string, $bindings as map(*)?, $options as map(xs:string, xs:string)|item()*}}<br />
|-
| '''Summary'''
|This function initializes a JDBC driver specified via Evaluates the supplied {{Code|$classquery}}string as XQuery expression and returns the resulting items.<br/>The evaluated query has its own query context. This step might If a returned node is stored in a database, a main-memory copy will be superfluous if returned as result, because the SQL referenced database is closed after query execution and will not embeddedbe accessible anymore.<br/ >|-| '''Errors'''|Variables and context items can be declared via {{ErrorCode|init|#Errors$bindings}} the . The specified driver keys must be QNames or strings:* If a key is not founda QName, it will be directly adopted as variable name.|} ==sql* It a key is a string, it may be prefixed with a dollar sign. Namespace can be specified using the [http:connect==//www.jclark.com/xml/xmlns.htm Clark Notation].* If the specified string is empty, the value will be bound to the context item.The {| width='100%'|-| width='120' | '''Signatures'''|{{Func|sql:connectCode|$url as xs:string|xs:anyURIoptions}}<br/ >parameter contains evaluation options:* {{Func|sql:connect|$url as xs:string, $user as xs:string, $password as xs:stringCode|xs:anyURIpermission}}<br/ >{{Func|sql:connect|$url as xs:string, $user as xs:string, $password as xs:string, $options as mapthe query will be evaluated with the specified permissions (see [[User Management]]).*){{Code|xs:anyURItimeout}}<br/ >: query execution will be interrupted after the specified number of seconds.|-| '''Summary'''|This function establishes a connection to a relational database and returns a connection id. The parameter * {{Code|$urlmemory}} is : query execution will be interrupted if the URL specified number of megabytes will be exceeded. This check works best if only one process is running at the database same time. Moreover, please note that this option enforces garbage collection, so it will take some additional time, and shall it requires GC to be of the form: enabled in your JVM.* {{Code|jdbcbase-uri}}:<driver name>set [https:[//<server>[www.w3.org/TR/xquery-31/<database>#dt-static-base-uri base-uri property]]}}for the query. If the parameters This URI will be used when resolving relative URIs by functions such as {{Code|$userfn:doc}} and .* {{Code|$passwordpass}} are specified: passes on the original error info (line and column number, they are used as credentials for connecting to the databaseoptional file uri). The By default, this option is {{Code|$optionsfalse}} parameter can be used to set connection options.
|-
| '''Errors'''
|{{Error|errorupdate|#Errors}} the query contains [[XQuery Update#Updating Expressions|updating expressions]].<br/>{{Error|permission|#Errors}} insufficient permissions for evaluating the query.<br/>{{Error|timeout|#Errors}} an SQL exception occurs, equery execution exceeded timeout.g<br/>{{Error|limit|#Errors}} query execution exceeded memory limit. missing JDBC driver or <br/>{{Error|nested|#Errors}} nested query evaluation is not existing relationallowed.<br/>Any other error that may occur while evaluating the query.
|-
| '''Examples'''
|Connects to an SQL Server and sets autocommit to * {{Code|xquery:eval("1+3")}} returns {{Code|true4}}.<br />* You can bind the context and e.g. operate on a certain database only:<br /><pre class="'brush:xquery"'>sqlxquery:connecteval('dbc:sqlserver:"//DBServer'country", map { 'autocommit': truedb:open('factbook') })
</pre>
|* The following expressions use strings as keys. All of them return 'XML':<br/><pre class='brush:xquery'>xquery:eval(".", map { '': 'XML' }),
==sqlxquery:execute==eval("declare variable $xml external; $xml", map { 'xml': 'XML' }),
{{Mark|Updated with Version 9.0}}xquery: Return update count for updating statements. {{Code|$options}} argument added. {| width='100%'|-| width='120' | '''Signatures'''|{{Func|sql:execute|$id as xs:anyURI, $statement as xs:string|item()*}}<br/>{{Func|sql:execute|$id as xs:anyURI, $statement as xs:string, $options as map(*)|itemeval()*}}|-| '''Summary'''| This function executes an SQL {{Code|$statement}}, using the connection with the specified {{Code|$id}}. The returned result depends on the kind of statement:* If an update statement was executed, the number of updated rows will be returned as integer.* Otherwise, an XML representation of all results will be returned.With {{Code|$options}}, the following parameter can be set:* {{Code|timeout}}: query execution will be interrupted after the specified number of seconds.|-| '''Errors'''|{{Error|error|#Errors}} an SQL exception occurs, e.g. not existing relation is retrieved.<br/ >{{Error|id|#Errors}} the specified connection does not exist.<br/ >|} ==sql:execute-prepared== {{Mark|Updated with Version 9.0}}: Return update count for updating statements. {| width "declare namespace pref='100%URI';|-| width='120' | '''Signatures'''|{{Func|sql:execute-prepared| declare variable $id as xspref:anyURI, $params as element(sql:parameters)|item()*}}<br/>{{Func|sql:execute-prepared|$id as xs:anyURI, $params as element(sql:parameters), $options as map(*)|item()*}}xml external;|-| '''Summary'''| This function executes a prepared statement with the specified {{Code| $id}}. The output format is identical to [[#sqlpref: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 class="brush:xquery">element sql:parameters { element sql:parameter { attribute type { "int" | "string" | "boolean" | "date" | "double" | xml"float" | "short" | "time" | "timestamp" | "sqlxml" }, attribute null { "true" | "false" }?, text }+}?</pre>With {{Code|$options}}, the following parameter can be set:* map {{Code|timeout}}: query execution will be interrupted after the specified number of seconds.|-| '''Errors'''|{{Error|attribute|#ErrorsURI}} an attribute different from {{Code|type}} and {{Code|null}} is set for a {{Code|<sql:parameter/>}} element.<br/ >{{Error|error|#Errors}} an SQL exception occurs, e.g. not existing relation is retrieved.<br/ >{{Error|id|#Errors}} the specified connection does not exist.<br/ >{{Error|parameters|#Errors}} wrong number of {{Code|<sql:parameter/>}} elements, or parameter type is not specified.<br/>{{Error|type|#Errors}} the value of a parameter cannot be converted to the specified format.|} ==sql:prepare== {| width='100%'|-| width=xml'120' | '''Signatures'''|{{Func|sql:prepare|$id as xs:anyURI, $statement as xs:string|xs:anyURI}}|-| '''Summary'''|This function prepares an SQL {{Code|$statement}}, using the specified connection {{Code|$id}}, and returns the id reference to this statement. The statement is a string 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 {{Code|<sql:parameter/>}} element must be {{Code|true}}.|-| '''Errors'''|{{Error|error|#Errors}} an SQL exception occurs.<br/ >{{Error|id|#Errors}} the specified connection does not exist.<br/ >|} ==sql:commit== {| width='100%'|-| width='120' | '''Signatures'''|{{Func|sql:commit|$id as xs:anyURI|empty-sequence()}}|-| '''Summary'''| This function commits the changes made to a relational database, using the specified connection {{Code|$id}}.|-| '''Errors'''|{{Error|error|#Errors}} an SQL exception occurs.<br/ >{{Error|id|#Errors}} the specified connection does not exist.<br/ >|} ==sql:rollback== {| width='100%'|-| width='120' | '''Signatures'''|{{Func|sql:rollback|$id as xs:anyURI|empty-sequence()}}|-| '''Summary'''| This function rolls back the changes made to a relational database, using the specified connection {{Code|$id}}.|-| '''Errors'''|{{Error|error|#Errors}} an SQL exception occurs.<br/ >{{Error|id|#Errors}} the specified connection does not exist.<br/ >|} ==sql:close== {| width='100%'|-| width='120' | '''Signatures'''|{{Func|sql:close|$id as xs:anyURI|empty-sequence()}}|-| '''Summary''XML'| This function closes a database connection with the specified {{Code|$id}}.<br/>Opened connections will automatically be closed after the XQuery expression has been evaluated, but in order to save memory, it is always recommendable to close connections that are not used anymore.|-| '''Errors'''|{{Error|error|#Errors}} an SQL exception occurs.<br/ >{{Error|id|#Errors}} the specified connection does not exist.<br/ >|} =Examples= ==Direct queries== A simple select statement can be executed as follows: <pre class="brush:xquery">let $id := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")return sql:execute($id, "SELECT * FROM coffees WHERE price < 10")</pre> The result may look like: <pre class="brush:xml"><sql:row xmlns:sql="http://basex.org/modules/sql"> <sql:column name="cof_name">French_Roast</sql:column> <sql:column name="sup_id">49</sql:column> <sql:column name="price">9.5</sql:column> <sql:column name="sales">15</sql:column> <sql:column name="total">30</sql:column></sql:row><sql:row xmlns:sql="http://basex.org/modules/sql"> <sql:column name="cof_name">French_Roast_Decaf</sql:column> <sql:column name="sup_id">49</sql:column> <sql:column name="price">7.5</sql:column> <sql:column name="sales">10</sql:column> <sql:column name="total">14</sql:column></sql:row></pre> ==Prepared Statements== A prepared select statement can be executed in the following way: <pre class="brush:xquery">(: Establish a connection :)let $conn := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")(: Obtain a handle to a prepared statement :)let $prep := sql:prepare($conn, "SELECT * FROM coffees WHERE price < ? AND cof_name = ?")(: 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)
</pre>
* The following expressions use QNames as keys. All of them return 'XML':<br/>
<pre class='brush:xquery'>
declare namespace pref = 'URI';
==SQLite== The following expression demonstrates how SQLite can be addressed using the [httpxquery://bitbucket.org/xerial/sqlite-jdbc Xerial SQLite JDBC driver]eval("declare variable $xml external; $xml", map { xs:QName('xml'): 'XML' }),
<pre class="brush:xquery">(: Initialize driver :)sql:init("org.sqlite.JDBC"),(: Establish a connection :)let $conn query := sql:connect("jdbc:sqlite:database.db")declare namespace pref='URI';return ( ( declare variable $pref: Create a new table :)xml external; sql:execute( $conn, "drop table if exists person"), sqlpref:execute($conn, "create table person (id integer, name string)xml"), (: Run 10 updates :) for $i in 1 to 10 let $q vars := "insert into person valuesmap { xs:QName(" || $i || ", '" || $i || "pref:xml')": 'XML' } return sqlxquery:executeeval($connquery, $q), (: Return table contents :) sql:execute($conn, "select * from person")vars)
</pre>
 
=Errors=
 
{{Mark|Updated with Version 9.0}}:
 
{| class="wikitable" width="100%"
! width="110"|Code
|Description
|-
|{{Code|attribute}}
|An attribute different from {{Code|type}} and {{Code|null}} is set for a {{Code|&lt;sql:parameter/&gt;}} element.
|-
|{{Code|error}}
|An SQL exception occurred.
|-
|{{Code|id}}
|A connection does not exist.
|-
|{{Code|init}}
|A database driver is not found.
|-
|{{Code|parameters}}
|Wrong number of {{Code|&lt;sql:parameter/&gt;}} elements, or parameter type is not specified.
|-
|{{Code|type}}
|The value of a parameter cannot be converted to the specified format.
|}
 
=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.
==xquery:eval-update==
|-
| '''Errors'''
|{{Error|update|#Errors}} the expression contains [[XQuery Update#Updating Expressions|updating expressions]].<br/>{{Error|permission|#Errors}} insufficient permissions for evaluating the query.<br/>{{Error|BXXQ0004timeout|#Errors}} query execution exceeded timeout.<br/>{{Error|nested|#Errors}} nested query evaluation is not allowed.<br/>Any other error that may occur while evaluating the query.
|}
|-
| '''Errors'''
|{{Error|update|#Errors}} the expression contains no [[XQuery Update#Updating Expressions|updating expressions]].<br/>{{Error|permission|#Errors}} insufficient permissions for evaluating the query.<br/>{{Error|BXXQ0004timeout|#Errors}} query execution exceeded timeout.<br/>{{Error|nested|#Errors}} nested query evaluation is not allowed.<br/>Any other error that may occur while evaluating the query.
|}
Bureaucrats, editor, reviewer, Administrators
13,550

edits

Navigation menu