Sql query object
The Query object can be used for queries that return a result set (select statements), as well as those that do not (create, update, insert, delete etc...).
var qry = new Myna.Query({
dataSource:"hr_ds",
sql:"select last_name,first_name from employees"
});This creates a Query object and, because both dataSource and sql were provided, immediately executes the SQL. When a SQL statement is executed, several related properties are populated on the query object. Of particular interest for this query is Myna.Query.data. This property contains an array of objects that represent the returned rows. Each of these objects has a property for every column in the resultset and its corresponding value. Another useful property is Myna.Query.columns which is an array of column information objects in the order of appearance in the resultset.
Here is a quick example of displaying a Query in a table in an EJS file
<%
var qry = new Myna.Query({
dataSource:"hr_ds",
sql:"select * from employees",
startRow:10,
maxRows:10
});
%>
<table border="1" >
<caption> Records <%=qry.startRow%> - <%=qry.maxRows%> of <%=qry.totalRows%></caption>
<tr>
<@loop array='qry.columns' element='column'>
<th><%=column.name%></th>
</@loop>
</tr>
<@loop array='qry.data' element='row'>
<tr>
<@loop array='qry.columns' element='column'>
<th><%=String(row[column.name.toLowerCase()])%></th>
</@loop>
</tr>
</@loop>
</table>
Notice the extra parameters: startRow and maxRows. These define a “window” in the result set to return into the data property. startRow starts at 1. Myna.Query.totalRows contains the total number of rows that would have been returned if it was not limited. Have a look at Myna.Query.pageSize and Myna.Query.page for an alternate way setting the result window.
Myna.Query is useful for updates and inserts as well. When inserting data the Myna.Query.updateCount property is updated with the number of rows affected. It is also possible to use parametrized values in your queries. For example, dates are handled in highly variable ways between different databases. It is also dangerous to directly include client data into SQL queries because of the the possibility of injecting sql code. This is where Myna.QueryParams comes in. This class represents an array of explicitly typed parameters to your query. This array matches the order of ‘?’ symbols in your query. Here is an example:
var sql ='insert into employees(first_name,last_name,age,hire_date) values (?,?,?,?)'
var params = new Myna.QueryParams([
{
value:"Bob"
},{
value:"Dobb"
},{
value:32,
type:"INT4"
},{
value:Date.parseDate("01/01/1970","m/d/Y"),
type:"DATE"
}
])
var qry = new Myna.Query({
dataSource:"hr_ds",
sql:sql,
parameters:params
})
Here is more compact and maintainable version of the same query using embedded JavaScript blocks:
var p = new Myna.QueryParams();
var qry = new Myna.Query({
dataSource:"hr_ds",
sql:<ejs>
insert into employees(first_name,last_name,age,hire_date) values (
<%=p.addValue("Bob")%>,
<%=p.addValue("Dobb")%>,
<%=p.addValue(32,"INT4")%>,
<%=p.addValue(Date.parseDate("01/01/1970","m/d/Y"),"DATE")%>
)
</ejs>,
parameters:p
})
Because Myna.QueryParams.addValue returns a ‘?’ symbol, your parameters will always be aligned to the position of the ‘?’ symbols
What if you want to the run the above query again, but with different parameters?
var p = new Myna.QueryParams();
p.addValue("Joe");
p.addValue("Schmoe");
p.addValue(72,"INT4");
p.addValue(Date.parseDate("10/15/1995","m/d/Y"),"DATE");
var qry.execute({
parameters:p
})
Myna.Query.execute executes a query again, optionally overriding its properties
Queries can be cached to enhance performance of frequently accessed but infrequently changing data
//cache employee information for 12 hours
var qry=new Myna.Query({
ds:"hr_ds",
sql:"select * from employees",
cache:{
refreshInterval:Date.getInterval(Date.HOUR,12)
}
})
See Myna.Cache for more detail on caching.
See also Myna.Query.getRowByColumn and Myna.Query.valueArray for alternate ways of accessing the data in a query object
| Myna. Query | Sql query object |
| Functions | |
| Myna. Query | Construct a Query object |
| Properties | |
| columns | An Array of Objects that represent the columns in the result set. |
| dateFormat | if set to a string format (see <Date.format>), then any date or timestamp values will be converted to formatted strings. |
| data | An Array of Objects That represents the query data. |
| dataSource | The name of the datasource used to run the query. |
| ds | alternate name for Myna.Query.dataSource |
| sql | The SQL String of the query |
| executionTime | Elapsed time in milliseconds to run the query |
| generatedKey | For insert queries, contains the generated prymary key, if any |
| updateCount | Number of rows affected by the last update |
| parameters | Myna.QueryParams object representing query parameters |
| maxRows | Maximum number of rows to return. |
| startRow | Row number in result from which to start returning rows. |
| pageSize | Number of rows to return per page.Null means all rows. |
| page | Page to return. |
| totalRows | total rows in the query, if the entire result had been returned. |
| result | contains just data result of this query. |
| db | the Myna.Database object associated wioth this query |
| Functions | |
| formatSql | returns returns a multiline text formated string of this.sql with any values merged in |
| getRowByColumn | returns first row of the result set that matches the column and value suppplied |
| parseResultSet | parses a JDBC resultSet object and populates data |
| valueArray | returns an array of values of a column in the result set. |
| defaultRowHandler | default rowHandler if not overridden |
| rowHandler | handles each row in the query result set |
| execute | Executes an SQL query and updates and returns this Query object. |
| Myna. QueryResultRow | Object that represents a row in a jdbc result set that can retrieve values and metadata |
| Functions and Properties | |
| QueryResultRow | Constructs QueryResultRow object |
| query | a reference to the calling query |
| rs | a reference to the calling query’s java.sql.ResultSet object |
| columns | a reference to the calling query’s columns property |
| getValue | returns the value of the indicated column of the current row |
| getRow | returns all the values of the current row as a JavaScript object |
| rowNum | the current row number, starting with 1 |
| Myna. QueryParams | Object that contains query parameter information |
| Functions | |
| QueryParams | Constructs QueryParams object |
| addValue | adds an sql parameter value to to QueryParams and returns a paceholder. |
Myna.Query = function ( optionsOrResultSet )
Construct a Query object
| optionsOrResultSet | Either a java.sql.ResultSet object, or a Options Object that contains optional properties (see below), or null or undefined to create an empty query object |
| sql | SQL string |
| dataSource | string datasource name defined in Myna Administrator |
| deferExec | Optional default false Normally, new query objects are executed immediately. Setting this to true cancels that behavior. The query will not be executed without an explicit call to execute |
| parameters | Optional Default null Myna.QueryParams |
| maxRows | Optional Default null Maximum number of rows to return. null for all rows |
| rowHandler | Optional Default defaultRowHandler function to process each row in the resultset. This function is passed an instance of Myna.QueryResultRow and what is returned will be pushed onto Myna.Query.data |
| startRow | Optional Default 1 Row number in result from which to start returning rows. Starts with 1. Used with maxRows |
| pageSize | Optional Default null Number of rows to return per page. Null means all rows. Used with page |
| page | Optional Default null Page to return. Starts with 1. This is used with pageSize as a shortcut for startRow and maxRows. |
| cache | Optional, default null If defined, this is an options object describing how this query should be cached. All options of Myna.Cache are supported except the the “code” parameter which is generated by the query. |
An Array of Objects that represent the columns in the result set.
[
{
name:<String column name>,
typeId:<numeric JDBC type id>,
typeName:<String type name>
},
...
]
... created by parseResultSet
if set to a string format (see <Date.format>), then any date or timestamp values will be converted to formatted strings. If set to null (default) these values will be Date objects. Note that this will not change the type for date/time columns in Query.columns or Query.result.columns
An Array of Objects That represents the query data.
[
{
<column name>:<column value>,
...
},
...
]
... created by parseResultSet
The name of the datasource used to run the query. Datasources are configured in the Myna Administrator, located at webroot/myna/administrator/index.sjs
alternate name for Myna.Query.dataSource
Myna.QueryParams object representing query parameters
Page to return. Starts with 1. This is used with pageSize as a shortcut for startRow and maxRows. startRow is set to (((page - 1) * pageSize)+1) and max rows is set to pageSize
total rows in the query, if the entire result had been returned. The actual number of rows is data.length
contains just data result of this query.
this property is an object that loks like this:
{
data:[{colname:value}],
totalRows:numeric,
maxRows:numeric,
startRow:numeric,
columns:[{name:string,type:string}]
}the “type” in columns is the result from Myna.Database.dbTypeToJs for the database column type. This property is more appropriate for sending to a client as it is smaller and does not contain any internal information about your database tables
the Myna.Database object associated wioth this query
this property is only set when this query was initialized with a datasource
formatSql:function ()
returns returns a multiline text formated string of this.sql with any values merged in
getRowByColumn:function( columnName, value, start )
returns first row of the result set that matches the column and value suppplied
| columnName | Stirng name of the column to search |
| value | value to match |
| start | Optional default 0 index to start the search from |
first row of the result set that matches the column and value suppplied
parseResultSet:function( jdbcResultSet )
parses a JDBC resultSet object and populates data
| jdbcResultSet | JDBC resultSet |
| options | Object of optional parameters. See below. |
| maxRows | Default 0 (All rows) Maximum number of rows to return |
| startRow | Default 1 Row number in result from which to start returning rows. Starts with 1 |
this
valueArray:function( columnName )
returns an array of values of a column in the result set.
| columnName | String Column name to return |
defaultRowHandler:function( row )
default rowHandler if not overridden
| row | instance of Myna.QueryResultRow |
The default rowHandler function returns each row of the resultset as a JavaScript Object by calling Myna.QueryResultRow.getRow
rowHandler:function( row )
handles each row in the query result set
| row | instance of Myna.QueryResultRow |
This function takes row information and returns an object to be appended to Myna.Query.data. This can be overridden in the query parameters
execute:function( options )
Executes an SQL query and updates and returns this Query object.
| options | Object of optional parameters. See Myna.Query. |
execute executes this query object, optionally updating its properties.
this
var qry = new Query({
dataSource:"mythtv",
sql:<ejs>
select *
from channels
</ejs>,
startRow:1,
maxRows:10
})
qry.execute({startRow:11})Object that represents a row in a jdbc result set that can retrieve values and metadata
This object is normally constructed by <Myna.parseResultSet> to pass to Myna.Query.rowHandler
| Functions and Properties | |
| QueryResultRow | Constructs QueryResultRow object |
| query | a reference to the calling query |
| rs | a reference to the calling query’s java.sql.ResultSet object |
| columns | a reference to the calling query’s columns property |
| getValue | returns the value of the indicated column of the current row |
| getRow | returns all the values of the current row as a JavaScript object |
| rowNum | the current row number, starting with 1 |
Myna.QueryResultRow=function( rs, query )
Constructs QueryResultRow object
| rs | a java.sql.ResultSet object, intialized to a valid row. |
| query | the Myna.Query object that created the row. This object is expects to be initalized with the query metadata prior to contructing this object |
getValue:function( indexOrName )
returns the value of the indicated column of the current row
| indexOrName | The 0 based index of the column, or the column name |
Object that contains query parameter information
This object can be contructed from an array or via the Myna.QueryParams.addValue function. It represents an array of explicitly typed values to use in a query.
| Functions | |
| QueryParams | Constructs QueryParams object |
| addValue | adds an sql parameter value to to QueryParams and returns a paceholder. |
Myna.QueryParams=function( config )
Constructs QueryParams object
| config | Optional default null Array of parameter objects in the form of [{value:’value’,type:’type’,isNull:false}] |
addValue:function( value, type, isNull )
adds an sql parameter value to to QueryParams and returns a paceholder.
| value | value to store |
| type | Optional default ‘VARCHAR’ String or numeric JDBC type. See java.sql.types for the names |
| isNull | Optional default false If true, the value is ignored and an SQL null of the supplied type will be used instead |
Placeholder value for a prepared statement: “?”
Construct a Query object
Myna.Query = function ( optionsOrResultSet )
returns returns a multiline text formated string of this.sql with any values merged in
formatSql:function ()
returns first row of the result set that matches the column and value suppplied
getRowByColumn:function( columnName, value, start )
parses a JDBC resultSet object and populates data
parseResultSet:function( jdbcResultSet )
returns an array of values of a column in the result set.
valueArray:function( columnName )
default rowHandler if not overridden
defaultRowHandler:function( row )
handles each row in the query result set
rowHandler:function( row )
Executes an SQL query and updates and returns this Query object.
execute:function( options )
Constructs QueryResultRow object
Myna.QueryResultRow=function( rs, query )
returns the value of the indicated column of the current row
getValue:function( indexOrName )
returns all the values of the current row as a JavaScript object
getRow:function()
Constructs QueryParams object
Myna.QueryParams=function( config )
adds an sql parameter value to to QueryParams and returns a paceholder.
addValue:function( value, type, isNull )
Static function that takes a column type name (“VARCHAR”) or a column type id (-5) and returns string that represents the equivalent Myna type (string, numeric, date, binary, unsupported)
Myna.Database.dbTypeToJs = function( sourceType )