GithubHelp home page GithubHelp logo

pixie's Introduction

This project is Not Actively Maintained but most of the features are fully working and there are no major security issues, I'm just not giving it much time.

Pixie Query Builder

Build Status Total Downloads Daily Downloads

A lightweight, expressive, framework agnostic query builder for PHP it can also be referred as a Database Abstraction Layer. Pixie supports MySQL, SQLite and PostgreSQL and it takes care of query sanitization, table prefixing and many other things with a unified API.

It has some advanced features like:

  • Query Events
  • Nested Criteria
  • Sub Queries
  • Nested Queries
  • Multiple Database Connections.

The syntax is quite similar to Laravel's query builder.

Example

// Make sure you have Composer's autoload file included
require 'vendor/autoload.php';

// Create a connection, once only.
$config = [
            'driver'    => 'mysql', // Db driver
            'host'      => 'localhost',
            'database'  => 'your-database',
            'username'  => 'root',
            'password'  => 'your-password',
            'charset'   => 'utf8', // Optional
            'collation' => 'utf8_unicode_ci', // Optional
            'prefix'    => 'cb_', // Table prefix, optional
            'options'   => [ // PDO constructor options, optional
                PDO::ATTR_TIMEOUT => 5,
                PDO::ATTR_EMULATE_PREPARES => false,
            ],
        ];

new \Pixie\Connection('mysql', $config, 'QB');

Simple Query:

The query below returns the row where id = 3, null if no rows.

$row = QB::table('my_table')->find(3);

Full Queries:

$query = QB::table('my_table')->where('name', '=', 'Sana');

// Get result
$query->get();

Query Events:

After the code below, every time a select query occurs on users table, it will add this where criteria, so banned users don't get access.

QB::registerEvent('before-select', 'users', function($qb)
{
    $qb->where('status', '!=', 'banned');
});

There are many advanced options which are documented below. Sold? Let's install.

Installation

Pixie uses Composer to make things easy.

Learn to use composer and add this to require section (in your composer.json):

"usmanhalalit/pixie": "2.*@dev"

And run:

composer update

Library on Packagist.

Full Usage API

Table of Contents


Connection

Pixie supports three database drivers, MySQL, SQLite and PostgreSQL. You can specify the driver during connection and the associated configuration when creating a new connection. You can also create multiple connections, but you can use alias for only one connection at a time.;

// Make sure you have Composer's autoload file included
require 'vendor/autoload.php';

$config = array(
            'driver'    => 'mysql', // Db driver
            'host'      => 'localhost',
            'database'  => 'your-database',
            'username'  => 'root',
            'password'  => 'your-password',
            'charset'   => 'utf8', // Optional
            'collation' => 'utf8_unicode_ci', // Optional
            'prefix'    => 'cb_', // Table prefix, optional
        );

new \Pixie\Connection('mysql', $config, 'QB');

// Run query
$query = QB::table('my_table')->where('name', '=', 'Sana');

Alias

When you create a connection:

new \Pixie\Connection('mysql', $config, 'MyAlias');

MyAlias is the name for the class alias you want to use (like MyAlias::table(...)), you can use whatever name (with Namespace also, MyNamespace\\MyClass) you like or you may skip it if you don't need an alias. Alias gives you the ability to easily access the QueryBuilder class across your application.

When not using an alias you can instantiate the QueryBuilder handler separately, helpful for Dependency Injection and Testing.

$connection = new \Pixie\Connection('mysql', $config);
$qb = new \Pixie\QueryBuilder\QueryBuilderHandler($connection);

$query = $qb->table('my_table')->where('name', '=', 'Sana');

var_dump($query->get());

$connection here is optional, if not given it will always associate itself to the first connection, but it can be useful when you have multiple database connections.

SQLite and PostgreSQL Config Sample

new \Pixie\Connection('sqlite', array(
                'driver'   => 'sqlite',
			    'database' => 'your-file.sqlite',
			    'prefix'   => 'cb_',
		    ), 'QB');
new \Pixie\Connection('pgsql', array(
                    'driver'   => 'pgsql',
                    'host'     => 'localhost',
                    'database' => 'your-database',
                    'username' => 'postgres',
                    'password' => 'your-password',
                    'charset'  => 'utf8',
                    'prefix'   => 'cb_',
                    'schema'   => 'public',
                ), 'QB');

Query

You must use table() method before every query, except raw query(). To select from multiple tables just pass an array.

QB::table(array('mytable1', 'mytable2'));

Get Easily

The query below returns the (first) row where id = 3, null if no rows.

$row = QB::table('my_table')->find(3);

Access your row like, echo $row->name. If your field name is not id then pass the field name as second parameter QB::table('my_table')->find(3, 'person_id');.

The query below returns the all rows where name = 'Sana', null if no rows.

$result = QB::table('my_table')->findAll('name', 'Sana');

Select

$query = QB::table('my_table')->select('*');

Multiple Selects

->select(array('mytable.myfield1', 'mytable.myfield2', 'another_table.myfield3'));

Using select method multiple times select('a')->select('b') will also select a and b. Can be useful if you want to do conditional selects (within a PHP if).

Select Distinct

->selectDistinct(array('mytable.myfield1', 'mytable.myfield2'));

Get All

Return an array.

$query = QB::table('my_table')->where('name', '=', 'Sana');
$result = $query->get();

You can loop through it like:

foreach ($result as $row) {
    echo $row->name;
}

Get First Row

$query = QB::table('my_table')->where('name', '=', 'Sana');
$row = $query->first();

Returns the first row, or null if there is no record. Using this method you can also make sure if a record exists. Access these like echo $row->name.

Get Rows Count

$query = QB::table('my_table')->where('name', '=', 'Sana');
$query->count();

Where

Basic syntax is (fieldname, operator, value), if you give two parameters then = operator is assumed. So where('name', 'usman') and where('name', '=', 'usman') is the same.

QB::table('my_table')
    ->where('name', '=', 'usman')
    ->whereNot('age', '>', 25)
    ->orWhere('type', '=', 'admin')
    ->orWhereNot('description', 'LIKE', '%query%')
    ;

Where In

QB::table('my_table')
    ->whereIn('name', array('usman', 'sana'))
    ->orWhereIn('name', array('heera', 'dalim'))
    ;

QB::table('my_table')
    ->whereNotIn('name', array('heera', 'dalim'))
    ->orWhereNotIn('name', array('usman', 'sana'))
    ;

Where Between

QB::table('my_table')
    ->whereBetween('id', 10, 100)
    ->orWhereBetween('status', 5, 8);

Where Null

QB::table('my_table')
    ->whereNull('modified')
    ->orWhereNull('field2')
    ->whereNotNull('field3')
    ->orWhereNotNull('field4');

Grouped Where

Sometimes queries get complex, where you need grouped criteria, for example WHERE age = 10 and (name like '%usman%' or description LIKE '%usman%').

Pixie allows you to do so, you can nest as many closures as you need, like below.

QB::table('my_table')
            ->where('my_table.age', 10)
            ->where(function($q)
                {
                    $q->where('name', 'LIKE', '%usman%');
                    // You can provide a closure on these wheres too, to nest further.
                    $q->orWhere('description', 'LIKE', '%usman%');
                });

Group By and Order By

$query = QB::table('my_table')->groupBy('age')->orderBy('created_at', 'ASC');

Multiple Group By

->groupBy(array('mytable.myfield1', 'mytable.myfield2', 'another_table.myfield3'));

->orderBy(array('mytable.myfield1', 'mytable.myfield2', 'another_table.myfield3'));

Using groupBy() or orderBy() methods multiple times groupBy('a')->groupBy('b') will also group by first a and than b. Can be useful if you want to do conditional grouping (within a PHP if). Same applies to orderBy().

Having

->having('total_count', '>', 2)
->orHaving('type', '=', 'admin');

Limit and Offset

->limit(30);

->offset(10);

Join

QB::table('my_table')
    ->join('another_table', 'another_table.person_id', '=', 'my_table.id')

Available methods,

  • join() or innerJoin
  • leftJoin()
  • rightJoin()

If you need FULL OUTER join or any other join, just pass it as 5th parameter of join method.

->join('another_table', 'another_table.person_id', '=', 'my_table.id', 'FULL OUTER')

Multiple Join Criteria

If you need more than one criterion to join a table then pass a closure as second parameter.

->join('another_table', function($table)
    {
        $table->on('another_table.person_id', '=', 'my_table.id');
        $table->on('another_table.person_id2', '=', 'my_table.id2');
        $table->orOn('another_table.age', '>', QB::raw(1));
    })

Raw Query

You can always use raw queries if you need,

$query = QB::query('select * from cb_my_table where age = 12');

var_dump($query->get());

You can also pass your bindings

QB::query('select * from cb_my_table where age = ? and name = ?', array(10, 'usman'));

Raw Expressions

When you wrap an expression with raw() method, Pixie doesn't try to sanitize these.

QB::table('my_table')
            ->select(QB::raw('count(cb_my_table.id) as tot'))
            ->where('value', '=', 'Ifrah')
            ->where(QB::raw('DATE(?)', 'now'))

NOTE: Queries that run through query() method are not sanitized until you pass all values through bindings. Queries that run through raw() method are not sanitized either, you have to do it yourself. And of course these don't add table prefix too, but you can use the addTablePrefix() method.

Insert

$data = array(
    'name' => 'Sana',
    'description' => 'Blah'
);
$insertId = QB::table('my_table')->insert($data);

insert() method returns the insert id.

Batch Insert

$data = array(
    array(
        'name'        => 'Sana',
        'description' => 'Blah'
    ),
    array(
        'name'        => 'Usman',
        'description' => 'Blah'
    ),
);
$insertIds = QB::table('my_table')->insert($data);

In case of batch insert, it will return an array of insert ids.

Insert with ON DUPLICATE KEY statement

$data = array(
    'name'    => 'Sana',
    'counter' => 1
);
$dataUpdate = array(
    'name'    => 'Sana',
    'counter' => 2
);
$insertId = QB::table('my_table')->onDuplicateKeyUpdate($dataUpdate)->insert($data);

Update

$data = array(
    'name'        => 'Sana',
    'description' => 'Blah'
);

QB::table('my_table')->where('id', 5)->update($data);

Will update the name field to Sana and description field to Blah where id = 5.

Delete

QB::table('my_table')->where('id', '>', 5)->delete();

Will delete all the rows where id is greater than 5.

Transactions

Pixie has the ability to run database "transactions", in which all database changes are not saved until committed. That way, if something goes wrong or differently then you intend, the database changes are not saved and no changes are made.

Here's a basic transaction:

QB::transaction(function ($qb) {
    $qb->table('my_table')->insert(array(
        'name' => 'Test',
        'url' => 'example.com'
    ));

    $qb->table('my_table')->insert(array(
        'name' => 'Test2',
        'url' => 'example.com'
    ));
});

If this were to cause any errors (such as a duplicate name or some other such error), neither data set would show up in the database. If not, the changes would be successfully saved.

If you wish to manually commit or rollback your changes, you can use the commit() and rollback() methods accordingly:

QB::transaction(function ($qb) {
    $qb->table('my_table')->insert(array(/* data... */));

    $qb->commit(); // to commit the changes (data would be saved)
    $qb->rollback(); // to rollback the changes (data would be rejected)
});

Get Built Query

Sometimes you may need to get the query string, its possible.

$query = QB::table('my_table')->where('id', '=', 3);
$queryObj = $query->getQuery();

getQuery() will return a query object, from this you can get sql, bindings or raw sql.

$queryObj->getSql();
// Returns: SELECT * FROM my_table where `id` = ?
$queryObj->getBindings();
// Returns: array(3)
$queryObj->getRawSql();
// Returns: SELECT * FROM my_table where `id` = 3

Sub Queries and Nested Queries

Rarely but you may need to do sub queries or nested queries. Pixie is powerful enough to do this for you. You can create different query objects and use the QB::subQuery() method.

$subQuery = QB::table('person_details')->select('details')->where('person_id', '=', 3);


$query = QB::table('my_table')
            ->select('my_table.*')
            ->select(QB::subQuery($subQuery, 'table_alias1'));

$nestedQuery = QB::table(QB::subQuery($query, 'table_alias2'))->select('*');
$nestedQuery->get();

This will produce a query like this:

SELECT * FROM (SELECT `cb_my_table`.*, (SELECT `details` FROM `cb_person_details` WHERE `person_id` = 3) as table_alias1 FROM `cb_my_table`) as table_alias2

NOTE: Pixie doesn't use bindings for sub queries and nested queries. It quotes values with PDO's quote() method.

Get PDO Instance

If you need to get the PDO instance you can do so.

QB::pdo();

Fetch results as objects of specified class

Simply call asObject query's method.

QB::table('my_table')->asObject('SomeClass', array('ctor', 'args'))->first();

Furthermore, you may fine-tune fetching mode by calling setFetchMode method.

QB::table('my_table')->setFetchMode(PDO::FETCH_COLUMN|PDO::FETCH_UNIQUE)->get();

Query Events

Pixie comes with powerful query events to supercharge your application. These events are like database triggers, you can perform some actions when an event occurs, for example you can hook after-delete event of a table and delete related data from another table.

Available Events

  • before-select
  • after-select
  • before-insert
  • after-insert
  • before-update
  • after-update
  • before-delete
  • after-delete

Registering Events

QB::registerEvent('before-select', 'users', function($qb)
{
    $qb->where('status', '!=', 'banned');
});

Now every time a select query occurs on users table, it will add this where criteria, so banned users don't get access.

The syntax is registerEvent('event type', 'table name', action in a closure).

If you want the event to be performed when any table is being queried, provide ':any' as table name.

Other examples:

After inserting data into my_table, details will be inserted into another table

QB::registerEvent('after-insert', 'my_table', function($queryBuilder, $insertId)
{
    $data = array('person_id' => $insertId, 'details' => 'Meh', 'age' => 5);
    $queryBuilder->table('person_details')->insert($data);
});

Whenever data is inserted into person_details table, set the timestamp field created_at, so we don't have to specify it everywhere:

QB::registerEvent('after-insert', 'person_details', function($queryBuilder, $insertId)
{
    $queryBuilder->table('person_details')->where('id', $insertId)->update(array('created_at' => date('Y-m-d H:i:s')));
});

After deleting from my_table delete the relations:

QB::registerEvent('after-delete', 'my_table', function($queryBuilder, $queryObject)
{
    $bindings = $queryObject->getBindings();
    $queryBuilder->table('person_details')->where('person_id', $binding[0])->delete();
});

Pixie passes the current instance of query builder as first parameter of your closure so you can build queries with this object, you can do anything like usual query builder (QB).

If something other than null is returned from the before-* query handler, the value will be result of execution and DB will not be actually queried (and thus, corresponding after-* handler will not be called either).

Only on after-* events you get three parameters: first is the query builder, third is the execution time as float and the second varies:

  • On after-select you get the results obtained from select.
  • On after-insert you get the insert id (or array of ids in case of batch insert)
  • On after-delete you get the query object (same as what you get from getQuery()), from it you can get SQL and Bindings.
  • On after-update you get the query object like after-delete.

Removing Events

QB::removeEvent('event-name', 'table-name');

Some Use Cases

Here are some cases where Query Events can be extremely helpful:

  • Restrict banned users.
  • Get only deleted = 0 records.
  • Implement caching of all queries.
  • Trigger user notification after every entry.
  • Delete relationship data after a delete query.
  • Insert relationship data after an insert query.
  • Keep records of modification after each update query.
  • Add/edit created_at and updated _at data after each entry.

Notes

  • Query Events are set as per connection basis so multiple database connection don't create any problem, and creating new query builder instance preserves your events.
  • Query Events go recursively, for example after inserting into table_a your event inserts into table_b, now you can have another event registered with table_b which inserts into table_c.
  • Of course Query Events don't work with raw queries.

If you find any typo then please edit and send a pull request.

© 2020 Muhammad Usman. Licensed under MIT license.

pixie's People

Contributors

acburdine avatar ad3n avatar antoiba86 avatar ascron avatar beaucox avatar griffithben avatar gurakuq avatar krp-kp avatar marc937 avatar mrjgreen avatar neoascetic avatar ninerec avatar ptejada avatar shine-on avatar techjewel avatar totododo avatar usmanhalalit avatar vikkio88 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  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  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

pixie's Issues

Select with function

Using function in select will throw error "Column not found: 1054 Unknown column". For example QB::table('sometable')->select('LEFT(somefield, 7) AS somealias')

[sqlite] date functions not working?

driver = sqlite

None of this works:

QB::table('my_table')->where('updated', '<', 'date(\'now\')');
QB::table('my_table')->where('updated', '<', 'date("now")');
QB::table('my_table')->where('updated', '<', QB::raw('date(\'now\')'));

However, this works:

QB::query('select * from my_table where updated < date("now")');

I've tried to debug a bit and I see the date('now') part it's going to PDO as it should be, without any sanitizing, so it seems like a PDO issue? Or am I doing something wrong?

Select could be more flexible

As addition to array, select could use seperated params : select('field1','field2','field3') or select('field1, field2, field3','another.joinfield')

whereNotIn() must be of the type array

Hello,

So I was thing to do the following query:

SELECT `orig_id` FROM `RPTC` WHERE `id` NOT IN (SELECT `id` FROM `PCT`)

My code was:

// Sub Query
$query2 = $db->table("PCT")->select("id");

// Main Query
$query = $db->table("RPTC")
            ->select("orig_id")
            ->whereNotIn("id", $db->subQuery($query2));

However I got this error message:

 Catchable fatal error: Argument 2 passed to Pixie\QueryBuilder\QueryBuilderHandler::whereNotIn() must be of the type array, object given, called

Is there any specific reason why Pixie doesn't allow for a sub-query as the whereIn / whereNotIn second parameter? How can this be accomplished? Apparently a simple where() accepts sub-queries.

Thank you.

get current table name

Hello,

Is it possible to get the table name in before-select event.

DB::registerEvent('before-select', ':any', function($queryBuilder)
    {
        $table = $queryBuilder -> getTableName();
        $queryBuilder->setFetchMode(PDO::FETCH_CLASS, 'row' . usfirst($table));
    }
);

I'm doing this with regex but there is maybe an easiest way !

Thank's

Kaimite

NOT operator support

I am using pixie in kind of Specification pattern implementation, and I am faced that it supports NOT SQL operator only with IN clause (whereNotIn).

Is it possible to add NOT operator support to any clause (whereIn, whereNotIn, orWhere, etc)?

Thanks!

PDO::ATTR_ERRMODE

Hello,

I just noticed that by default QueryBuilderHandler always sets this:

$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

Why is this behavior forced? I tried to change the error mode like:

$mysql = new \Pixie\QueryBuilder\QueryBuilderHandler($mysqlConnection);
$pdo = $mysql->pdo();
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING);

But it always trow exceptions. By some reason is ignoring my attribute change...

Thank you.

Count not working?

Using the .*@dev composer version on a server running MariaDB, I cannot seem to get count to work.

Thankyou

->insert($data) with objects

Hello,

Is there any particular reason why at ->insert($data) the $data variable can't be an object for single inserts?
Or better yet, it could accept arrays of objects or an object with multiple objects inside to be inserted.

Thank you.

Log query execution time

This is possible with event system, but there will be extra lag on events processing, so raw execution time should be calculated separately. Probably it is good candidate as third parameter of every after-* method.

Insert Raw() at any given point

Hello,

I was noticing this isn't possible, for e.g.:

$query = QB::table("example");
$query->select("id", "name");
$query->raw("where id != null");
$result = $query->get();

The line $query->raw("where id != null"); seems to be ignored.

Is there any specific reason why I can't insert a raw() on the middle of the query? I guess it wasn't implement do the fluid interface, because we never know what parts of the query are set first...

Set a class and constructor args for fetchAll

It would be nice to be able to setup a class and constructor argument for the results when using the get() method.
Something like:

public function asObject($class = '\\stdClass', $args = null)
{
    $this->resultClass = $class;
    $this->resultArgs = $args;
    return $this;
}

whereIn() backslash issue

Hello,

I was tying to build a query with a whereIn() call including strings with backslashes...

$query->whereIn("name", ["\\One\\Two", "\\Antother\\One"]);

However by some reason the escaping seems to be failing and the query object raw SQL ends up as:

SELECT * FROM `Globals` WHERE `name` IN ('\One\Two', '\Antother\One'); 

And it doesn't work, If I go into mysql console and try the code generated by Pixie it won't find anything, however... if I add another slash..

SELECT * FROM `Globals` WHERE `name` IN ('\\One\\Two', '\\Antother\\One'); 

It finds the entries on my DB correctly. Any specific reason why Pixie doesn't place the double backslashes?

PS: On normal WHERE queries this problem doesn't happen.

Thank you.

How to use columns aliases?

I want to specify aliases for columns, i. e. something like SELECT username AS name FROM users.
Currently I can use raw statements to do that, but they are little bit unhandy. Is there better way to do this? If yes, probably need to add note to the documentation. Otherwise, please, implement it! It will be very helpful, especially on legacy databases.

Thanks.

Raw() as Join table

Hello,
So I was tying to build this query:

SELECT * FROM `Store\Order\ProductStore` 

LEFT JOIN `Store\Order\ProductStore` t ON 
`Store\Order\ProductStore`.`product_id` = `t`.`product_id` AND 
`Store\Order\ProductStore`.`id` < `t`.`id` 

WHERE `Store\Order\ProductStore`.`product_id` IN (94) AND 
`t`.`id` IS NOT null 
GROUP BY `Store\Order\ProductStore`.`product_id`

I tried to go this way:

$query = QB::table($table);
$query->leftJoin(QB::raw("`" . $table . "` t"), function($table){
    $table->on($table . ".product_id", "=", "t.product_id");
    $table->on($table . ".id", "<", "t.id");
});
$query->whereIn($table . ".product_id", $input->ids);
$query->where("t.id", "IS", QB::raw("null"));
$query->groupBy($table . ".product_id");

However it doesn't work, I get the following erro stack:

{
    "function": "Util\\{closure}",
    "args": [
        2,
        "explode() expects parameter 2 to be string, array given",
        "AppCore\/Include\/usmanhalalit\/pixie\/src\/Pixie\/QueryBuilder\/Adapters\/BaseAdapter.php",
        455,
        {
            "value": []
        }
    ]
},
{
    "file": "AppCore\/Include\/usmanhalalit\/pixie\/src\/Pixie\/QueryBuilder\/Adapters\/BaseAdapter.php",
    "line": 455,
    "function": "explode",
    "args": [
        ".",
        [],
        2
    ]
},
{
    "file": "AppCore\/Include\/usmanhalalit\/pixie\/src\/Pixie\/QueryBuilder\/Adapters\/BaseAdapter.php",
    "line": 327,
    "function": "wrapSanitizer",
    "class": "Pixie\\QueryBuilder\\Adapters\\BaseAdapter",
    "object": {},
    "type": "->",
    "args": [
        []
    ]
},
{
    "file": "AppCore\/Include\/usmanhalalit\/pixie\/src\/Pixie\/QueryBuilder\/Adapters\/BaseAdapter.php",
    "line": 509,
    "function": "arrayStr",
    "class": "Pixie\\QueryBuilder\\Adapters\\BaseAdapter",
    "object": {},
    "type": "->",
    "args": [
        {
            "\u0000*\u0000value": "`Store\\Order\\ProductStore` t",
            "\u0000*\u0000bindings": []
        },
        ""
    ]
},

Any tips on why this happening? If this is expected what's the way to do the table name alias with Pixie? Why isn't a raw query supported?

Thank you.

How to get raw query results?

I'm attempting to find out if a table exists in MySQL using the following:

$query = $this->db->query("SHOW TABLES LIKE ?", [$table]);

However, I can't seem to get the results of that Query where I can tell the number of rows and if the table exists or not.

How should I go about this?

JOIN on literal is quoted with backticks

When I use a join with a literal, in a multiple on statement, the literal is quoted with backticks:

->leftJoin($qb->raw('table2 AS tbl2'), function($table) use ($userId, $qb) {
            //userid gets enclosed with backticks, changed to raw
            $table->on('tbl2.UserId','=',$userId);
            $table->on('tbl2.JoinId', '=', 'tbl1.JoinId');
})

Result:

... LEFT JOIN `tbl2`.`UserId` = `1234` AND `tbl2`.`JoinId` = `tbl1`.`JoinId`....

So I changed my join to use raw:

->leftJoin($qb->raw('table2 AS tbl2'), function($table) use ($userId, $qb) {
            //userid gets enclosed with backticks, changed to raw
            $table->on($qb->raw('tbl2.UserId = ?',$userId));
            $table->on('tbl2.JoinId', '=', 'tbl1.JoinId');
})

Result:

... LEFT JOIN `tbl2`.`UserId` =  ? `` AND `tbl2`.`JoinId` = `tbl1`.`JoinId`....

There are extra backticks left in the query.

Multiple join

Can i join one table several times?

Can i use alias like:
SELECT t1.* FROM table1 AS t1
INNER JOIN table2 AS t2 ON t1.id = t2.table1id
INNER JOIN table2 AS t22 ON t1.id = t22.table1id AND ...

Option for setting the default fetch mode

It would be great to be able to set the default fetch mode in the query builder.
Not sure how to go about doing this but if it's something you might consider, I'd be happy to have go at something and submit a PR.

orderBy for multiple columns

Hi -

I'm having trouble with the orderBy method. When I want to order by more than one column I can't seem to pass the columns in an array as shown in your GitHub docs. I have a feeling I'm missing the boat here... Can anyone help me?

This doesn't work:

$query = QB::table('movies')
  ->select(array('fs_name','name','release_date', 'rating','video_format','imdb_stars'));
$query->orderBy(array( 'release_date', 'DESC', 'sort_name', 'ASC'));
$queryObj = $query->getQuery();
echo $queryObj->getRawSql();
$result = $query->get();

Errors:

Warning: explode() expects parameter 2 to be string, array given in .../vendor/usmanhalalit/pixie/src/Pixie/QueryBuilder/Adapters/BaseAdapter.php on line 360
Warning: Invalid argument supplied for foreach() in .../vendor/usmanhalalit/pixie/src/Pixie/QueryBuilder/Adapters/BaseAdapter.php on line 362
Warning: implode(): Invalid arguments passed in .../vendor/usmanhalalit/pixie/src/Pixie/QueryBuilder/Adapters/BaseAdapter.php on line 368
...

The raw SQL is:

SELECT `fs_name`, `name`, `release_date`, `rating`, `video_format`, `imdb_stars` FROM `movies` ORDER BY ASC

This works:

$query = QB::table('movies')
  ->select(array('fs_name','name','release_date', 'rating','video_format','imdb_stars'));
$query->orderBy('release_date', 'DESC');
$query->orderBy('sort_name', 'ASC');
$queryObj = $query->getQuery();
echo $queryObj->getRawSql();
$result = $query->get();

The raw SQL is:

SELECT `fs_name`, `name`, `release_date`, `rating`, `video_format`, `imdb_stars` FROM `movies` ORDER BY `release_date` DESC,`sort_name` ASC

Transaction Support

Laravel has support for transactions via the

DB::transaction(function(){
     DB::insert(...);
     DB::delete(...);
     etc.....
});

which auto begins and commits a transaction before and after calling the callback function.

Would you consider adding a method to support this?

Raw() in WHERE resulting in quoted output

Hello,

I was doing this: $query->where("t.id", "IS", self::$mysql->raw("null"));

If I try to debug the query, I get this:

AND `t`.`id` IS null GROUP B...

However when I run the query, it gives me a PDO Exception with the following:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''null' GROUP BY `S...

By inspecting MySQL's general_log I found out, Pixie or PDO are actually trying to escape the "null" value with single quotes:

 AND `t`.`id` IS 'null' GROUP ...

Why is this happening? Raw should not escape anything...

Thank you.

join on subquery support

If this is something pixie currently support I'd like to know
Otherwise i'd like to expand support to join on subqueries
for example

select * from table1 alias1
inner join (select id from table2 where field = 1) alias2 on alias2.id =alias1.id

i see the join param expects a string rather than an object so right now my ideal setup is not funcitonal:

$subquery = QB::table('table2')->select('name')->select('id)->where('field','=',1);
$query = QB::table('table1)->innerJoin(QB::table(QB::subQuery($subquery,'alias2')),'alias1.id','=','alias2.id');

I know the sql is a simple and dumb example I'm in a real world situation where we join on a subquery and I'd like to accomplish this without using raw

whereNot is not working for some reason

When I try to run a query with whereNot I get the following error,

Fatal error: Call to undefined method Pixie\QueryBuilder\QueryBuilderHandler::whereNot() in /home/ubuntu/workspace.....

Getting the where clause

I was wondering if it's possible to get the WHERE clause that makes up the statement from the query? Would like to be able to get what the WHERE clause that was used in the execution of the query.

Try this call but no results:
$query->getQuery('criteriaonly');

calling
$query->getQuery(); - Returns the entire SQL Query that is to get executed.

any possible way of accomplishing what is required?

whereBetween / orWhereBetween at Grouped Where issue

Hello,

I was doing the following query:

$query = self::$qb->table(self::$defaultTbl)
                  ->select("id")
                  ->where("active", true);

$query->where(function($qb) use($lowLimit, $highLimit) {
    $qb->whereBetween("field1", $lowLimit, $highLimit);
    $qb->orWhereBetween("field2", $lowLimit, $highLimit);
});

However it fails saying there's an error on the SQL. I used ->getRawSql() to debug this and got this:

SELECT `id` FROM `group` WHERE `active` = 1 AND (`field1` BETWEEN 0 AND 30OR `field2` BETWEEN 0 AND 30)

Apparently there's a space missing on the OR here:

(`field1` BETWEEN 0 AND 30OR `field2` 

Can someone point me where this issue might be? I tried to follow pixie's _where() code but got lost.

Thank you.

Schema handeling

Would it be possible to add the ability to create (and, eventually, update) database schema?

->setFetchMode() kept between raw queries

Hello,

There seems to be a behaviour mismatch between the way raw queries and pixie queries handle ->setFetchMode().

For instance, If I do:

$query = $db->table("page")
            ->where("title", "=", "test title")
            ->setFetchMode(\PDO::FETCH_ASSOC);

The returned array will give me an array as expected. Next time if I just issue:

$query = $db->table("page")
            ->where("title", "=", "test title");

Without specifying a fetch mode, it will default to PDO::FETCH_OBJ as expected.

This is fine, however in raw queries, the fetch mode value is kept between two queries:

$query = $db->query("select * from page where title = 'test title'");
$query->setFetchMode(\PDO::FETCH_ASSOC);

Will return an array as expected. If I issue next, a query without specifying a fetch mode:

$query = $db->query("select * from page where title = 'test title'");

It will return an array as well. It will keep returning arrays until I manually set it to return objects again.

Why isn't the fetch mode changed to the default PDO::FETCH_OBJ after $query->get() similarly to what happens in non-raw queries?

Thank you.

Raw query as value breaking all WHERE clauses

Good morning,

I was trying the following:

$query = $db->table($groupTbl)
            ->select("id")
            ->where($db->raw("`" . $groupTbl . "`.dateCreated"), ">", $db->raw("'2015-04-20 15:00:00'"));

However it doesn't work properly as I get the following raw query:

SELECT `id` FROM `Funcionarios\Dados` WHERE `Data`.dateCreated

As you can see the second part of the query was omitted. It's missing > '2015-04-20 15:00:00'. This issue seems to affect all where queries like whereBetween, orWhere etc. Is there any specific reason for this inconsistency?

Thank you.

where string

Hello,

is it possible to specify a "where" like this :

QB::table('my_table')->where("field> 35 ORfield2 != 'test' ");

I want to specify a where string in a form field.

Thank's for your answers and sorry for my english :)

Kaimite

Just the query.

I am using a migration framework called LibMigrate. It expects me to return the SQL it should run. That is why I do not want to open yet another connection if that is not even required. So...what is the correct way to just obtain the SQL without conencting?

Kind regards, Ingwie.

Backslash on table name breaks UPDATE/DELETE queries

Hello,

I was trying to get records out of a table called CMS\Page, yes there's a backslash on the table name. Unfortunately the backslash seems to break update queries...

I get a PDO exception like:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\\Page SET `id`='4',`title`='title1',`content`='test' at line 1"

This doesn't happen on select queries.

By inspecting general_log on MySQL server I found out that it was trying to run the following query:

UPDATE CMS\Page SET `id`='4',`title`='title1',`content`='content',`dateUpdated`='2015-03-17 00:32:05' WHERE `id` = '4'

As you can see, the table name, is not properly escaped as ``CMS\Page SET like it should.

For instance on a select query it escapes the table name properly:

SELECT `id`, `date`, `dateUpdated`, `title` FROM `CMS\Page` LIMIT 20

The same issue applied to delete queries.

Note: I'm not sure how this should be fixed, I tried to edit ->addTablePrefix() method, however it seemed to do more harm than good.

Thank you.

orderBy array

I understand now that I have to split my orderBys if I am specifying DESC. Thanks,

However, the array option in orderBy still does not seem to work:

$query = \QB::table('movies')
  ->select(array('fs_name','name','release_date', 'rating','video_format','imdb_stars'));
$query->orderBy(array( 'release_date', 'sort_name'));
$queryObj = $query->getQuery();
echo $queryObj->getRawSql();
$result = $query->get();

gives:

Warning: explode() expects parameter 2 to be string, array given in .../vendor/usmanhalalit/pixie/src/Pixie/QueryBuilder/Adapters/BaseAdapter.php on line 360
Warning: Invalid argument supplied for foreach() in .../vendor/usmanhalalit/pixie/src/Pixie/QueryBuilder/Adapters/BaseAdapter.php on line 362
Warning: implode(): Invalid arguments passed in .../vendor/usmanhalalit/pixie/src/Pixie/QueryBuilder/Adapters/BaseAdapter.php on line 368
...

raw SQL:

SELECT `fs_name`, `name`, `release_date`, `rating`, `video_format`, `imdb_stars` FROM `movies` ORDER BY ASC

My error or ???

Beau.

How do I filter by function?

I'd like to do something like:

QB::table('sometable')->where("date < datetime('now', '-600 seconds')")->get();

after-insert event query object in params ?

Hello,
is it possible to have the "query object" in after-insert event ?
I use after-insert / update / delete events to log each queries in a flat file.
If my sql server crash I can restore all queries done after my daily backup.

but in the after-select event I can't get query with :

$query = $queryObject -> getRawSql();

something like that :

QB::registerEvent('after-insert', ':any', function($queryBuilder, $insertId, $executionTime, $queryObject)
    {
        logQuery($queryObject -> getRawSql());
    }
);

I tried this :

$queryObj   = $queryBuilder -> getQuery();
$query = $queryObj -> getRawSql();

but it's not the good query :'(

Thank's !

Handle DateTime objects

Would it be possible to handle DateTime objects passed as conditions in where() ?

something like if ($value instanceof \DateTime) $value->format("Y-m-d H:i:s");

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.