Difference between revisions of "SQL Module"

From BaseX Documentation
Jump to navigation Jump to search
m (Text replacement - "syntaxhighlight" to "pre")
 
(8 intermediate revisions by 2 users not shown)
Line 13: Line 13:
 
{| width='100%'
 
{| width='100%'
 
|- valign="top"
 
|- valign="top"
| width='120' | '''Signatures'''
+
| width='120' | '''Signature'''
|{{Func|sql:init|$class as xs:string|empty-sequence()}}
+
|<pre>sql:init(
 +
  $class as xs:string
 +
) as empty-sequence()</pre>
 
|- valign="top"
 
|- valign="top"
 
| '''Summary'''
 
| '''Summary'''
Line 24: Line 26:
  
 
==sql:connect==
 
==sql:connect==
 +
 +
{{Announce|Updated with Version 11:}} Optional credentials.
  
 
{| width='100%'
 
{| width='100%'
 
|- valign="top"
 
|- valign="top"
| width='120' | '''Signatures'''
+
| width='120' | '''Signature'''
|{{Func|sql:connect|$url as xs:string|xs:anyURI}}<br/ >{{Func|sql:connect|$url as xs:string, $username as xs:string, $password as xs:string|xs:anyURI}}<br/ >{{Func|sql:connect|$url as xs:string, $username as xs:string, $password as xs:string, $options as map(*)?|xs:anyURI}}<br/ >
+
|<pre>sql:connect(
 +
  $url       as xs:string,
 +
  $options   as map(*)?   := map { }
 +
) as xs:anyURI</pre>
 
|- valign="top"
 
|- valign="top"
 
| '''Summary'''
 
| '''Summary'''
|This function establishes a connection to a relational database and returns a connection id. The parameter {{Code|$url}} is the URL of the database and shall be of the form: {{Code|jdbc:<driver name>:[//<server>[/<database>]]}}. If {{Code|$username}} 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.
+
|This function establishes a connection to a relational database and returns a connection id. The parameter {{Code|$url}} is the URL of the database and shall be of the form: {{Code|jdbc:<driver name>:[//<server>[/<database>]]}}. Values specified for {{Code|$username}} and {{Code|$password}} are used as credentials for connecting to the database. The {{Code|$options}} parameter can be used to set connection options.
 
|- valign="top"
 
|- valign="top"
 
| '''Errors'''
 
| '''Errors'''
Line 38: Line 45:
 
| '''Examples'''
 
| '''Examples'''
 
|Connects to an SQL Server and sets autocommit to {{Code|true}}:
 
|Connects to an SQL Server and sets autocommit to {{Code|true}}:
<syntaxhighlight lang="xquery">
+
<pre lang='xquery'>
 
sql:connect('dbc:sqlserver://DBServer', map { 'autocommit': true() })
 
sql:connect('dbc:sqlserver://DBServer', map { 'autocommit': true() })
</syntaxhighlight>
+
</pre>
 
|}
 
|}
  
Line 47: Line 54:
 
{| width='100%'
 
{| width='100%'
 
|- valign="top"
 
|- valign="top"
| width='120' | '''Signatures'''
+
| width='120' | '''Signature'''
|{{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(*)?|item()*}}
+
|<pre>sql:execute(
 +
  $id         as xs:anyURI,
 +
  $statement as xs:string,
 +
  $options   as map(*)?   := map { }
 +
) as item()*</pre>
 
|- valign="top"
 
|- valign="top"
 
| '''Summary'''
 
| '''Summary'''
Line 65: Line 76:
 
{| width='100%'
 
{| width='100%'
 
|- valign="top"
 
|- valign="top"
| width='120' | '''Signatures'''
+
| width='120' | '''Signature'''
|{{Func|sql:execute-prepared|$id as xs: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()*}}
+
|<pre>sql:execute-prepared(
 +
  $id       as xs:anyURI,
 +
  $params   as element(sql:parameters),
 +
  $options as map(*)?                 := map { }
 +
) as item()*</pre>
 
|- valign="top"
 
|- valign="top"
 
| '''Summary'''
 
| '''Summary'''
 
| This function executes a prepared statement with the specified {{Code|$id}}. The output format is identical to {{Function||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/ >
 
| This function executes a prepared statement with the specified {{Code|$id}}. The output format is identical to {{Function||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/ >
<syntaxhighlight lang="xquery">
+
<pre lang='xquery'>
 
element sql:parameters {
 
element sql:parameters {
 
   element sql:parameter {
 
   element sql:parameter {
Line 79: Line 94:
 
   }+
 
   }+
 
}?
 
}?
</syntaxhighlight>
+
</pre>
 
With {{Code|$options}}, the following parameter can be set:
 
With {{Code|$options}}, the following parameter can be set:
 
* {{Code|timeout}}: query execution will be interrupted after the specified number of seconds.
 
* {{Code|timeout}}: query execution will be interrupted after the specified number of seconds.
Line 91: Line 106:
 
{| width='100%'
 
{| width='100%'
 
|- valign="top"
 
|- valign="top"
| width='120' | '''Signatures'''
+
| width='120' | '''Signature'''
|{{Func|sql:prepare|$id as xs:anyURI, $statement as xs:string|xs:anyURI}}
+
|<pre>sql:prepare(
 +
  $id         as xs:anyURI,
 +
  $statement as xs:string
 +
) as xs:anyURI</pre>
 
|- valign="top"
 
|- valign="top"
 
| '''Summary'''
 
| '''Summary'''
Line 105: Line 123:
 
{| width='100%'
 
{| width='100%'
 
|- valign="top"
 
|- valign="top"
| width='120' | '''Signatures'''
+
| width='120' | '''Signature'''
|{{Func|sql:commit|$id as xs:anyURI|empty-sequence()}}
+
|<pre>sql:commit(
 +
  $id as xs:anyURI
 +
) as empty-sequence()</pre>
 
|- valign="top"
 
|- valign="top"
 
| '''Summary'''
 
| '''Summary'''
Line 119: Line 139:
 
{| width='100%'
 
{| width='100%'
 
|- valign="top"
 
|- valign="top"
| width='120' | '''Signatures'''
+
| width='120' | '''Signature'''
|{{Func|sql:rollback|$id as xs:anyURI|empty-sequence()}}
+
|<pre>sql:rollback(
 +
  $id as xs:anyURI
 +
) as empty-sequence()</pre>
 
|- valign="top"
 
|- valign="top"
 
| '''Summary'''
 
| '''Summary'''
Line 133: Line 155:
 
{| width='100%'
 
{| width='100%'
 
|- valign="top"
 
|- valign="top"
| width='120' | '''Signatures'''
+
| width='120' | '''Signature'''
|{{Func|sql:close|$id as xs:anyURI|empty-sequence()}}
+
|<pre>sql:close(
 +
  $id as xs:anyURI
 +
) as empty-sequence()</pre>
 
|- valign="top"
 
|- valign="top"
 
| '''Summary'''
 
| '''Summary'''
Line 149: Line 173:
 
A simple select statement can be executed as follows:
 
A simple select statement can be executed as follows:
  
<syntaxhighlight lang="xquery">
+
<pre lang='xquery'>
 
let $id := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")
 
let $id := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")
 
return sql:execute($id, "SELECT * FROM coffees WHERE price < 10")
 
return sql:execute($id, "SELECT * FROM coffees WHERE price < 10")
</syntaxhighlight>
+
</pre>
  
 
The result may look like:
 
The result may look like:
  
<syntaxhighlight lang="xml">
+
<pre lang="xml">
 
<sql:row xmlns:sql="http://basex.org/modules/sql">
 
<sql:row xmlns:sql="http://basex.org/modules/sql">
 
   <sql:column name="cof_name">French_Roast</sql:column>
 
   <sql:column name="cof_name">French_Roast</sql:column>
Line 171: Line 195:
 
   <sql:column name="total">14</sql:column>
 
   <sql:column name="total">14</sql:column>
 
</sql:row>
 
</sql:row>
</syntaxhighlight>
+
</pre>
  
 
==Prepared Statements==
 
==Prepared Statements==
Line 177: Line 201:
 
A prepared select statement can be executed in the following way:
 
A prepared select statement can be executed in the following way:
  
<syntaxhighlight lang="xquery">
+
<pre lang='xquery'>
 
(: Establish a connection :)
 
(: Establish a connection :)
 
let $conn := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")
 
let $conn := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")
Line 189: Line 213:
 
(: Execute prepared statement :)
 
(: Execute prepared statement :)
 
return sql:execute-prepared($prep, $params)
 
return sql:execute-prepared($prep, $params)
</syntaxhighlight>
+
</pre>
  
 
==SQLite==
 
==SQLite==
Line 195: Line 219:
 
The following expression demonstrates how SQLite can be addressed with the [https://bitbucket.org/xerial/sqlite-jdbc/ Xerial SQLite JDBC driver]:
 
The following expression demonstrates how SQLite can be addressed with the [https://bitbucket.org/xerial/sqlite-jdbc/ Xerial SQLite JDBC driver]:
  
<syntaxhighlight lang="xquery">
+
<pre lang='xquery'>
 
(: Initialize driver :)
 
(: Initialize driver :)
 
sql:init("org.sqlite.JDBC"),
 
sql:init("org.sqlite.JDBC"),
Line 211: Line 235:
 
   sql:execute($conn, "select * from person")
 
   sql:execute($conn, "select * from person")
 
)
 
)
</syntaxhighlight>
+
</pre>
  
 
=Errors=
 
=Errors=
Line 242: Line 266:
  
 
=Changelog=
 
=Changelog=
 +
 +
;Version 11
 +
* Updated: {{Function||sql:connect}}: Optional credentials.
  
 
;Version 9.6
 
;Version 9.6

Latest revision as of 18:39, 1 December 2023

This 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 lib directory. To connect to MySQL, for example, download the Connector/J Driver and extract the archive into this directory.

Conventions[edit]

All functions and errors in this module are assigned to the http://basex.org/modules/sql namespace, which is statically bound to the sql prefix.

Functions[edit]

sql:init[edit]

Signature
sql:init(
  $class  as xs:string
) as empty-sequence()
Summary This function initializes a JDBC driver specified via $class. This step might be superfluous if the SQL database is not embedded.
Errors init: the specified driver is not found.

sql:connect[edit]

Updated with Version 11: Optional credentials.

Signature
sql:connect(
  $url        as xs:string,
  $options    as map(*)?    := map { }
) as xs:anyURI
Summary This function establishes a connection to a relational database and returns a connection id. The parameter $url is the URL of the database and shall be of the form: jdbc:<driver name>:<server> [/<database>]. Values specified for $username and $password are used as credentials for connecting to the database. The $options parameter can be used to set connection options.
Errors error: an SQL exception occurred when connecting to the database.
Examples Connects to an SQL Server and sets autocommit to true:
sql:connect('dbc:sqlserver://DBServer', map { 'autocommit': true() })

sql:execute[edit]

Signature
sql:execute(
  $id         as xs:anyURI,
  $statement  as xs:string,
  $options    as map(*)?    := map { }
) as item()*
Summary This function executes an SQL $statement, using the connection with the specified $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 $options, the following parameter can be set:

  • timeout: query execution will be interrupted after the specified number of seconds.
Errors error: an error occurred while executing SQL.
id: the specified connection does not exist.
timeout: query execution exceeded timeout.

sql:execute-prepared[edit]

Signature
sql:execute-prepared(
  $id       as xs:anyURI,
  $params   as element(sql:parameters),
  $options  as map(*)?                  := map { }
) as item()*
Summary This function executes a prepared statement with the specified $id. The output format is identical to sql:execute. The optional parameter $params is an element <sql:parameters/> representing the parameters for a prepared statement along with their types and values. The following schema shall be used:
element sql:parameters {
  element sql:parameter {
    attribute type { "bigdecimal" | "boolean" | "byte" | "date" | "double" | "float" |
      "int" | "long" | "short" | "sqlxml" | "string" | "time" | "timestamp" },
    attribute null { "true" | "false" }?,
    text
  }+
}?

With $options, the following parameter can be set:

  • timeout: query execution will be interrupted after the specified number of seconds.
Errors attribute: an attribute different from type and null is set for a <sql:parameter/> element.
error: an error occurred while executing SQL.
id: the specified connection does not exist.
parameters: no parameter type specified.
timeout: query execution exceeded timeout.
type: the value of a parameter cannot be converted to the specified format.

sql:prepare[edit]

Signature
sql:prepare(
  $id         as xs:anyURI,
  $statement  as xs:string
) as xs:anyURI
Summary This function prepares an SQL $statement, using the specified connection $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 NULL, then the attribute null of the <sql:parameter/> element must be true.
Errors error: an error occurred while executing SQL.
id: the specified connection does not exist.

sql:commit[edit]

Signature
sql:commit(
  $id  as xs:anyURI
) as empty-sequence()
Summary This function commits the changes made to a relational database, using the specified connection $id.
Errors error: an error occurred while executing SQL.
id: the specified connection does not exist.

sql:rollback[edit]

Signature
sql:rollback(
  $id  as xs:anyURI
) as empty-sequence()
Summary This function rolls back the changes made to a relational database, using the specified connection $id.
Errors error: an error occurred while executing SQL.
id: the specified connection does not exist.

sql:close[edit]

Signature
sql:close(
  $id  as xs:anyURI
) as empty-sequence()
Summary This function closes a database connection with the specified $id.
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: an error occurred while executing SQL.
id: the specified connection does not exist.

Examples[edit]

Direct queries[edit]

A simple select statement can be executed as follows:

let $id := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")
return sql:execute($id, "SELECT * FROM coffees WHERE price < 10")

The result may look like:

<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">3.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>

Prepared Statements[edit]

A prepared select statement can be executed in the following way:

(: 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)

SQLite[edit]

The following expression demonstrates how SQLite can be addressed with the Xerial SQLite JDBC driver:

(: Initialize driver :)
sql:init("org.sqlite.JDBC"),
(: Establish a connection :)
let $conn := sql:connect("jdbc:sqlite:database.db")
return (
  (: Create a new table :)
  sql:execute($conn, "drop table if exists person"),
  sql:execute($conn, "create table person (id integer, name string)"),
  (: Run 10 updates :)
  for $i in 1 to 10
  let $q := "insert into person values(" || $i || ", '" || $i || "')"
  return sql:execute($conn, $q),
  (: Return table contents :)
  sql:execute($conn, "select * from person")
)

Errors[edit]

Code Description
attribute An attribute different from type and null is set for a <sql:parameter/> element.
error An SQL exception occurred.
id A connection does not exist.
init A database driver is not found.
parameters No parameter type specified.
timeout Query execution exceeded timeout.
type The value of a parameter cannot be converted to the specified format.

Changelog[edit]

Version 11
Version 9.6
Version 9.0
  • Updated: sql:execute, sql:execute-prepared: Return update count for updating statements. $options argument added.
  • Updated: Connection ids are URIs now.
  • Updated: error codes updated; errors now use the module namespace
Version 7.5

The module was introduced with Version 7.0.