GithubHelp home page GithubHelp logo

go-db's Introduction

go\DB: работа с различными БД из PHP

Latest Stable Version Minimum PHP Version Build Status Coverage Status License

logo

Установка

Документация

Форматы данных

Дополнительно

Поддерживаемые адаптеры

Отдельное спасибо

  • Dallone aka Алексей Полев, за адаптер PgSQL

go-db's People

Contributors

apolev avatar mkedo avatar steadyua avatar vasa-c 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

Watchers

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

go-db's Issues

Плейсхолдер ?w с параметром true,false,null или array() генерирует условие не работающее в PostgreSQL

$db->query('SELECT "schema_name" FROM "information_schema"."schemata" WHERE ?w', array( array() ));
//  "SELECT "schema_name" FROM "information_schema"."schemata" WHERE 1"; 
//  error="ERROR:  argument of WHERE must be type boolean, not type integer


$db->query("SET search_path TO information_schema");
$table = new go\DB\Table($db, 'schemata');
$table->select(array('schema_name') );

// "SELECT "schema_name" FROM "schemata" WHERE 1"; 
//  error="ERROR:  argument of WHERE must be type boolean, not type integer

Placeholder ?where

array(
    'a' => 1,
    'b' => 2,
    'c' => array(3, 4, 5),
);

?where:

WHERE `a`=1 AND `b`=2 AND `c` IN (3, 4, 5)

empty array => WHERE 1

Table

$table = $db->getTable('tablename');

$table->select($cols, $where)->assoc();
$table->delete($where);
$table->getCount();

?order

ORDER BY ?o
ORDER BY ?order

scalar: id - id ASC
list: ['a','b'] - a ASC, b ASC
dict: ['a' => true, 'b' => false] - a ASC, b DESC

autoreplace {} (Even if there is no prefix)

/* Замена {table} */
        if($this->prefix) {
            $query = \preg_replace_callback('~{(.*?)}~', array($this, 'tableClb'), $this->pattern);
        }else{
            $query=$this->pattern;
        }

lifehack

Data elements less then placeholders

Hi, на одном сервере обновил php с 5.3 до 5.4 с сохранением списка расширений, но godb теперь ругается на сабж. В коде ничего не менялось, подключение:

$db = go\DB\Storage::getInstance()->create($this->params);

далее я делаю запросы через

go\DB\query("SELECT * FROM ?t WHERE id=?i LIMIT 1", array('forms', $id), 'row')

но почему-то массив с data пустой
вотафак?

конфиг пхп:

PHP 5.4.38 (cli) (built: Mar  8 2015 15:03:16) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies
    with eAccelerator v1.0-dev, Copyright (c) 2004-2012 eAccelerator, by eAccelerator

[PHP Modules]
bz2
Core
ctype
curl
date
dom
eAccelerator
ereg
filter
gd
hash
iconv
json
libxml
mbstring
mhash
mysql
mysqli
mysqlnd
pcre
PDO
pdo_mysql
Phar
posix
Reflection
session
SimpleXML
soap
SPL
standard
tokenizer
xml
xmlreader
xmlrpc
xmlwriter
zip
zlib

[Zend Modules]
eAccelerator

\go\DB\Exceptions\Query::getErrorCode() возвращает NULL

try {
//.. запрос с ошибкой
} catch (\go\DB\Exceptions\Query $e){
var_dump($e->getErrorCode()); //NULL
var_dump($e->getCode()); // Здесь возвращает нужный
}

В конструкторе не устанавливается $this->errorcode = (int)$errorcode;

Pre-queries

Configuration queries executed only when connected

Небуферизированные запросы

Привет,

насколько мне удалось изучить документацию и код, сейчас нет возможности выполнить небуферизированный запрос.
Для Mysql это MYSQLI_USE_RESULT при mysqli::query, для Mysqlold это mysql_unbuffered_query и т.д.
Это очень полезно если запросы возвращают большие объемы данных, например при дампе таблиц и пр.
Были ли мысли добавить такой функционал, и если да то как, я бы мог помочь с реализацией если необходимо.

Pgsql driver, не устанавливается параметр host

$params = array(
'host' => 'localhost', // <-- игнорируется
'username' => 'test',
'password' => 'test',
'dbname' => 'test',
'charset' => 'utf8',
'_debug' => true,
'_prefix' => '',
);

$db = go\DB\DB::create($params, 'pgsql');
// З.Ы. Я заметил что, все параметры которые не указаны в $paramsDefault (Implementations/Pgsql)
// отбрасываются. У postgresql параметров подключения несколько больше
// http://www.postgresql.org/docs/9.1/interactive/libpq-connect.html

Fatal error: Wrong parameters for Exception (pgsql, wrong password)

Fatal error: Wrong parameters for Exception([string $exception [, long $code [, Exception $previous = NULL]]]) in /.../goDB/Exceptions/Runtime.php on line 24

var_dump($message, $code, $previous); //
array(4) { ["type"]=> int(2) ["message"]=> string(118) "pg_connect(): Unable to connect to PostgreSQL server: FATAL: Peer authentication failed for user "postgres"" ["file"]=> string(64) "/.../goDB/Implementations/Pgsql.php" ["line"]=> int(48) } NULL NULL

Extended Table format

'name' -> `prefix_name`
['db' => 'dbname', 'table' => 'name'] -> `dname`.`prefix_table`
['one', 'two', 'three'] -> `one`.`two`.`prefix_three`

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.