Skip to content

Commit c66e398

Browse files
author
Samuel Akopyan
committed
Chunk implementation for AR
1 parent 60fcdd0 commit c66e398

File tree

12 files changed

+76
-35
lines changed

12 files changed

+76
-35
lines changed

demos/simple-blog/protected/controllers/PostsController.php

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -135,21 +135,27 @@ public function indexAction($msg = '')
135135
if (!$this->_view->currentPage) {
136136
$this->_view->actionMessage = CWidget::create('CMessage', array('error', 'Wrong parameter passed! Please try again later.', array('button' => true)));
137137
} else {
138-
/* $this->_view->posts = Posts::model()->findAll(array(
139-
'limit' => (($this->_view->currentPage - 1) * $this->_view->pageSize) . ', ' . $this->_view->pageSize,
140-
'order' => 'post_datetime DESC',
141-
));*/
138+
$conditions = array(
139+
'limit' => (($this->_view->currentPage - 1) * $this->_view->pageSize) . ', ' . $this->_view->pageSize,
140+
'order' => 'post_datetime DESC',
141+
);
142142

143-
$posts = null;
144-
Posts::model()->chunk(2, function ($records) use(&$posts){
145-
foreach ($records as $key => $record) {
146-
$posts[] = $record;
147-
}
148-
//CDebug::d($record);
149-
});
150-
//CDebug::dd($posts);
151-
152-
$this->_view->posts = $posts;
143+
if (!true) {
144+
$this->_view->posts = Posts::model()->findAll(array(
145+
'limit' => (($this->_view->currentPage - 1) * $this->_view->pageSize) . ', ' . $this->_view->pageSize,
146+
'order' => 'post_datetime DESC',
147+
));
148+
}else{
149+
$posts = null;
150+
Posts::model()->chunk($conditions, [], -2, function ($records) use(&$posts){
151+
foreach ($records as $key => $record) {
152+
$posts[] = $record;
153+
}
154+
//CDebug::d($record);
155+
});
156+
//CDebug::dd($posts);
157+
$this->_view->posts = $posts;
158+
}
153159
}
154160

155161
$this->_view->render('posts/index');

framework/db/CActiveRecord.php

Lines changed: 45 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -581,24 +581,46 @@ private function _createObjectFromTable()
581581

582582
/**
583583
* Split AR result into parts (chunks)
584+
* Ex.: chunk(array('condition'=>'post_id = :postID AND is_active = :isActive', 'select'=>'', 'group|groupBy'=>'', 'order|orderBy'=>'id DESC', 'limit'=>'0, 10'), array(':postID'=>10, ':isActive'=>1));
585+
* Ex.: chunk(CConfig::get('db.prefix').$this->_tableTranslation.'.news_text LIKE :keywords', array(':keywords'=>'%'.$keywords.'%'));
586+
*
587+
* @param array $conditions
588+
* @param array $params
584589
* @param int $size
585-
* @param null $callback
590+
* @param callable $callback
591+
*
592+
* @return null
586593
*/
587-
public function chunk(int $size, callable $callback = null)
594+
public function chunk(array $conditions = [], array $params = [], int $size = 0, callable $callback = null)
588595
{
589596
if (is_int($size) && $size > 0 && !empty($callback)) {
590-
$from = 0;
591-
// echo('limit'."$from, $size");
592-
while ($result = $this->findAll(array('limit'=>"$from, $size"))){
597+
if (!isset($conditions['limit'])) {
598+
$from = 0;
599+
$limitSize = $size;
600+
} else {
601+
$limitParts = explode(',', $conditions['limit']);
602+
$from = isset($limitParts[0]) ? $limitParts[0] : 0;
603+
$limitSize = isset($limitParts[1]) ? $limitParts[1] : $size;
604+
if ($size >= $limitSize) {
605+
$size = $limitSize;
606+
}
607+
}
608+
609+
$conditions['limit'] = "$from, $size";
610+
$count = 0;
611+
612+
while ($result = $this->findAll($conditions, $params)){
593613
$callback($result);
594614
$from += $size;
595-
// echo('limit'."$from, $size");
596-
// if ($from > 10){
597-
// return;
598-
// }
615+
$conditions['limit'] = "$from, $size";
616+
617+
$count += $size;
618+
if ($count >= $limitSize) {
619+
break;
620+
}
599621
}
600622
} else {
601-
CDebug::AddMessage('errors', 'chunk', A::t('core', 'Wrong params for chunk: {size} or callback method is callable.', array('{size}' => $size)));
623+
CDebug::AddMessage('errors', 'chunk', A::t('core', 'Wrong params for chunk size: {size} or callback method is callable.', array('{size}' => $size)));
602624
}
603625

604626
return null;
@@ -713,16 +735,19 @@ public function findByPk($pk, $conditions = '', $params = array(), $cacheId = fa
713735
return null;
714736
}
715737
}
716-
717-
/**
718-
* This method queries your database to find related objects by attributes
719-
* Ex.: findByAttributes($attributes, 'postID = :postID AND isActive = :isActive', array(':postID'=>10, ':isActive'=>1));
720-
* Ex.: findByAttributes($attributes, array('condition'=>'postID = :postID AND isActive = :isActive', 'order|orderBy'=>'id DESC', 'limit'=>'0, 10'), 'params'=>array(':postID'=>10, ':isActive'=>1));
721-
* Ex.: $attributes = array('first_name'=>$firstName, 'last_name'=>$lastName);
722-
* @param array $attributes
723-
* @param mixed $conditions
724-
* @param array $params
725-
*/
738+
739+
/**
740+
* This method queries your database to find related objects by attributes
741+
* Ex.: findByAttributes($attributes, 'postID = :postID AND isActive = :isActive', array(':postID'=>10, ':isActive'=>1));
742+
* Ex.: findByAttributes($attributes, array('condition'=>'postID = :postID AND isActive = :isActive', 'order|orderBy'=>'id DESC', 'limit'=>'0, 10'), 'params'=>array(':postID'=>10, ':isActive'=>1));
743+
* Ex.: $attributes = array('first_name'=>$firstName, 'last_name'=>$lastName);
744+
*
745+
* @param array $attributes
746+
* @param mixed $conditions
747+
* @param array $params
748+
*
749+
* @return mixed
750+
*/
726751
public function findByAttributes($attributes, $conditions = '', $params = array())
727752
{
728753
if (is_array($conditions)) {

framework/messages/ar/core.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,4 +186,5 @@
186186
'You cannot delete the last remaining record in table {table}!' => 'لا يمكنك حذف السجل الأخير المتبقي في الجدول {table}!',
187187
'Warnings' => 'تحذيرات',
188188
'Wrong column name: {index} in table {table}' => 'اسم عمود غير صحيح: "{index}" في الجدول "{table}" - لا يمكن الوصول إلى خاصية غير موجودة لكائن AR',
189+
'Wrong params for chunk size: {size} or callback method is callable.' => 'Wrong params for chunk size: {size} or callback method is callable.',
189190
);

framework/messages/de/core.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,4 +184,5 @@
184184
'You cannot delete the last remaining record in table {table}!' => 'Sie können die letzten verbliebenen Satz in der Tabelle {table} nicht löschen!',
185185
'Warnings' => 'Warnungen',
186186
'Wrong column name: {index} in table {table}' => 'Falsche Spalte name: {index} in Tabelle {table}',
187+
'Wrong params for chunk size: {size} or callback method is callable.' => 'Wrong params for chunk size: {size} or callback method is callable.',
187188
);

framework/messages/en/core.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,4 +186,5 @@
186186
'You cannot delete the last remaining record in table {table}!' => 'You cannot delete the last remaining record in table {table}!',
187187
'Warnings' => 'Warnings',
188188
'Wrong column name: {index} in table {table}' => 'Wrong column name: "{index}" in table "{table}" - can\'t access non existent property of AR object',
189+
'Wrong params for chunk size: {size} or callback method is callable.' => 'Wrong params for chunk size: {size} or callback method is callable.',
189190
);

framework/messages/es/core.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,4 +186,5 @@
186186
'You cannot delete the last remaining record in table {table}!' => 'No se puede eliminar el único registro existente en la tabla {table}.',
187187
'Warnings' => 'Advertencias',
188188
'Wrong column name: {index} in table {table}' => 'Nombre de columna incorrecta: {index} en la tabla {table}.',
189+
'Wrong params for chunk size: {size} or callback method is callable.' => 'Wrong params for chunk size: {size} or callback method is callable.',
189190
);

framework/messages/fr/core.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,4 +186,5 @@
186186
'You cannot delete the last remaining record in table {table}!' => 'Vous ne pouvez pas supprimer le dernier enregistrement restante dans le tableau {table}!',
187187
'Warnings' => 'Avertissements',
188188
'Wrong column name: {index} in table {table}' => 'Nom de colonne incorrect: {index} dans la table {table}',
189+
'Wrong params for chunk size: {size} or callback method is callable.' => 'Wrong params for chunk size: {size} or callback method is callable.',
189190
);

framework/messages/he/core.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,4 +186,5 @@
186186
'You cannot delete the last remaining record in table {table}!' => 'לא ניתן למחוק את הרשומה האחרונה שנותרה בטבלה {table}!',
187187
'Warnings' => 'אזהרות',
188188
'Wrong column name: {index} in table {table}' => 'שם עמוד שגוי: {index} בטבלה {table}',
189+
'Wrong params for chunk size: {size} or callback method is callable.' => 'Wrong params for chunk size: {size} or callback method is callable.',
189190
);

framework/messages/it/core.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,4 +186,5 @@
186186
'You cannot delete the last remaining record in table {table}!' => 'Non è possibile eliminare l\'ultimo record rimasto nella tabella {table}!',
187187
'Warnings' => 'Avvertenze',
188188
'Wrong column name: {index} in table {table}' => 'Colonna sbagliato nome: {index} nella tabella {table}',
189+
'Wrong params for chunk size: {size} or callback method is callable.' => 'Wrong params for chunk size: {size} or callback method is callable.',
189190
);

framework/messages/nl/core.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,9 +181,10 @@
181181
'Unable to find the model class "{model}".' => 'Kan het model de klas "{model}".',
182182
'Unknown' => 'Onbekend',
183183
'Unknown operator "{operator}".' => 'Onbekende operator "{operator}".',
184-
'Uploaded {file} is not a valid image! Please check carefully the file type.' => 'Ge�ploade file <strong>{file}</strong> is geen geldige afbeelding! Gelieve zorgvuldig te controleren het bestandstype.',
184+
'Uploaded {file} is not a valid image! Please check carefully the file type.' => 'Geploade file <strong>{file}</strong> is geen geldige afbeelding! Gelieve zorgvuldig te controleren het bestandstype.',
185185
'version' => 'versie',
186186
'You cannot delete the last remaining record in table {table}!' => 'U kunt de laatst overgebleven record niet verwijderen in tabel {table}!',
187187
'Warnings' => 'Waarschuwingen',
188188
'Wrong column name: {index} in table {table}' => 'naam verkeerd column: {index} in tabel {table}',
189+
'Wrong params for chunk size: {size} or callback method is callable.' => 'Wrong params for chunk size: {size} or callback method is callable.',
189190
);

0 commit comments

Comments
 (0)