stellarwp / db

A WPDB wrapper and query builder library.
GNU General Public License v2.0
64 stars 4 forks source link

Add Generator API methods #17

Closed lucatume closed 8 months ago

lucatume commented 8 months ago

This PR adds the DB::generate_results and DB::generate_col methods to allow unbounded queries to run, under the hood, in a bounded manner.

The query results will be fetched in batches that will be returned by a Generator, reducing database and memory load where no alternative is possible.

Example, given a db with 100 posts, one could run the following query:

SELECT * FROM wp_posts

The following code will iterate over all posts in the database, fetching them in batches of 100 each:

$all_posts = DB::generate_results( 'SELECT * FROM wp_posts', OBJECT, 100 );

foreach( $all_posts as $post ) {
    // Do something with the post ...
}

The same can be done for columns:

$all_ids = DB::generate_col( 'SELECT ID FROM wp_posts', 0, 100 );

foreach( $all_ids as $id ) {
    // Do something with the post ID ...
}