A singleton class that acts as the entry point for all actions performed in patio.
Examplevar patio = require("patio"); patio.createConnection(....); patio.camelize = true; patio.quoteIdentifiers=false; patio.parseInt8=false patio.defaultPrimaryKeyType = "integer" //"bigint" patio.createModel("my_table"); //CHANGING IDENTIFIER INPUT METHOD //use whatever is passed in patio.identifierInputMethod = null; //convert to uppercase patio.identifierInputMethod = "toUpperCase"; //convert to camelCase patio.identifierInputMethod = "camelize"; //convert to underscore patio.identifierInputMethod = "underscore"; //CHANGING IDENTIFIER OUTPUT METHOD //use whatever the db returns patio.identifierOutputMethod = null; //convert to uppercase patio.identifierOutputMethod = "toUpperCase"; //convert to camelCase patio.identifierOutputMethod = "camelize"; //convert to underscore patio.identifierOutputMethod = "underscore"; //TURN QUOTING OFF patio.quoteIdentifiers = falseExtends Static Properties
Property | Type | Default Value | Description |
patio.Time | Mixin that provides time formatting/coversion functions. | ||
Property | Type | Default Value | Description |
DATABASES | patio.Database[] |
[]
| An array of databases that are currently connected. |
LOGGER | Logger |
comb.logger("patio")
| Returns the root comb logger using this logger you can set the levels add appenders etc. |
camelize | function | 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"; | |
defaultDatabase | patio.Database |
null
| Returns the default database. This is the first database created using patio#connect. |
defaultPrimaryKeyType | String | Set the default primary key type when not specified for all databases by default. By default, patio uses "integer". | |
identifierInputMethod | String | 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
patio uses toUpperCase identifiers in all SQL strings for most databases. | |
identifierOutputMethod | String | 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
| |
parseInt8 | Boolean | 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. | |
quoteIdentifiers | Boolean | Set whether to quote identifiers for all databases by default. By default, patio quotes identifiers in all SQL strings. | |
underscore | function | 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"; | |
function (){ this._super(arguments); var constants = SQL.Constants; for (var i in constants) { this[i] = constants[i]; } }
This method is used to create a patio.Model object.
Examplevar Flight = patio.addModel("flight", { instance:{ toObject:function () { var obj = this._super(arguments); obj.weekdays = this.weekdaysArray; obj.legs = this.legs.map(function (l) { return l.toObject(); }); return obj; }, _setWeekdays:function (weekdays) { this.weekdaysArray = weekdays.split(","); return weekdays; } }, static:{ init:function () { this.oneToMany("legs", { model:"flightLeg", orderBy:"scheduledDepartureTime", fetchType:this.fetchType.EAGER }); }, byAirline:function (airline) { return this.filter({airline:airline}).all(); }, arrivesAt:function (airportCode) { return this.join(this.flightLeg.select("flightId").filter({arrivalCode:airportCode}).distinct(), {flightId:"id"}).all(); }, departsFrom:function (airportCode) { return this.join(this.flightLeg.select("flightId").filter({departureCode:airportCode}).distinct(), {flightId:"id"}).all(); }, getters:{ flightLeg:function () { if (!this.__flightLeg) { this.__flightLeg = this.patio.getModel("flightLeg"); } return this.__flightLeg; } } } });Arguments
the table to use as the base for the model.
an object to be used as the prototype for the model. See comb.define.
patio.Model|patio.Model[]
: models of this model. See patio.plugins.ClassTableInheritancePlugin.
[proto.plugins] this can be used to specify additional plugins to use such as.
function (table,supers,proto){ return model.create.apply(model, arguments); }
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.
Examplevar config = { "patio" : { level : "INFO", appenders : [ { type : "RollingFileAppender", file : "/var/log/patio.log", }, { type : "RollingFileAppender", file : "/var/log/patio-error.log", name : "errorFileAppender", level : "ERROR" } ] }; patio.configureLogging(config);Arguments
function (opts){ comb.logger.configure(opts); if (!opts) { LOGGER.level = "info"; } }
function (){ return this.createConnection.apply(this, arguments); }
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//connect using an object var DB = patio.createConnection({ host : "127.0.0.1", port : 3306, type : "mysql", maxConnections : 1, minConnections : 1, user : "test", password : "testpass", database : 'test' }); //connect using a connection string var CONNECT_STRING = "mysql://test:testpass@localhost:3306/test?maxConnections=1&minConnections=1"; var DB = patio.createConnection(CONNECT_STRING); //...do something DB.createTable("myTable", function(){ this.name("text"); this.value("integer"); }).chain(function(){ //tables created!!! });Arguments
the options used to initialize the database connection. This may be a database connetion string or object.
10
] Number
: the number of connections to pool.
3
] Number
: the number of connections to pool.
"mysql"
] String
: the type of database to communicate with.
String
: the user to authenticate as.
String
: the password of the user.
String
: the name of the database to use, the database specified here is the default database for all connections.
function (options){ var ret = Database.connect(options); this.emit("connect", ret); return ret; }
Disconnects all databases in use.
Argumentsnull
] : a callback to call when disconnect has completed
comb.Promise
a promise that is resolved once all databases have disconnected.
function (cb){ var ret = Database.disconnect(cb), self = this; ret.classic(function (err) { if (err) { self.emit("error", err); } else { self.emit("disconnect"); } }); return ret.promise(); }
Returns a model from the name of the table for which the model was created.
var TestModel = patio.addModel("test_model").sync(function(err){ if(err){ console.log(err.stack); }else{ var TestModel = patio.getModel("test_model"); } });
If you have two tables with the same name in different databases then you can use the db parameter also.
var DB1 = patio.createConnection("mysql://test:testpass@localhost:3306/test_1"); var DB2 = patio.createConnection("mysql://test:testpass@localhost:3306/test_2"); var Test1 = patio.addModel(DB1.from("test"); var Test2 = patio.addModel(DB2.from("test"); //sync the models patio.syncModels().chain(function(){ //now you can use them var test1Model = new Test1(); var test2Model = new Test2(); });Arguments
the name of the table that the model represents.
optional database in case you have two models with the same table names in different databases.
function (name,db){ return model.getModel(name, db); }
Logs a DEBUG level message to the "patio" logger.
Sourcefunction (){ if (LOGGER.isDebug) { LOGGER.debug.apply(LOGGER, arguments); } }
Logs an ERROR level message to the "patio" logger.
Sourcefunction (){ if (LOGGER.isError) { LOGGER.error.apply(LOGGER, arguments); } }
Logs a FATAL level message to the "patio" logger.
Sourcefunction (){ if (LOGGER.isFatal) { LOGGER.fatal.apply(LOGGER, arguments); } }
Logs an INFO level message to the "patio" logger.
Sourcefunction (){ if (LOGGER.isInfo) { LOGGER.info.apply(LOGGER, arguments); } }
Logs a TRACE level message to the "patio" logger.
Sourcefunction (){ if (LOGGER.isTrace) { LOGGER.trace.apply(LOGGER, arguments); } }
Logs a WARN level message to the "patio" logger.
Sourcefunction (){ if (LOGGER.isWarn) { LOGGER.warn.apply(LOGGER, arguments); } }
Migrates the database using migration files found in the supplied directory.
-migrations - createFirstTables.0.js - shortDescription.1.js - another.2.js . . . -lastMigration.n.jsIn 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
//yyyyMMdd 20110131 //yyyyMMddHHmmss 20110131123940 //unix epoch timestamp 1328035161as long as it is greater than 20000101 other wise it will be assumed to be part of an integer migration.
-migrations - createFirstTables.1328035161.js - shortDescription.1328035360.js - another.1328035376.js . . . -lastMigration.n.jsIn 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.
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"); };
the database or connection string to a database to migrate.
String
: directory that the migration files reside in
{}
] Object
: optional parameters.
String
: the column in the table that version information should be stored.
String
: the table that version information should be stored.
Number
: the target migration(i.e the migration to migrate up/down to).
String
: the version that the database is currently at if the current version is not provided it is retrieved from the database.
Promise
a promise that is resolved once the migration is complete.
function (db){ db = isString(db) ? this.connect(db) : db; var args = argsToArray(arguments); args.splice(0, 1); return migrate.run.apply(migrate, [db].concat(args)); }
Helper method to sync all models at once.
Examplevar User = patio.addModel("user"); var Blog = patio.addModel("blog"); //using promise api patio.syncModels().chain(function(){ var user = new User(); }, function(error){ console.log(err); }); //using a callback patio.syncModels(function(err){ if(err){ console.log(err); }else{ var user = new User(); } });Arguments
an optional callback to be invoked when all models have been synced
comb.Promise
a promise that will be resolved when the models have been synced.
function (cb){ return model.syncModels(cb); }