Slow SQL queries - sql

I'm having some issues with my webpage.
It was running really slow, so I read on the Internet that it might be a bad usage of SQL. So I commented the SQL lines that were more 'complex' and it started running smoothly again.
My question is: 'Is there a way to make this SQL request "lighter"?
#companies = Company.where('tbl_companys.state = "enabled"')
#companies = #companies.includes(:benefit).where("tbl_benefits.end_date >= {Date.today}" )
#companies = #companies.includes(:benefit).where(tbl_benefits: { state: 'enabled' })
has_benef_gastro = false
has_benef_hote = false
has_benef_ent = false
until has_benef_gastro == true
#esta_gastro = (#companies.where('id_category = "2-gastronomia"').shuffle)[0]
#benefit_gastro = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', #esta_gastro.id_company, Date.today).first
if #benefit_gastro.nil? == false
has_benef_gastro = true
end
end
until has_benef_hote == true
#esta_hotelero = (#companies.where('id_category = "1-hoteleria"').shuffle)[0]
#benefit_hote = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', #esta_hotelero.id_company, Date.today).first
if #benefit_hote.nil? == false
has_benef_gastro = true
end
end
until has_benef_ent == true
#esta_ent = (#companies.where('id_category = "3-entretenimiento"').shuffle)[0]
#benefit_ent = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', #esta_ent.id_company, Date.today).first
if #benefit_ent.nil? == false
has_benef_gastro = true
end
end
Thanks for your help !

You're shuffling the #esta_gastro, #esta_hotelero, #esta_ent, and the #benefit_ variables every time, which doesn't really make sense. It requires multiple new DB queries every single time you do a loop.
If you want to find a random selection, just create your sets outside of the loop, shuffle once (outside of the loop), and then iterate over those sets until you meet your criteria.
For example:
#esta_gastro = #companies.where('id_category = "2-gastronomia"').shuffle
#benefits = Benefit.where('end_date >= ? AND state = "enabled"', Date.today)
#benefit_gastro = nil
i = 0
until !#benefit_gastro.blank?
#benefit_gastro = #benefits.where('id_company = ?', #esta_gastro[i].id_company).first
i += 1
end
EDIT
If the whole goal is to get the #benefit_gastro defined, then I don't even think you need a loop. You could just define the #esta_gastro set and then use it find all the Benefits that correspond. Because #esta_gastro is shuffled, your #benefit_gastro will be random:
#esta_gastro = #companies.where('id_category = "2-gastronomia"').shuffle
#benefit_gastro = Benefit.where('end_date >= ? AND state = "enabled"', Date.today).where('id_company = ?', #esta_gastro.map(&:id)).limit(1)

I ended up doing a plain SQL request so I didn't had to struggle with some rails issues.
Thanks anyway !

Related

Attempt to index a nil value (field 'SpawnPoint)'

I have created a fivem server for a friend of mine, and i'm currently having an issue with garages. Currently trying to index a nil value of 'spawnpoint'
for i=1, #v.Vehicles, 1 do
if GetDistanceBetweenCoords(coords, v.Vehicles[i].Spawner.x, v.Vehicles[i].Spawner.y, v.Vehicles[i].Spawner.z, true) < Config.MarkerSize.x then
isInMarker = true
currentStation = k
currentPart = 'VehicleSpawner'
currentPartNum = i
end
if GetDistanceBetweenCoords(coords, v.Vehicles[i].SpawnPoint.x, v.Vehicles[i].SpawnPoint.y, v.Vehicles[i].SpawnPoint.z, true) < Config.MarkerSize.x then
isInMarker = true
currentStation = k
currentPart = 'VehicleSpawnPoint'
currentPartNum = i
end
end
As brianolive already said, it seems like not every v.Vehicle has a SpawnPoint. You can fix this for instance by proofing for existence of SpawnPoint.
if v.Vehicles[i].SpawnPoint and (
GetDistanceBetweenCoords(
coords, v.Vehicles[i].SpawnPoint.x, v.Vehicles[i].SpawnPoint.y,
v.Vehicles[i].SpawnPoint.z, true
) < Config.MarkerSize.x
) then

VB replacing an object in a list

I have 2 lists approvedSuppliers and originalSupplierData
When approved Suppliers gets populated we clone the entry into the originalSupplierData . If they have modified a record but don't save we ask the user if they want to revert the changes . If they want to revert I am trying to replace the entry in approved suppliers with a clone of the original data. My current code for the revert is
Public Sub RevertChanges(SupplierID As Integer)
Dim orignalSupplier As Approved_Supplier = originalSupplierlist.Where(Function(x) x.ID = SupplierID).Single()
Dim modifiedSupplier As Approved_Supplier = ApprovedSuppliers.Where(Function(x) x.ID = SupplierID).Single()
modifiedSupplier = orignalSupplier.Clone
End Sub
The modifiedSupplier gets updated with the original values however the actual item in the list is not updated with the values.
If I modify one of the properties the list gets update. I am not sure what i am doing wrong can anyone point me in the right direction please?
Edit
The code for populating the list from the database is
supplierTableAdapter.Fill(supplierTable)
_approvedSuppliers = New List(Of Approved_Supplier)
originalSupplierlist = New List(Of Approved_Supplier)()
For Each row As ApprovedSuppliersDataset.ApprovedSupplierRow In supplierTable
supplier = New Approved_Supplier()
supplier.supplierID = row.PLSupplierAccountID
supplier.AccountNumber = row.SupplierAccountNumber
supplier.SupplierName = row.SupplierAccountName
supplier.SupplierAddress = CompileAddress(row)
supplier.Phone = CompilePhoneNumber(row)
If row.IsIDNull = False Then
supplier.ID = row.ID
If row.IsAdded_ByNull = False Then
supplier.AddedBy = row.Added_By
End If
If row.IsApprovedNull = False Then
supplier.Approved = row.Approved
End If
If row.IsAuditorNull = False Then
supplier.Auditor = row.Auditor
End If
If row.IsAudit_CommentsNull = False Then
supplier.AuditComments = row.Audit_Comments
End If
If row.IsAudit_DateNull = False Then
supplier.AuditDate = row.Audit_Date
End If
If row.IsDate_AddedNull = False Then
supplier.DateAdded = row.Date_Added
End If
If row.IsNotesNull = False Then
supplier.Notes = row.Notes
End If
If row.IsQuestionnaire_Return_DateNull = False Then
supplier.QuestionnaireReturnDate = row.Questionnaire_Return_Date
End If
If row.IsQuestionnaire_Sent_DateNull = False Then
supplier.QuestionnaireSentDate = row.Questionnaire_Sent_Date
End If
If row.IsQuestionnaire_StatusNull = False Then
supplier.QuestionnaireStatus = row.Questionnaire_Status
End If
If row.IsReplinNull = False Then
supplier.Replin = row.Replin
End If
If row.IsReview_CommentsNull = False Then
supplier.ReviewComment = row.Review_Comments
End If
If row.IsReview_DateNull = False Then
supplier.ReviewDate = row.Review_Date
End If
If row.IsReviewerNull = False Then
supplier.Reviewers = row.Reviewer
End If
If row.IsStakeholder_ContactNull = False Then
supplier.StakeholderContact = row.Stakeholder_Contact
End If
If row.IsStandardsNull = False Then
supplier.Standards = row.Standards
End If
If row.IsStandard_ExpiryNull = False Then
supplier.StandardExpiry = row.Standard_Expiry
End If
If row.IsStatusNull = False Then
supplier.Status = row.Status
End If
If row.IsSupplier_Expiry_DateNull = False Then
supplier.SupplierExpiryDate = row.Supplier_Expiry_Date
End If
If row.IsSupplier_ScopeNull = False Then
supplier.SupplierScope = row.Supplier_Scope
End If
If row.Is_T_CsNull = False Then
supplier.TC = row._T_Cs
End If
End If
supplier.ClearISDirty()
_approvedSuppliers.Add(supplier)
originalSupplierlist.Add(supplier.Clone)
Next
and for the clone we have
Public Function Clone() As Object Implements ICloneable.Clone
Dim cloned As New Approved_Supplier()
cloned.ID = Me.ID
cloned.DateAdded = Me.DateAdded
cloned.Status = Me.Status
cloned.AddedBy = Me.AddedBy
cloned.Approved = Me.Approved
cloned.AuditDate = Me.AuditDate
cloned.Auditor = Me.Auditor
cloned.AuditComments = Me.AuditComments
cloned.QuestionnaireStatus = Me.QuestionnaireStatus
cloned.QuestionnaireSentDate = Me.QuestionnaireSentDate
cloned.QuestionnaireReturnDate = Me.QuestionnaireReturnDate
cloned.ReviewDate = Me.ReviewDate
cloned.Reviewers = Me.Reviewers
cloned.ReviewComment = Me.ReviewComment
cloned.Standards = Me.Standards
cloned.StandardExpiry = Me.StandardExpiry
cloned.SupplierScope = Me.SupplierScope
cloned.Replin = Me.Replin
cloned.TC = Me.TC
cloned.Notes = Me.Notes
cloned.StakeholderContact = Me.StakeholderContact
cloned.SupplierExpiryDate = Me.SupplierExpiryDate
cloned.supplierID = Me.supplierID
cloned.AccountNumber = Me.AccountNumber
cloned.SupplierName = Me.SupplierName
cloned.SupplierAddress = Me.SupplierAddress
cloned.Phone = Me.Phone
cloned.Email = Me.Email
cloned.ClearISDirty()
Return cloned
End Function
You are not replacing in the list by affecting modifiedSupplier.
Try by getting the index of the modifiedSupplier and then replacing the item at the found index by your clone.
Public Sub RevertChanges(SupplierID As Integer)
Dim orignalSupplier As Approved_Supplier = originalSupplierlist.Where(Function(x) x.ID = SupplierID).Single()
Dim modifiedIndex As Integer = ApprovedSuppliers.FindIndex(Function(x) x.ID = SupplierID)
ApprovedSuppliers(modifiedIndex) = orignalSupplier.Clone()
End Sub

vb6 to vb.net for OracleInProcServer.OraDynaset

I am converting a project which is coded in old vb6 way. I am replacing the instances of OracleInProcServer.OraDynaset to Datatable for getting the data from database. But a form is generated in a dynamic way has the below code. i don't know how be there a alternate code for there in vb.net. Is there any way I can replace the below code without using dsAnswer As OracleInProcServer.OraDynaset. I don't know what is ! here also and how it is working.
Dim dsAnswer As OracleInProcServer.OraDynaset
Select Case dsAnswer!Shape.Value
Case 0 To 5
iShapes = iShapes + 1
'Load(f!shpCtrl(iShapes))
frmDynaForm.shpCtrl.Load(iShapes)
frmDynaForm.shpCtrl(iShapes).FillColor = System.Drawing.Color.FromArgb(DecodeColorDesc(Format$(dsAnswer!Color.Value)))
'frmDynaForm.shpCtrl(iShapes).Shape = dsAnswer!Shape.Value
frmDynaForm.shpCtrl(iShapes).Top = dsAnswer!Top.Value
frmDynaForm.shpCtrl(iShapes).Left = dsAnswer!Left.Value
frmDynaForm.shpCtrl(iShapes).Height = dsAnswer!Height.Value
frmDynaForm.shpCtrl(iShapes).Width = dsAnswer!Width.Value
frmDynaForm.shpCtrl(iShapes).BorderWidth = dsAnswer!BorderWidth.Value
frmDynaForm.shpCtrl(iShapes).Visible = True
Case -1
iLines = iLines + 1
'Load(f!lineCtrl(iLines))
frmDynaForm.lineCtrl.Load(iShapes)
frmDynaForm.lineCtrl(iLines).BorderColor = System.Drawing.Color.FromArgb(DecodeColorDesc(Format$(dsAnswer!Color.Value)))
frmDynaForm.lineCtrl(iLines).Y1 = dsAnswer!Top.Value
frmDynaForm.lineCtrl(iLines).X1 = dsAnswer!Left.Value
frmDynaForm.lineCtrl(iLines).Y2 = dsAnswer!Height.Value
frmDynaForm.lineCtrl(iLines).X2 = dsAnswer!Width.Value
frmDynaForm.lineCtrl(iLines).BorderWidth = dsAnswer!BorderWidth.Value
frmDynaForm.lineCtrl(iLines).Visible = True
End Select

Data Type mismatch in criteria expression when Table Adapter Update

I have already been searched solution and can't get the right solution yet.
ObjDRow = DataDataSet.Client.Rows.Find(strClientNo)
With ObjDRow
.ClientName = txtClientName.Text.Trim
.ClientAddr = txtAddr.Text.Trim
If txtRegOffice.Text = "" Then
.ClientRegOfficeAddr = txtAddr.Text.Trim
Else
.ClientRegOfficeAddr = txtRegOffice.Text.Trim
End If
.MailtoCorresAddr = RBtnCorresAddr.Checked
.MailtoRegOffice = RBtnRegOffice.Checked
.ClientHPhone = mskHandPhone.Text.Trim
.ClientPager = mskPagerNo.Text.Trim
.ClientTel = mskTelephone.Text.Trim
.ClientFaxNo = mskFax.Text.Trim
.ClientEmail = txtEmail.Text.Trim
.PrimaryPartner = txtPriPartner.Text.Trim
.SecondPartner = txtSecPartner.Text.Trim
.BroughtInBy = cboPreferredBy.Text.Trim
.PersonIncharge = cboPersonIncharge.Text.Trim
.GLAC = cboGLAcode.Text.Trim
.ContactPerson = txtContactPerson.Text.Trim
.AcraNo = txtAcraNo.Text.Trim
.Active = chkActive.Checked
If dtpfyear.Checked = True Then
.YearEnd = dtpfyear.Text
End If
.DeptNo = cboDeptNo.Text.Trim
.DateJoined = dtDateJoined.Value
If cboClientName.SelectedIndex = -1 Then
.Group = txtClientNo.Text
Else
.Group = cboClientName.SelectedValue
End If
.GroupStatus = RButtonMainYes.Checked
.MainGroup = RButtonSubYes.Checked
If IsDate(dtIncorporationDate.Text) Then
.DateOfIncorporation = dtIncorporationDate.Text
Else
.SetDateOfIncorporationNull()
End If
End With
ObjDRow.EndEdit()
ClientTableAdapter.Update(DataDataSet.Client)
Error is occurs when ClientTableAdapter Update.
This error occurs for some client only.
I already check datatype of database and table adapter's datatype and all datatype are same.
My input value datatype and table adapter's datatype are same.
This error occurs even I command all line of update code (.ClientName to last line) but this error still occurs.WTF
Most answers say this is a single quote problem but In my case, There is no single quote.
All data types are same and input values are the same with datatype.
** Updated**
This error still occurs even I do like=>
ObjDRow = DataDataSet.Client.Rows.Find(strClientNo)
ObjDRow.EndEdit()
ClientTableAdapter.Update(DataDataSet.Client)
There is nothing change just select and update.
But if I remove ObjDRow.EndEdit().All are fine. There is no error.

Telerik RadGrid Performance Too slow in Winforms

i am loading more than 50000 Records in Rad grid win forms. how to optimize and makes the grid to loads fast (instant)?. is there option to load pagewise filter in telerik rad grid columns filter?.
Me.cncFilesGridRad.MasterTemplate.AllowAddNewRow = False
Me.cncFilesGridRad.MasterTemplate.AllowDeleteRow = False
Me.cncFilesGridRad.MasterTemplate.ShowRowHeaderColumn = False
Me.cncFilesGridRad.MasterTemplate.ShowHeaderCellButtons = False
Me.cncFilesGridRad.UseScrollbarsInHierarchy = True
Me.cncFilesGridRad.ShowGroupPanel = False
Me.cncFilesGridRad.HorizontalScroll.Enabled = True
Me.cncFilesGridRad.MasterTemplate.EnableSorting = True
Me.cncFilesGridRad.MasterTemplate.EnableGrouping = False
Me.cncFilesGridRad.EnableFiltering = True
Me.cncFilesGridRad.ShowHeaderCellButtons = True
Me.cncFilesGridRad.MasterTemplate.EnableFiltering = True
Me.cncFilesGridRad.ShowFilteringRow = False
Me.cncFilesGridRad.MasterTemplate.ShowFilterCellOperatorText = False
Me.cncFilesGridRad.MasterTemplate.AllowCellContextMenu = False
Me.cncFilesGridRad.EnableFastScrolling = True
Me.cncFilesGridRad.BeginUpdate()
Me.cncFilesGridRad.DataSource = GlobalVariables.CNCFilesCollection
Me.cncFilesGridRad.AutoSizeRows = True
Me.cncFilesGridRad.TableElement.RowHeight = 60
Me.cncFilesGridRad.TableElement.FilterRowHeight = 40
Me.cncFilesGridRad.GridViewElement.PagingPanelElement.NumericButtonsCount = 25
Me.cncFilesGridRad.VirtualMode = True
AddTemplateToGrid()
Me.cncFilesGridRad.MasterTemplate.Templates(0).AllowAddNewRow = False
Me.cncFilesGridRad.MasterTemplate.Templates(0).AllowDeleteRow = False
Me.cncFilesGridRad.MasterTemplate.Templates(0).AllowEditRow = False
For Each col As GridViewDataColumn In Me.cncFilesGridRad.Columns
col.IsVisible = False
Next
For Each col As GridViewDataColumn In Me.cncFilesGridRad.MasterTemplate.Templates(0).Columns
col.IsVisible = False
Next
'child row column
column = Me.cncFilesGridRad.MasterTemplate.Templates(0).Columns("Name")
column.HeaderText = "Name"
column.IsVisible = True
column.ReadOnly = True
'parent rows
checkColumn = New GridViewCheckBoxColumn()
checkColumn.DataType = GetType(Integer)
checkColumn.HeaderText = "Select"
checkColumn.Name = "Select"
checkColumn.IsVisible = True
checkColumn.EditMode = EditMode.OnValueChange
checkColumn.Width = 83
Me.cncFilesGridRad.MasterTemplate.Columns.Add(checkColumn)
Me.cncFilesGridRad.Columns.Move(checkColumn.Index, 0)
commandColumn = New GridViewCommandColumn()
commandColumn.Name = "EditColumn"
commandColumn.UseDefaultText = True
commandColumn.DefaultText = "Edit"
commandColumn.FieldName = "Edit"
commandColumn.Width = 50
commandColumn.TextAlignment = ContentAlignment.MiddleCenter
Me.cncFilesGridRad.MasterTemplate.Columns.Add(commandColumn)
Me.cncFilesGridRad.Columns.Move(commandColumn.Index, 1)
descriptor.PropertyName = "Name"
Me.cncFilesGridRad.Columns("Name").SortOrder = RadSortOrder.Ascending
Me.cncFilesGridRad.MasterTemplate.SortDescriptors.Add(descriptor)
Me.cncFilesGridRad.MasterTemplate.Templates(0).AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill
Me.cncFilesGridRad.CurrentRow = Nothing
filterDescriptor.PropertyName = "Name"
filterDescriptor.[Operator] = FilterOperator.StartsWith
filterDescriptor.IsFilterEditor = True
Me.cncFilesGridRad.Columns("Name").FilterDescriptor = filterDescriptor
how to improve the rad grid performance while loading more Records?
Load the records as the page moves, i.e. one page can have 100 records, when we click second page, it will have another 100 records.. that will improve performance.
What you should be looking at is the Pagination capability. And Telerik's GridView control supports this feature naturally.
The data layer of RadGridView now supports pagination of data natively. You can still bind RadGridView to the same data providers as before with the addition of the paging option. There is a number of features, which will allow you to easily configure and manage the paging of the data.
Please refer to the following links for more details on how paging works.
http://docs.telerik.com/devtools/winforms/gridview/paging/overview#paging-overview
http://docs.telerik.com/devtools/winforms/gridview/paging/paging-panel
http://www.telerik.com/videos/winforms/radgridview-for-winforms-webinar