Showing 1 changed files with 52 additions and 4 deletions
+52 -4
lib/DBI/Custom.pm
... ...
@@ -170,14 +170,23 @@ sub do{
170 170
 # Create query
171 171
 sub create_query {
172 172
     my ($self, $template) = @_;
173
+    my $class = ref $self;
173 174
     
174 175
     # Create query from SQL template
175 176
     my $sql_template = $self->sql_template;
176
-    my $query = eval{$sql_template->create_query($template)};
177
-    croak($@) if $@;
178 177
     
179
-    # Create Query object;
180
-    $query = DBI::Custom::Query->new($query);
178
+    # Try to get cached query
179
+    my $query = $class->_query_caches->{$template};
180
+    
181
+    # Create query
182
+    unless ($query) {
183
+        $query = eval{$sql_template->create_query($template)};
184
+        croak($@) if $@;
185
+        
186
+        $query = DBI::Custom::Query->new($query);
187
+        
188
+        $class->_add_query_cache($template, $query);
189
+    }
181 190
     
182 191
     # Connect if not
183 192
     $self->connect unless $self->connected;
... ...
@@ -556,6 +565,34 @@ sub delete_all {
556 565
     return $self->delete($table, {}, $edit_query_cb, {allow_delete_all => 1});
557 566
 }
558 567
 
568
+sub _query_caches     : ClassAttr { type => 'hash',
569
+                                    auto_build => sub {shift->_query_caches({}) } }
570
+                                    
571
+sub _query_cache_keys : ClassAttr { type => 'array',
572
+                                    auto_build => sub {shift->_query_cache_keys([])} }
573
+                                    
574
+sub query_cache_max   : ClassAttr { auto_build => sub {shift->query_cache_max(50)} }
575
+
576
+# Add query cahce
577
+sub _add_query_cache {
578
+    my ($class, $template, $query) = @_;
579
+    my $query_cache_keys = $class->_query_cache_keys;
580
+    my $query_caches     = $class->_query_caches;
581
+    
582
+    return $class if $query_caches->{$template};
583
+    
584
+    $query_caches->{$template} = $query;
585
+    push @$query_cache_keys, $template;
586
+    
587
+    my $overflow = @$query_cache_keys - $class->query_cache_max;
588
+    
589
+    for (my $i = 0; $i < $overflow; $i++) {
590
+        my $template = shift @$query_cache_keys;
591
+        delete $query_caches->{$template};
592
+    }
593
+    
594
+    return $class;
595
+}
559 596
 
560 597
 Object::Simple->build_class;
561 598
 
... ...
@@ -857,6 +894,17 @@ If tranzation is died, rollback is execute.
857 894
     
858 895
 This method is same as DBI last_insert_id;
859 896
 
897
+=head1 Class Accessors
898
+
899
+=head2 query_cache_max
900
+
901
+    # Max query cache count
902
+    $class           = $class->query_cache_max($query_cache_max);
903
+    $query_cache_max = $class->query_cache_max;
904
+    
905
+    # Sample
906
+    DBI::Custom->query_cache_max(50);
907
+
860 908
 =head1 CAUTION
861 909
 
862 910
 DBI::Custom have DIB object internal.