GithubHelp home page GithubHelp logo

nticompass / codeigniter-subqueries Goto Github PK

View Code? Open in Web Editor NEW
56.0 11.0 19.0 41 KB

An active record subquery library for CodeIgniter. Also contains useful db helper functions.

Home Page: https://generic.computers.pictures

License: MIT License

PHP 100.00%

codeigniter-subqueries's Introduction

Subqueries. For CodeIgniter.

By Eric Siegel

Information

This is a subquery library for CodeIgniter’s (1.7.x - 2.0.2) active record class. It lets you use the active record methods to create subqueries in your SQL.

It supports SELECT, JOIN, FROM, WHERE, etc. It also supports UNION ALL!

(Yes, you can have subqueries inside subqueries inside UNIONs and UNIONs inside subqueries.)

Instructions

Put Subquery.php into /application/libraries, then load it in your code using $this->load->library('subquery');. I guess you can add 'subquery' to $autoload['libraries'] (in /application/config/autoload.php), if you want.

CodeIgniter 2.1.x

This library doesn't work with CodeIgniter 2.1.x out of the box. It requires modifications to a file in /system to make it work.

You need to edit /system/database/DB_active_rec.php and modify the signature of _compile_select (should be line 1673). In the older version(s) of CodeIgniter, this function was not protected, so if you remove the protected keyword from the function, my library will work.

(There's probably a reason this function is protected.)

In the develop version of CodeIgniter (which works with this library just fine, by the way), there is a public function that you can use. You can "steal" the get_compiled_select function from the /system/database/DB_query_builder.php file (line 1283).

/**
 * Get SELECT query string
 *
 * Compiles a SELECT query string and returns the sql.
 *
 * @param    string    the table name to select from (optional)
 * @param    bool    TRUE: resets QB values; FALSE: leave QB vaules alone
 * @return    string
 */
public function get_compiled_select($table = '', $reset = TRUE)
{
    if ($table !== '')
    {
        $this->_track_aliases($table);
        $this->from($table);
    }

    $select = $this->_compile_select();

    if ($reset === TRUE)
    {
        $this->_reset_select();
    }

    return $select;
}

Put this function inside /system/database/DB_active_rec.php.

My library will check for the existance of either a _compile_select or get_compiled_select method. If none of these methods exist, the library will fail to load.

Methods

  • start_subquery: Creates a new database object to be used for the subquery
    • Parameters:
      • $statement: SQL statement to put subquery into ('select', 'from', 'join', 'where', 'where_in', etc.)
      • $join_type: JOIN type (only for join statements)
      • $join_on: JOIN ON clause (only for join statements)
    • Returns: CodeIgniter db object to call active record methods on
  • end_subquery: Closes the database object and writes the subquery
    • Parameters:
      • $alias: Alias to use in query, or field to use for WHERE
      • $operator: Operator to use for WHERE ('=', '!=', '<', etc.) / WHERE IN (TRUE for WHERE IN, FALSE for WHERE NOT IN)
        • If it's a SELECT, this parameter will turn it into COALESCE((SELECT ...), $operator) AS $alias
      • $database: Database object to use when dbStack is empty (optional)
    • Returns: Nothing
  • start_union: Creates a new database object to be used for unions
    • Parameters: None
    • Returns: CodeIgniter db object to call active record methods on
  • end_union: Combines all opened db objects into a UNION ALL query
    • Parameters:
      • $database: Database object to use when dbStack is empty (optional)
    • Returns: Nothing

Examples

The most basic use of this library is to have a subquery in a SELECT statement. This is very simple. Let's say you want to get this query:

SELECT field1, (SELECT field2 FROM table2 WHERE table1.field3 = table2.field3) as field2X
FROM table1 WHERE field4 = 'test'

You would do this in your code:

$this->db->select('field1');
$sub = $this->subquery->start_subquery('select');
$sub->select('field2')->from('table2');
$sub->where('table1.field3 = table2.field3');
$this->subquery->end_subquery('field2X');
$this->db->from('table1')
$this->db->where('field4', 'test');

If it's possible that your subquery might return a NULL row, you can set a default value. That's done like this:

$this->db->select('field1');
$sub = $this->subquery->start_subquery('select');
$sub->select('field2')->from('table2');
$sub->where('table1.field3 = table2.field3');
// Note the second parameter here
$this->subquery->end_subquery('field2X', 'field5');
$this->db->from('table1')
$this->db->where('field4', 'test');

This will generate:

SELECT field1, COALESCE((SELECT field2 FROM table2 WHERE table1.field3 = table2.field3), field5) as field2X
FROM table1 WHERE field4 = 'test'

By passing different values to start_subquery, you can make this library do anyting!

Here's a WHERE IN example:

$this->db->select('field1, field2')->from('table1');
$sub = $this->subquery->start_subquery('where_in');
$sub->select('field3')->from('table2')->where('field2', 'test');
$this->subquery->end_subquery('field4', FALSE);

This will generate:

SELECT field1, field2 FROM table1
WHERE field4 NOT IN (SELECT field3 FROM table2 WHERE field2 = 'test')

UNION queries have a slightly different syntax. For subqueries, every start_subquery needs an end_subquery, but with UNION you only need one end_union - no matter how many start_unions you have.

$sub1 = $this->subquery->start_union();
$sub1->select('field1')->from('table1');
$sub2 = $this->subquery->start_union();
$sub2->select('field2')->from('table2');
$sub3 = $this->subquery->start_union();
$sub3->select('field3')->from('table3');
$this->subquery->end_union();
$this->db->order_by('field1', 'DESC');

codeigniter-subqueries's People

Contributors

clemblanco avatar danfinnie avatar nticompass avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

codeigniter-subqueries's Issues

Indicate return types

The current version

/**
 * start_union - Creates a new database object to be used for unions
 *
 * @return A new database object to use for a union query
 */
function start_union(){
	$this->unions++;
	return $this->start_subquery('');
}

Causes
image
Because the A from "A new database..." is the first argument here.

Instead the first word should be the returned type:

/**
 * @return CI_Loader A new database object to use for a union query
 */

Problem using in union

$sub1 = $this->subquery->start_union();
$sub1->select('fm.challan_id as id,lc.challan_no as challan_no')
        ->from('freightmemo fm')->join('lorrychallan lc','fm.challan_id=lc.id')
        ->where('fm.id',$this->input->post('bindto'));
$sub2 = $this->subquery->start_union();
$sub2->select('ch.id as id,ch.challan_no as challan_no')
        ->from('lorrychallan ch')->join('freightmemo fm','fm.challan_id=ch.id','LEFT OUTER')
        ->where('fm.challan_id IS NULL',NULL,FALSE);
$this->subquery->end_union();

Now how can i get the result in return just like other query

$this->db->get()->result_array();

this is not working with above query

Fatal error in CodeIgnitor 1.7.2

Fatal error: Call to undefined method CI_DB_mysqli_driver::set_dbprefix() in /data/www/paomi.com/user/libraries/Subquery.php on line 57

I found that set_dbprefix is really not in the source of CI 1.7.2.

How to use $this->subquery->defaultDB() ?

Pardon for my beginner in object oriented PHP Codeigniter. I am confused about using $this->subquery->defaultDB() ?

$db2 = $this->load->database('db2', TRUE);

$this->load->library('Subquery');
$this->subquery->defaultDB($db2)
$sub = $this->subquery->start_subquery('select');
$sub->select('number')->from('numbers')->where('numberID', 2);
$this->subquery->end_subquery('number');

$query = $db2->get('mytable');

but the subquery still use the default database not db2. Thank you.

Error when use 2 or more group_by inside subqueries

show error queries when contain 2 or more group_by inside subqueries. example
$this->db->select('field1');
$sub = $this->subquery->start_subquery('from');
$sub->select('field1');
$sub->from($table_1);
$sub->where('field2', $con1)
->where('DATE(field3) >=', $con2)
->where('DATE(field3) <=', $tgcon3_to);
$sub->group_by('field4')
->group_by('field5');
$this->subquery->end_subquery('test');
$total = $this->db->count_all_results();

Licence

Hey, I could ask if you could licence this as MIT?

CI 2.1 issue: get_compiled_select()

PHP Fatal error: Call to undefined method CI_DB_mysql_driver::get_compiled_select() in /var/www/ids/application/libraries/Subquery.php on line 88

Question in Union Example

The Union example is shown like this

$sub1 = $this->subquery->start_union();
$sub1->select('field1')->from('table1');
$sub2 = $this->subquery->start_union();
$sub2->select('field2')->from('table2');
$sub3 = $this->subquery->start_union();
$sub3->select('field3')->from('table3');
$this->subquery->end_union();
$this->db->order_by('field1', 'DESC');

But, isn't subquery a method of active record, like this?

$sub1 = $this->db->subquery->start_union();
$sub1->select('field1')->from('table1');
$sub2 = $this->db->subquery->start_union();
$sub2->select('field2')->from('table2');
$sub3 = $this->db->subquery->start_union();
$sub3->select('field3')->from('table3');
$this->subquery->end_union();
$this->db->order_by('field1', 'DESC');

where doesn't support "table.name"

$this->subquery->start_subquery('where');
$this->subquery->end_subquery('table.field');

This doesn't work. Please update end_subquery to parse out table names.

Error running the library within CI 2.1.3 (stable)

Hi try to load the library in my project and get this error (just set in autoload.php nothing else):

** Subquery library cannot run. Missing get_compiled_select. Please use the dev version of CodeIgniter.

I change to develop and get 505 Internal error, any help?

0 becomes null

I'm doing some left joins involving "count", and when results are displayed zeros become null.

where (not) exists

Hello. Can I use your library for construction "where exists(subquery)"?

CI 2.0.3 compile_select problem

Hello,

After i upgraded to latest CI i get this problem.

PHP Fatal error: Call to protected method CI_DB_active_record::_compile_select() from context 'Subquery' in /var/www/website/application/libraries/Subquery.php on line 84

Greetings
ws

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.