How do I use a dynamic variable as a Meteor/MongoDB collection name? - mongodb

So I tried this but it didn't work (on isServer) :
var tableName= "";
(...)
if (silly_cond === 1){
tableName = "Table1";
}else{
tableName = "Table2";
}
TableCol = new Mongo.Collection(tableName);
For some reason I can't get it to work. It seems to only accept
TableCol = new Mongo.Collection("Table1");
The idea was to fetch the tablename from the table ID, and apply the same JS to different tables (on different templates). What am I doing wrong?

You need to declare tableName outside the functions, otherwise it can't be seen.
var tableName = "";
if (silly_cond === 1){
tableName = "Table1";
}else{
tableName = "Table2";
}
TableCol = new Mongo.Collection(tableName);

I ended up using the dburles:mongo-collection-instances package. It let's me access any collection by the collection name. So in my example:
TableCol = new Mongo.Collection("Table1");
Using the above package I just write for example:
var dbvar = "Table1";
Meteor.Collection.get(dbvar).find()
and this way I can use variables to get collections.

Related

BIRT - creating a temporary table

I am building a BIRT report based on a dynamic table. I have a function that needs to return a table with variable number of columns of different types, so we have decided that this function will create a temporary table and just return its name.
So in the BIRT beforeFactory I am running the query that calls this function and then I am trying to read from the table of returned name and create a report table dynamically based on the number of columns and types. Two questions:
1. Is there a better way to return a table with variable number of columns? (this cannot be all the possible columns that I later filter as that would exceed maximum number of allowed columns)?
2. How to make Birt to see my temporary table? Here is the code, that I run in beforeFactory. Apparenty the table does not exists when calling second query.
importPackage(Packages.java.lang);
importPackage(Packages.org.eclipse.birt.report.data.adapter);
importPackage(Packages.org.eclipse.birt.report.data.adapter.api);
importPackage(Packages.org.eclipse.birt.report.data.adapter.impl);
importPackage(Packages.org.eclipse.birt.report.model.api);
importPackage(Packages.org.eclipse.birt.data.engine.api.querydefn);
//Get Data Source
var dataSource =
reportContext.getDesignHandle().getDesign().findDataSource("mydb");
//Create Data Set for data table name
var elementFactory =
reportContext.getReportRunnable().designHandle.getElementFactory();
var dataSet = elementFactory.newOdaDataSet("tableName",
"org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet");
dataSet.setDataSource(dataSource.getName());
dataSet.setQueryText("select table_name from my_export_function('str1',
'str2');");
reportContext.getDesignHandle().getDataSets( ).add(dataSet);
//Create Data Session
var myconfig =
reportContext.getReportRunnable().getReportEngine().getConfig();
var des = DataRequestSession.newSession(myconfig, new DataSessionContext(3));
var dset = reportContext.getDesignHandle().findDataSet("tableName");
des.defineDataSource(des.getModelAdaptor()
.adaptDataSource(reportContext.getDesig nHandle()
.findDataSource("mydb")));
des.defineDataSet(des.getModelAdaptor()
.adaptDataSet(reportContext.getDesignHandle()
.findDataSet("tableName")));
//Query Definition
queryDefinition = new QueryDefinition();
queryDefinition.setDataSetName(dataSet.getName());
queryDefinition.setAutoBinding(true);
var pq = des.prepare(queryDefinition);
var qr = pq.execute(null);
var ri = qr.getResultIterator();
var tableName = "";
while (ri.next()) {
tableName = ri.getString("table_name");
}
var dataSet2 = elementFactory.newOdaDataSet("reportData",
"org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet");
dataSet2.setDataSource(dataSource.getName());
dataSet2.setQueryText("select * from " + tableName + ";");
System.out.println("TTTT: " + dataSet2.getQueryText());
reportContext.getDesignHandle().getDataSets( ).add(dataSet2);
//Query Definition
queryDefinition2 = new QueryDefinition();
queryDefinition2.setDataSetName(dataSet2.getName());
queryDefinition2.setAutoBinding(true);
var pq2 = des.prepare(queryDefinition2);
var qr2 = pq2.execute(null);
var ri2 = qr2.getResultIterator( );
var cc = ri2.getResultMetaData().getColumnCount();
System.out.println("col_01_name: " +
ri2.getResultMetaData().getColumnLabel(1));
System.out.println("Count: " + cc);
while (ri2.next()) {
System.out.println("Table: "+ ri2);
System.out.println("col_01: "+ ri2.getValue("col_01"));
}
ri.close();
qr.close();
ri2.close();
qr2.close();
des.close();
I managed to make the code work. Following lines solved the problem with second query:
var des2 = DataRequestSession.newSession(myconfig, new DataSessionContext(3));
des2.defineDataSource(des2.getModelAdaptor()
.adaptDataSource(reportContext.getDesig nHandle()
.findDataSource("mydb")));
des2.defineDataSet(des2.getModelAdaptor()
.adaptDataSet(reportContext.getDesignHandle()
.findDataSet("tableName")));
and then:
var pq2 = des2.prepare(queryDefinition2);
Also we have changed the function to return the query instead of creating a temporary table.

SugarCRM 7 override auto-increment field

Through a logichook, I'm trying to insert a new Quote record through the bean class. The "quote_num" field is an auto-increment field. When I try this code below, instead of inserting in MySQL with the quote_num i specify, it uses the next number in the auto-increment sequence. I know I could just use an SQL INSERT but I'm trying to stick to the bean. Any ideas?
$newQuote = new Quote();
$newQuote->name = "Web Order";
$newQuote->quote_num = 902011;
$newQuote->quote_order_c = $orderorcredit;
$newQuote->save();
For Auto Increment : You can do like below ,
$count = "SELECT IFNULL(MAX(your field), 0) as count FROM table;
$count = '';
while ($row = $GLOBALS['db']->fetchByAssoc($result)) {
$count_coc = $row['count'];
}
$bean->ignore_update = true;
$bean->number_c = $count_coc + 1;
$bean->save();

function does not exist in pg_proc in postgresql

I tried to call my user defined function in pgresql from C# code,
my function creation script is as follows,
CREATE OR REPLACE FUNCTION public."GetUserDailyData"(
cid integer,
hid integer,
currday integer)
RETURNS character varying AS
$BODY$
DECLARE
returndata varchar = '';
BEGIN
SELECT data->20+currday into returndata FROM pops
WHERE hybid = hid and cropid = cid;
return returndata;
END
$BODY$
LANGUAGE plpgsql
COST 100;
My method to call this function is as follows,
public static object ExecuteScalar(string conString, string spName, NpgsqlParameter[] param)
{
using (var conn = new NpgsqlConnection(conString))
{
conn.Open();
using (var tran = conn.BeginTransaction())
using (var command = conn.CreateCommand())
{
command.CommandText = spName;
command.CommandType = CommandType.StoredProcedure;
for (var i = 0; i < param.Length; i++)
{
command.Parameters.Add(new NpgsqlParameter());
command.Parameters[i] = param[i];
}
var result = command.ExecuteScalar();
return result;
}
}
}
I tried everything even checked the existence of this function in pg_proc using
select * from pg_proc where proname = 'GetUserDailyData'
and it reflected the function details row.
But every time it is giving the same error.
Any kind of suggestion would be highly appreciated. Thanks.
Adding objects with case sensitive names in PostgreSQL can lead to these complications; in this case you need to specify the name of the stored procedure between quotes, however it would be advisable to simply not create any objects that rely on case sensitivity, use underscores instead, or when create/refer to objects using CamelCase without the quotes (which creates/refers to the objects in low-caps). In any case, you may also need to specify the whole interface (not just the name) as the CommandText, and specify the data types of the parameters (see this).
...
command.CommandText = "\"" + spName + "\"";
...

Processing multiple result-sets returned from a stored procedure in Entity Framework

I have a stored procedure like this :
CREATE STORED PROCEDURE Test1
AS
BEGIN
SELECT * FROM Table1
SELECT * FROM Table2
END
Now I want to use this procedure in EF.How?! can I use both two SELECT requests returned from procedure in EF ?!
Note : I know how can I use this stored procedure if it returns just on result
Thanks
Here is the answer your question
using (var db = new EF_DEMOEntities())
{
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "[dbo].[proc_getmorethanonetable]";
try
{
db.Database.Connection.Open();
using (var reader = cmd.ExecuteReader())
{
var orders = ((IObjectContextAdapter)db).ObjectContext.Translate<Order>(reader);
GridView1.DataSource = orders.ToList();
GridView1.DataBind();
reader.NextResult();
var items =
((IObjectContextAdapter)db).ObjectContext.Translate<Item>(reader);
GridView2.DataSource = items.ToList();
GridView2.DataBind();
reader.NextResult();
var collect = ((IObjectContextAdapter)db).ObjectContext.Translate<object>(reader);
GridView3.DataSource = collect.ToList();
GridView3.DataBind();
}
}
finally
{
db.Database.Connection.Close();
}
}

EntityFrameWork and TableValued Parameter

I'm trying to call a stored procedure from EntityFramework which uses Table-value parameter.
But when I try to do function import I keep getting a warning message saying -
The function 'InsertPerson' has a parameter 'InsertPerson_TVP' at
parameter index 0 that has a data type 'table type' which is currently
not supported for the target .NET Framework version. The function was
excluded.
I did a initial search here and found few posts which says It's possible in EntityFrameWork with some work arounds and few saying it's not supported in current versions.
Does any one know a better approach or solution for this problem?
I ended up doing this, Please note we are working on EF DataContext(not ObjectContext)
Executing a Stored procedure with output parameter
using (DataContext context = new DataContext())
{
////Create table value parameter
DataTable dt = new DataTable();
dt.Columns.Add("Displayname");
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("TimeStamp");
DataRow dr = dt.NewRow();
dr["Displayname"] = "DisplayName";
dr["FirstName"] = "FirstName";
dr["LastName"] ="LastName";
dr["TimeStamp"] = "TimeStamp";
dt.Rows.Add(dr);
////Use DbType.Structured for TVP
var userdetails = new SqlParameter("UserDetails", SqlDbType.Structured);
userdetails.Value = dt;
userdetails.TypeName = "UserType";
////Parameter for SP output
var result = new SqlParameter("ResultList", SqlDbType.NVarChar, 4000);
result.Direction = ParameterDirection.Output;
context.Database.ExecuteSqlCommand("EXEC UserImport #UserDetails, #ResultList OUTPUT", userdetails, result);
return result == null ? string.Empty : result.Value.ToString();
}
My Table-Value-Parameter (UDT Table) script looks like this:
CREATE TYPE [dbo].[UserType] AS TABLE (
[DisplayName] NVARCHAR (256) NULL,
[FirstName] NVARCHAR (256) NULL,
[LastName] NVARCHAR (256) NULL,
[TimeStamp] DATETIME NULL
)
And my store procedure begins like
CREATE PROCEDURE UserImport
-- Add the parameters for the stored procedure here
#UserDetails UserType Readonly,
#ResultList NVARCHAR(MAX) output
AS
For Stored procedure without output parameter we don't need any ouput parameter added/passed to SP.
Hope it helps some one.
Perhaps we could also consider the SqlQuery method:
[Invoke]
public SomeResultType GetResult(List<int> someIdList)
{
var idTbl = new DataTable();
idTbl.Columns.Add("Some_ID");
someIdList.ForEach(id => idTbl.Rows.Add(id));
var idParam = new SqlParamter("SomeParamName", SqlDbType.Structured);
idParam.TypeName = "SomeTBVType";
idParam.Value = idTbl;
// Return type will be IEnumerable<T>
var result = DbContext.Database.SqlQuery<SomeResultType>("EXEC SomeSPName, #SomeParamName", idParam);
// We can enumerate the result...
var enu = result.GetEnumerator();
if (!enu.MoveNext()) return null;
return enu.Current;
}
var detailTbl = new DataTable();
detailTbl.Columns.Add("DetailID");
detailTbl.Columns.Add("Qty");
txnDetails.ForEach(detail => detailTbl.Rows.Add(detail.DetailID, detail.Qty));
var userIdParam = new System.Data.SqlClient.SqlParameter("#UserID", SqlDbType.Int);
userIdParam.Value = 1;
var detailParam = new System.Data.SqlClient.SqlParameter("#Details", SqlDbType.Structured);
detailParam.TypeName = "DetailUpdate";
detailParam.Value = detailTbl;
var txnTypeParam = new System.Data.SqlClient.SqlParameter("#TransactionType", SqlDbType.VarChar);
txnTypeParam.Value = txnType;
var result = await db.Database.ExecuteSqlCommandAsync("MySP #UserID, #Details, #TransactionType", userIdParam, detailParam, txnTypeParam);
if(result >= 0)
return StatusCode(HttpStatusCode.OK);
else
return StatusCode(HttpStatusCode.InternalServerError);