A singleton class that acts as the entry point for all actions performed in patio.

Example
  1. var patio = require("patio");
  2.  
  3. patio.createConnection(....);
  4.  
  5. patio.camelize = true;
  6. patio.quoteIdentifiers=false;
  7. patio.parseInt8=false
  8. patio.defaultPrimaryKeyType = "integer" //"bigint"
  9.  
  10. patio.createModel("my_table");
  11.  
  12.  
  13. //CHANGING IDENTIFIER INPUT METHOD
  14.  
  15.  
  16. //use whatever is passed in
  17. patio.identifierInputMethod = null;
  18. //convert to uppercase
  19. patio.identifierInputMethod = "toUpperCase";
  20. //convert to camelCase
  21. patio.identifierInputMethod = "camelize";
  22. //convert to underscore
  23. patio.identifierInputMethod = "underscore";
  24.  
  25.  
  26. //CHANGING IDENTIFIER OUTPUT METHOD
  27.  
  28. //use whatever the db returns
  29. patio.identifierOutputMethod = null;
  30. //convert to uppercase
  31. patio.identifierOutputMethod = "toUpperCase";
  32. //convert to camelCase
  33. patio.identifierOutputMethod = "camelize";
  34. //convert to underscore
  35. patio.identifierOutputMethod = "underscore";
  36.  
  37. //TURN QUOTING OFF
  38. patio.quoteIdentifiers = false
Extends Static Properties
PropertyTypeDefault ValueDescription
patio.Time

Mixin that provides time formatting/coversion functions.

Instance Properties
PropertyTypeDefault ValueDescription
DATABASESpatio.Database[] []

An array of databases that are currently connected.

LOGGERLogger comb.logger("patio")

Returns the root comb logger using this logger you can set the levels add appenders etc.

camelizefunction

Sets the whether or not to camelize identifiers coming from the database and to underscore identifiers when sending identifiers to the database. Setting this property to true has the same effect as:

    patio.identifierOutputMethod = "camelize";
    patio.identifierInputMethod = "underscore";
defaultDatabasepatio.Database null

Returns the default database. This is the first database created using patio#connect.

defaultPrimaryKeyTypeString

Set the default primary key type when not specified for all databases by default. By default, patio uses "integer".

identifierInputMethodString

Set the method to call on identifiers going into the database. This affects how identifiers are sent to the database. So if you use camelCased and the db identifiers are all underscored use camelize. The method can include

  • toUpperCase
  • toLowerCase
  • camelize
  • underscore
  • Other String instance method names.

patio uses toUpperCase identifiers in all SQL strings for most databases.

identifierOutputMethodString

Set the method to call on identifiers coming out of the database. This affects the how identifiers are represented by calling the method on them. The method can include

  • toUpperCase
  • toLowerCase
  • camelize
  • underscore
  • Other String instance method names.
most database implementations in patio use toLowerCase

parseInt8Boolean

Sets whether bigint types should be parsed to a number. An error will be thrown if set and the number is set and the number is greater than 2^53 or less than -2^53.

quoteIdentifiersBoolean

Set whether to quote identifiers for all databases by default. By default, patio quotes identifiers in all SQL strings.

underscorefunction

Sets the whether or not to underscore identifiers coming from the database and to camelize identifiers when sending identifiers to the database. Setting this property to true has the same effect as:

    patio.identifierOutputMethod = "underscore";
    patio.identifierInputMethod = "camelize";

Constructor

Defined index.js Source
  1. function (){
  2. this._super(arguments);
  3. var constants = SQL.Constants;
  4. for (var i in constants) {
  5. this[i] = constants[i];
  6. }
  7. }

addModel Function Public


Defined index.js

This method is used to create a patio.Model object.

Example
  1. var Flight = patio.addModel("flight", {
  2. instance:{
  3. toObject:function () {
  4. var obj = this._super(arguments);
  5. obj.weekdays = this.weekdaysArray;
  6. obj.legs = this.legs.map(function (l) {
  7. return l.toObject();
  8. });
  9. return obj;
  10. },
  11.  
  12. _setWeekdays:function (weekdays) {
  13. this.weekdaysArray = weekdays.split(",");
  14. return weekdays;
  15. }
  16. },
  17.  
  18. static:{
  19.  
  20. init:function () {
  21. this.oneToMany("legs", {
  22. model:"flightLeg",
  23. orderBy:"scheduledDepartureTime",
  24. fetchType:this.fetchType.EAGER
  25. });
  26. },
  27.  
  28. byAirline:function (airline) {
  29. return this.filter({airline:airline}).all();
  30. },
  31.  
  32. arrivesAt:function (airportCode) {
  33. return this.join(this.flightLeg.select("flightId").filter({arrivalCode:airportCode}).distinct(), {flightId:"id"}).all();
  34. },
  35.  
  36. departsFrom:function (airportCode) {
  37. return this.join(this.flightLeg.select("flightId").filter({departureCode:airportCode}).distinct(), {flightId:"id"}).all();
  38. },
  39.  
  40. getters:{
  41. flightLeg:function () {
  42. if (!this.__flightLeg) {
  43. this.__flightLeg = this.patio.getModel("flightLeg");
  44. }
  45. return this.__flightLeg;
  46. }
  47. }
  48. }
  49. });
Arguments Source
  1. function (table,supers,proto){
  2. return model.create.apply(model, arguments);
  3. }

configureLogging Function Public


Defined index.js

This can be used to configure logging. If a options hash is passed in then it will passed to the comb.logging.PropertyConfigurator. If the options are omitted then a ConsoleAppender will be added and the level will be set to info.

Example
  1. var config = {
  2. "patio" : {
  3. level : "INFO",
  4. appenders : [
  5. {
  6. type : "RollingFileAppender",
  7. file : "/var/log/patio.log",
  8. },
  9. {
  10. type : "RollingFileAppender",
  11. file : "/var/log/patio-error.log",
  12. name : "errorFileAppender",
  13. level : "ERROR"
  14. }
  15. ]
  16. };
  17.  
  18. patio.configureLogging(config);
Arguments Source
  1. function (opts){
  2. comb.logger.configure(opts);
  3. if (!opts) {
  4. LOGGER.level = "info";
  5. }
  6. }

connect Function Public


Defined index.js

Source
  1. function (){
  2. return this.createConnection.apply(this, arguments);
  3. }

createConnection Function Public


Defined index.js

Returns a patio.Database object that can be used to for querying.

This method is the entry point for all interactions with a database including getting patio.Datasets for creating queries(see patio.Database#from).

The patio.Database returned can also be used to create( patio.Database#createTable), alter(@link patio.Database#alterTable}), rename( patio.Database#renameTable), and drop( patio.Database#dropTable) as well as many other patio.Database actions.

Example
  1. //connect using an object
  2. var DB = patio.createConnection({
  3. host : "127.0.0.1",
  4. port : 3306,
  5. type : "mysql",
  6. maxConnections : 1,
  7. minConnections : 1,
  8. user : "test",
  9. password : "testpass",
  10. database : 'test'
  11. });
  12. //connect using a connection string
  13. var CONNECT_STRING = "mysql://test:testpass@localhost:3306/test?maxConnections=1&minConnections=1";
  14. var DB = patio.createConnection(CONNECT_STRING);
  15.  
  16. //...do something
  17. DB.createTable("myTable", function(){
  18. this.name("text");
  19. this.value("integer");
  20. }).chain(function(){
  21. //tables created!!!
  22. });
Arguments Source
  1. function (options){
  2. var ret = Database.connect(options);
  3. this.emit("connect", ret);
  4. return ret;
  5. }

disconnect Function Public


Defined index.js

Disconnects all databases in use.

Arguments Returns Source
  1. function (cb){
  2. var ret = Database.disconnect(cb), self = this;
  3. ret.classic(function (err) {
  4. if (err) {
  5. self.emit("error", err);
  6. } else {
  7. self.emit("disconnect");
  8. }
  9. });
  10. return ret.promise();
  11. }

getModel Function Public


Defined index.js

Returns a model from the name of the table for which the model was created.

  1.  
  2. var TestModel = patio.addModel("test_model").sync(function(err){
  3. if(err){
  4. console.log(err.stack);
  5. }else{
  6. var TestModel = patio.getModel("test_model");
  7. }
  8. });
  9.  

If you have two tables with the same name in different databases then you can use the db parameter also.

  1.  
  2.  
  3. var DB1 = patio.createConnection("mysql://test:testpass@localhost:3306/test_1");
  4. var DB2 = patio.createConnection("mysql://test:testpass@localhost:3306/test_2");
  5. var Test1 = patio.addModel(DB1.from("test");
  6. var Test2 = patio.addModel(DB2.from("test");
  7.  
  8. //sync the models
  9. patio.syncModels().chain(function(){
  10. //now you can use them
  11. var test1Model = new Test1();
  12. var test2Model = new Test2();
  13. });
  14.  

Arguments Source
  1. function (name,db){
  2. return model.getModel(name, db);
  3. }

logDebug Function Public


Defined index.js

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

Source
  1. function (){
  2. if (LOGGER.isDebug) {
  3. LOGGER.debug.apply(LOGGER, arguments);
  4. }
  5. }

logError Function Public


Defined index.js

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

Source
  1. function (){
  2. if (LOGGER.isError) {
  3. LOGGER.error.apply(LOGGER, arguments);
  4. }
  5. }

logFatal Function Public


Defined index.js

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

Source
  1. function (){
  2. if (LOGGER.isFatal) {
  3. LOGGER.fatal.apply(LOGGER, arguments);
  4. }
  5. }

logInfo Function Public


Defined index.js

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

Source
  1. function (){
  2. if (LOGGER.isInfo) {
  3. LOGGER.info.apply(LOGGER, arguments);
  4. }
  5. }

logTrace Function Public


Defined index.js

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

Source
  1. function (){
  2. if (LOGGER.isTrace) {
  3. LOGGER.trace.apply(LOGGER, arguments);
  4. }
  5. }

logWarn Function Public


Defined index.js

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

Source
  1. function (){
  2. if (LOGGER.isWarn) {
  3. LOGGER.warn.apply(LOGGER, arguments);
  4. }
  5. }

migrate Function Public


Defined index.js

Migrates the database using migration files found in the supplied directory.

Integer Migrations

Integer migrations are the simpler of the two migrations but are less flexible than timestamp based migrations. In order for patio to determine which versions to use the file names must end in .js where versionNumber is a integer value representing the version number. NOTE:With integer migrations missing versions are not allowed.

An example directory structure might look like the following:
-migrations
     - createFirstTables.0.js
     - shortDescription.1.js
     - another.2.js
     .
     .
     .
     -lastMigration.n.js
     
In order to easily identify where certain schema alterations have taken place it is a good idea to provide a brief but meaningful migration name.
         createEmployee.0.js
         alterEmployeeNameColumn.1.js
     

Timestamp Migrations

Timestamp migrations are the more complex of the two migrations but offer greater flexibility especially with development teams. This is because Timestamp migrations do not require consecutive version numbers, ,allow for duplicate version numbers(but this should be avoided), keeps track of all currently applied migrations, and it will merge missing migrations. In order for patio to determine the order of the migration files the file names must end in .js where the timestamp can be any form of a time stamp.
//yyyyMMdd
20110131
//yyyyMMddHHmmss
20110131123940
//unix epoch timestamp
1328035161
     
as long as it is greater than 20000101 other wise it will be assumed to be part of an integer migration.

An example directory structure might look like the following:
-migrations
     - createFirstTables.1328035161.js
     - shortDescription.1328035360.js
     - another.1328035376.js
     .
     .
     .
     -lastMigration.n.js
     
In order to easily identify where certain schema alterations have taken place it is a good idea to provide a brief but meaningful migration name.
         createEmployee.1328035161.js
         alterEmployeeNameColumn.1328035360.js
     

NOTE:If you start with IntegerBased migrations and decide to transition to Timestamp migrations the patio will attempt the migrate the current schema to the timestamp based migration schema.

In order to run a migraton all one has to do is call patio.migrate(DB, directory, options);
 var DB = patio.connect("my://connection/string");
 patio.migrate(DB, __dirname + "/migrations").chain(function(){
     console.log("migrations finished");
 });
Example migration file
//Up function used to migrate up a version
exports.up = function(db) {
  //create a new table
  db.createTable("company", function() {
      this.primaryKey("id");
      this.companyName(String, {size : 20, allowNull : false});
  });
  db.createTable("employee", function(table) {
      this.primaryKey("id");
      this.firstName(String);
      this.lastName(String);
      this.middleInitial("char", {size : 1});
  });
};

//Down function used to migrate down version
exports.down = function(db) {
   db.dropTable("employee", "company");
};

Arguments Returns Source
  1. function (db){
  2. db = isString(db) ? this.connect(db) : db;
  3. var args = argsToArray(arguments);
  4. args.splice(0, 1);
  5. return migrate.run.apply(migrate, [db].concat(args));
  6. }

syncModels Function Public


Defined index.js

Helper method to sync all models at once.

Example
  1. var User = patio.addModel("user");
  2. var Blog = patio.addModel("blog");
  3.  
  4. //using promise api
  5. patio.syncModels().chain(function(){
  6. var user = new User();
  7. }, function(error){
  8. console.log(err);
  9. });
  10.  
  11. //using a callback
  12.  
  13. patio.syncModels(function(err){
  14. if(err){
  15. console.log(err);
  16. }else{
  17. var user = new User();
  18. }
  19. });
Arguments Returns Source
  1. function (cb){
  2. return model.syncModels(cb);
  3. }

Documentation generated using coddoc.