GithubHelp home page GithubHelp logo

respect / relational Goto Github PK

View Code? Open in Web Editor NEW
243.0 243.0 32.0 982 KB

A fluent, intuitive ORM for any relational database engine

Home Page: http://respect.github.io/Relational

License: Other

PHP 100.00%

relational's People

Contributors

augustohp avatar danielcosta avatar eric-chau avatar faabiosr avatar filhodanuvem avatar henriquemoody avatar kinncj avatar nickl- avatar rogeriopradoj avatar thiagophx avatar wesleyvicthor avatar williancarminato avatar zeebinz 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

relational's Issues

Bug when conditions are applied to more than one table

Hello all of you who develop Respect. First, let me thank you and say you're doing a really good job! I'm using Respect in a project of mine and today I was not able to perform a query based on the examples in your documentation.

The project I'm working on is a CMS, and I want to fetch all the contents that belongs to the category of ID equal to 30, which ID is different from 60. According to your documentation, I thought of this command:

$aContent = $mapper->content(array('id !=' => 60))->category[30]->fetchAll();

It was not bringing me the contents I expected, so I dove into the code and inserted an echo where you generate the query to see what the framework was looking for (release 0.5.1, file Mapper.php, line 223):

    protected function createStatement(
        Collection $collection, $withExtra = null
    ) {
        $query = $this->generateQuery($collection);

        if ($withExtra instanceof Sql) {
            $query->appendQuery($withExtra);
        }
        echo $query; exit;

The generated query was:

SELECT content.*, category.* FROM content INNER JOIN category ON content.category_id = category.id WHERE category.id = ?

I decided to replace my command by your example:

<?php $mapper->comment(array("created_at >"=>strtotime('today')))
             ->post(array("created_at >"=>strtotime('7 days ago')))
             ->author[7]
             ->fetchAll();

And the generated query was actually:

SELECT comment.*, post.*, author.* FROM comment INNER JOIN post ON comment.post_id = post.id INNER JOIN author ON post.author_id = author.id WHERE author.id = ?

It seems it's only taking into account the last condition from the join.

Error while loading objects from mapper

Like described under #69 the way we instantiate objects that came from a database loading, we're now using Reflection and instantiating without using __construct.

This broke most part of my code logic, and I actually need my constructor being called while loading from repository.

This can be seen under Respect\Relational\Mapper, lines 460 to 462.

Does anyone else have the same problem?

Wouldn't that be better done from a config or something like?

-- EDIT
Indeed, wouldn't that be better if we just use instantiation with args? Or make our __construct params optional? ... function __construct( $arg1 = null )

http://php.net/manual/pt_BR/reflectionclass.newinstanceargs.php

Conditions

Hi, I've just stumbled on a simple thing. I'm sorry if it is already answered somewhere, but I couldn't how to do a condition with the "OR" operator, instead of "AND".

I mean, basically, I'm searching for an author. The documentation shows this:
$mapper->author(array("name"=>"Alexandre"))->fetch();

Which works fine, but let's say I'm not really sure of what the user may have typed on the search box (it could be the author's name or the author's id).
I tried this:
$mapper->author(array("name"=>"Alexandre", "id"=>1))->fetch();

I believe this generates the following SQL (or something like this):
SELECT * FROM author WHERE name = Alexandre AND id = 1

I would actually like a way to generate the following (or something like it):
SELECT * FROM author WHERE name = Alexandre OR id = 1

Is it possible? Thanks in advance!

Get last inserted id

i'm using $db>insertInto('table_name', $data)
->values($data)->exec();
but this will return a boolean, how to i get last inserted id?

PostgreSQL support

At #36 @robinson-rso raised an interesting question, can we handle schemas.
@tuliobraga raised #40 there are problems with lastInsertId.

This made me realise that I have never tested this against postgres as a matter of fact I don't even have a php instance compiled --with-pdo-pgsql. Postgres has always been the rock solid alternative but they've really stepped up their game as far as ease of installation and accessibility is concerned. This is not something to take lightly if we care at all about this project.

These are some actions actions we can take to remedy this:

  • Run unit tests against PostgreSQL and publish the results
  • Investigate if travis is capable and update config to test against PostgreSQL and others
  • Extend test cases to scrutinise PostgreSQL specific problems where required
  • Identify additional features perhaps unique to PostgreSQL and discuss their possible inclusion

I urge everyone with PostgreSQL capabilities to please help out with this issue, run the tests and submit the results.

@Respect can we treat this with the highest priority.

Sql: parameters should allow repeat references

Because of the way the Sql class currently parameterizes its statements and stores values by key in $sql->params and $sql->data, it isn't possible to reference the same field twice with different values, e.g.:

$sql->select('*')->from('table')->where(array('a >' => 1, 'a !=' => 4));

// == SELECT * FROM table WHERE a > :A AND a != :A
// == SELECT * FROM table WHERE a > 4 AND a != 4

Which is obviously not what we want. OK, so we can keep track of the different A references and number them (A, A1, etc), but now we have the problem that the conditions are also stored by key so can't be repeated, making statements like this difficult:

SELECT * FROM table WHERE (a > 1 AND b = 'foo') OR (a > 4 AND b = 'bar')

Because the 'a >' and 'b' keys of $sql->data and $sql->params will be overwritten. So we'd have to keep track of and number these keys too.

It strikes me that rather than using named params like this for the bindings, it would be simpler just to use the '?' placeholders, get rid of $sql->data and leave $sql->params as a simple array. Since everything is built serially anyway, you'd only need to add a '?' to the query string then append the value to the params list, so we'd end up with (ignoring how to add the brackets for now):

$sql->query = 'SELECT * FROM table WHERE (a > ? AND b = ?) OR (a > ? AND b = ?)';

$sql->params = array(1, 'foo', 4, 'bar');

Which is all we need for PDOStatement::execute. This would also simplify the class quite a bit, and allow us to add nested subqueries more easily. Are there any downsides to this? Are named parameters actually needed anywhere else?

Is there a way to select columns without Sql:: and database views?

Hello,
Each time I need to reduce overhead related to too many unneeded columns I've to create a database view and fetch from this view. The question is: is there a way to set output columns?

I tried this ( from issue #24):

    $mapper->bill_notice_list = c\Filtered::by('description', 'next_notification_date')->bill_notice();
    $billNotices = $mapper->bill_notice_list(
        array('usercustomer_id' => $usercustomerId)
    )->fetchAll();

but no data retrieved.

Error: Declaration of Respect\Relational\Mapper::persist()

Run the code follow:

<?php

require './bootstrap.php';

use Respect\Relational\Mapper;
use Respect\Data\Collections\Collection;

$mapper = new Mapper(new PDO('mysql:host=localhost;dbname=Respect_Relational','root',''));

Return the follow error:

Fatal error: Declaration of Respect\Relational\Mapper::persist() must be compatible with Respect\Data\AbstractMapper::persist($object, Respect\Data\Collections\Collection $onCollection) in /vendor/Respect/Relational/library/Respect/Relational/Mapper.php on line 17

ANSI SQL standard

Found the free ANS SQL standard Part 1:
http://standards.iso.org/ittf/PubliclyAvailableStandards/index.html
ISO_IEC_9075-1_2008

According to Wikipedia there are 14 parts:
ISO/IEC 9075-1:2008 Framework (SQL/Framework)
ISO/IEC 9075-2:2008 Foundation (SQL/Foundation)
ISO/IEC 9075-3:2008 Call-Level Interface (SQL/CLI)
ISO/IEC 9075-4:2008 Persistent Stored Modules (SQL/PSM)
ISO/IEC 9075-9:2008 Management of External Data (SQL/MED)
ISO/IEC 9075-10:2008 Object Language Bindings (SQL/OLB)
ISO/IEC 9075-11:2008 Information and Definition Schemas (SQL/Schemata)
ISO/IEC 9075-13:2008 SQL Routines and Types Using the Java TM Programming Language (SQL/JRT)
ISO/IEC 9075-14:2008 XML-Related Specifications (SQL/XML)

This is also not the latest as 2011 replaces it

I wonder if ISO will donate to open source?

Select only some field

How can I select some fields instead * using the Mapper?

It's easy using SQL or DB interface:

Sql::select('*')

...

$db->select('*')

Syntax error

Well, I really love Respect/Relational, in minutes I can catch this, connect in my database and fetch my data, this is beauty!
But I think that one problem of this framework too is your better feature; the flexibility.

For example

use Respect\Relational\Db;

$db = new Db($pdo);
$data = $db->select('*')->from('Games')->fecth();

I wrote fecth instead of fetch and (I have really a problem with this word LOL, but ...), nothing happened, $data yet is a object Db. I undestand the why, but I think that this is a problem for any people.

I know that we need of a parser to recognize which words are avoid and I believe that this turn Relational more complex ๐Ÿ˜• .
But for a discussion, anyone yet thought this?

How do you execute queries made with the Sql class?

Hi there!

I'm trying to select specific columns from multiple tables. The multi-join tables section of the documentation pointed me to the Sql class, but I have no idea how to actually run that query, any pointers?

I built the query like this:

Sql::select('sales.id, products.name, users.name')
    ->from('sales', 'products', 'users')
    ->where(array(
        "sales.products_id" => "products.id",
        "sales.users_id" => "users.id"
 ));

Sorry if this is really obvious, I couldn't find anything in the documentation, and I didn't see anything obvious in the testing file for the Sql class either.

Transactions

Hi Again!

I was wondering how can I work with transactions like Rollback and Commit.

I've checked that the flush() method already deals with it, but here's what I'm trying to accomplish:

Let's say I have the following database structure:

sales (id INT AUTO_INCREMENT, date TIMESTAMP)
sales_item (id INT AUTO_INCREMENT, sales_id INT, products_id INT, value FLOAT )
products (id INT AUTO_INCREMENT, description VARCHAR(255) )

I want to save a sale in one click. So here's what I'm trying to do:

$sale = new \stdClass;
$sale->date = new date('Y-m-d H:i:s');
$mapper->persist($sale);

// Here is the tricky part
// I need the $sale->id to do this, see:
$sale_item = new \stdClass;
$sale_item->sales_id = $sales->id;
$sale_item->product_id = 1;
$sale_item->value = 10;

$mapper->persist($sale_item);

$mapper->flush();

The problem is that $sales->id is NULL as the mapper wasn't flushed at that point. I know I can flush it and get the ID I want, but if anything happens and I can't save the sale_item, the sale would be already commited, which means I'd have to delete it and flush the database again. Is it possible to achieve what I want?

Handling Non-Conventional Databases

We have a legacy database which we can't easily re-structure, and it's not consistent in it's naming. For instance, we have 3 tables:

Account (id, UUID, Name)
User (UserID, AccountID, Name)
Phone (UUID, AccountUUID, Number)

User is joined to Account with User.AccountID = Account.id.
Phone is joined to Account with Phone.AccountUUID = Account.UUID

Will Relational support this sort of mashup? I have used $mapper->entityNamespace to create a class for each table, but I can't seem to figure out what to put in the User class, for instance, to tell it to relate to Account correctly.

Can anyone point me in the right direction?

Thanks,
Travis

Issue about a new feature

Hi Guys!

What is the possibility to implement something like the code below?

 $mapper->postsFromAuthor('id' => '7|8|9')->fetchAll();

Would be "in" implementation but with a regex syntax.

OneToN

When you have one to n relationship, it doesn't return all the children as it shloud.

TABLES

comment
post
author

PHP

$comments = $mapper->comment->post->author->fetchAll();

EXPECTED

$comments[0]->post_id->author_id->name;

ACTUAL RESULT

is_object($comments[0]->post_id->author_id);
returns false

Instance of DateTime() in DATETIME entity property

How can be the best approach to format a DATETIME field through a \DateTime() instance ?

Today if you do:

<?php
$entity->date = new \DateTime();

the mapper will try to find the field id of DateTime object.

The implementation to fix this may seem like:

<?php 
foreach ($cols as &$c) {
        if (is_object($c) && $c instanceof \DateTime) {
                $c = $c->format('Y-m-d H:i:s');
        } elseif (is_object($c)) {
                $c = $c->{$primaryName};
        }
} 

reference: #L235-245

Maybe it would be nice if on fetch the data, properties based on DATETIME came with an instance of \DateTime().

suggestions ?

Redesign and refactoring

After great feedback from our users, we now believe its time for a cleaner and more powerful Respect\Relational. Major points in this refactor:

Schema cleanup

Although the idea of different schema providers is great, their implementation is incomplete and people rarely uses them. We should focus on removing different schemas and upgrading AbstractSchema+Infered to a component more close to the Mapper.

As a result of this, users are encouraged to always use the three main conventions for Respect\Relational.

Future new schema providers are not discarded, but we should focus on getting our API awesome before trying out different things.

Finders become Collections

Currently finders are the objects that represent node chains in a Relational query. For $mapper->post->author[3]->fetch(), which is the query for retrieving all posts from author 3, both post and author are instantiated as Finders.

We're planning to extend this to make these finders do more than querying. $mapper->post->author->persist($object) for example would persist the $object to a predefined set of collections (a post and a table author). This will allow users to reuse the $mapper->post->author better and have more cohesive, schema-less, objects.

This also deprecates persisting directly into a Mapper instance. Users should know where they're persisting.

Collection shortcuts

Collections are always hierarchical. They implement the composite pattern. This allow us to create collection shortcuts:

<?php
$mapper->postsFromAuthor = $mapper->posts->author; //create the shortcut and assign to the mapper
$posts = $mapper->postsFromAuthor[3]->fetchAll(); //retrieve posts from the author 3
$mapper->postsFromAuthor->persist($newPost); //persists a new post with author

We also need to make these changes reduce our codebase =)

After this, Respect\Relational will not be called an ORM anymore. We need a better name for this approach.

Many-to-many using the same table 2 times

Hello,
How columns should be names to allow a many-to-many relationship when the same table is referenced, for example

table customer(id)
table customer_customer(id, customer_id, other_customer_id, other_data)

how the other_customer_id should be named to be respect compliant?

Non-incrementable PKs not working

As reported by @jeanpimentel, persist() is not working for non-incrementable PKs. It results in an INSERT 100% of the times.

Possible workaround is to call markTracked($entity, 'table_name', $entity->id) manually for updates, before persist()ing.

There is no single, cross-sgdb command that act as REPLACE INTO or INSERT ... ON DUPLICATE KEY UPDATE, so we may need a thin abstraction layer after all, or two queries.

Multi-join tables

Hi, I'm having some trouble working with this.

Please consider the following database structure:

user (id INT AUTO_INCREMENT, name VARCHAR(32))
message (id INT AUTO_INCREMENT, user_from_id INT, user_to_id INT, text TEXT, created_at TIMESTAMP)

Let's say I'm trying to create a simple message system. One user can send a message to another user. Now let's say I'm creating some sort of admin area so system administrators can see all messages, who sent them and who they were sent to (I know it's not a very common thing to do, but I'm using this example because I think it's easier to understand =D).

When I $mapper->message->fetchAll() I get the the ids of both users (from and to), but not their names. I've tried to use $mapper->message($mapper->user, $mapper->user)->fetchAll() without success (the identifiers are not following the standard style). I've created a style like this:

<?php
use Respect\Data\Styles as respect;
class MessageStyle extends respect\Standard{
        protected $remoteIdentifiers = array(
        'user_from_id' => 'user',
        'user_to_id' => 'user2'
    );

    public function remoteIdentifier($name){
        $remoteIdentifiers = $this->remoteIdentifiers;
        $identifier = array_search($name, $remoteIdentifiers);

        return ($identifier) ? $identifier : parent::remoteIdentifier($name);
    }

    public function remoteFromIdentifier($name){
        $remoteIdentifiers = $this->remoteIdentifiers;
        if( array_key_exists($name, $remoteIdentifiers) ){
            return $remoteIdentifiers[$name];
        }

        return parent::remoteFromIdentifier($name);
    }
}

I was able to load the information of user_from_id correctly, but had no success on user_to_id. I've also noticed that the variable $name on the remoteIdentifier() method is set to have the table name, not the alias, therefore my routine wouldn't work as expected. I've latter added a counter to it and was able to return the proper identifier, but still wasn't able to get both user_from and user_to information on one database request.

Any suggestions?

Thank you in advance.

Problem with protected properties in Entity Class

Hi!

Im working with Entity Class using for reference this manual section https://github.com/Respect/Relational#entity-classes.

My code is working ok, except one item.

When i use protected properties in classes, this properties not persist in the database. I'm looking in the source code of Relational and i really not understand why this "columns" are not persist. (In time, i'm using magic methods for __call, __get, __isset and __set).

Anyone works with protected properties and Entity Classes to help me in a solution?

\Respect\Data\Styles\Sakila Doesn't work

Sakila Style and every Style which uses the same name convention for both Primary Key and Foreign Key.

When making a simple inner join like:

$m->news->news_cat->fetchAll();

The mapper gets confused about what is a FK and what is a PK as the logic for both is the same. This way, it assumes the PK as FK and never prints its contents.

Eg:

$result = $m->city->country->fetch();
var_dump($result);
/**

object(stdClass)[44]
  public 'last_update' => string '2006-02-15 04:45:25' (length=19)
  public 'country_id' => 
    object(stdClass)[46]
      public 'last_update' => string '2006-02-15 04:44:00' (length=19)
      public 'country' => string 'Afghanistan' (length=11)
      public 'country_id' => 
        &object(stdClass)[46]
  public 'city' => string 'Kabul' (length=5)
  public 'city_id' => 
    &object(stdClass)[44]

**/

I think a solution for this is to send the table name for the constructor of the Style. Or similar way which I could differ a PK from a FK even when the convention is the same

Sql::orderBy doesn't quote columns

I've this query which does not quote columns and then mysql retrieve an incorrect order. The table has timestamp column

$mapper->news->fetchAll(Sql::orderBy('timestamp', 'id')->desc()->limit($initial, $pageSize))

Resulting query:

SELECT news.* FROM news ORDER BY timestamp, id DESC LIMIT 0, 200

expected:

SELECT news.* FROM news ORDER BY `timestamp`, `id` DESC LIMIT 0, 200

Is there a way to instruct Sql to quote columns?

Respect/Relational/Sql not working with orderBy()->asc() or orderBy()->desc()

I was trying to do Sql::orderBy('updated_at')->desc() when I noticed this.

I added some tests:

public function testSimpleSelectOrderBy()
{
    $sql = (string) $this->object->select('*')->from('table')->orderBy('column');
    $this->assertEquals("SELECT * FROM table ORDER BY column", $sql);
}

public function testSimpleSelectOrderByAsc()
{
    $sql = (string) $this->object->select('*')->from('table')->orderBy('column')->asc();
    $this->assertEquals("SELECT * FROM table ORDER BY column ASC", $sql);
}

public function testSimpleSelectOrderByDesc()
{
    $sql = (string) $this->object->select('*')->from('table')->orderBy('column')->desc();
    $this->assertEquals("SELECT * FROM table ORDER BY column DESC", $sql);
}

Results:

There were 2 failures:

1) Respect\Relational\SqlTest::testSimpleSelectOrderByAsc
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-SELECT * FROM table ORDER BY column ASC
+SELECT * FROM table ORDER BY column

/var/www/GitHub-Summary/vendor/Respect/Relational/tests/library/Respect/Relational/SqlTest.php:121

2) Respect\Relational\SqlTest::testSimpleSelectOrderByDesc
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-SELECT * FROM table ORDER BY column DESC
+SELECT * FROM table ORDER BY column

/var/www/GitHub-Summary/vendor/Respect/Relational/tests/library/Respect/Relational/SqlTest.php:127

So, I was debugging and I found it at:

protected function preBuild($operation, $parts)
{
    $parts = $this->normalizeParts($parts, $operation === 'on' ? true : false);
    if (empty($parts))
        return $this;
    $this->buildOperation($operation);
    return $this->build($operation, $parts);
}

With asc() or desc(), $parts is always empty and it returns.
And I can't simply remove the conditional. If I do, a test fails.

There was 1 failure:

1) Respect\Relational\SqlTest::testSelectWhereArrayEmptyAnd
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-SELECT * FROM table WHERE column=:Column AND other_column=:OtherColumn
+SELECT * FROM table WHERE column=:Column AND other_column=:OtherColumn AND

I can do this with Sql::orderBy ('updated_at DESC') but I don't think that it's the best solution.
What do you think?

PostgresSQL lastInsertId error

I found a bug with postgreSQL. If you're using postgreSQL's driver, when Respect\Mapper::checkNewIdentity calls PDO::lastInsertId(), it must pass the sequence name as a parameter to this method. Currently, the pk column is setted with postgreSQL OID.

Respect\Relational Abstract Collections

Respect\Relational Abstract Collections

Respect\Relational uses Respect\Data collections to express two things:

1 - How tables are related

This is done by the very nature of Collection compositing:

  <?php
  $comments = new Collection('comments');
  $comments->stack($posts   = new Collection('posts');
  $comments->stack($authors = new Collection('authors');
  $authors->setCondition(7);

This is telling that each comment has a post and each post has an author. Also tells that authors have a condition of being 7, which Relational abstracts as the primary key identified by the chosen SQL style (for example, the default is comments.id).

For luck, this building, stacking and configuring can be more straightforward by using the magic layer that produces the same object as the previous sample:

  <?php
  $comments = Collection::comments()->posts()->authors[7];

1 - How tables are hydrated

Since the collection knows who is inside who, they have all necessary information to inform Relational about which objects goes inside another objects. The above operation used in Relational could bring a result similar to:

  <?php
  array(
     (object) array(
         'id' => 1,
         'text' => 'Some Comment',
         'post_id' => (object) array (
             'id' => 1,
             'title' => 'Some Post',
             'author' => (object) array(
                  'id' => 7,
                  'name' => 'Gaigalas'
             )
         )
    )
  )

This has some limitations. Collections can't filter columns nor Relational can hydrate results differently.

Proposal

The idea is now is to separate how Collections handle hydration and relation by abstracting them into separate strategies:

<?php
$mapper->serverStatus = new DictionaryCollection('servers', 'status'); //Servers table, status column.
$mapper->serverStatus->fetchAll(); //Array key/pair using PK and status column

$mapper->dictionary('server', 'status')->fetchAll(); //Same as above

Some other samples:

Named Collections

Normal hydration brings a numeric array of hydrated objects. Named Collections brings an array with keys as primary keys:

<?php
$mapper->onlineUsersByPk = new NamedCollection('users');
$mapper->onlineUsersByPk->setCondition(array('online' => 1));

$mapper->named('users', array('online' => 1)); //Same as above

Mixed Collection Inheritance (Joined Table Inheritance)

Uses two tables to form a result.

<?php
$mapper->premiumAndNormalUsers = new MixedCollection('users', 'user_type');

$mapper->mixed('users', 'premium_users')->fetchAll(); //Same as above

Typed Collections (Single Table Inheritance)

Uses a discriminator column as the collection name.

<?php 
$mapper->bugs = new TypedCollection('bugs', 'bug_type'); //Single Table Inheritance

$mapper->typed('bugs', 'bug_type')->fetchAll(); //Same as above

Filtered Collections (Specific SELECT conditions)

Brings only specified columns. Two notations possible:

  • name to bring all columns from the collection matching this name
  • name.column to bring a specific column

Note that the identifier for a collection will always be brought in normal collections. Named and dictionary collections can override this behavior.

<?php 
$mapper->posts = new FilteredCollection('posts', 'authors.name');
$mapper->comments = Collection::comments(array('moderated'=>1))
                              ->posts()->authors();

class_alias('FilteredCollection', 'SelectCollection');

$mapper->select('posts', 'authors.name')
       ->comments(array('moderated'=>1))
       ->posts
       ->authors
       ->fetchAll(); //Same as above

This all came into mind when I was working on Template and though that we could be more open on how Relational brings it's results back, so we can change these results less when passing to another libraries =)

I would like some feedback on this before putting my hands to work!

@augustohp @nickl- @henriquemoody @wesleyvicthor @iannsp

SQL SERVER TOP (LIMIT)

I need to build a query using the TOP argument (it's like MySql LIMIT XX) in a legacy database. Does anybody have some idea how can I build it using Mapper? By default the query is like that: SELECT TOP 10 * FROM [TABLE].

Access to $db property from Mapper

Is there some way (method) to access the protected $db property from Mapper class? Sometimes I need to build and execute "handmade" queries ( using Db::query('...') ).

PostgreSQL Schema

Is Relational capable of dealing with PostgreSQL Schemas? I am not sure if I can map the schemas and tables properly. I have used variables instead methods to map schemas:

$vendor = 'og0001.vendor';
$array = $mapper->$vendor->fetchAll();

Will Relational support schemas?

Thanks!

Sql -> Query refactoring

We're planning to expand our data access API to databases other than relational. This would be outside the Relational project, but is desirable to be consistent across the projects.

This change is simple. We need to rename Respect\Relational\Sql to Respect\Relational\Query.

I'd like to receive feedback on this! Thanks!

Schema support

The bits I was allowed to see from the ANS SQL standard ISO/IEC 9075, was the results from a search query for "SQL table name" and I quote.

ISO/IEC 9075 specifies that an object such as an SQL-invoked routine, a user-defined type, a domain, a table, a view, or a privilege shall be part of exactly one schema.

At #36 @robinson-rso raised an interesting question, can we handle schemas. Which is at first I thought nothing strange of surely PDO will take care of that, but does it?
PostgreSQL's use of schemas is not all that different to using multiple MySQL databases simultaneously where you would prefix the table name with the database name.

The following tasks items should be actioned.

  • Can we use multiple databases out of the box- create tests to prov it

if not

  • Can we deal with PostgreSQL schema in connection string? this won't solve multiple databases/schemas but at least it's not completely defunct.
  • Investigate how others have approached the problem
  • Discuss and design the ideal solution which will allow multiple databases/schemas

@Respect and the friends of Respect what are your thoughts on this?
Please help with suggestions, research and test results.

Fixed 'Undefined Property' error when trying to do a simple fetchAll from a table with no table_id field

On our database we have some tables with primary keys that are not numeric IDs and do not conform to the Sakila convention of being named 'table_id' (ex. the pk could be called "username").
We don't need complex queries on those tables, so Relational should be able to ignore a missing 'table_id' field when just doing a simple SELECT ALL query.
Unfortunately, a single code line on Mapper.php (line 351) causes an error which stops the application.
The current line reads:

'pk_'.$primaryName => $row->{$primaryName},

This causes an error when the row fetched from the database has no field named "id", or "table_id" under the Sakila style.
The issue gets fixed if I change it to:

'pk_'.$primaryName => isset($row->{$primaryName}) ? $row->{$primaryName} : null,

This fix, IMHO has no drawbacks and makes the code more robust, allowing simple queries (no joins, of course) for any table wether it's primary key name conforms to naming rules or not.

I can't just patch this on my app because it will be lost when reinstalling/updating the library via Composer.
Would you please apply this patch and assign a new version Tag so that we can update the library on our app via Composer?
Otherwise, we will need to change the database schema or use low level queries, which we would rather avoid.

Events

Does anyone have the intention to use events with relational?

Yes, events. Like... dbms's triggers... Anyone?

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.