A Database object represents a virtual connection to a database. The Database class is meant to be subclassed by database adapters in order to provide the functionality needed for executing queries.

Static Properties
PropertyTypeDefault ValueDescription
AUTOINCREMENTproperty'AUTOINCREMENT'

Default AUTO INCREMENT SQL

CASCADEproperty'CASCADE'

Default CASCACDE SQL

COMMA_SEPARATORproperty'

Default comma

DATABASESpatio.Database[]DATABASES

A list of currently connected Databases.

NOT_NULLproperty' NOT NULL'

Default NOT NULL SQL

NO_ACTIONproperty'NO ACTION'

Default NO ACTION SQL

NULLproperty' NULL'

Default NULL SQL

PRIMARY_KEYproperty' PRIMARY KEY'

Default PRIMARY KEY SQL

RESTRICTproperty'RESTRICT'

Default RESTRICT SQL

SET_DEFAULTproperty'SET DEFAULT'

Default SET DEFAULT SQL

SET_NULLproperty'SET NULL'

Default SET NULL SQL

TEMPORARYproperty'TEMPORARY '

Default TEMPORARY SQL

UNDERSCOREproperty'_'

Default UNDERSCORE SQL, used in index creation.

UNIQUEproperty' UNIQUE'

Default UNIQUE SQL

UNSIGNEDproperty' UNSIGNED'

Default UNSIGNED SQL

identifierInputMethodStringfunction (){ return this.__identifierInputMethod; }

The String or comb method to use transform identifiers with when they are sent to database. See patio#identifierInputMethod

identifierOutputMethodStringfunction (){ return this.__identifierOutputMethod; }

The String or comb method to use transform identifiers with when they are retrieved from database. See patio#identifierOutputMethod

loggerfunctionfunction (){ return LOGGER; }

The "patio.Database" logger.

quoteIdentifiersBooleanfunction (){ return this.__quoteIdentifiers; }

Boolean of whether or not to quote identifiers before sending then to the database. See patio#quoteIdentifiers

Instance Properties
PropertyTypeDefault ValueDescription
SQL_BEGINproperty'BEGIN'

The BEGIN SQL fragment used to signify the start of a transaciton.

SQL_COMMITproperty'COMMIT'

The COMMIT SQL fragment used to signify the end of a transaction and the final commit.

SQL_RELEASE_SAVEPOINTproperty'RELEASE SAVEPOINT autopoint_%d'

The RELEASE SAVEPOINT SQL fragment used by trasactions when using save points. The adapter should override this SQL fragment if the adapters SQL is different.

This fragment will not be used if patio.Database#supportsSavepoints is false.

SQL_ROLLBACKproperty'ROLLBACK'

The ROLLBACK SQL fragment used to rollback a database transaction. This should be overrode by adapters if the SQL for the adapters database is different.

SQL_ROLLBACK_TO_SAVEPOINTproperty'ROLLBACK TO SAVEPOINT autopoint_%d'

The ROLLBACK TO SAVEPOINT SQL fragment used to rollback a database transaction to a particular save point. This should be overrode by adapters if the SQL for the adapters database is different.

This fragment will not be used if patio.Database#supportsSavepoints is false.

SQL_SAVEPOINTproperty'SAVEPOINT autopoint_%d'

The SAVEPOINT SQL fragment used for creating a save point in a database transaction.

This fragment will not be used if patio.Database#supportsSavepoints is false.

TRANSACTION_ISOLATION_LEVELSproperty{ uncommitted: 'READ UNCOMMITTED', committed: 'READ COMMITTED', repeatable: 'REPEATABLE READ', serializable: 'SERIALIZABLE' }

Object containing different database transaction isolation levels. This object is used to look up the proper SQL when starting a new transaction and setting the isolation level in the options.

__schemaUtiltyDatasetfunctionfunction (){ this.__schemaUtiltyDs = this.__schemaUtiltyDs || this.dataset; return this.__schemaUtiltyDs; }
autoIncrementSqlfunctionfunction (){ return this._static.AUTOINCREMENT; }
beginTransactionSqlStringfunction (){ return this.SQL_BEGIN; }

SQL to BEGIN a transaction. See patio.Database#SQL_BEGIN for default,

commitTransactionSqlStringfunction (){ return this.SQL_COMMIT; }

SQL to COMMIT a transaction. See patio.Database#SQL_COMMIT for default,

connectionExecuteMethodproperty"execute"

The method name to invoke on a connection. The method name should be overrode by an adapter if the method to execute a query is different for the adapter specific connection class.

connectionPoolDefaultOptionsObjectfunction (){ return {}; }

The default options for the connection pool.

datasetpatio.Dataset

returns an empty adapter specific patio.Dataset that can be used to query the patio.Database with.

defaultPrimaryKeyTypeString "integer"

Default type for primary/foreign keys when a type is not specified.

defaultPrimaryKeyTypeDefaultString "integer"

Default type for primary/foreign keys when a type is not specified.

defaultSchemaDefault{String|patio.sql.Identifier}function (){ return null; }

Default schema to use. This is generally null but may be overridden by an adapter.

identifierInputMethodStringfunction (){ return this.__identifierInputMethod; }

The String or comb method to use transform identifiers with when sending identifiers to the database. If this property is undefined then patio.Database#identifierInputMethodDefault will be used.

identifierInputMethodDefaultString toUpperCase

The default String or comb method to use transform identifiers with when sending identifiers to the database.

identifierOutputMethodStringfunction (){ return this.__identifierOutputMethod; }

The String or comb method to use transform identifiers with when they are retrieved from database. If this property is undefined then patio.Database#identifierOutputMethodDefault will be used.

identifierOutputMethodDefaultString toLowerCase

The default String or comb method to use transform identifiers with when they are retrieved from the database.

inputIdentifierFuncFunctionfunction (){ var ds = this.dataset; return function (ident) { return ds.inputIdentifier(ident); }; }

Return a function for the dataset's patio.Dataset#inputIdentifierMethod. Used in metadata parsing to make sure the returned information is in the correct format.

loggerfunctionfunction (){ return LOGGER; }

The "patio.Database" logger.

metadataDatasetpatio.Datasetfunction (){ if (this.__metadataDataset) { return this.__metadataDataset; } var ds = this.dataset; ds.identifierInputMethod = this.identifierInputMethod; ds.identifierOutputMethod = this.identifierOutputMethod; this.__metadataDataset = ds; return ds; }

Return a dataset that uses the default identifier input and output methods for this database. Used when parsing metadata so that column are returned as expected.

outputIdentifierFuncFunctionfunction (){ var ds = this.dataset; return function (ident) { return ds.outputIdentifier(ident); }; }

Return a function for the dataset's patio.Dataset#outputIdentifierMethod. Used in metadata parsing to make sure the returned information is in the correct format.

quoteIdentifiersBoolean true

Boolean of whether or not to quote identifiers before sending then to the database. If this property is undefined then then patio.Database#quoteIdentifiersDefault will be used.

quoteIdentifiersDefaultBoolean true

Default boolean of whether or not to quote identifiers before sending then to the database.

rollbackTransactionSqlStringfunction (){ return this.SQL_ROLLBACK; }

SQL to ROLLBACK a transaction. See patio.Database#SQL_ROLLBACK for default,

serialPrimaryKeyOptionsObject {primaryKey : true, type : "integer", autoIncrement : true}

Default serial primary key options, used by the table creation code.

supportsPreparedTransactionsBoolean false

Whether the database and adapter support prepared transactions (two-phase commit)

supportsSavepointsBoolean false

Whether the database and adapter support savepoints.

supportsTransactionIsolationLevelsBoolean false

Whether the database and adapter support transaction isolation levels.

temporaryTableSqlfunctionfunction (){ return this._static.TEMPORARY; }
uriString

A database URI used to create the database connection. This property is available even if an object was used to create the database connection.

Constructor

Defined database/index.js Source
function (opts){
   opts = opts || {};
   if (!patio) {
       patio = require("../index");
   }
   this.patio = patio;
   this._super(arguments, [opts]);
   opts = merge(this.connectionPoolDefaultOptions, opts);
   this.schemas = {};
   this.type = opts.type;
   this.defaultSchema = opts.defaultSchema || this.defaultSchemaDefault;
   this.preparedStatements = {};
   this.opts = opts;
   this.pool = ConnectionPool.getPool(opts, hitch(this, this.createConnection), hitch(this, this.closeConnection), hitch(this, this.validate));
           
}
            

connect Static Function Public


Defined database/connect.js

Creates a connection to a Database see patio#createConnection.

Arguments Source
function (connectionString,opts){
   opts = opts || {};
   if (isString(connectionString)) {
       var url = URL.parse(connectionString, true);
       if (url.auth) {
           var parts = url.auth.split(":");
           if (!opts.user) {
               opts.user = parts[0];
           }
           if (!opts.password) {
               opts.password = parts[1];
           }
       }
       opts.type = url.protocol.replace(":", "");
       opts.host = url.hostname;
       if (url.port) {
           opts.port = url.port;
       }
       if (url.pathname) {
           var path = url.pathname;
           var pathParts = path.split("/").slice(1);
           if (pathParts.length >= 1) {
               opts.database = pathParts[0];
           }
       }
       opts = merge(opts, url.query, {uri: connectionString});
   } else {
       opts = merge({}, connectionString, opts);
   }
   if (opts && isHash(opts) && (opts.adapter || opts.type)) {
       var type = (opts.type = opts.adapter || opts.type);
       var Adapter = ADAPTERS[type];
       if (Adapter) {
           var adapter = new Adapter(opts);
           this.DATABASES.push(adapter);
           return adapter;
       } else {
           throw new DatabaseError(type + " adapter was not found");
       }
   } else {
       throw new DatabaseError("Options required when connecting.");
   }
           
}
    

logDebug Static Function Public


Defined database/logging.js

Logs a DEBUG level message to the "patio.Database" logger.

Source
function (){
   if (LOGGER.isDebug) {
       LOGGER.debug.apply(LOGGER, arguments);
   }
           
}
    

logError Static Function Public


Defined database/logging.js

Logs a ERROR level message to the "patio.Database" logger.

Source
function (){
   if (LOGGER.isError) {
       LOGGER.error.apply(LOGGER, arguments);
   }
           
}
    

logFatal Static Function Public


Defined database/logging.js

Logs a FATAL level message to the "patio.Database" logger.

Source
function (){
   if (LOGGER.isFatal) {
       LOGGER.fatal.apply(LOGGER, arguments);
   }
           
}
    

logInfo Static Function Public


Defined database/logging.js

Logs an INFO level message to the "patio.Database" logger.

Source
function (){
   if (LOGGER.isInfo) {
       LOGGER.info.apply(LOGGER, arguments);
   }
           
}
    

logTrace Static Function Public


Defined database/logging.js

Logs a TRACE level message to the "patio.Database" logger.

Source
function (){
   if (LOGGER.isTrace) {
       LOGGER.trace.apply(LOGGER, arguments);
   }
           
}
    

logWarn Static Function Public


Defined database/logging.js

Logs a WARN level message to the "patio.Database" logger.

Source
function (){
   if (LOGGER.isWarn) {
       LOGGER.warn.apply(LOGGER, arguments);
   }
           
}
    

__alterTableSql Function Private


Defined database/schema.js

Arguments Source
function (table,op){
   var ret = new Promise();
   var quotedName = op.name ? this.__quoteIdentifier(op.name) : null;
   var alterTableOp = null;
   switch (op.op) {
   case "addColumn":
       alterTableOp = format("ADD COLUMN %s", this.__columnDefinitionSql(op));
       break;
   case "dropColumn":
       alterTableOp = format("DROP COLUMN %s", quotedName);
       break;
   case "renameColumn":
       alterTableOp = format("RENAME COLUMN %s TO %s", quotedName, this.__quoteIdentifier(op.newName));
       break;
   case "setColumnType":
       alterTableOp = format("ALTER COLUMN %s TYPE %s", quotedName, this.typeLiteral(op));
       break;
   case "setColumnDefault":
       alterTableOp = format("ALTER COLUMN %s SET DEFAULT %s", quotedName, this.literal(op["default"]));
       break;
   case "setColumnNull":
       alterTableOp = format("ALTER COLUMN %s %s NOT NULL", quotedName, op["null"] ? "DROP" : "SET");
       break;
   case "addIndex":
       return ret.callback(this.__indexDefinitionSql(table, op)).promise();
   case "dropIndex":
       return ret.callback(this.__dropIndexSql(table, op)).promise();
   case "addConstraint":
       alterTableOp = format("ADD %s", this.__constraintDefinitionSql(op));
       break;
   case "dropConstraint":
       alterTableOp = format("DROP CONSTRAINT %s", quotedName);
       break;
   case "noInherit":
       alterTableOp = format("NO INHERIT %s", quotedName);
       break;
   default :
       throw new DatabaseError("Invalid altertable operator");
   }
   return ret.callback(format("ALTER TABLE %s %s", this.__quoteSchemaTable(table), alterTableOp)).promise();
           
}
    

__alterTableSqlList Function Private


Defined database/schema.js

Arguments Source
function (table,operations){
   var self = this;
   return new PromiseList(operations.map(function (operation) {
       return self.__alterTableSql(table, operation);
   }));
           
}
    

__columnDefinitionSql Function Private


Defined database/schema.js

Arguments Source
function (column){
   var sql = [format("%s %s", this.__quoteIdentifier(column.name), this.typeLiteral(column))];
   column.unique && sql.push(this._static.UNIQUE);
   (column.allowNull === false || column["null"] === false) && sql.push(this._static.NOT_NULL);
   (column.allowNull === true || column["null"] === true) && sql.push(this._static.NULL);
   !isUndefined(column["default"]) && sql.push(format(" DEFAULT %s", this.literal(column["default"])));
   column.primaryKey && sql.push(this._static.PRIMARY_KEY);
   column.autoIncrement && sql.push(" " + this.autoIncrementSql);
   column.table && sql.push(this.__columnReferencesColumnConstraintSql(column));
   return sql.join("");
           
}
    

__columnListSql Function Private


Defined database/schema.js

Arguments Source
function (generator){
   var self = this;
   return generator.columns.map(function (column) {
       return self.__columnDefinitionSql(column);
   }).concat(generator.constraints.map(function (constraint) {
       return self.__constraintDefinitionSql(constraint);
   })).join(this._static.COMMA_SEPARATOR);
           
}
    

__columnReferencesColumnConstraintSql Function Private


Defined database/schema.js

Arguments Source
function (column){
   return this.__columnReferencesSql(column);
           
}
    

__columnReferencesSql Function Private


Defined database/schema.js

Arguments Source
function (column){
   var sql = format(" REFERENCES %s", this.__quoteSchemaTable(column.table));
   column.key && (sql += format("(%s)", array.toArray(column.key).map(this.__quoteIdentifier, this).join(this._static.COMMA_SEPARATOR)));
   column.onDelete && (sql += format(" ON DELETE %s", this.__onDeleteClause(column.onDelete)));
   column.onUpdate && (sql += format(" ON UPDATE %s", this.__onUpdateClause(column.onUpdate)));
   column.deferrable && (sql += " DEFERRABLE INITIALLY DEFERRED");
   return sql;
           
}
    

__columnReferencesTableConstraintSql Function Private


Defined database/schema.js

Arguments Source
function (constraint){
   return format("FOREIGN KEY %s%s", this.literal(constraint.columns.map(function (c) {
       return isString(c) ? sql.stringToIdentifier(c) : c;
   })), this.__columnReferencesSql(constraint));
           
}
    

__constraintDefinitionSql Function Private


Defined database/schema.js

Arguments Source
function (constraint){
   var ret = [constraint.name ? format("CONSTRAINT %s ", this.__quoteIdentifier(constraint.name)) : ""];
   switch (constraint.type) {
   case "check":
       var check = constraint.check;
       ret.push(format("CHECK %s", this.__filterExpr(isArray(check) && check.length === 1 ? check[0] : check)));
       break;
   case "primaryKey":
       ret.push(format("PRIMARY KEY %s", this.literal(constraint.columns.map(function (c) {
           return isString(c) ? sql.stringToIdentifier(c) : c;
       }))));
       break;
   case "foreignKey":
       ret.push(this.__columnReferencesTableConstraintSql(constraint));
       break;
   case "unique":
       ret.push(format("UNIQUE %s", this.literal(constraint.columns.map(function (c) {
           return isString(c) ? sql.stringToIdentifier(c) : c;
       }))));
       break;
   default:
       throw new DatabaseError(format("Invalid constriant type %s, should be 'check', 'primaryKey', foreignKey', or 'unique'", constraint.type));
   }
   return ret.join("");
           
}
    

__createTableFromGenerator Function Private


Defined database/schema.js

Arguments Source
function (name,generator,options){
   return this.executeDdl(this.__createTableSql(name, generator, options));
           
}
    

__createTableIndexesFromGenerator Function Private


Defined database/schema.js

Arguments Source
function (name,generator,options){
   var e = options.ignoreIndexErrors;
   var ret;
   var promises = generator.indexes.map(function (index) {
       var ps = this.__indexSqlList(name, [index]).map(this.executeDdl, this);
       return new PromiseList(ps);
   }, this);
   if (promises.length) {
       ret = new PromiseList(promises).chain(function (res) {
           return res;
       }, function (err) {
           if (!e) {
               throw err;
           }
       });
   } else {
       ret = new Promise().callback();
   }
   return ret.promise();
           
}
    

__createTableSql Function Private


Defined database/schema.js

Arguments Source
function (name,generator,options){
   return format("CREATE %sTABLE %s (%s)", options.temp ? this.temporaryTableSql : "", this.__quoteSchemaTable(name), this.__columnListSql(generator));
           
}
    

__createViewSql Function Private


Defined database/schema.js

Arguments Source
function (name,source,opts){
   var sql = "CREATE";
   opts = opts || {};
   if (opts.replace) {
       sql += " OR REPLACE";
   }
   sql += " VIEW %s AS %s";
   return format(sql, this.__quoteSchemaTable(name), source);
           
}
    

__defaultIndexName Function Private


Defined database/schema.js

Arguments Source
function (tableName,columns){
   var parts = this.__schemaAndTable(tableName);
   var schema = parts[0], table = parts[1];
   var index = [];
   if (schema && schema !== this.defaultSchema) {
       index.push(schema);
   }
   index.push(table);
   index = index.concat(columns.map(function (c) {
       return isString(c) ? c : this.literal(c).replace(/\W/g, "");
   }, this));
   index.push("index");
   return index.join(this._static.UNDERSCORE);
           
}
    

__dropIndexSql Function Private


Defined database/schema.js

Arguments Source
function (table,op){
   return format("DROP INDEX %s", this.__quoteIdentifier(op.name || this.__defaultIndexName(table, op.columns)));
           
}
    

__dropTableSql Function Private


Defined database/schema.js

Arguments Source
function (name){
   return format("DROP TABLE %s", this.__quoteSchemaTable(name));
           
}
    

__dropViewSql Function Private


Defined database/schema.js

Arguments Source
function (name){
   return format("DROP VIEW %s", this.__quoteSchemaTable(name));
           
}
    

__filterExpr Function Private


Defined database/schema.js

Arguments Source
function (args,block){
   var ds = this.__schemaUtiltyDataset;
   return ds.literal(ds._filterExpr.apply(ds, arguments));
           
}
    

__indexDefinitionSql Function Private


Defined database/schema.js

Arguments Source
function (tableName,index){
   var indexName = index.name || this.__defaultIndexName(tableName, index.columns);
   if (index.type) {
       throw new DatabaseError("Index types are not supported for this database");
   } else if (index.where) {
       throw new DatabaseError("Partial indexes are not supported for this database");
   } else {
       return format("CREATE %sINDEX %s ON %s %s", index.unique ? "UNIQUE " : "", this.__quoteIdentifier(indexName), this.__quoteSchemaTable(tableName), this.literal(index.columns.map(function (c) {
           return isString(c) ? new Identifier(c) : c;
       })));
   }
           
}
    

__indexSqlList Function Private


Defined database/schema.js

Array of SQL DDL statements, one for each index specification, for the given table.

Arguments Source
function (tableName,indexes){
   var self = this;
   return indexes.map(function (index) {
       return self.__indexDefinitionSql(tableName, index);
   });
           
}
    

__onDeleteClause Function Private


Defined database/schema.js

Arguments Source
function (action){
   return this._static[action.toUpperCase()] || this._static.NO_ACTION;
           
}
    

__onUpdateClause Function Private


Defined database/schema.js

Arguments Source
function (action){
   return this._static[action.toUpperCase()] || this._static.NO_ACTION;
           
}
    

__quoteIdentifier Function Private


Defined database/schema.js

Arguments Source
function (v){
   return this.__schemaUtiltyDataset.quoteIdentifier(v);
           
}
    

__quoteSchemaTable Function Private


Defined database/schema.js

Arguments Source
function (table){
   return this.__schemaUtiltyDataset.quoteSchemaTable(table);
           
}
    

__renameTableSql Function Private


Defined database/schema.js

Arguments Source
function (name,newName){
   return format("ALTER TABLE %s RENAME TO %s", this.__quoteSchemaTable(name), this.__quoteSchemaTable(newName));
           
}
    

__resetSchemaUtilityDataset Function Private


Defined database/schema.js

Source
function (){
   this.__schemaUtiltyDs = null;
           
}
    

__schemaAndTable Function Private


Defined database/schema.js

Arguments Source
function (tableName){
   return this.__schemaUtiltyDataset.schemaAndTable(tableName);
           
}
    

__typeLiteralGeneric Function Private


Defined database/schema.js

Arguments Source
function (column){
   var type = column.type;
   var meth = "__typeLiteralGeneric";
   var isStr = isString(type);
   var proper = isStr ? type.charAt(0).toUpperCase() + type.substr(1) : null;
   if (type === String || (isStr && type.match(/string/i))) {
       meth += "String";
   } else if ((isStr && type.match(/number/i)) || type === Number) {
       meth += "Numeric";
   } else if ((isStr && type.match(/datetime/i)) || type === DateTime) {
       meth += "DateTime";
   } else if ((isStr && type.match(/date/i)) || type === Date) {
       meth += "Date";
   } else if ((isStr && type.match(/year/i)) || type === Year) {
       meth += "Year";
   } else if ((isStr && type.match(/timestamp/i)) || type === TimeStamp) {
       meth += "Timestamp";
   } else if ((isStr && type.match(/time/i)) || type === Time) {
       meth += "Time";
   } else if ((isStr && type.match(/decimal/i)) || type === Decimal) {
       meth += "Decimal";
   } else if ((isStr && type.match(/float/i)) || type === Float) {
       meth += "Float";
   } else if ((isStr && type.match(/boolean/i)) || type === Boolean) {
       meth += "Boolean";
   } else if ((isStr && type.match(/buffer/i)) || type === Buffer) {
       meth += "Blob";
   } else if ((isStr && type.match(/json/i)) || type === Json) {
       meth += "Json";
   } else if (isStr && isFunction(this[meth + proper])) {
       meth += proper;
   } else {
       return this.__typeLiteralSpecific(column);
   }
   return this[meth](column);
           
}
    

__typeLiteralGenericBlob Function Private


Defined database/schema.js

Arguments Source
function (column){
   return "blob";
           
}
    

__typeLiteralGenericBoolean Function Private


Defined database/schema.js

Arguments Source
function (column){
   return "boolean";
           
}
    

__typeLiteralGenericDate Function Private


Defined database/schema.js

Arguments Source
function (column){
   var type = column.type, ret = "date";
   if (column.onlyTime) {
       ret = "time";
   } else if (column.timeStamp) {
       ret = "timestamp";
   } else if (column.dateTime) {
       ret = "datetime";
   } else if (column.yearOnly) {
       ret = "year";
   }
   return ret;
           
}
    

__typeLiteralGenericDateTime Function Private


Defined database/schema.js

Arguments Source
function (column){
   return "datetime";
           
}
    

__typeLiteralGenericDecimal Function Private


Defined database/schema.js

Arguments Source
function (column){
   return "double precision";
           
}
    

__typeLiteralGenericFloat Function Private


Defined database/schema.js

Arguments Source
function (column){
   return "double precision";
           
}
    

__typeLiteralGenericJson Function Private


Defined database/schema.js

Arguments Source
function (column){
   return "json";
           
}
    

__typeLiteralGenericNumeric Function Private


Defined database/schema.js

Arguments Source
function (column){
   return column.size ? format("numeric(%s)", array.toArray(column.size).join(', ')) : column.isInt ? "integer" : column.isDouble ? "double precision" : "numeric";
           
}
    

__typeLiteralGenericString Function Private


Defined database/schema.js

Arguments Source
function (column){
   return column.text ? "text" : format("%s(%s)", column.fixed ? "char" : "varchar", column.size || 255);
           
}
    

__typeLiteralGenericTime Function Private


Defined database/schema.js

Arguments Source
function (column){
   return "time";
           
}
    

__typeLiteralGenericTimestamp Function Private


Defined database/schema.js

Arguments Source
function (column){
   return "timestamp";
           
}
    

__typeLiteralGenericYear Function Private


Defined database/schema.js

Arguments Source
function (column){
   return "year";
           
}
    

__typeLiteralSpecific Function Private


Defined database/schema.js

Arguments Source
function (column){
   var type = column.type;
   type = type === "double" ? "double precision" : type;
   if (type === "varchar") {
       column.size = isNumber(column.size) ? column.size : 255;
   }
   var elements = column.size || column.elements;
   return format("%s%s%s", type, elements ? this.literal(toArray(elements)) : "", column.unsigned ? " UNSIGNED" : "");
           
}
    

_schemaAutoincrementingPrimaryKey Function Private


Defined database/schema.js

Arguments Source
function (schema){
   return !!schema.primaryKey;
           
}
    

addColumn Function Public


Defined database/schema.js

Adds a column to the specified table. This method expects a column name, a datatype and optionally a hash with additional constraints and options:

This method is a shortcut to patio.Database#alterTable with an addColumn call.

Example
//Outside of a table
//ALTER TABLE test ADD COLUMN name text UNIQUE'
DB.addColumn("test", "name", "text", {unique : true});
        
Arguments Returns Source
function (table,column,type,opts){
   var args = argsToArray(arguments).slice(1);
   return this.alterTable(table, function () {
       this.addColumn.apply(this, args);
   });
           
}
    

addIndex Function Public


Defined database/schema.js

Adds an index to a table for the given columns

This method is a shortcut to patio.Database#alterTable with an addIndex call.

Example
DB.addIndex("test", "name", {unique : true});
     //=> 'CREATE UNIQUE INDEX test_name_index ON test (name)'
DB.addIndex("test", ["one", "two"]);
     //=> ''CREATE INDEX test_one_two_index ON test (one, two)''
        
Arguments Returns Source
function (table,columns,options){
   options = options || {};
   var ignoreErrors = options.ignoreErrors === true;
   return this.alterTable(table, function () {
       this.addIndex(columns, options);
   }).chain(function (res) {
       return res;
   }, function (err) {
       if (!ignoreErrors) {
           throw err;
       }
   });
           
}
    

alreadyInTransaction Function Public


Defined database/query.js

Returns true if this DATABASE is currently in a transaction.

Arguments Returns Source
function (conn,opts){
   opts = opts || {};
   return this.__transactions.indexOf(conn) !== -1 && (!this.supportsSavepoints || !opts.savepoint);
           
}
    

alterTable Function Public


Defined database/schema.js

Alters the given table with the specified block.

NOTE: The block is invoked in the scope of the table that is being altered. The block is also called with the table as the first argument. Within the block you must use this(If the block has not been bound to a different scope), or the table object that is passed in for all alter table operations. See patio.AlterTableGenerator for avaiable operations.

Note that addColumn accepts all the options available for column definitions using createTable, and addIndex accepts all the options available for index definition.

Example
//using the table object
  DB.alterTable("items", function(table){
     //you must use the passed in table object.
    table.addColumn("category", "text", {default : 'javascript'});
    table.dropColumn("category");
    table.renameColumn("cntr", "counter");
    table.setColumnType("value", "float");
    table.setColumnDefault("value", "float");
    table.addIndex(["group", "category"]);
    table.dropIndex(["group", "category"]);
  });

  //using this
   DB.alterTable("items", function(){
    this.addColumn("category", "text", {default : 'javascript'});
    this.dropColumn("category");
    this.renameColumn("cntr", "counter");
    this.setColumnType("value", "float");
    this.setColumnDefault("value", "float");
    this.addIndex(["group", "category"]);
    this.dropIndex(["group", "category"]);
  });

  //This will not work
  DB.alterTable("items", comb.hitch(someObject, function(){
   //This is called in the scope of someObject so this
   //will not work and will throw an error
    this.addColumn("category", "text", {default : 'javascript'});
  }));

   //This will work
  DB.alterTable("items", comb.hitch(someObject, function(table){
   //This is called in the scope of someObject so you must
   //use the table argument
    table.category("text", {default : 'javascript'});
  }));
        
Arguments Returns Source
function (name,generator,block){
   if (isFunction(generator)) {
       block = generator;
       generator = new AlterTableGenerator(this, block);
   }
   var self = this;
   return this.__alterTableSqlList(name, generator.operations).chain(function (res) {
       return asyncArray(comb(res).pluck("1")
           .flatten())
           .forEach(function (sql) {
               return self.executeDdl(sql);
           })
           .chain(function () {
               return self.removeCachedSchema(name);
           });
   });
           
}
    

castTypeLiteral Function Public


Defined database/index.js

Casts the given type to a SQL type.

Example
DB.castTypeLiteral(Number) //=> numeric
  DB.castTypeLiteral("foo") //=> foo
  DB.castTypeLiteral(String) //=> varchar(255)
  DB.castTypeLiteral(Boolean) //=> boolean
        
Arguments Returns Source
function (type){
   return this.typeLiteral({type: type});
           
}
    

closeConnection Function Public


Defined database/connect.js

This is an abstract method that should be implemented by adapters to close a connection to the database.

Arguments Source
function (conn){
   throw new NotImplemented("Close connection must be implemented by the adapter");
           
}
    

createConnection Function Public


Defined database/connect.js

This is an abstract method that should be implemented by adapters to create a connection to the database.

Arguments Source
function (options){
   throw new NotImplemented("Create connection must be implemented by the adapter");
           
}
    

createOrReplaceView Function Public


Defined database/schema.js

Creates a view, replacing it if it already exists:

Example
DB.createOrReplaceView("cheapItems", "SELECT * FROM items WHERE price < 100");
     //=> CREATE OR REPLACE VIEW cheapItems AS SELECT * FROM items WHERE price < 100
  DB.createOrReplaceView("miscItems", DB.from("items").filter({category : 'misc'}));
    //=> CREATE OR REPLACE VIEW miscItems AS SELECT * FROM items WHERE category = 'misc'
        
Arguments Returns Source
function (name,source,opts){
   if (isInstanceOf(source, Dataset)) {
       source = source.sql;
   }
   opts = opts || {};
   opts.replace = true;
   var self = this;
   return this.executeDdl(this.__createViewSql(name, source, opts)).chain(function () {
       return self.removeCachedSchema(name);
   });
           
}
    

createTable Function Public


Defined database/schema.js

Creates a table with the columns given in the provided block:

NOTE: The block is invoked in the scope of the table that is being created. The block is also called with the table as the first argument. Within the block you must use this(If the block has not been bound to a different scope), or the table object that is passed in for all create table operations. See patio.SchemaGenerator for available operations.

Example
//using the table to create the table
  DB.createTable("posts", function(table){
    table.primaryKey("id");
    table.column('title", "text");
    //you may also invoke the column name as
    //function on the table
    table.content(String);
    table.index(title);
  });

  //using this to create the table
  DB.createTable("posts", function(){
    this.primaryKey("id");
    this.column('title", "text");
    //you may also invoke the column name as
    //function on the table
    this.content(String);
    this.index(title);
  });
        
Arguments Returns Source
function (name,options,block){
   if (isFunction(options)) {
       block = options;
       options = {};
   }
   this.removeCachedSchema(name);
   if (isInstanceOf(options, SchemaGenerator)) {
       options = {generator: options};
   }
   var generator = options.generator || new SchemaGenerator(this, block), self = this;
   return this.__createTableFromGenerator(name, generator, options).chain(function () {
       return self.__createTableIndexesFromGenerator(name, generator, options);
   });
           
}
    

createTableUnlessExists Function Public


Defined database/schema.js

Creates the table unless the table already exists.

See patio.Database#createTable for parameter types.

Arguments Source
function (name,options,block){
   var self = this;
   return this.tableExists(name).chain(function (exists) {
       if (!exists) {
           return self.createTable(name, options, block);
       }
   });
           
}
    

createView Function Public


Defined database/schema.js

Creates a view based on a dataset or an SQL string:

Example
DB.createView("cheapItems", "SELECT * FROM items WHERE price < 100");
     //=> CREATE VIEW cheapItems AS SELECT * FROM items WHERE price < 100
  DB.createView("miscItems", DB.from("items").filter({category : 'misc'}));
    //=> CREATE  VIEW miscItems AS SELECT * FROM items WHERE category = 'misc'
        
Arguments Source
function (name,source,opts){
   if (isInstanceOf(source, Dataset)) {
       source = source.sql;
   }
   return this.executeDdl(this.__createViewSql(name, source, opts));
           
}
    

disconnect Function Public


Defined database/connect.js

Disconnects the database closing all connections.

Returns Source
function (){
   var self = this;
   return this.pool.endAll()
       .chain(function () {
           return self.onDisconnect(self);
       })
       .chain(function () {
           return null;
       });
           
}
    

dropColumn Function Public


Defined database/schema.js

Removes a column from the specified table.

This method is a shortcut to patio.Database#alterTable with an dropColumn call.

Example
DB.dropColumn("items", "category");
         //=> 'ALTER TABLE items DROP COLUMN category',
        
Arguments Returns Source
function (table,column){
   column = argsToArray(arguments).slice(1);
   return this.alterTable(table, function () {
       this.dropColumn.apply(this, column);
   });
           
}
    

dropIndex Function Public


Defined database/schema.js

Removes an index for the given table and column/s.

This method is a shortcut to patio.Database#alterTable with an dropIndex call.

Example
DB.dropIndex("posts", "title");
     //=>'DROP INDEX posts_title_index
  DB.dropIndex("posts", ["author", "title"]);
     //'DROP INDEX posts_author_title_index'
        
Arguments Returns Source
function (table,columns,options){
   var args = argsToArray(arguments).slice(1);
   return this.alterTable(table, function () {
       this.dropIndex.apply(this, args);
   });
           
}
    

dropTable Function Public


Defined database/schema.js

Drops one or more tables corresponding to the given names.

Example
DB.dropTable("test");
     //=>'DROP TABLE test'
DB.dropTable("a", "bb", "ccc");
     //=>'DROP TABLE a',
     //=>'DROP TABLE bb',
     //=>'DROP TABLE ccc'
        
Arguments Returns Source
function (names){
   if (!isArray(names)) {
       names = comb(arguments).toArray();
   }
   names = names.filter(function (t) {
       return isString(t) || isInstanceOf(t, Identifier, QualifiedIdentifier);
   });
   var self = this;
   return asyncArray(names).forEach(function (name) {
       return self.executeDdl(self.__dropTableSql(name)).chain(function () {
           return self.removeCachedSchema(name);
       });
   }, 1);
           
}
    

dropView Function Public


Defined database/schema.js

Drops one or more views corresponding to the given names.

Example
DB.dropView("test_view");
     //=>'DROP VIEW test_view'
DB.dropTable("test_view_1", "test_view_2", "test_view_3");
     //=>'DROP VIEW test_view_1',
     //=>'DROP VIEW test_view_2',
     //=>'DROP VIEW test_view_3'
        
Arguments Returns Source
function (names,opts){
   if (isArray(names)) {
       opts = opts || {};
       var self = this;
       return asyncArray(names).forEach(function (name) {
           return self.executeDdl(self.__dropViewSql(name, opts)).chain(function () {
               self.removeCachedSchema(name);
           });
       }, null, 1).chain(function () {
           return null;
       });
   } else {
       var args = argsToArray(arguments);
       if (comb.isHash(args[args.length - 1])) {
           opts = args.pop();
       }
       return this.dropView(args.filter(function (t) {
           return isString(t) || isInstanceOf(t, Identifier, QualifiedIdentifier);
       }), opts);
   }
           
}
    

execute Function Public


Defined database/query.js

Executes the given SQL on the database. This method should be implemented by adapters. This method should not be called directly by user code.

Arguments Source
function (sql,opts,conn){
   var ret;
   if (opts.stream) {
       ret = this.__executeStreamed(sql, opts, conn);
   } else {
       ret = this.__executePromised(sql, opts, conn);
   }
   return ret;
           
}
    

executeDdl Function Public


Defined database/query.js

Method that should be used when submitting any DDL (Data DefinitionLanguage) SQL, such as patio.Database#createTable. By default, calls patio.Database#executeDui. This method should not be called directly by user code.

Arguments Source
function (sql,opts){
   opts = opts || {};
   return this.executeDui(sql, opts);
           
}
    

executeDui Function Public


Defined database/query.js

Method that should be used when issuing a DELETE, UPDATE, or INSERT statement. By default, calls patio.Database#execute. This method should not be called directly by user code.

Arguments Source
function (sql,opts){
   opts = opts || {};
   return this.execute(sql, opts);
           
}
    

executeInsert Function Public


Defined database/query.js

Method that should be used when issuing a INSERT statement. By default, calls patio.Database#executeDui. This method should not be called directly by user code.

Arguments Source
function (sql,opts){
   opts = opts || {};
   return this.executeDui(sql, opts);
           
}
    

fetch Function Public


Defined database/dataset.js

Fetches records for an arbitrary SQL statement. If a block is given, it is used to iterate over the records:

  DB.fetch('SELECT * FROM items', function(r){
     //do something with row
  });
If a block is not given then patio.Database#fetch method returns a patio.Dataset instance:
  DB.fetch('SELECT * FROM items').all().chain(function(records){
     //do something with the records.
  });

patio.Database#fetch can also perform parameterized queries for protection against SQL injection:

  DB.fetch('SELECT * FROM items WHERE name = ?', myName).all().chain(function(records){
     //do something with the records.
  });

Arguments Returns Source
function (args,block){
   var ret;
   args = argsToArray(arguments);
   block = isFunction(args[args.length - 1]) ? args.pop() : null;
   var ds = this.dataset.withSql.apply(this.dataset, args);
   if (block) {
       ret = ds.forEach(block).chain(function () {
           return ds;
       }).promise();
   } else {
       ret = ds;
   }
   return ret;
           
}
    

forceCreateTable Function Public


Defined database/schema.js

Forcibly creates a table, attempting to drop it unconditionally (and catching any errors), then creating it.

See patio.Database#createTable for parameter types.

Example
// DROP TABLE a
 // CREATE TABLE a (a integer)
  DB.forceCreateTable("a", function(){
     this.a("integer");
  });
        
Arguments Source
function (name,options,block){
   var self = this;
   return this.dropTable(name).chainBoth(function () {
       return self.createTable(name, options, block);
   });
           
}
    

forceDropTable Function Public


Defined database/schema.js

Forcible drops one or more tables corresponding to the given names, ignoring errors.

Example
DB.dropTable("test");
     //=>'DROP TABLE test'
DB.dropTable("a", "bb", "ccc");
     //=>'DROP TABLE a',
     //=>'DROP TABLE bb',
     //=>'DROP TABLE ccc'
        
Arguments Returns Source
function (names){
   if (!isArray(names)) {
       names = comb(arguments).toArray();
   }
   names = names.filter(function (t) {
       return isString(t) || isInstanceOf(t, Identifier, QualifiedIdentifier);
   });
   var l = names.length, ret = new Promise(), self = this;
   var drop = function (i) {
       if (i &lt; l) {
           var name = names[i++];
           self.executeDdl(self.__dropTableSql(name)).both(function () {
               self.removeCachedSchema(name);
               drop(i);
           });
       } else {
           ret.callback();
       }
   };
   drop(0);
   return ret.promise();
           
}
    

from Function Public


Defined database/dataset.js

Returns a new patio.Dataset with the [@link patio.Dataset#from} method invoked. If a block is given, it is used as a filter(see patio.Dataset#filter on the dataset.

Example
DB.from("items").sql //=> SELECT * FROM items
  DB.from("items", function(){
         return this.id.gt(2)
  }).sql; //=> SELECT * FROM items WHERE (id > 2)
        
Arguments Returns Source
function (args,block){
   args = argsToArray(arguments);
   block = isFunction(args[args.length - 1]) ? args.pop() : null;
   var ds = this.dataset;
   ds = ds.from.apply(ds, args);
   return block ? ds.filter(block) : ds;
           
}
    

get Function Public


Defined database/query.js

Proxy for patio.Dataset#get.

Source
function (){
   return this.dataset.get.apply(this.dataset, arguments);
           
}
    

indexes Function Public


Defined database/query.js

Return a Promise that is resolved with an object containing index information.

The keys are index names. Values are objects with two keys, columns and unique. The value of columns is an array of column names. The value of unique is true or false depending on if the index is unique.

Should not include the primary key index, functional indexes, or partial indexes.

Example
DB.indexes("artists").chain(function(indexes){
    //e.g. indexes === {artists_name_ukey : {columns : [name], unique : true}};
  })
        
Arguments Source
function (table,opts){
   throw new NotImplemented("indexes should be overridden by adapters");
           
}
    

literal Function Public


Defined database/index.js

This function acts as a proxy to patio.Dataset#literal.

See patio.Dataset#literal.

Arguments Source
function (v){
   return this.dataset.literal(v);
           
}
    

logDebug Function Public


Defined database/logging.js

Logs a DEBUG level message to the "patio.Database" logger.

Source
function (){
   LOGGER.debug.apply(LOGGER, arguments);
           
}
    

logError Function Public


Defined database/logging.js

Logs an ERROR level message to the "patio.Database" logger.

Arguments Source
function (error){
   LOGGER.error.apply(LOGGER, arguments);
           
}
    

logFatal Function Public


Defined database/logging.js

Logs a FATAL level message to the "patio.Database" logger.

Source
function (){
   LOGGER.fatal.apply(LOGGER, arguments);
           
}
    

logInfo Function Public


Defined database/logging.js

Logs an INFO level message to the "patio.Database" logger.

Source
function (){
   LOGGER.info.apply(LOGGER, arguments);
           
}
    

logTrace Function Public


Defined database/logging.js

Logs a TRACE level message to the "patio.Database" logger.

Source
function (){
   LOGGER.trace.apply(LOGGER, arguments);
           
}
    

logWarn Function Public


Defined database/logging.js

Logs a WARN level message to the "patio.Database" logger.

Source
function (){
   LOGGER.warn.apply(LOGGER, arguments);
           
}
    

removeCachedSchema Function Public


Defined database/query.js

Remove the cached schema for the given table name

Example
DB.schema("artists").chain(function(){
     DB.removeCachedSchema("artists");
});
        
Arguments Source
function (table){
   if (this.schemas && !isEmpty(this.schemas)) {
       delete this.schemas[this.__quoteSchemaTable(table)];
   }
           
}
    

renameColumn Function Public


Defined database/schema.js

Renames a column in the specified table.

This method is a shortcut to patio.Database#alterTable with an renameColumn call.

Example
DB.renameColumn("items", "cntr", "counter");
     //=> ALTER TABLE items RENAME COLUMN cntr TO counter
        
Arguments Returns Source
function (table,column,newColumn){
   var args = argsToArray(arguments).slice(1);
   return this.alterTable(table, function () {
       this.renameColumn.apply(this, args);
   });
           
}
    

renameTable Function Public


Defined database/schema.js

Renames a table.

Example
comb.executeInOrder(DB, function(DB){
  DB.tables(); //=> ["items"]
  DB.renameTable("items", "old_items");
         //=>'ALTER TABLE items RENAME TO old_items'
  DB.tables; //=> ["old_items"]
});
        
Arguments Returns Source
function (name,newName){
   var self = this;
   return this.executeDdl(this.__renameTableSql(name, newName)).chain(function () {
       self.removeCachedSchema(name);
   }).promise();
           
}
    

run Function Public


Defined database/query.js

Runs the supplied SQL statement string on the database server..

Example
DB.run("SET some_server_variable = 42")
        
Arguments Returns Source
function (sql,opts){
   opts = opts || {};
   return this.executeDdl(sql, opts);
           
}
    

schema Function Public


Defined database/query.js

Parse the schema from the database.

Example
DB.schema("artists").chain(function(schema){
    //example schema
    {
     id :  {
         type : "integer",
         primaryKey : true,
         "default" : "nextval('artist_id_seq'::regclass)",
         jsDefault : null,
         dbType : "integer",
         allowNull : false
      },
     name : {
         type : "string",
         primaryKey : false,
         "default" : null,
         jsDefault  : null,
         dbType : "text",
         allowNull : false
      }
    }
  })
        
Arguments Returns