Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Y
yii2bootstrap
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
夏彬
yii2bootstrap
Commits
f642caf1
Commit
f642caf1
authored
Feb 01, 2013
by
Carsten Brandt
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
redis db backend WIP
parent
0f6eda37
Changes
7
Expand all
Hide whitespace changes
Inline
Side-by-side
Showing
7 changed files
with
1281 additions
and
0 deletions
+1281
-0
ActiveQuery.php
framework/db/redis/ActiveQuery.php
+172
-0
ActiveRecord.php
framework/db/redis/ActiveRecord.php
+145
-0
ActiveRelation.php
framework/db/redis/ActiveRelation.php
+23
-0
Command.php
framework/db/redis/Command.php
+567
-0
Connection.php
framework/db/redis/Connection.php
+248
-0
Transaction.php
framework/db/redis/Transaction.php
+91
-0
schema.md
framework/db/redis/schema.md
+35
-0
No files found.
framework/db/redis/ActiveQuery.php
0 → 100644
View file @
f642caf1
<?php
/**
* ActiveRecord class file.
*
* @author Carsten Brandt <mail@cebe.cc>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace
yii\db\redis
;
/**
* ActiveRecord is the base class for classes representing relational data in terms of objects.
*
*
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
class
ActiveQuery
extends
\yii\db\ActiveQuery
{
/**
* Executes query and returns all results as an array.
* @return array the query results. If the query results in nothing, an empty array will be returned.
*/
public
function
all
()
{
$command
=
$this
->
createCommand
();
$rows
=
$command
->
queryAll
();
if
(
$rows
!==
array
())
{
$models
=
$this
->
createModels
(
$rows
);
if
(
!
empty
(
$this
->
with
))
{
$this
->
populateRelations
(
$models
,
$this
->
with
);
}
return
$models
;
}
else
{
return
array
();
}
}
/**
* Executes query and returns a single row of result.
* @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
* the query result may be either an array or an ActiveRecord object. Null will be returned
* if the query results in nothing.
*/
public
function
one
()
{
$command
=
$this
->
createCommand
();
$row
=
$command
->
queryRow
();
if
(
$row
!==
false
&&
!
$this
->
asArray
)
{
/** @var $class ActiveRecord */
$class
=
$this
->
modelClass
;
$model
=
$class
::
create
(
$row
);
if
(
!
empty
(
$this
->
with
))
{
$models
=
array
(
$model
);
$this
->
populateRelations
(
$models
,
$this
->
with
);
$model
=
$models
[
0
];
}
return
$model
;
}
else
{
return
$row
===
false
?
null
:
$row
;
}
}
/**
* Returns the number of records.
* @param string $q the COUNT expression. Defaults to '*'.
* Make sure you properly quote column names.
* @return integer number of records
*/
public
function
count
(
$q
=
'*'
)
{
$this
->
select
=
array
(
"COUNT(
$q
)"
);
return
$this
->
createCommand
()
->
queryScalar
();
}
/**
* Returns the sum of the specified column values.
* @param string $q the column name or expression.
* Make sure you properly quote column names.
* @return integer the sum of the specified column values
*/
public
function
sum
(
$q
)
{
$this
->
select
=
array
(
"SUM(
$q
)"
);
return
$this
->
createCommand
()
->
queryScalar
();
}
/**
* Returns the average of the specified column values.
* @param string $q the column name or expression.
* Make sure you properly quote column names.
* @return integer the average of the specified column values.
*/
public
function
average
(
$q
)
{
$this
->
select
=
array
(
"AVG(
$q
)"
);
return
$this
->
createCommand
()
->
queryScalar
();
}
/**
* Returns the minimum of the specified column values.
* @param string $q the column name or expression.
* Make sure you properly quote column names.
* @return integer the minimum of the specified column values.
*/
public
function
min
(
$q
)
{
$this
->
select
=
array
(
"MIN(
$q
)"
);
return
$this
->
createCommand
()
->
queryScalar
();
}
/**
* Returns the maximum of the specified column values.
* @param string $q the column name or expression.
* Make sure you properly quote column names.
* @return integer the maximum of the specified column values.
*/
public
function
max
(
$q
)
{
$this
->
select
=
array
(
"MAX(
$q
)"
);
return
$this
->
createCommand
()
->
queryScalar
();
}
/**
* Returns the query result as a scalar value.
* The value returned will be the first column in the first row of the query results.
* @return string|boolean the value of the first column in the first row of the query result.
* False is returned if the query result is empty.
*/
public
function
scalar
()
{
return
$this
->
createCommand
()
->
queryScalar
();
}
/**
* Returns a value indicating whether the query result contains any row of data.
* @return boolean whether the query result contains any row of data.
*/
public
function
exists
()
{
$this
->
select
=
array
(
new
Expression
(
'1'
));
return
$this
->
scalar
()
!==
false
;
}
/**
* Creates a DB command that can be used to execute this query.
* @param Connection $db the DB connection used to create the DB command.
* If null, the DB connection returned by [[modelClass]] will be used.
* @return Command the created DB command instance.
*/
public
function
createCommand
(
$db
=
null
)
{
/** @var $modelClass ActiveRecord */
$modelClass
=
$this
->
modelClass
;
if
(
$db
===
null
)
{
$db
=
$modelClass
::
getDb
();
}
if
(
$this
->
sql
===
null
)
{
if
(
$this
->
from
===
null
)
{
$tableName
=
$modelClass
::
tableName
();
$this
->
from
=
array
(
$tableName
);
}
/** @var $qb QueryBuilder */
$qb
=
$db
->
getQueryBuilder
();
$this
->
sql
=
$qb
->
build
(
$this
);
}
return
$db
->
createCommand
(
$this
->
sql
,
$this
->
params
);
}
}
framework/db/redis/ActiveRecord.php
0 → 100644
View file @
f642caf1
<?php
/**
* ActiveRecord class file.
*
* @author Carsten Brandt <mail@cebe.cc>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace
yii\db\redis
;
/**
* ActiveRecord is the base class for classes representing relational data in terms of objects.
*
* @include @yii/db/ActiveRecord.md
*
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
abstract
class
ActiveRecord
extends
\yii\db\ActiveRecord
{
/**
* Returns the list of all attribute names of the model.
* The default implementation will return all column names of the table associated with this AR class.
* @return array list of attribute names.
*/
public
function
attributes
()
{
return
array
();
}
/**
* Returns the database connection used by this AR class.
* By default, the "db" application component is used as the database connection.
* You may override this method if you want to use a different database connection.
* @return Connection the database connection used by this AR class.
*/
public
static
function
getDb
()
{
// TODO
return
\Yii
::
$application
->
getDb
();
}
/**
* Creates an [[ActiveQuery]] instance for query purpose.
*
* @include @yii/db/ActiveRecord-find.md
*
* @param mixed $q the query parameter. This can be one of the followings:
*
* - a scalar value (integer or string): query by a single primary key value and return the
* corresponding record.
* - an array of name-value pairs: query by a set of column values and return a single record matching all of them.
* - null: return a new [[ActiveQuery]] object for further query purpose.
*
* @return ActiveQuery|ActiveRecord|null When `$q` is null, a new [[ActiveQuery]] instance
* is returned; when `$q` is a scalar or an array, an ActiveRecord object matching it will be
* returned (null will be returned if there is no matching).
* @see createQuery()
*/
public
static
function
find
(
$q
=
null
)
{
// TODO
$query
=
static
::
createQuery
();
if
(
is_array
(
$q
))
{
return
$query
->
where
(
$q
)
->
one
();
}
elseif
(
$q
!==
null
)
{
// query by primary key
$primaryKey
=
static
::
primaryKey
();
return
$query
->
where
(
array
(
$primaryKey
[
0
]
=>
$q
))
->
one
();
}
return
$query
;
}
/**
* Creates an [[ActiveQuery]] instance with a given SQL statement.
*
* Note that because the SQL statement is already specified, calling additional
* query modification methods (such as `where()`, `order()`) on the created [[ActiveQuery]]
* instance will have no effect. However, calling `with()`, `asArray()` or `indexBy()` is
* still fine.
*
* Below is an example:
*
* ~~~
* $customers = Customer::findBySql('SELECT * FROM tbl_customer')->all();
* ~~~
*
* @param string $sql the SQL statement to be executed
* @param array $params parameters to be bound to the SQL statement during execution.
* @return ActiveQuery the newly created [[ActiveQuery]] instance
*/
public
static
function
findBySql
(
$sql
,
$params
=
array
())
{
$query
=
static
::
createQuery
();
$query
->
sql
=
$sql
;
return
$query
->
params
(
$params
);
}
/**
* Creates an [[ActiveQuery]] instance.
* This method is called by [[find()]], [[findBySql()]] and [[count()]] to start a SELECT query.
* You may override this method to return a customized query (e.g. `CustomerQuery` specified
* written for querying `Customer` purpose.)
* @return ActiveQuery the newly created [[ActiveQuery]] instance.
*/
public
static
function
createQuery
()
{
return
new
ActiveQuery
(
array
(
'modelClass'
=>
get_called_class
(),
));
}
/**
* Returns the schema information of the DB table associated with this AR class.
* @return TableSchema the schema information of the DB table associated with this AR class.
*/
public
static
function
getTableSchema
()
{
return
static
::
getDb
()
->
getTableSchema
(
static
::
tableName
());
}
/**
* Returns the primary key name(s) for this AR class.
* The default implementation will return the primary key(s) as declared
* in the DB table that is associated with this AR class.
*
* If the DB table does not declare any primary key, you should override
* this method to return the attributes that you want to use as primary keys
* for this AR class.
*
* Note that an array should be returned even for a table with single primary key.
*
* @return string[] the primary keys of the associated database table.
*/
public
static
function
primaryKey
()
{
return
static
::
getTableSchema
()
->
primaryKey
;
}
}
framework/db/redis/ActiveRelation.php
0 → 100644
View file @
f642caf1
<?php
/**
* ActiveRecord class file.
*
* @author Carsten Brandt <mail@cebe.cc>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace
yii\db\redis
;
/**
* ActiveRecord is the base class for classes representing relational data in terms of objects.
*
*
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
class
ActiveRelation
extends
\yii\db\ActiveRelation
{
}
framework/db/redis/Command.php
0 → 100644
View file @
f642caf1
This diff is collapsed.
Click to expand it.
framework/db/redis/Connection.php
0 → 100644
View file @
f642caf1
<?php
/**
* Connection class file
*
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace
yii\db\redis
;
use
\yii\base\Component
;
use
yii\base\NotSupportedException
;
use
yii\base\InvalidConfigException
;
use
\yii\db\Exception
;
/**
*
*
*
*
* @since 2.0
*/
class
Connection
extends
Component
{
/**
* @event Event an event that is triggered after a DB connection is established
*/
const
EVENT_AFTER_OPEN
=
'afterOpen'
;
/**
* @var string the Data Source Name, or DSN, contains the information required to connect to the database.
* DSN format: redis://[auth@][server][:port][/db]
* @see charset
*/
public
$dsn
;
/**
* @var string the username for establishing DB connection. Defaults to empty string.
*/
public
$username
=
''
;
/**
* @var string the password for establishing DB connection. Defaults to empty string.
*/
public
$password
=
''
;
/**
* @var \Jamm\Memory\RedisServer
*/
public
$redis
;
/**
* @var boolean whether to enable profiling for the SQL statements being executed.
* Defaults to false. This should be mainly enabled and used during development
* to find out the bottleneck of SQL executions.
* @see getStats
*/
public
$enableProfiling
=
false
;
/**
* @var string the common prefix or suffix for table names. If a table name is given
* as `{{%TableName}}`, then the percentage character `%` will be replaced with this
* property value. For example, `{{%post}}` becomes `{{tbl_post}}` if this property is
* set as `"tbl_"`. Note that this property is only effective when [[enableAutoQuoting]]
* is true.
* @see enableAutoQuoting
*/
public
$keyPrefix
;
/**
* @var Transaction the currently active transaction
*/
private
$_transaction
;
/**
* Closes the connection when this component is being serialized.
* @return array
*/
public
function
__sleep
()
{
$this
->
close
();
return
array_keys
(
get_object_vars
(
$this
));
}
/**
* Returns a value indicating whether the DB connection is established.
* @return boolean whether the DB connection is established
*/
public
function
getIsActive
()
{
return
$this
->
redis
!==
null
;
}
/**
* Establishes a DB connection.
* It does nothing if a DB connection has already been established.
* @throws Exception if connection fails
*/
public
function
open
()
{
if
(
$this
->
redis
===
null
)
{
if
(
empty
(
$this
->
dsn
))
{
throw
new
InvalidConfigException
(
'Connection.dsn cannot be empty.'
);
}
// TODO parse DSN
$host
=
'localhost'
;
$port
=
6379
;
try
{
\Yii
::
trace
(
'Opening DB connection: '
.
$this
->
dsn
,
__CLASS__
);
// TODO connection to redis seems to be very easy, consider writing own connect
$this
->
redis
=
new
\Jamm\Memory\RedisServer
(
$host
,
$port
);
$this
->
initConnection
();
}
catch
(
\PDOException
$e
)
{
\Yii
::
error
(
"Failed to open DB connection (
{
$this
->
dsn
}
): "
.
$e
->
getMessage
(),
__CLASS__
);
$message
=
YII_DEBUG
?
'Failed to open DB connection: '
.
$e
->
getMessage
()
:
'Failed to open DB connection.'
;
throw
new
Exception
(
$message
,
(
int
)
$e
->
getCode
(),
$e
->
errorInfo
);
}
}
}
/**
* Closes the currently active DB connection.
* It does nothing if the connection is already closed.
*/
public
function
close
()
{
if
(
$this
->
redis
!==
null
)
{
\Yii
::
trace
(
'Closing DB connection: '
.
$this
->
dsn
,
__CLASS__
);
$this
->
redis
=
null
;
$this
->
_transaction
=
null
;
}
}
/**
* Initializes the DB connection.
* This method is invoked right after the DB connection is established.
* The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
* if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
* It then triggers an [[EVENT_AFTER_OPEN]] event.
*/
protected
function
initConnection
()
{
$this
->
trigger
(
self
::
EVENT_AFTER_OPEN
);
}
/**
* Creates a command for execution.
* @param string $query the SQL statement to be executed
* @param array $params the parameters to be bound to the SQL statement
* @return Command the DB command
*/
public
function
createCommand
(
$query
=
null
,
$params
=
array
())
{
$this
->
open
();
$command
=
new
Command
(
array
(
'db'
=>
$this
,
'query'
=>
$query
,
));
return
$command
->
addValues
(
$params
);
}
/**
* Returns the currently active transaction.
* @return Transaction the currently active transaction. Null if no active transaction.
*/
public
function
getTransaction
()
{
return
$this
->
_transaction
&&
$this
->
_transaction
->
isActive
?
$this
->
_transaction
:
null
;
}
/**
* Starts a transaction.
* @return Transaction the transaction initiated
*/
public
function
beginTransaction
()
{
$this
->
open
();
$this
->
_transaction
=
new
Transaction
(
array
(
'db'
=>
$this
,
));
$this
->
_transaction
->
begin
();
return
$this
->
_transaction
;
}
/**
* Returns the schema information for the database opened by this connection.
* @return Schema the schema information for the database opened by this connection.
* @throws NotSupportedException if there is no support for the current driver type
*/
public
function
getSchema
()
{
$driver
=
$this
->
getDriverName
();
throw
new
NotSupportedException
(
"Connection does not support reading schema information for '
$driver
' DBMS."
);
}
/**
* Returns the query builder for the current DB connection.
* @return QueryBuilder the query builder for the current DB connection.
*/
public
function
getQueryBuilder
()
{
return
$this
->
getSchema
()
->
getQueryBuilder
();
}
/**
* Obtains the schema information for the named table.
* @param string $name table name.
* @param boolean $refresh whether to reload the table schema even if it is found in the cache.
* @return TableSchema table schema information. Null if the named table does not exist.
*/
public
function
getTableSchema
(
$name
,
$refresh
=
false
)
{
return
$this
->
getSchema
()
->
getTableSchema
(
$name
,
$refresh
);
}
/**
* Returns the name of the DB driver for the current [[dsn]].
* @return string name of the DB driver
*/
public
function
getDriverName
()
{
if
((
$pos
=
strpos
(
$this
->
dsn
,
':'
))
!==
false
)
{
return
strtolower
(
substr
(
$this
->
dsn
,
0
,
$pos
));
}
else
{
return
'redis'
;
}
}
/**
* Returns the statistical results of SQL queries.
* The results returned include the number of SQL statements executed and
* the total time spent.
* In order to use this method, [[enableProfiling]] has to be set true.
* @return array the first element indicates the number of SQL statements executed,
* and the second element the total time spent in SQL execution.
* @see \yii\logging\Logger::getProfiling()
*/
public
function
getQuerySummary
()
{
$logger
=
\Yii
::
getLogger
();
$timings
=
$logger
->
getProfiling
(
array
(
'yii\db\Command::query'
,
'yii\db\Command::execute'
));
$count
=
count
(
$timings
);
$time
=
0
;
foreach
(
$timings
as
$timing
)
{
$time
+=
$timing
[
1
];
}
return
array
(
$count
,
$time
);
}
}
framework/db/redis/Transaction.php
0 → 100644
View file @
f642caf1
<?php
/**
* Transaction class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace
yii\db\redis
;
use
yii\base\InvalidConfigException
;
use
yii\db\Exception
;
/**
* Transaction represents a DB transaction.
*
* @property boolean $isActive Whether the transaction is active. This property is read-only.
*
* @since 2.0
*/
class
Transaction
extends
\yii\base\Object
{
/**
* @var Connection the database connection that this transaction is associated with.
*/
public
$db
;
/**
* @var boolean whether this transaction is active. Only an active transaction
* can [[commit()]] or [[rollBack()]]. This property is set true when the transaction is started.
*/
private
$_active
=
false
;
/**
* Returns a value indicating whether this transaction is active.
* @return boolean whether this transaction is active. Only an active transaction
* can [[commit()]] or [[rollBack()]].
*/
public
function
getIsActive
()
{
return
$this
->
_active
;
}
/**
* Begins a transaction.
* @throws InvalidConfigException if [[connection]] is null
*/
public
function
begin
()
{
if
(
!
$this
->
_active
)
{
if
(
$this
->
db
===
null
)
{
throw
new
InvalidConfigException
(
'Transaction::db must be set.'
);
}
\Yii
::
trace
(
'Starting transaction'
,
__CLASS__
);
$this
->
db
->
open
();
$this
->
db
->
createCommand
(
'MULTI'
)
->
execute
();
$this
->
_active
=
true
;
}
}
/**
* Commits a transaction.
* @throws Exception if the transaction or the DB connection is not active.
*/
public
function
commit
()
{
if
(
$this
->
_active
&&
$this
->
db
&&
$this
->
db
->
isActive
)
{
\Yii
::
trace
(
'Committing transaction'
,
__CLASS__
);
$this
->
db
->
createCommand
(
'EXEC'
)
->
execute
();
// TODO handle result of EXEC
$this
->
_active
=
false
;
}
else
{
throw
new
Exception
(
'Failed to commit transaction: transaction was inactive.'
);
}
}
/**
* Rolls back a transaction.
* @throws Exception if the transaction or the DB connection is not active.
*/
public
function
rollback
()
{
if
(
$this
->
_active
&&
$this
->
db
&&
$this
->
db
->
isActive
)
{
\Yii
::
trace
(
'Rolling back transaction'
,
__CLASS__
);
$this
->
db
->
pdo
->
commit
();
$this
->
_active
=
false
;
}
else
{
throw
new
Exception
(
'Failed to roll back transaction: transaction was inactive.'
);
}
}
}
framework/db/redis/schema.md
0 → 100644
View file @
f642caf1
To allow AR to be stored in redis we need a special Schema for it.
HSET prefix:className:primaryKey
http://redis.io/commands
Current Redis connection:
https://github.com/jamm/Memory
# Queries
wrap all these in transactions MULTI
## insert
SET all attribute key-value pairs
SET all relation key-value pairs
make sure to create back-relations
## update
SET all attribute key-value pairs
SET all relation key-value pairs
## delete
DEL all attribute key-value pairs
DEL all relation key-value pairs
make sure to update back-relations
http://redis.io/commands/hmget sounds suiteable!
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment