IBM DB2 Embedded SQL for PHPАлександр Веремьевcawaspb@gmail.com
Что такоевстраиваемый SQL      ?????
$dbname = db_name;$dbuser = username;$dbpwd = password;EXEC SQL connect to :$dbname user :$dbuser using :$dbpwd;...$userid...
EXEC SQL DECLARE c1 CURSOR for  select id, time, subject, message    from emails    where userid = :$userid AND status = N...
Часть SQL-92 стандартаНепосредственная поддержка со стороны СУБД в тех или иныхязыках:- IBM DB2 (C/C++, Java, COBOL, FORTR...
IBM DB2 Embedded SQL for PHP support:PHP extension db2_embsqldb2_embsql_precompile($input_file, $dbname, $options_string);...
Особенности реализации встроенного SQL в IBM DB2.    Static SQL.<?php                                                     ...
<?php/** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this p...
Статический SQL.- отсутствие повторной компиляции, использование готового планавыполнения (отличные результаты на OLTP наг...
Связывание типов.              PHP                              SQL- динамическая типизация        - статическая типизация...
Связывание типов.          PHP                 SQL    $var1 (integer)                      SELECT … INTO :$var1 …    …    ...
Связывание типов, C/C++:EXEC SQL BEGIN DECLARE SECTION;  char dbName[16];  char userid[30];  char passwd[30];  SQL TYPE IS...
db2_embsql extension:1. Декларативность секции   EXEC SQL BEGIN DECLARE SECTION;   …   EXEC SQL END DECLARE SECTION;2. Физ...
3. Маппинг имѐн host variables (и производных lvalue конструкций)   на внутренние имена HV в SQL выражениях, отправляемых ...
Маппинг типов:SMALLINT (16-bit integer)   -   integrerINTEGER (32-bit integer)    -   integrerBIGINT   (64-bit integer)   ...
Решение проблемы предугадывания типов, input/output variables:EXEC SQL SELECT LOGIN, FIRSTNAME, LASTNAME          INTO :$l...
Декларация “базовых” переменных:EXEC SQL BEGIN DECLARE SECTION;        VARCHAR(32) $login;        VARCHAR(64) $firstname, ...
Декларация “производных” переменных:EXEC SQL BEGIN DECLARE SECTION;        VARCHAR(32) $this->login;        VARCHAR(64) $t...
Как работают вызовы SQL statements:<?php/** * Zend Framework *                                                            ...
пример прекомпилированного С кода:/*EXEC SQL select count(*) into :tbl_cnt   from   syscat.tables;*/{#line 39 "dbconn.sqc"...
#line 39 "dbconn.sqc"  sqlacall((unsigned short)24,1,0,3,0L);#line 39 "dbconn.sqc"  sqlastop(0L);}#line 39 "dbconn.sqc" EM...
Архитектура extension’а как магазинного автомата:                                                                         ...
Плюсы:- cтатичность SQL;- отсутствие фазы компиляции запроса на этапе выполнения;- отсутствие фазы построения плана запрос...
Минусы:- cтатичность SQL;- дополнительная фаза - прекомпиляция;- необходимость существования соответствующих объектовбазы ...
Ограничения embedded SQL:- невозможность использования Host variables в именахобъектов имѐн таблиц, функций, процедур, …, ...
IBM DB2 и динамический SQL для PHP:http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/topic/com.ibm.swg.im.dbclient.php....
Способы увеличения производительности динамического SQL:- увеличение размера STATEMENT CACHE – pckacheszимеется некоторая ...
- конвертирование динамического SQL в статический:1. Коллектор запросов (CLI/ODBC параметры):STATICMODE=CAPTURESTATICCAPFI...
Планы- Пре-релиз конец мая – начало июня.- Релиз, передача в Open Source – конец июня.
Embedded SQL            vsORM frameworks/ActiveRecord           ???
ВопросыАлександр Веремьевcawaspb@gmail.com
Upcoming SlideShare
Loading in …5
×

ZFConf 2012: Реализация доступа к СУБД IBM DB2 посредством встраиваемого SQL (Александр Веремьев)

1,319 views

Published on

http://www.zfconf.ru/2012/talks/ibm-db2-embedded-sql-for-php-implementation/

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,319
On SlideShare
0
From Embeds
0
Number of Embeds
334
Actions
Shares
0
Downloads
12
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

ZFConf 2012: Реализация доступа к СУБД IBM DB2 посредством встраиваемого SQL (Александр Веремьев)

  1. 1. IBM DB2 Embedded SQL for PHPАлександр Веремьевcawaspb@gmail.com
  2. 2. Что такоевстраиваемый SQL ?????
  3. 3. $dbname = db_name;$dbuser = username;$dbpwd = password;EXEC SQL connect to :$dbname user :$dbuser using :$dbpwd;...$userid = $_POST[userid];$password = $_POST[password];EXEC SQL select firstname, lastname into :$firstname, :$lastname from users where login = :$userid AND password = :$password;if ($SQLCODE == 100 /* NOT FOUND */) { echo "Wrong login/password combination.n";} else { echo $firstname . "n" . $lastname . "n";}
  4. 4. EXEC SQL DECLARE c1 CURSOR for select id, time, subject, message from emails where userid = :$userid AND status = NEW;EXEC SQL BEGIN DECLARE SECTION; INTEGER $email_id; TMESTAMP $time; VARCHAR(256) $subject; CLOB(16M) $message_body;EXEC SQL END DECLARE SECTION;EXEC SQL OPEN c1;EXEC SQL FETCH c1 into :$email_id, :$time, :$subject, :$message_body;while ($SQLCODE != 100 /* NOT FOUND */) { // process message ... EXEC SQL FETCH c1 into :$email_id, :$time, :$subject, :$message_body;}
  5. 5. Часть SQL-92 стандартаНепосредственная поддержка со стороны СУБД в тех или иныхязыках:- IBM DB2 (C/C++, Java, COBOL, FORTRAN, REXX)- Oracle (Ada, C/C++, COBOL, FORTRAN, Pascal, PL/I)- PostgreSQL (C/C++, COBOL)- Microsof SQL Server (COBOL)- MySQL (COBOL)- Sybase-…
  6. 6. IBM DB2 Embedded SQL for PHP support:PHP extension db2_embsqldb2_embsql_precompile($input_file, $dbname, $options_string);db2_embsql_precompile_string($php_code, $dbname, $options_string);
  7. 7. Особенности реализации встроенного SQL в IBM DB2. Static SQL.<?php <?php/** /** * Zend Framework * Zend Framework * * * LICENSE * LICENSE * * * This source file is subject to the new BSD license that is bundled * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * to license@zend.com so we can send you a copy immediately. * * * @category Zend * @category Zend * @package Zend_Pdf * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Pdf.php 22908 2010-08-25 20:52:47Z alexander $ * @version $Id: Pdf.php 22908 2010-08-25 20:52:47Z alexander $ */ */ /** User land classes and interfaces turned on by Zend/Pdf.php file inclusion. */ DB2/** User land classes and interfaces turned on by Zend/Pdf.php file inclusion. *//** @todo Section should be removed with ZF 2.0 release as obsolete */ /** @todo Section should be removed with ZF 2.0 release as obsolete *//** Zend_Pdf_Page */ /** Zend_Pdf_Page */require_once Zend/Pdf/Page.php; require_once Zend/Pdf/Page.php;/** Zend_Pdf_Canvas */ /** Zend_Pdf_Canvas */require_once Zend/Pdf/Canvas.php; require_once Zend/Pdf/Canvas.php;/** Internally used classes */ /** Internally used classes */require_once Zend/Pdf/Element/Dictionary.php; require_once Zend/Pdf/Element/Dictionary.php;require_once Zend/Pdf/Element/Name.php; require_once Zend/Pdf/Element/Name.php;require_once Zend/Pdf/Element/Null.php; require_once Zend/Pdf/Element/Null.php;require_once Zend/Pdf/Element/Numeric.php; require_once Zend/Pdf/Element/Numeric.php;require_once Zend/Pdf/Element/String.php; require_once Zend/Pdf/Element/String.php;/** /** * General entity which describes PDF document. * General entity which describes PDF document. * It implements document abstraction with a document level operations. * It implements document abstraction with a document level operations. * * * Class is used to create new PDF document or load existing document. * Class is used to create new PDF document or load existing document. * See details in a class constructor description * See details in a class constructor description * * * Class agregates document level properties and entities (pages, bookmarks, * Class agregates document level properties and entities (pages, bookmarks, * document level actions, attachments, form object, etc) * document level actions, attachments, form object, etc) * * * @category Zend * @category Zend * @package Zend_Pdf * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @license http://framework.zend.com/license/new-bsd New BSD License */ */class Zend_Pdf class Zend_Pdf{ { /**** Class Constants ****/ /**** Class Constants ****/ /** /** * Version number of generated PDF documents. * Version number of generated PDF documents. */ */ const PDF_VERSION = 1.4; const PDF_VERSION = 1.4; /** /** * PDF file header. * PDF file header. */ */ const PDF_HEADER = "%PDF-1.4n%xE2xE3xCFxD3n"; /** * * * * Pages collection * /** * @todo implement it as a class, which supports ArrayAccess and Iterator interfaces, * Set user defined memory manager * to provide incremental parsing and pages tree updating. * * That will give good performance and memory (PDF size) benefits. * @param Zend_Memory_Manager $memoryManager * */ * @var array - array of Zend_Pdf_Page object static public function setMemoryManager(Zend_Memory_Manager $memoryManager) */ { public $pages = array(); self::$_memoryManager = $memoryManager; /** } * List of inheritable attributesfor pages tree } * * @var array */ protected static $_inheritableAttributes = array(Resources, MediaBox, CropBox, Rotate); /** * Request used memory manager * * @return Zend_Memory_Manager */ static public function getMemoryManager() { if (self::$_memoryManager === null) { require_once Zend/Memory.php; self::$_memoryManager = Zend_Memory::factory(none); } return self::$_memoryManager; } /** * Set user defined memory manager * * @param Zend_Memory_Manager $memoryManager */ static public function setMemoryManager(Zend_Memory_Manager $memoryManager) { self::$_memoryManager = $memoryManager; } /** * Set the document-level JavaScript * * @param string $javascript */ public function setJavaScript($javascript) { $this->_javaScript = $javascript; } /** * Convert date to PDF format (its close to ASN.1 (Abstract Syntax Notation * One) defined in ISO/IEC 8824). * * @todo This really isnt the best location for this method. It should * probably actually exist as Zend_Pdf_Element_Date or something like that. * * @todo Address the following E_STRICT issue: * PHP Strict Standards: date(): It is not safe to rely on the systems .BND * timezone settings. Please use the date.timezone setting, the TZ * environment variable or the date_default_timezone_set() function. In * case you used any of those methods and you are still getting this * warning, you most likely misspelled the timezone identifier. * * @param integer $timestamp (optional) If omitted, uses the current time. * @return string */ public static function pdfDate($timestamp = null) { if ($timestamp === null) { $date = date(D:YmdHisO); } else { $date = date(D:YmdHisO, $timestamp); } return substr_replace($date, , -2, 0) . ; }}
  8. 8. <?php/** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. PHP код * PHP код * @category Zend * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc.(http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Pdf.php 22908 2010-08-25 20:52:47Z alexander $ *//** User land classes and interfaces turned on by Zend/Pdf.php file inclusion. *//** @todo Section should be removed with ZF 2.0 release as obsolete *//** Zend_Pdf_Page */require_once Zend/Pdf/Page.php;/** Zend_Pdf_Canvas */require_once Zend/Pdf/Canvas.php;/** Internally used classes */require_once Zend/Pdf/Element/Dictionary.php;require_once Zend/Pdf/Element/Name.php;require_once Zend/Pdf/Element/Null.php;require_once Zend/Pdf/Element/Numeric.php;require_once Zend/Pdf/Element/String.php;/** * General entity which describes PDF document. * It implements document abstraction with a document level operations. * * Class is used to create new PDF document or load existing document. * See details in a class constructor description * * Class agregates document level properties and entities (pages, bookmarks, * document level actions, attachments, form object, etc) * * @category Zend * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc.(http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */class Zend_Pdf{ /**** Class Constants ****/ /** * Version number of generated PDF documents. */ const PDF_VERSION = 1.4; /** * PDF file header. */ const PDF_HEADER = "%PDF-1.4n%xE2xE3xCFxD3n"; /** * Pages collection * * @todo implement it as a class, which supports ArrayAccess and Iteratorinterfaces, * to provide incremental parsing and pages tree updating. * That will give good performance and memory (PDF size) benefits. * * @var array - array of Zend_Pdf_Page object */ public $pages = array(); /** * List of inheritable attributesfor pages tree * * @var array */ protected static $_inheritableAttributes = array(Resources, MediaBox,CropBox, Rotate); /** * Request used memory manager * * @return Zend_Memory_Manager */ static public function getMemoryManager() { if (self::$_memoryManager === null) { require_once Zend/Memory.php; self::$_memoryManager = Zend_Memory::factory(none); } return self::$_memoryManager; } /** * Set user defined memory manager * * @param Zend_Memory_Manager $memoryManager */ static public function setMemoryManager(Zend_Memory_Manager $memoryManager) { self::$_memoryManager = $memoryManager; } /** * Set the document-level JavaScript * * @param string $javascript */ public function setJavaScript($javascript) { $this->_javaScript = $javascript; } /** * Convert date to PDF format (its close to ASN.1 (Abstract Syntax Notation SQL * One) defined in ISO/IEC 8824). * * @todo This really isnt the best location for this method. It should * probably actually exist as Zend_Pdf_Element_Date or something like that. Компиляция * * @todo Address the following E_STRICT issue: * PHP Strict Standards: date(): It is not safe to rely on the systems * timezone settings. Please use the date.timezone setting, the TZ * environment variable or the date_default_timezone_set() function. In * case you used any of those methods and you are still getting this * warning, you most likely misspelled the timezone identifier. * * @param integer $timestamp (optional) If omitted, uses the current time. * @return string */ public static function pdfDate($timestamp = null) { if ($timestamp === null) { $date = date(D:YmdHisO); } else { $date = date(D:YmdHisO, $timestamp); } return substr_replace($date, , -2, 0) . ; }}
  9. 9. Статический SQL.- отсутствие повторной компиляции, использование готового планавыполнения (отличные результаты на OLTP нагрузке);- защита от SQL injection;- улучшенная модель security.
  10. 10. Связывание типов. PHP SQL- динамическая типизация - статическая типизация- слабая типизация - строгая типизация1 1 поддерживается неявный кастинг для некоторого подмножества типов.
  11. 11. Связывание типов. PHP SQL $var1 (integer) SELECT … INTO :$var1 … … $var1 (string) INSERT INTO … VALUES(:$var1, …) $var2 (float) SELECT … WHERE COL1 > :$var2 $var1 (string)
  12. 12. Связывание типов, C/C++:EXEC SQL BEGIN DECLARE SECTION; char dbName[16]; char userid[30]; char passwd[30]; SQL TYPE IS CLOB(2M) img_data;EXEC SQL END DECLARE SECTION;...EXEC SQL CONNECT TO :dbName USER :userid USING :passwd;
  13. 13. db2_embsql extension:1. Декларативность секции EXEC SQL BEGIN DECLARE SECTION; … EXEC SQL END DECLARE SECTION;2. Физическое размещение HV в модуле extension’а.
  14. 14. 3. Маппинг имѐн host variables (и производных lvalue конструкций) на внутренние имена HV в SQL выражениях, отправляемых на прекомпиляцию. $this->myCoolVariable $values[$index]->val $options[my_cool_option] …
  15. 15. Маппинг типов:SMALLINT (16-bit integer) - integrerINTEGER (32-bit integer) - integrerBIGINT (64-bit integer) - integrerREAL - floatDOUBLE - floatDECIMAL - STRINGCHAR(n) - STRINGCHAR(n) FOR BIT DATA - STRINGVARCHAR(n) - STRINGCLOB(n) - STRINGBLOB(n) - STRINGDATE - STRINGTIME - STRINGTIMESTAMP - STRING...
  16. 16. Решение проблемы предугадывания типов, input/output variables:EXEC SQL SELECT LOGIN, FIRSTNAME, LASTNAME INTO :$login, :$firstname, :$lastname FROM USERS WHERE ID = :$user_id;vsEXEC SQL INSERT INTO USERS VALUES( :$login, :$firstname, :$lastname);
  17. 17. Декларация “базовых” переменных:EXEC SQL BEGIN DECLARE SECTION; VARCHAR(32) $login; VARCHAR(64) $firstname, VARCHAR(64) $lastname;EXEC SQL BEGIN DECLARE SECTION;...$login = $this->login;$firstname = $this->firstname;$lastname = $this->lastname;EXEC SQL INSERT INTO USERS VALUES(:$login, :$firstname, :$lastname);
  18. 18. Декларация “производных” переменных:EXEC SQL BEGIN DECLARE SECTION; VARCHAR(32) $this->login; VARCHAR(64) $this->firstname, VARCHAR(64) $this->lastname;EXEC SQL BEGIN DECLARE SECTION;...EXEC SQL INSERT INTO USERS VALUES( :$this->login, :$this->firstname, :$this->lastname);
  19. 19. Как работают вызовы SQL statements:<?php/** * Zend Framework * DB2 Run Database * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd Time Services Manager SELECT … * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Pdf.php 22908 2010-08-25 20:52:47Z alexander $ *//** User land classes and interfaces turned on by Zend/Pdf.php file inclusion. *//** @todo Section should be removed with ZF 2.0 release as obsolete *//** Zend_Pdf_Page */require_once Zend/Pdf/Page.php;/** Zend_Pdf_Canvas */require_once Zend/Pdf/Canvas.php;/** Internally used classes */require_once Zend/Pdf/Element/Dictionary.php;require_once Zend/Pdf/Element/Name.php; :HV1require_once Zend/Pdf/Element/Null.php;require_once Zend/Pdf/Element/Numeric.php;require_once Zend/Pdf/Element/String.php;/** * General entity which describes PDF document. * It implements document abstraction with a document level operations. * * Class is used to create new PDF document or load existing document. * See details in a class constructor description * * Class agregates document level properties and entities (pages, bookmarks, :HV2 * document level actions, attachments, form object, etc) * * @category Zend * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */class Zend_Pdf{ /**** Class Constants ****/ /** * Version number of generated PDF documents. */ const PDF_VERSION = 1.4; /** * PDF file header. CALL */ const PDF_HEADER = "%PDF-1.4n%xE2xE3xCFxD3n"; /** * Pages collection * * @todo implement it as a class, which supports ArrayAccess and Iterator interfaces, * to provide incremental parsing and pages tree updating. * That will give good performance and memory (PDF size) benefits. * * @var array - array of Zend_Pdf_Page object */ public $pages = array(); /** Packages * List of inheritable attributesfor pages tree Packages * Packages * @var array */ protected static $_inheritableAttributes = array(Resources, MediaBox, CropBox, Rotate); /** * Request used memory manager * * @return Zend_Memory_Manager */ static public function getMemoryManager() { if (self::$_memoryManager === null) { require_once Zend/Memory.php; self::$_memoryManager = Zend_Memory::factory(none); } return self::$_memoryManager; } /** * Set user defined memory manager * * @param Zend_Memory_Manager $memoryManager */ static public function setMemoryManager(Zend_Memory_Manager $memoryManager) { self::$_memoryManager = $memoryManager; } /** * Set the document-level JavaScript * * @param string $javascript */ public function setJavaScript($javascript) { $this->_javaScript = $javascript; } /** * Convert date to PDF format (its close to ASN.1 (Abstract Syntax Notation * One) defined in ISO/IEC 8824). * Data * @todo This really isnt the best location for this method. It should Packages * probably actually exist as Zend_Pdf_Element_Date or something like that. Packages * * @todo Address the following E_STRICT issue: * PHP Strict Standards: date(): It is not safe to rely on the systems * timezone settings. Please use the date.timezone setting, the TZ * environment variable or the date_default_timezone_set() function. In * case you used any of those methods and you are still getting this * warning, you most likely misspelled the timezone identifier. * * @param integer $timestamp (optional) If omitted, uses the current time. * @return string */ public static function pdfDate($timestamp = null) { if ($timestamp === null) { $date = date(D:YmdHisO); } else { Result $date = date(D:YmdHisO, $timestamp); } return substr_replace($date, , -2, 0) . ; }} :HV3
  20. 20. пример прекомпилированного С кода:/*EXEC SQL select count(*) into :tbl_cnt from syscat.tables;*/{#line 39 "dbconn.sqc" sqlastrt(sqla_program_id, &sqla_rtinfo, &sqlca);#line 39 "dbconn.sqc" sqlaaloc(3,1,2,0L); { struct sqla_setdata_list sql_setdlist[1];#line 39 "dbconn.sqc" sql_setdlist[0].sqltype = 496; sql_setdlist[0].sqllen = 4;#line 39 "dbconn.sqc" sql_setdlist[0].sqldata = (void*)&tbl_cnt;#line 39 "dbconn.sqc" sql_setdlist[0].sqlind = 0L;#line 39 "dbconn.sqc" sqlasetdata(3,0,1,sql_setdlist,0L,0L); }
  21. 21. #line 39 "dbconn.sqc" sqlacall((unsigned short)24,1,0,3,0L);#line 39 "dbconn.sqc" sqlastop(0L);}#line 39 "dbconn.sqc" EMB_SQL_CHECK("Count tables"); printf("select count(*) from syscat.tables;n--------n %dn", tbl_cnt);
  22. 22. Архитектура extension’а как магазинного автомата: Очередь вызововPHP engine <?php /** * Zend Framework * DB2_ESQL * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. extension * * @category Zend * @package Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Pdf.php 22908 2010-08-25 20:52:47Z alexander $ */ /** User land classes and interfaces turned on by Zend/Pdf.php file inclusion. */ /** @todo Section should be removed with ZF 2.0 release as obsolete */ /** Zend_Pdf_Page */ require_once Zend/Pdf/Page.php; /** Zend_Pdf_Canvas */ require_once Zend/Pdf/Canvas.php; /** Internally used classes */ require_once Zend/Pdf/Element/Dictionary.php; /** * General entity which describes PDF document. * It implements document abstraction with a document level operations. * * Class is used to create new PDF document or load existing document. sqlaaloc(...) * See details in a class constructor description * * * @category * @package Zend Zend_Pdf * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) sqlacall(...) * @license http://framework.zend.com/license/new-bsd New BSD License { */ class Zend_Pdf /**** Class Constants ****/ /** sqlacmpd(...) * Version number of generated PDF documents. */ const PDF_VERSION = 1.4; /** * PDF file header. */ sqladloc(...) const PDF_HEADER = "%PDF-1.4n%xE2xE3xCFxD3n"; /** /** * List of inheritable attributesfor pages tree * * @var array sqlastls(...) */ protected static $_inheritableAttributes = array(Resources, MediaBox, CropBox, Rotate); /** * Request used memory manager * sqlastlv(...) * @return Zend_Memory_Manager { */ static public function getMemoryManager() if (self::$_memoryManager === null) { require_once Zend/Memory.php; sqlastlva(...) self::$_memoryManager = Zend_Memory::factory(none); } /** } return self::$_memoryManager; * Set user defined memory manager sqlasetdata(...) * * @param Zend_Memory_Manager $memoryManager */ static public function setMemoryManager(Zend_Memory_Manager $memoryManager) { self::$_memoryManager = $memoryManager; sqlastop(...) } /** * Set the document-level JavaScript * * @param string $javascript */ sqlastrt(...) public function setJavaScript($javascript) { } /** $this->_javaScript = $javascript; * Convert date to PDF format (its close to ASN.1 (Abstract Syntax Notation sqlausda(...) * One) defined in ISO/IEC 8824). * * @todo This really isnt the best location for this method. It should * probably actually exist as Zend_Pdf_Element_Date or something like that. * * @todo Address the following E_STRICT issue: * PHP Strict Standards: date(): It is not safe to rely on the systems * timezone settings. Please use the date.timezone setting, the TZ * environment variable or the date_default_timezone_set() function. In * case you used any of those methods and you are still getting this * warning, you most likely misspelled the timezone identifier. * * @param integer $timestamp (optional) If omitted, uses the current time. * @return string */ public static function pdfDate($timestamp = null) { if ($timestamp === null) { $date = date(D:YmdHisO); } else { $date = date(D:YmdHisO, $timestamp); } return substr_replace($date, , -2, 0) . ; НV area } }
  23. 23. Плюсы:- cтатичность SQL;- отсутствие фазы компиляции запроса на этапе выполнения;- отсутствие фазы построения плана запроса на этапе выполнения;- проверка SQL на этапе прекомпиляции;- защищѐнность от вымывания кэшей SQL запросов;- управляемость планов выполнения, возможность вестисравнительную статистику по изменяемости плановпо модулям приложений, пакет как measurement объѐмов ихарактера данных в проекции приложения;- модель security – права на выполнение на уровне пакета.
  24. 24. Минусы:- cтатичность SQL;- дополнительная фаза - прекомпиляция;- необходимость существования соответствующих объектовбазы на момент компиляции;- прирост производительности незаметен на длительныхзапросах (10 и более секунд);- слабая ориентированность на “ad hoc” запросы:имеется поддержка динамического SQL, но она ничемне лучше native подходов с помощью odbc/cli;- отсутствие выигрыша для редко выполняемых запросов.
  25. 25. Ограничения embedded SQL:- невозможность использования Host variables в именахобъектов имѐн таблиц, функций, процедур, …, кроме какпри использовании динамического SQL (PREPAPRE, EXECUTE);- невозможность использования scrollable курсоров;
  26. 26. IBM DB2 и динамический SQL для PHP:http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/topic/com.ibm.swg.im.dbclient.php.doc/doc/c0021523.html1. ibm_db2 extensionhttp://www.php.net/manual/en/book.ibm-db2.php2. pdo_ibm driverhttp://www.php.net/manual/en/book.pdo.php3. Unified odbc extensionhttp://www.php.net/manual/en/book.uodbc.php
  27. 27. Способы увеличения производительности динамического SQL:- увеличение размера STATEMENT CACHE – pckacheszимеется некоторая точка насыщения, предмет для мониторинга:* pkg_cache_lookups (package cache lookups)* pkg_cache_inserts (package cache inserts)* pkg_cache_size_top (package cache high water mark)* pkg_cache_num_overflows (package cache overflows)- использование параметризованных запросовесть “Но” – план выполнения будет строиться без учѐта реальногозначения параметра- StmtConcentrator CLI/ODBC параметр
  28. 28. - конвертирование динамического SQL в статический:1. Коллектор запросов (CLI/ODBC параметры):STATICMODE=CAPTURESTATICCAPFILE=<path>STATICPACKAGE=<package_schema>.<package_name>2. Работа приложения3. db2cap bind …4. STATICMODE=MATCH
  29. 29. Планы- Пре-релиз конец мая – начало июня.- Релиз, передача в Open Source – конец июня.
  30. 30. Embedded SQL vsORM frameworks/ActiveRecord ???
  31. 31. ВопросыАлександр Веремьевcawaspb@gmail.com

×