Myna. DataManager

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.

Here is an example

    +- - - - - - - - - - - - - - - - - -+
| 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();

For more about extending DataManager classes, see

Also check out empManager.columns for metadata about each column in the table, such as name, default value, size, type, nullable, precision and more.

Summary
Myna. DataManagerCreates Objects for reading from and writing to database tables
Functions and Properties
DataManagerContructs a Myna.DataManager Object for the supplied dataSource
dsDatasource associated with this Myna.DataManager
dbMyna.Database object that represents the database this table resides in
getManagerConstructs a ManagerObject for the supplied table.
managerTemplateBase template for ManagerObjects.
beanTemplateBase template for BeanObjects.
ManagerObjectTable data access object generated and returned by Myna.DataManager.getManager
Properties
dmThe Myna.DataManager object that created this manager
dbThe Myna.Database for this manager
tableThe Myna.Table for this manager
dsThe datasource name for this manager
columnsThe columns array from Myna.Table.columns for this table
columnNamesThe columnNames array from Myna.Table.columnNames for this table
beanTemplatea ManagerObject specific base template for BeanObjects.
Functions
loadTableDatainternal function to load table data into the manager
removeRemoves a row from the managed table matching the supplied primary key
createCreates a record in the database, optionally generating a primary key
findreturns an array of primaryKey values that match a search
findBeansreturns a Myna.DataSet of bean objects that match a search
genKeygenerates a primary key value
getByIdReturns a BeanObject representing the row identified by the supplied primary key
BeanObjectRow data access object generated and returned by ManagerObject.getById
Properties
managerThe ManagerObject that created this bean
dmThe Myna.DataManager object that created this bean
dsThe datasource name for this bean
dataa simple JS object containing this bean’s data
idThe value of the primary key of this bean
columnsThe columns array from Myna.Table.columns for this table
columnNamesThe columnNames array from Myna.Table.columnNames for this table
Functions
get_<columnName>gets a value for <columnName>
set_<columnName>sets a value for <columnName>
setFieldsSets multiple fields at once
saveFieldPersists a value to its underlying row
getDatareturn a structure of this bean’s data
getParentreturn a bean representing this bean’s parent record
getChildrenreturn a Myna.DataSet of beans representing this bean’s child records

Functions and Properties

DataManager

Myna.DataManager = function (dataSource)

Contructs a Myna.DataManager Object for the supplied dataSource

Parameters

dataSourceDatasource Name

ds

Datasource associated with this Myna.DataManager

db

Myna.Database object that represents the database this table resides in

getManager

Myna.DataManager.prototype.getManager=function(tableName)

Constructs a ManagerObject for the supplied table.

Parameters

tableNamelowercase name of the table

Detail

Creates a ManagerObject for the supplied table.

See

managerTemplate

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:

beanTemplate

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
);
})

See: ManagerObject.beanTemplate

ManagerObject

Table data access object generated and returned by Myna.DataManager.getManager

Summary
Properties
dmThe Myna.DataManager object that created this manager
dbThe Myna.Database for this manager
tableThe Myna.Table for this manager
dsThe datasource name for this manager
columnsThe columns array from Myna.Table.columns for this table
columnNamesThe columnNames array from Myna.Table.columnNames for this table
beanTemplatea ManagerObject specific base template for BeanObjects.
Functions
loadTableDatainternal function to load table data into the manager
removeRemoves a row from the managed table matching the supplied primary key
createCreates a record in the database, optionally generating a primary key
findreturns an array of primaryKey values that match a search
findBeansreturns a Myna.DataSet of bean objects that match a search
genKeygenerates a primary key value
getByIdReturns a BeanObject representing the row identified by the supplied primary key

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.

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
);
})

See: Myna.DataManager.beanTemplate

Functions

loadTableData

loadTableData:function(tableName)

internal function to load table data into the manager

remove

remove:function(id)

Removes a row from the managed table matching the supplied primary key

Parameters

idprimary key value of the row to remove

create

create:function(requiredFields)

Creates a record in the database, optionally generating a primary key

Parameters

requiredFieldsAn object where the keys are column names and the values are the values to insert.

Detail

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.

Returns

instance of the Bean that represents the new row.  See getById

Example

    +- - - - - - - - - - - - - - - - - -+
| 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

find:function(pattern,
caseSensitive)

returns an array of primaryKey values that match a search

Parameters

patternif 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.
caseSensitiveOptional, default false if true, patterns will be matched in a case-sensitive manner

Examples

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%"
})

See

findBeans

findBeans

findBeans:function(pattern,
caseSensitive)

returns a Myna.DataSet of bean objects that match a search

Parameters

patternif 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.
caseSensitiveOptional, default false if true, patterns will be matched in a case-sensitive manner

Examples

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")

See

find

genKey

genKey:function()

generates a primary key value

Detail

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

getById:function(id)

Returns a BeanObject representing the row identified by the supplied primary key

Parameters

idprimary key value of the row to retrieve

Detail

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.

See

BeanObject

Row data access object generated and returned by ManagerObject.getById

Summary
Properties
managerThe ManagerObject that created this bean
dmThe Myna.DataManager object that created this bean
dsThe datasource name for this bean
dataa simple JS object containing this bean’s data
idThe value of the primary key of this bean
columnsThe columns array from Myna.Table.columns for this table
columnNamesThe columnNames array from Myna.Table.columnNames for this table
Functions
get_<columnName>gets a value for <columnName>
set_<columnName>sets a value for <columnName>
setFieldsSets multiple fields at once
saveFieldPersists a value to its underlying row
getDatareturn a structure of this bean’s data
getParentreturn a bean representing this bean’s parent record
getChildrenreturn a Myna.DataSet of beans representing this bean’s child records

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>

Detail

This function is generated for every column in the associated table.

set_<columnName>

sets a value for <columnName>

Parameters

newvalnew value for the column

Returns

Myna.ValidationResult object representing the result of the set.

Detail

This function is generated for every column in the associated table, except for the primary key.

setFields

setFields:function(fields)

Sets multiple fields at once

Parameters

fieldsan object of column names and their values

Returns

Myna.ValidationResult representing the result of this action.

Detail

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

saveField:function(fieldName,
newval)

Persists a value to its underlying row

Parameters

fieldNameA column name in the row to savee a value to
newvalThe value to save

Returns

Myna.ValidationResult representing the result of this action.

Detail

This function is normally called from the “set” function, but may be useful when overriding the generated “set” function.

getData

getData:function()

return a structure of this bean’s data

Detail

This is a copy of the data, so it will not change when the object is modified

getParent

getParent:function(column)

return a bean representing this bean’s parent record

Parameters

columnOptional, default: first foreign key column name in this table to dereference.  Must be a properly defined foreign key in the database

Example

var orderBean = new Myna.DataManager("myapp")
.getManager("orders")
.getById(curOrderId);
var customerBean = orderBean.getParent("customer_id");
Myna.print(customerBean.last_name);

getChildren

getChildren:function(table,
column)

return a Myna.DataSet of beans representing this bean’s child records

Parameters

tablename of child table to check for matching rows
columnOptional, 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

Example

var customerBean = new Myna.DataManager("myapp")
.getManager("customers")
.getById(curCustomerId);
var orders = customerBean.getChildren("orders");
Myna.print("Orders Total: " +orders.sumByCol("order_total"));
Myna.DataManager = function (dataSource)
Contructs a Myna.DataManager Object for the supplied dataSource
Provides database metadata and manages Myna.Table objects
Myna.DataManager.prototype.getManager=function(tableName)
Constructs a ManagerObject for the supplied table.
Table data access object generated and returned by Myna.DataManager.getManager
Row data access object generated and returned by ManagerObject.getById
Creates Objects for reading from and writing to database tables
Create modify and delete SQL tables
Structure representing the defined columns in this table, keyed by the column name.
An array of column names, in the order they appear in the table.
loadTableData:function(tableName)
internal function to load table data into the manager
remove:function(id)
Removes a row from the managed table matching the supplied primary key
create:function(requiredFields)
Creates a record in the database, optionally generating a primary key
find:function(pattern,
caseSensitive)
returns an array of primaryKey values that match a search
findBeans:function(pattern,
caseSensitive)
returns a Myna.DataSet of bean objects that match a search
A normalized data structure for working with tabular data
genKey:function()
generates a primary key value
getById:function(id)
Returns a BeanObject representing the row identified by the supplied primary key
setFields:function(fields)
Sets multiple fields at once
saveField:function(fieldName,
newval)
Persists a value to its underlying row
getData:function()
return a structure of this bean’s data
getParent:function(column)
return a bean representing this bean’s parent record
getChildren:function(table,
column)
return a Myna.DataSet of beans representing this bean’s child records
Base template for ManagerObjects.
Base template for BeanObjects.
a ManagerObject specific base template for BeanObjects.
Stores the results of one or more validation operations