3 namespace RedBeanPHP\Repository;
5 use RedBeanPHP\OODBBean as OODBBean;
6 use RedBeanPHP\QueryWriter as QueryWriter;
7 use RedBeanPHP\RedException as RedException;
8 use RedBeanPHP\BeanHelper as BeanHelper;
9 use RedBeanPHP\RedException\SQL as SQLException;
10 use RedBeanPHP\Repository as Repository;
14 * OODB manages two repositories, a fluid one that
15 * adjust the database schema on-the-fly to accomodate for
16 * new bean types (tables) and new properties (columns) and
17 * a frozen one for use in a production environment. OODB
18 * allows you to swap the repository instances using the freeze()
21 * @file RedBeanPHP/Repository/Fluid.php
22 * @author Gabor de Mooij and the RedBeanPHP community
26 * copyright (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community
27 * This source file is subject to the BSD/GPLv2 License that is bundled
28 * with this source code in the file license.txt.
30 class Fluid extends Repository
33 * Figures out the desired type given the cast string ID.
34 * Given a cast ID, this method will return the associated
35 * type (INT(10) or VARCHAR for instance). The returned type
36 * can be processed by the Query Writer to build the specified
37 * column for you in the database. The Cast ID is actually just
38 * a superset of the QueryWriter types. In addition to default
39 * Query Writer column types you can pass the following 'cast types':
40 * 'id' and 'string'. These will map to Query Writer specific
41 * column types (probably INT and VARCHAR).
43 * @param string $cast cast identifier
47 private function getTypeFromCast( $cast )
49 if ( $cast == 'string' ) {
50 $typeno = $this->writer->scanType( 'STRING' );
51 } elseif ( $cast == 'id' ) {
52 $typeno = $this->writer->getTypeForID();
53 } elseif ( isset( $this->writer->sqltype_typeno[$cast] ) ) {
54 $typeno = $this->writer->sqltype_typeno[$cast];
56 throw new RedException( 'Invalid Cast' );
63 * Orders the Query Writer to create a table if it does not exist already and
64 * adds a note in the build report about the creation.
66 * @param OODBBean $bean bean to update report of
67 * @param string $table table to check and create if not exists
71 private function createTableIfNotExists( OODBBean $bean, $table )
73 //Does table exist? If not, create
74 if ( !$this->tableExists( $this->writer->esc( $table, TRUE ) ) ) {
75 $this->writer->createTable( $table );
76 $bean->setMeta( 'buildreport.flags.created', TRUE );
81 * Modifies the table to fit the bean data.
82 * Given a property and a value and the bean, this method will
83 * adjust the table structure to fit the requirements of the property and value.
84 * This may include adding a new column or widening an existing column to hold a larger
85 * or different kind of value. This method employs the writer to adjust the table
86 * structure in the database. Schema updates are recorded in meta properties of the bean.
88 * This method will also apply indexes, unique constraints and foreign keys.
90 * @param OODBBean $bean bean to get cast data from and store meta in
91 * @param string $property property to store
92 * @param mixed $value value to store
96 private function modifySchema( OODBBean $bean, $property, $value )
99 $table = $bean->getMeta( 'type' );
100 $columns = $this->writer->getColumns( $table );
101 $columnNoQ = $this->writer->esc( $property, TRUE );
102 if ( !$this->oodb->isChilled( $bean->getMeta( 'type' ) ) ) {
103 if ( $bean->getMeta( "cast.$property", -1 ) !== -1 ) { //check for explicitly specified types
104 $cast = $bean->getMeta( "cast.$property" );
105 $typeno = $this->getTypeFromCast( $cast );
108 $typeno = $this->writer->scanType( $value, TRUE );
110 if ( isset( $columns[$this->writer->esc( $property, TRUE )] ) ) { //Is this property represented in the table ?
111 if ( !$cast ) { //rescan without taking into account special types >80
112 $typeno = $this->writer->scanType( $value, FALSE );
114 $sqlt = $this->writer->code( $columns[$this->writer->esc( $property, TRUE )] );
115 if ( $typeno > $sqlt ) { //no, we have to widen the database column type
116 $this->writer->widenColumn( $table, $property, $typeno );
117 $bean->setMeta( 'buildreport.flags.widen', TRUE );
121 $this->writer->addColumn( $table, $property, $typeno );
122 $bean->setMeta( 'buildreport.flags.addcolumn', TRUE );
126 if (strrpos($columnNoQ, '_id')===(strlen($columnNoQ)-3)) {
127 $destinationColumnNoQ = substr($columnNoQ, 0, strlen($columnNoQ)-3);
128 $indexName = "index_foreignkey_{$table}_{$destinationColumnNoQ}";
129 $this->writer->addIndex($table, $indexName, $columnNoQ);
130 $typeof = $bean->getMeta("sys.typeof.{$destinationColumnNoQ}", $destinationColumnNoQ);
131 $isLink = $bean->getMeta( 'sys.buildcommand.unique', FALSE );
132 //Make FK CASCADING if part of exclusive list (dependson=typeof) or if link bean
133 $isDep = ( $bean->moveMeta( 'sys.buildcommand.fkdependson' ) === $typeof || is_array( $isLink ) );
134 $result = $this->writer->addFK( $table, $typeof, $columnNoQ, 'id', $isDep );
135 //If this is a link bean and all unique columns have been added already, then apply unique constraint
136 if ( is_array( $isLink ) && !count( array_diff( $isLink, array_keys( $this->writer->getColumns( $table ) ) ) ) ) {
137 $this->writer->addUniqueConstraint( $table, $bean->moveMeta('sys.buildcommand.unique') );
138 $bean->setMeta("sys.typeof.{$destinationColumnNoQ}", NULL);
146 * Part of the store() functionality.
147 * Handles all new additions after the bean has been saved.
148 * Stores addition bean in own-list, extracts the id and
149 * adds a foreign key. Also adds a constraint in case the type is
150 * in the dependent list.
152 * Note that this method raises a custom exception if the bean
153 * is not an instance of OODBBean. Therefore it does not use
154 * a type hint. This allows the user to take action in case
155 * invalid objects are passed in the list.
157 * @param OODBBean $bean bean to process
158 * @param array $ownAdditions list of addition beans in own-list
162 protected function processAdditions( $bean, $ownAdditions )
164 $beanType = $bean->getMeta( 'type' );
166 foreach ( $ownAdditions as $addition ) {
167 if ( $addition instanceof OODBBean ) {
169 $myFieldLink = $beanType . '_id';
170 $alias = $bean->getMeta( 'sys.alias.' . $addition->getMeta( 'type' ) );
171 if ( $alias ) $myFieldLink = $alias . '_id';
173 $addition->$myFieldLink = $bean->id;
174 $addition->setMeta( 'cast.' . $myFieldLink, 'id' );
177 $addition->setMeta( "sys.typeof.{$alias}", $beanType );
179 $addition->setMeta( "sys.typeof.{$beanType}", $beanType );
182 $this->store( $addition );
184 throw new RedException( 'Array may only contain OODBBeans' );
190 * Stores a cleaned bean; i.e. only scalar values. This is the core of the store()
191 * method. When all lists and embedded beans (parent objects) have been processed and
192 * removed from the original bean the bean is passed to this method to be stored
195 * @param OODBBean $bean the clean bean
199 protected function storeBean( OODBBean $bean )
201 if ( $bean->getMeta( 'changed' ) ) {
202 $this->check( $bean );
203 $table = $bean->getMeta( 'type' );
204 $this->createTableIfNotExists( $bean, $table );
206 $updateValues = array();
207 foreach ( $bean as $property => $value ) {
208 if ( $property !== 'id' ) {
209 $this->modifySchema( $bean, $property, $value );
211 if ( $property !== 'id' ) {
212 $updateValues[] = array( 'property' => $property, 'value' => $value );
216 $bean->id = $this->writer->updateRecord( $table, $updateValues, $bean->id );
217 $bean->setMeta( 'changed', FALSE );
219 $bean->setMeta( 'tainted', FALSE );
223 * Handles exceptions. Suppresses exceptions caused by missing structures.
225 * @param Exception $exception exception
229 protected function handleException( \Exception $exception )
231 if ( !$this->writer->sqlStateIn( $exception->getSQLState(),
233 QueryWriter::C_SQLSTATE_NO_SUCH_TABLE,
234 QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN ) )
241 * Dispenses a new bean (a OODBBean Bean Object)
242 * of the specified type. Always
243 * use this function to get an empty bean object. Never
244 * instantiate a OODBBean yourself because it needs
245 * to be configured before you can use it with RedBean. This
246 * function applies the appropriate initialization /
247 * configuration for you.
249 * @param string $type type of bean you want to dispense
250 * @param string $number number of beans you would like to get
251 * @param boolean $alwaysReturnArray if TRUE always returns the result as an array
255 public function dispense( $type, $number = 1, $alwaysReturnArray = FALSE )
257 $OODBBEAN = defined( 'REDBEAN_OODBBEAN_CLASS' ) ? REDBEAN_OODBBEAN_CLASS : '\RedBeanPHP\OODBBean';
259 for ( $i = 0; $i < $number; $i++ ) {
260 $bean = new $OODBBEAN;
261 $bean->initializeForDispense( $type, $this->oodb->getBeanHelper() );
262 $this->check( $bean );
263 $this->oodb->signal( 'dispense', $bean );
267 return ( count( $beans ) === 1 && !$alwaysReturnArray ) ? array_pop( $beans ) : $beans;
271 * Loads a bean from the object database.
272 * It searches for a OODBBean Bean Object in the
273 * database. It does not matter how this bean has been stored.
274 * RedBean uses the primary key ID $id and the string $type
275 * to find the bean. The $type specifies what kind of bean you
276 * are looking for; this is the same type as used with the
277 * dispense() function. If RedBean finds the bean it will return
278 * the OODB Bean object; if it cannot find the bean
279 * RedBean will return a new bean of type $type and with
280 * primary key ID 0. In the latter case it acts basically the
281 * same as dispense().
284 * If the bean cannot be found in the database a new bean of
285 * the specified type will be generated and returned.
287 * @param string $type type of bean you want to load
288 * @param integer $id ID of the bean you want to load
292 public function load( $type, $id )
294 $bean = $this->dispense( $type );
295 if ( isset( $this->stash[$this->nesting][$id] ) ) {
296 $row = $this->stash[$this->nesting][$id];
299 $rows = $this->writer->queryRecord( $type, array( 'id' => array( $id ) ) );
300 } catch ( SQLException $exception ) {
301 if ( $this->writer->sqlStateIn( $exception->getSQLState(),
303 QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
304 QueryWriter::C_SQLSTATE_NO_SUCH_TABLE )
310 if ( empty( $rows ) ) {
313 $row = array_pop( $rows );
315 $bean->importRow( $row );
317 $this->oodb->signal( 'open', $bean );
320 return $bean->setMeta( 'tainted', FALSE );