Creates Objects for reading from and writing to database tables
Myna.DataManager is a dynamic Object-Relational Mapping (ORM) tool to simplify basic Create, Read, Update and Delete (CRUD) operations on database tables.
The basic concept is that for a given table Myna.DataManager can generate a manager object that represents that table and knows how to create and delete rows. That manager can then generate a bean object that represents a specific row in the table that knows how to read and write column values to that row. Both of these types objects can be extended for extra functionality.
+- - - - - - - - - - - - - - - - - -+
| table employees |
+- - - - - - - - - - - - - - - - - -+
| emp_id int4 primary key |
| fname varchar |
| mname varchar |
| lname varchar |
| manager_id int4 |
| hire_date date |
+- - - - - - - - - - - - - - - - - -+
var dm = new Myna.DataManager("hr_datasource");
var empManager = dm.getManager("employees");
var newEmpBean = empManager.create({
fname:"Bob",
lname:"Dobb",
hire_date:Date.parse("02/21/1992","m/d/Y")
})
Myna.println (newEmp.get_emp_id()) // Prints the auto generated primary key
newEmp.set_mname("R"); //sets this value in an update
// column values are also available as property proxies on the bean objects:
// see https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Getters_and_Setters
// for how this works
Myna.println (newEmp.emp_id) // calls get_emp_id() on the bean
newEmp.mname = "R"; // calls set_emp_id("R") on the bean
// you can also add your own functions to mangers and beans
empManager.beanTemplate.getBoss=function(){
if (this.get_manager_id().length){
return this.manager.get_by_id(this.data.manager_id);
} else return this.manager.get_by_id(0); //CEO
}
//this loads the emplyeesBean defined in empManager.beanTemplate
var myBoss = empManager.get_by_id(1000012).getBoss();
Also check out empManager.columns for metadata about each column in the table, such as name, default value, size, type, nullable, precision and more.
| Myna. DataManager | Creates Objects for reading from and writing to database tables |
| Functions and Properties | |
| DataManager | Contructs a Myna.DataManager Object for the supplied dataSource |
| ds | Datasource associated with this Myna.DataManager |
| db | Myna.Database object that represents the database this table resides in |
| getManager | Constructs a ManagerObject for the supplied table. |
| managerTemplate | Base template for ManagerObjects. |
| beanTemplate | Base template for BeanObjects. |
| ManagerObject | Table data access object generated and returned by Myna.DataManager.getManager |
| Properties | |
| dm | The Myna.DataManager object that created this manager |
| db | The Myna.Database for this manager |
| table | The Myna.Table for this manager |
| ds | The datasource name for this manager |
| columns | The columns array from Myna.Table.columns for this table |
| columnNames | The columnNames array from Myna.Table.columnNames for this table |
| beanTemplate | a ManagerObject specific base template for BeanObjects. |
| Functions | |
| loadTableData | internal function to load table data into the manager |
| remove | Removes a row from the managed table matching the supplied primary key |
| create | Creates a record in the database, optionally generating a primary key |
| find | returns an array of primaryKey values that match a search |
| findBeans | returns a Myna.DataSet of bean objects that match a search |
| genKey | generates a primary key value |
| getById | Returns a BeanObject representing the row identified by the supplied primary key |
| BeanObject | Row data access object generated and returned by ManagerObject.getById |
| Properties | |
| manager | The ManagerObject that created this bean |
| dm | The Myna.DataManager object that created this bean |
| ds | The datasource name for this bean |
| data | a simple JS object containing this bean’s data |
| id | The value of the primary key of this bean |
| columns | The columns array from Myna.Table.columns for this table |
| columnNames | The columnNames array from Myna.Table.columnNames for this table |
| Functions | |
| get_<columnName> | gets a value for <columnName> |
| set_<columnName> | sets a value for <columnName> |
| setFields | Sets multiple fields at once |
| saveField | Persists a value to its underlying row |
| getData | return a structure of this bean’s data |
| getParent | return a bean representing this bean’s parent record |
| getChildren | return a Myna.DataSet of beans representing this bean’s child records |
Myna.DataManager = function ( dataSource )
Contructs a Myna.DataManager Object for the supplied dataSource
| dataSource | Datasource Name |
Myna.Database object that represents the database this table resides in
Myna.DataManager.prototype.getManager=function( tableName )
Constructs a ManagerObject for the supplied table.
| tableName | lowercase name of the table |
Creates a ManagerObject for the supplied table.
Base template for ManagerObjects.
This contains all the functions of ManagerObject. Behavior of ManagerObjects can be altered by modifying this object:
var dm = new Myna.DataManager("hr_datasource");
//the init function is called right after instantiating a <ManagerObject>
dm.managerTemplate.init=function(){
Myna.log("debug",this.table.tableName +" manager called");
}
//replace existing function
dm.managerTemplate.genKey=function(value){
return new Myna.Query({
ds:this.ds,
sql:<ejs>
select sequence_<%=this.table.tableName%>.nextval from dual
</ejs>
}).data[0].nexval
}
//append or prepend function
dm.managerTemplate.before("remove",function(id){
Myna.log(
"audit",
"Table " +this.table.tableName +
" row "+ this.data[this.table.primaryKey] + " removed.",
"Removed by " + Myna.dump($cookie.getAuthUser()) +
"<br> Values " + Myna.dump(this.getById(id).data)
);
})See:
Base template for BeanObjects.
This contains all the functions of BeanObject. Behavior of BeanObjects can be altered by modifying this object:
var dm = new Myna.DataManager("hr_datasource");
//the init function is called right after instantiating a <BeanObject>
dm.beanTemplate.init=function(){
Myna.log(
"audit",
"Table " +this.manager.table.tableName +
"Accessed by " +Myna.dump($cookie.getAuthUser())
);
}
//replace existing function
// This would make more sense to be set on a Manager's beanTemplate object
dm.beanTemplate.set_age=function(value){
//this is a calculated column and should not be set
return;
}
//append or prepend function
dm.beanTemplate.before("saveField",function(fname,newval){
Myna.log(
"audit",
"Table " +this.manager.table.tableName +
" row "+ this.data[this.table.primaryKey]
+ " column " + fname+" modified",
"Modified by " + Myna.dump($cookie.getAuthUser()) +
"<br>Old value:" + this.data[fname] +
"<br>New value:" + newval
);
})Table data access object generated and returned by Myna.DataManager.getManager
| Properties | |
| dm | The Myna.DataManager object that created this manager |
| db | The Myna.Database for this manager |
| table | The Myna.Table for this manager |
| ds | The datasource name for this manager |
| columns | The columns array from Myna.Table.columns for this table |
| columnNames | The columnNames array from Myna.Table.columnNames for this table |
| beanTemplate | a ManagerObject specific base template for BeanObjects. |
| Functions | |
| loadTableData | internal function to load table data into the manager |
| remove | Removes a row from the managed table matching the supplied primary key |
| create | Creates a record in the database, optionally generating a primary key |
| find | returns an array of primaryKey values that match a search |
| findBeans | returns a Myna.DataSet of bean objects that match a search |
| genKey | generates a primary key value |
| getById | Returns a BeanObject representing the row identified by the supplied primary key |
The Myna.DataManager object that created this manager
The Myna.Database for this manager
The Myna.Table for this manager
The columns array from Myna.Table.columns for this table
The columnNames array from Myna.Table.columnNames for this table
a ManagerObject specific base template for BeanObjects.
This is a copy of Myna.DataManager.beanTemplate which contains all the functions of BeanObject. Changes to this object only affect beans created by this manager. Behavior of BeanObjects can be altered by modifying this object:
var dm = new Myna.DataManager("hr_datasource");
var man = dm.getManager("employees")
//the init function is called right after instantiating a <BeanObject>
man.beanTemplate.init=function(){
Myna.log(
"audit",
"Employee " +this.data.emp_id +
"Accessed by " +Myna.dump($cookie.getAuthUser())
);
}
//replace existing function
man.beanTemplate.set_age=function(value){
//this is a calculated column and should not be set
return;
}
//append or prepend function
man.beanTemplate.before("saveField",function(fname,newval){
Myna.log(
"audit",
"Employee + this.data.emp_id + " column " + fname+" modified",
"Modified by " + Myna.dump($cookie.getAuthUser()) +
"<br>Old value:" + this.data[fname] +
"<br>New value:" + newval
);
})
remove:function( id )
Removes a row from the managed table matching the supplied primary key
| id | primary key value of the row to remove |
create:function( requiredFields )
Creates a record in the database, optionally generating a primary key
| requiredFields | An object where the keys are column names and the values are the values to insert. |
requiredFields must contain entries for all non-null columns without default values, except the primary key. If the primary key is not specified, and the column does not have a default value, genKey is called to generate a key. Any extra columns supplied will be inserted as well.
instance of the Bean that represents the new row. See getById
+- - - - - - - - - - - - - - - - - -+
| table employees |
+- - - - - - - - - - - - - - - - - -+
| emp_id int4 primary key |
| fname varchar |
| mname varchar |
| lname varchar |
| manager_id int4 |
| hire_date date |
+- - - - - - - - - - - - - - - - - -+
var dm = new Myna.DataManager("hr_datasource");
var empManager = dm.getManager("employees");
var newEmpBean = empManager.create({
fname:"Bob",
lname:"Dobb",
hire_date:Date.parse("02/21/1992","m/d/Y")
})
find:function( pattern, caseSensitive )
returns an array of primaryKey values that match a search
| pattern | if this is a string, the primary key will be searched for this value. If this is an object, each key is expected to by a column name and the value a pattern to search for. In either mode, the SQL wildcard (%) can be used for a “like” search. |
| caseSensitive | Optional, default false if true, patterns will be matched in a case-sensitive manner |
var employees = new Myna.DataManager("some_ds").getManager("employees");
// a primary key search
var bob_exists = employees.find("55652315").length
//one column search for exact match
var bobs_emps = employees.find({
manager_id:"55652315"
})
//Who are Bob's employees?
bobs_emps.forEach(function(employee_id){
Myna.print(employees.getById(employee_id).get_name() +"<br>");
})
//more complicated search with wildcards
var bobs_helpers = employees.find({
manager_id:"55652315",
job_title:"%assitant%"
})
findBeans:function( pattern, caseSensitive )
returns a Myna.DataSet of bean objects that match a search
| pattern | if this is a string, the primary key will be searched for this value. If this is an object, each key is expected to by a column name and the value a pattern to search for. In either mode, the SQL wildcard (%) can be used for a “like” search. |
| caseSensitive | Optional, default false if true, patterns will be matched in a case-sensitive manner |
var employees = new Myna.DataManager("some_ds").getManager("employees");
// a primary key search
var bob_exists = employees.find("55652315").length
//one column search for exact match
var bobs_emps = employees.findBeans({
manager_id:"55652315"
})
//Who are Bob's employees?
bobs_emps.forEach(function(employee){
Myna.print(employee.get_name() +"<br>");
})
//What are their email addresses?
Myna.printDump(bobs_emps.valueArray("email"),"Bob's Emloyees' Email")
//more complicated search with wildcards
var bobs_helpers = employees.findBeans({
manager_id:"55652315",
job_title:"%assitant%"
})
//Using aggregate math: Bob's employees average salary
//See Myna.DataSet
var bobs_emps_avg_sal = employees.findBeans({
manager_id:"55652315"
}).average("salary")
genKey:function()
generates a primary key value
By default this returns the maximum value of the primary key column + 1. This is not the ideal algorithm and should be replaced with a database specific means of generating a primary key.
This function can be replaced in Myna.DataManager.managerTemplate or by replacing the function in ManagerObject
var dm = new Myna.DataManager("some datasource");
//via manager template
dm.managerTemplate.genKey=function(){
<your code here returning a key here>
}
//via the ManagerObject
var man = dm.getManager("employees")
man.genKey = function(){
<your code here returning a key here>
}
getById:function( id )
Returns a BeanObject representing the row identified by the supplied primary key
| id | primary key value of the row to retrieve |
This function loads the data from the indicated row into into a <Myna.DataManager.prototype.BeanBase> object. Each bean is generated with get_<column name> and set_<column name> functions. The set functions will immediately set the value in the underlying row.
Row data access object generated and returned by ManagerObject.getById
| Properties | |
| manager | The ManagerObject that created this bean |
| dm | The Myna.DataManager object that created this bean |
| ds | The datasource name for this bean |
| data | a simple JS object containing this bean’s data |
| id | The value of the primary key of this bean |
| columns | The columns array from Myna.Table.columns for this table |
| columnNames | The columnNames array from Myna.Table.columnNames for this table |
| Functions | |
| get_<columnName> | gets a value for <columnName> |
| set_<columnName> | sets a value for <columnName> |
| setFields | Sets multiple fields at once |
| saveField | Persists a value to its underlying row |
| getData | return a structure of this bean’s data |
| getParent | return a bean representing this bean’s parent record |
| getChildren | return a Myna.DataSet of beans representing this bean’s child records |
The ManagerObject that created this bean
The Myna.DataManager object that created this bean
The columns array from Myna.Table.columns for this table
The columnNames array from Myna.Table.columnNames for this table
gets a value for <columnName>
This function is generated for every column in the associated table.
sets a value for <columnName>
| newval | new value for the column |
Myna.ValidationResult object representing the result of the set.
This function is generated for every column in the associated table, except for the primary key.
setFields:function( fields )
Sets multiple fields at once
| fields | an object of column names and their values |
Myna.ValidationResult representing the result of this action.
This function will examine each non-function property of fields and call the corosponding “set” function, if available. Properties that do not match a “set” function are ignored
saveField:function( fieldName, newval )
Persists a value to its underlying row
| fieldName | A column name in the row to savee a value to |
| newval | The value to save |
Myna.ValidationResult representing the result of this action.
This function is normally called from the “set” function, but may be useful when overriding the generated “set” function.
getData:function()
return a structure of this bean’s data
This is a copy of the data, so it will not change when the object is modified
getParent:function( column )
return a bean representing this bean’s parent record
| column | Optional, default: first foreign key column name in this table to dereference. Must be a properly defined foreign key in the database |
var orderBean = new Myna.DataManager("myapp")
.getManager("orders")
.getById(curOrderId);
var customerBean = orderBean.getParent("customer_id");
Myna.print(customerBean.last_name);
getChildren:function( table, column )
return a Myna.DataSet of beans representing this bean’s child records
| table | name of child table to check for matching rows |
| column | Optional, default: first exported key to child table column_name to match in child table. This is only necessary if the child table declares more than one foreign key to this table |
var customerBean = new Myna.DataManager("myapp")
.getManager("customers")
.getById(curCustomerId);
var orders = customerBean.getChildren("orders");
Myna.print("Orders Total: " +orders.sumByCol("order_total"));Contructs a Myna.DataManager Object for the supplied dataSource
Myna.DataManager = function ( dataSource )
Constructs a ManagerObject for the supplied table.
Myna.DataManager.prototype.getManager=function( tableName )
internal function to load table data into the manager
loadTableData:function( tableName )
Removes a row from the managed table matching the supplied primary key
remove:function( id )
Creates a record in the database, optionally generating a primary key
create:function( requiredFields )
returns an array of primaryKey values that match a search
find:function( pattern, caseSensitive )
returns a Myna.DataSet of bean objects that match a search
findBeans:function( pattern, caseSensitive )
generates a primary key value
genKey:function()
Returns a BeanObject representing the row identified by the supplied primary key
getById:function( id )
Sets multiple fields at once
setFields:function( fields )
Persists a value to its underlying row
saveField:function( fieldName, newval )
return a structure of this bean’s data
getData:function()
return a bean representing this bean’s parent record
getParent:function( column )
return a Myna.DataSet of beans representing this bean’s child records
getChildren:function( table, column )