attributeError: 'str' object has no attribute 'dbname' - odoo-8

I created a new modul to rewrite a _read_group_process_groupby method
from server\openerp\modules.py and add group by hour option,
but I get this error:
the method from my module
\addons-custom\my_group_hours\models\models.py
is the following
#api.model
def _read_group_process_groupby(self, gb, query, context):
split = gb.split(':')
field_type = self._fields[split[0]].type
gb_function = split[1] if len(split) == 2 else None
temporal = field_type in ('date', 'datetime')
tz_convert = field_type == 'datetime' and context.get('tz') in pytz.all_timezones
qualified_field = self._inherits_join_calc(self._table, split[0], query)
if temporal:
display_formats = {
'hour': 'HH:mm dd MMM yyyy',
'day': 'dd MMM yyyy',
'week': "'W'w YYYY",
'month': 'MMMM yyyy',
'quarter': 'QQQ yyyy',
'year': 'yyyy',
}
time_intervals = {
'hour': dateutil.relativedelta.relativedelta(hours=1),
'day': dateutil.relativedelta.relativedelta(days=1),
'week': datetime.timedelta(days=7),
'month': dateutil.relativedelta.relativedelta(months=1),
'quarter': dateutil.relativedelta.relativedelta(months=3),
'year': dateutil.relativedelta.relativedelta(years=1)
}
if tz_convert:
qualified_field = "timezone('%s', timezone('UTC',%s))" % (context.get('tz', 'UTC'), qualified_field)
qualified_field = "date_trunc('%s', %s)" % (gb_function or 'month', qualified_field)
if field_type == 'boolean':
qualified_field = "coalesce(%s,false)" % qualified_field
return {
'field': split[0],
'groupby': gb,
'type': field_type,
'display_format': display_formats[gb_function or 'month'] if temporal else None,
'interval': time_intervals[gb_function or 'month'] if temporal else None,
'tz_convert': tz_convert,
'qualified_field': qualified_field
}
models.BaseModel._read_group_process_groupby = _read_group_process_groupby

#api.model is used to expose a new-style method to the old API.
When your method is called, gb is passed as cr and it results in:
AttributeError: 'str' object has no attribute 'dbname'
You need just to remove the decorator.

Related

Invalid Datetime format: 1366 Incorrect integer value LARAVEL

I'm trying to update or insert multiple data when a post approve. Insert condition is working but update function giving error.
(SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer
value: '[10000,10000]' for column
parijattech_web_app.palika_to_school_kriyakalap.cash at row 3 update
palika_to_school_kriyakalap SET cash = [ 10000, 10000 ],
palika_to_school_kriyakalap.updated_at = 2022 -12 -26 04: 58: 52 WHERE
kriya_name IN (SALARY, POSHAK) AND school_id IN (24, 24))
My code is so messy. So, how can i improve my coding skill?
Here is my Controller
public function approve(Request $request, $biniyojan_id)
{
$upudate = DB::table('biniyojan')
->where('biniyojan_id', $biniyojan_id)
->update(['biniyojan_status' => 1]);
if ($upudate) {
$budget_data = BiniyojanDetails::where('biniyojan_id', $biniyojan_id)->where('biniyojan_id', $biniyojan_id)->get();
$kriya = Palika_ToSchool_Kriyakalap::whereIn('kriya_name', $budget_data->pluck('kriyakalap'))
->whereIn('school_id', $budget_data->pluck('school_id'))
->get();
$budget_cash = BiniyojanDetails::where('biniyojan_id', $biniyojan_id)
->whereIn('school_id', $kriya->pluck('school_id'))
->whereIn('kriyakalap', $kriya->pluck('kriya_name'))
->get();
$updated_bini = $budget_cash->pluck('cash')->toArray();
$updated_kriya_cash = $kriya->pluck('cash')->toArray();
$newArray = array_map(function () {
return array_sum(func_get_args());
}, $updated_bini, $updated_kriya_cash);
if ($kriya->pluck('school_id') == $budget_data->pluck('school_id')) {
Palika_ToSchool_Kriyakalap::whereIn('kriya_name', $budget_data->pluck('kriyakalap'))
->whereIn('school_id', $budget_data->pluck('school_id'))
->update(['cash' => $newArray]);
} else {
foreach ($budget_data as $bud) {
$data = [
'school_id' => $bud->school_id,
'kriya_name' => $bud->kriyakalap,
'cash' => $bud->cash,
];
Palika_ToSchool_Kriyakalap::where('kriya_name' != $bud->kriyakalap)
->insert($data);
}
}
return redirect()->back()->with('status', 'Approved!!!');
}
else{
return redirect()->back()->with('error', 'Error!!!');
}
}

EFCore 2.2 GroupBy Sum and DateDiff

I'm trying to translate the following SQL in to an EF Core query and I'm getting warnings that GroupBy and Sum will be evaluated locally. Is there anyway currently to write this that it will fully translate to SQL?
SELECT UserId, ST.StatusId, SUM(DATEDIFF(MINUTE, StartDate, ISNULL(EndDate,GETDATE()))) AS Time
FROM StatusTransaction ST
WHERE
TeamManagerId = 1
AND StartDate >= N'01-01-2019'
AND ISNULL(EndDate,GETDATE()) <= N'01-02-2019'
GROUP BY UserId, ST.StatusId
ORDER BY UserId
And these are the EF queries I've used:
var efFunction = await context
.Where(st => st.TeamManagerId == tmId && st.StartDate >= dateFrom && (st.EndDate ?? DateTime.Now) <= dateTo)
.GroupBy(st => new { st.UserId, st.StatusId })
.Select(g => new
{
g.Key.UserId,
g.Key.StatusId,
Time = g.Sum(st => Microsoft.EntityFrameworkCore.EF.Functions.DateDiffMinute(st.StartDate, st.EndDate)) // null check not done on end date - (st.EndDate ?? DateTime.Now) causes an error here
}).ToListAsync(cancellationToken).ConfigureAwait(false);
var simpleDateSubtraction = await context
.Where(st => st.TeamManagerId == tmId && st.StartDate >= dateFrom && (st.EndDate ?? DateTime.Now) <= dateTo)
.GroupBy(st => new { st.UserId, st.StatusId })
.Select(g => new
{
g.Key.UserId,
g.Key.StatusId,
Time = g.Sum(st => st.EndDate.Value.Subtract(st.StartDate).Minutes)// null check not done on end date - (st.EndDate ?? DateTime.Now) causes an error here
}).ToListAsync(cancellationToken).ConfigureAwait(false);
var groupBySimpleSum = await context
.Where(st => st.TeamManagerId == tmId)
.GroupBy(st => new { st.TeamManagerId, st.OperationsManagerId })
.Select(g => new
{
g.Key.OperationsManagerId,
g.Key.TeamManagerId,
Foo = g.Sum(st => st.UserId) // nonsense but a simple column to sum, this translates fully to SQL
}).ToListAsync(cancellationToken).ConfigureAwait(false);
First, EF Core still doesn't support translating TimeSpan operations, and DateTime difference produces TimeSpan, hence EF.Functions.DateDiff methods are the right way to go.
Second, it still can translate GroupBy aggregates only on simple member accessor expressions. So you have to either pre Select the GroupBy expressions:
var query = context
.Where(st => st.TeamManagerId == tmId
&& st.StartDate >= dateFrom
&& (st.EndDate ?? DateTime.Now) <= dateTo
)
.Select(st => new
{
st.UserId,
st.StatusId,
Time = EF.Functions.DateDiffMinute(st.StartDate, st.EndDate ?? DateTime.Now)
})
.GroupBy(st => new { st.UserId, st.StatusId })
.Select(g => new
{
g.Key.UserId,
g.Key.StatusId,
Time = g.Sum(st => st.Time)
});
or use the GroupBy overload which allows pre selecting the source for the aggregates:
var query = context
.Where(st => st.TeamManagerId == tmId
&& st.StartDate >= dateFrom
&& (st.EndDate ?? DateTime.Now) <= dateTo
)
.GroupBy(st => new { st.UserId, st.StatusId }, st => new
{
Time = EF.Functions.DateDiffMinute(st.StartDate, st.EndDate ?? DateTime.Now)
})
.Select(g => new
{
g.Key.UserId,
g.Key.StatusId,
Time = g.Sum(st => st.Time)
});

how to concat join by qb in doctrine?

I want to add a join to my query in if condition but it returned an error.
how we can do it in doctrine?
is there any thing like:
$qb->andWhere('p.$gender = :g')->setParameter('g', $gender);
for join in doctrine symfony??
$qb->select("p")->from("PfmSanadBundle:Person", "p");
if ((isset($province) && trim($province) !== '') && (isset($City) && trim($City) !== '')){
$qb->join("p" ,"students", "ps")
->join("ps" ,"organization", "po")
->join("po" ,"cityProvince", "pc")
->join("pc" ,"province", "pp");
}
if ((isset($province) && trim($province) !== '') && !isset($City)) {
$qb->join("p.students", "ps")
->join("ps.organization", "po");
}
$res = $qb->getQuery()->getArrayResult();
error (postman):
"error": {
"code": 500,
"message": "Internal Server Error",
"exception": [
{
"message": "[Semantical Error] line 0, col 49 near 'p students INNER': Error: Class 'p' is not defined.",
"class": "Doctrine\ORM\Query\QueryException",
"trace": [
{
Join method usage is following
// Example - $qb->join('u.Group', 'g', Expr\Join::WITH, $qb->expr()->eq('u.status_id', '?1'))
// Example - $qb->join('u.Group', 'g', 'WITH', 'u.status = ?1')
// Example - $qb->join('u.Group', 'g', 'WITH', 'u.status = ?1', 'g.id')
public function join($join, $alias, $conditionType = null, $condition = null, $indexBy = null);
Thus following lines
$qb->join("p" ,"students", "ps")
->join("ps" ,"organization", "po")
->join("po" ,"cityProvince", "pc")
->join("pc" ,"province", "pp");
change to
$qb->join("p.students", "ps")
->join("ps.organization", "po")
->join("po.cityProvince", "pc")
->join("pc.province", "pp");

how to use (dynamic)null concept to this query

i wan to bind grid view with different kinds of conditions show here i'm use (dynamic)null concept for query declaration but at end of rest i can't getting field that associated with query.
here i put my code :
public void FillGrid(string GroupByText, string ColumnName, string SearchText)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = (dynamic)null;
switch (GroupByText)
{
case "Enquiry":
query = db.Enquiries.Where(i => i.enttype_id.Equals("1")).OrderByDescending(i => i.Created_date).Select(i => new
{
Ref_no = i.Ref_no,
Name = db.Parties.Where(p => p.Id.Equals(i.party_id)).Select(p => p.Name).SingleOrDefault(),
StatusName = db.Status.Where(s => s.Id.Equals(i.status_id)).Select(s => s.StatusName).SingleOrDefault(),
CategoryName = db.Categories.Where(c => c.Id.Equals(i.category_id)).Select(c => c.category_name).SingleOrDefault(),
IsUregent = i.IsUregent,
Created_date = i.Created_date
}).FilterForColumn(ColumnName,SearchText).ToList();
break;
case "Visit":
query = db.Enquiries.Where(i => i.enttype_id.Equals("2")).OrderByDescending(i => i.Created_date).Select(i => new
{
Ref_no = i.Ref_no,
Name = db.Parties.Where(p => p.Id.Equals(i.party_id)).Select(p => p.Name).SingleOrDefault(),
StatusName = db.Status.Where(s => s.Id.Equals(i.status_id)).Select(s => s.StatusName).SingleOrDefault(),
CategoryName = db.Categories.Where(c => c.Id.Equals(i.category_id)).Select(c => c.category_name).SingleOrDefault(),
IsUregent = i.IsUregent,
Created_date = i.Created_date
}).FilterForColumn(ColumnName,SearchText).ToList();
break;
default:
query = db.Enquiries.OrderByDescending(i => i.Created_date).Select(i => new
{
Ref_no = i.Ref_no,
Name = db.Parties.Where(p => p.Id.Equals(i.party_id)).Select(p => p.Name).SingleOrDefault(),
StatusName = db.Status.Where(s => s.Id.Equals(i.status_id)).Select(s => s.StatusName).SingleOrDefault(),
CategoryName = db.Categories.Where(c => c.Id.Equals(i.category_id)).Select(c => c.category_name).SingleOrDefault(),
IsUregent = i.IsUregent,
Created_date = i.Created_date
}).FilterForColumn(ColumnName, SearchText).ToList();
break;
}
int count = 0;
DataSet myDataSet = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Ref_no", typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("StatusName", typeof(int)));
dt.Columns.Add(new DataColumn("CategoryName", typeof(string)));
dt.Columns.Add(new DataColumn("IsUregent", typeof(bool)));
dt.Columns.Add(new DataColumn("Created_date", typeof(DateTime)));
foreach (var item in query)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["Ref_no"] = item.//not founding field that
}
}
}
}
what is the return type of .FilterForColumn(ColumnName,SearchText) ?
if it does just filtering, without changing the Data Type, i think you can use this:
var query = Enumerable.Repeat(new
{
Ref_no = string.Empty,
Name = string.Empty,
StatusName = default(int),
CategoryName = string.Empty,
IsUregent = default(bool),
Created_date = default(DateTime)
}, 0)
.ToList();
instead of this:
var query = (dynamic)null;
and probably this can solve your problem

IQueryable Sort not working

What is wrong with the code below with regards to sorting? The sort code is hit, but the sorting is never applied to the results.
var results = new List<Location>();
var county = context.boc_County.Where(x => x.Description.Contains(phrase.ToLower())).ToList();
results.AddRange(_mapper.MapCountyFromDb(county));
var town = context.boc_Town.Where(x => x.Description.Contains(phrase.ToLower())).ToList();
results.AddRange(_mapper.MapTownFromDb(town));
if (orderBy == "Identifier")
{
if (direction == "ASC")
results = results.OrderBy(x => x.Identifier);
else
results = results.OrderByDescending(x => x.Identifier);
}
if (orderBy == "Type")
{
if (direction == "ASC")
results = results.OrderBy(x => x.LocationType.ToString());
else
results = results.OrderByDescending(x => x.LocationType.ToString());
}
if (orderBy == "Description")
{
if (direction == "ASC")
results = results.OrderBy(x => x.Description);
else
results = results.OrderByDescending(x => x.Description);
}
var model = new LocationSearchResult()
{
Locations = query.Skip(page * pageSize).Take(pageSize),
TotalCount = query.Count()
};
return model;
OrderBy and OrderByDescending don't change the caller, they return new IQueryable/IEnuemrable instead. You have to assign it back to another (or the same) variable. Otherwise calling them has no sense.
Because you're using List<T> you have to add additional ToList() call to make it compile and work:
if (orderBy == "Identifier")
{
if (direction == "ASC")
results = results.OrderBy(x => x.Identifier).ToList();
else
results = results.OrderByDescending(x => x.Identifier).ToList();
}
// (...)
or you can use List<T>.Sort instead:
if (orderBy == "Identifier")
{
if (direction == "ASC")
results.Sort((x1, x2) => x1.Compare(x2));
else
results.Sort((x1, x2) => x2.Compare(x1));
}

Resources