diff --git a/views_natural_sort.module b/views_natural_sort.module index 8c27b82..7b5ebcf 100644 --- a/views_natural_sort.module +++ b/views_natural_sort.module @@ -91,19 +91,42 @@ function views_natural_sort_nodeapi(&$node, $op) { * A drupal node object containing at least a nid and title. */ function _views_natural_sort_store_node($node) { + + //TODO: consider using ctools + $cache = &_views_natural_sort_get_cache(); + $record = new stdClass(); $record->nid = $node->nid; $record->field = 'title'; $record->content = views_natural_sort_encode($node->title); + + if (empty($cache)) { + $cache = array(); + $result = db_query("SELECT nid, field FROM {views_natural_sort}"); + while ($row = db_fetch_object($result)) { + if (empty($cache[$row->field])) { + $cache[$row->field] = array(); + } + $cache[$row->field][] = $row->nid; + } + } // Try to update. On fail, try inserting. - $return = drupal_write_record('views_natural_sort', $record, array('nid', 'field')); - if (!db_affected_rows()) { + if (in_array($record->nid, $cache[$record->field])) { + $return = drupal_write_record('views_natural_sort', $record, array('nid', 'field')); + } + else { $return = drupal_write_record('views_natural_sort', $record); + $cache[$record->field][] = $record->nid; } - + dpm($return); return $return; } +function _views_natural_sort_get_cache() { + static $cache; + return $cache; +} + /** * _views_natural_sort_remove_node * @@ -111,7 +134,14 @@ function _views_natural_sort_store_node($node) { * A drupal node object containing at least a nid. */ function _views_natural_sort_remove_node($node) { + //TODO: consider using ctools + $cache = &_views_natural_sort_get_cache(); + $cache_key = array_search($node->nid, $cache['title']); + db_query('DELETE FROM {views_natural_sort} WHERE nid = %d', $node->nid); + if ($cache_key !== FALSE) { + unset($cache['title'][$cache_key]); + } } /**