SQL API
Overview
The SQL API contains the Profound.js APIs used to run SQL statements against a database from a Profound.js module. The APIs follow the same model as embedded SQL in RPG: a statement can be run in a single step, or it can be prepared, have parameters bound to it, executed, and then fetched from row by row under program control. Rows can be returned as plain JavaScript objects, or fetched into strongly typed fields and data structures declared with pjs.define().
Because Profound.js runs these operations top-down without callbacks, the code reads in the same order it executes, which makes it straightforward to convert existing RPG programs with embedded SQL or to write new business logic.
The SQL API can be used with IBM i Db2, MySQL/MariaDB, Microsoft SQL Server, Oracle, and ODBC database connections. When using an IBM i database, these APIs require the Profound.js Connector module. Some options, such as the number of rows to fetch and fetching into strongly typed fields, are only available with the IBM i Db2 driver; each API page lists its own requirements and limitations. The SQL statement passed to any of these APIs must be valid for the database that the connection uses.
The APIs in this section fall into the following groups:
Running a query in one step - Prepare, execute, and fetch in a single call; for example
pjs.query()andpjs.parallelQueries().Preparing and executing statements - Control each step of the statement lifecycle with a statement handle; for example
pjs.prepare(),pjs.bindParameters(), andpjs.execute().Fetching rows - Move the cursor of an executed statement and read rows into fields, data structures, or objects; for example
pjs.fetch()andpjs.hasMoreRows().Selecting a database connection - Direct an API at a connection other than the default; for example
pjs.getDB()andpjs.getRemoteDB().Setting attributes and options - Change connection attributes, statement attributes, and program-level SQL options; for example
pjs.setStmtAttr()andpjs.setSQLOption().Building SQL statements - Escape user input and generate database-specific SQL syntax; for example
pjs.escapeString()andpjs.sqlHelper.Working without SQL - Add, retrieve, update, delete, and count records without writing SQL; for example the
pjs.dataAPIs.
Running a Query in One Step
These APIs are the simplest way to run SQL. They prepare the statement, bind any parameters, execute it, and fetch the results in a single call.
pjs.query() - Runs an SQL statement and returns the fetched rows as a JavaScript object or array of objects, or fetches them into strongly typed fields. Can also
INSERTorUPDATErecords from a plain JavaScript object.pjs.parallelQueries() - Runs an array of SQL statements at the same time and returns an array containing the result of each statement.
Preparing and Executing Statements
These APIs give the program control over each step of the statement lifecycle, in the same way as PREPARE, DECLARE CURSOR, OPEN, EXECUTE, and CLOSE in embedded SQL. Each API returns or accepts a statement handle. Most of these APIs can also be called as a method of the handle (for example, stmt.execute() instead of pjs.execute(stmt)).
pjs.allocStmt() - Allocates a statement handle for a statement that has no parameter markers.
pjs.prepare() - Prepares an SQL statement that contains parameter markers (
?) and returns a statement handle.pjs.bindParameters() - Binds values, or Profound.js fields for input/output parameters, to the parameter markers of a prepared statement.
pjs.execute() - Executes a prepared statement after its parameters have been bound.
pjs.executeDirect() - Executes an SQL statement string that has no parameter markers on a handle from
pjs.allocStmt().pjs.close() - Closes a statement handle and its cursor. Open handles are closed automatically when the module ends or an error occurs, but every handle should be closed when the program is finished with it.
Fetching Rows
After a statement has been executed with pjs.execute() or pjs.executeDirect(), the SQL Fetch API reads rows from its cursor. These APIs correspond to the FETCH statement in embedded SQL and include:
pjs.fetch() and pjs.fetchNext() - Fetch the next row, or block of rows, from the current cursor position.
pjs.fetchPrior(), pjs.fetchFirst(), pjs.fetchLast(), pjs.fetchAbsolute(), and pjs.fetchRelative() - Move the cursor backward, to the first or last row, to a specific row number, or to a row at an offset from the current position.
pjs.rowCount(), pjs.hasMoreRows(), and statement.endOfData() - Report how many rows the last fetch returned and whether the end of the result set has been reached.
Selecting a Database Connection
By default, every SQL API uses the instance's default database connection. To use a different connection defined in the Profound.js configuration, pass a database connection definition object as the first parameter of the API, followed by the parameters documented for that API.
pjs.getDB() - Returns a database connection definition object for a named connection from the configuration, or for the default connection.
pjs.getRemoteDB() - Returns a connection definition object for a remote IBM i Db2 database. Only supported when the module is called from IBM i through
PJSCALLor a proxy program.pjs.connect() - Connects to a remote IBM i Db2 database, the equivalent of the embedded SQL
CONNECTstatement.pjs.disconnect() - Disconnects from a remote IBM i Db2 database.
pjs.getConnection() - Returns the underlying connection object established by Profound.js for a database connection, which exposes the properties and methods of the database driver in use.
Setting Attributes and Options
pjs.setConnectAttr() - Sets an attribute of an SQL connection, such as the commitment control level.
pjs.setStmtAttr() - Sets an attribute of a statement handle, such as cursor sensitivity or the
preciseDecimalsetting for its result set.pjs.setSQLOption() - Sets an IBM i Db2 SQL option for the current program or module, such as
NAMING,COMMIT, orDATFMT, the equivalent ofEXEC SQL SET OPTION.pjs.getSQLOption() - Returns the current value of an SQL option set with
pjs.setSQLOption().
Building SQL Statements
pjs.escapeString() - Escapes single quotes in a string so that user input can be placed safely inside an SQL statement. Prepared statements with bound parameters do this automatically and are the preferred approach.
pjs.sqlHelper - Provides functions that format table names, column names, and parameter tokens using the correct syntax for the target database, so that one module can build SQL for more than one database type.
Working Without SQL
Data API - The
pjs.dataAPIs add, retrieve, update, delete, and count records in a table or view from plain JavaScript values. Profound.js builds the SQL for the database in use, so the same code runs against any supported database.
Diagnostics and Error Handling
After each SQL API call, the SQL diagnostics are reported in the SQLCA. The SQLCA fields are available in a Profound.js module under their lowercase names; sqlcode is 0 and sqlstate is "00000" when the call succeeded, and sqlcode is 100 when a fetch finds no more rows. When the PJS_SQL_DEBUG environment variable is set, the SQL API also writes diagnostic information to the instance's standard output (see SQL Diagnostics).
Typical Program Flow
The following example shows how the APIs in this section fit together. A search value is bound to a prepared statement, the matching rows are fetched one at a time into strongly typed fields, and the statement is closed. The example uses the sample IBM i Db2 table demolib/productsp with the columns prid (packed decimal 5,0), prname (char 30), and prdesc (char 60); replace the library, table, and column names with your own.
function listProducts(search) {
// Define one field for each column that will be fetched.
// The field definitions should match the table column definitions.
pjs.define("prid", { type: "packed decimal", length: 5, decimals: 0 });
pjs.define("prname", { type: "char", length: 30 });
pjs.define("prdesc", { type: "char", length: 60 });
var count = 0;
// Prepare the statement. The ? is a parameter marker that will be
// replaced by a bound value, so user input never has to be escaped.
var stmt = pjs.prepare("SELECT prid, prname, prdesc FROM demolib/productsp WHERE prdesc LIKE ? ORDER BY prid");
// Bind the search value and execute the statement.
stmt.bindParameters("%" + search.trim() + "%");
stmt.execute();
// sqlstate is updated after every SQL API call. "00000" means success.
if (sqlstate == "00000") {
// Fetch the first row. Each column value is placed into the matching field.
pjs.fetch(stmt, prid, prname, prdesc);
// hasMoreRows() returns false once a fetch finds no more rows.
while (stmt.hasMoreRows()) {
console.log("Product " + prid + ": " + prname);
count++;
// Fetch the next row into the same fields.
pjs.fetch(stmt, prid, prname, prdesc);
}
}
// Close the cursor and free the statement handle.
stmt.close();
return count;
}
exports.default = listProducts;For the simple case of retrieving all matching rows in one call, the same result can be produced with pjs.query():
// Prepare, bind, execute, and fetch in one step. The rows are returned as an
// array of plain JavaScript objects whose property names are the column names.
var records = pjs.query("SELECT prid, prname, prdesc FROM demolib/productsp WHERE prdesc LIKE ? ORDER BY prid", "%" + search.trim() + "%");
records.forEach(function(record) {
console.log("Product " + record.prid + ": " + record.prname);
});Related Pages
- Data API
- pjs.allocStmt()
- pjs.bindParameters()
- pjs.close()
- pjs.connect()
- pjs.disconnect()
- pjs.escapeString()
- pjs.execute()
- pjs.executeDirect()
- pjs.getConnection()
- pjs.getDB()
- pjs.getRemoteDB()
- pjs.getSQLOption()
- pjs.parallelQueries()
- pjs.prepare()
- pjs.query()
- pjs.setConnectAttr()
- pjs.setSQLOption()
- pjs.setStmtAttr()
- pjs.sqlHelper
- SQL Diagnostics
- SQL Examples
- SQL Fetch API