/src/model/mteTableSql.class.php

https://github.com/pabloeuy/motte · PHP · 1050 lines · 496 code · 94 blank · 460 comment · 130 complexity · 78f894078291ab9cac2b3a48b7027440 MD5 · raw file

  1. <?php
  2. /**
  3. * Clase para el manejo de tablas SQL
  4. *
  5. * @filesource
  6. * @package motte
  7. * @subpackage model
  8. * @version 1.0
  9. * @license http://opensource.org/licenses/gpl-license.php GPL - GNU Public license
  10. * @author Pedro Gauna (pgauna@gmail.com) /
  11. * Carlos Gagliardi (carlosgag@gmail.com) /
  12. * Braulio Rios (braulioriosf@gmail.com) /
  13. * Pablo Erartes (pabloeuy@gmail.com) /
  14. * GBoksar/Perro (gustavo@boksar.info)
  15. * @link http://motte.codigolibre.net Motte Website
  16. */
  17. class mteTableSql extends mteDataSql {
  18. /**
  19. * table name
  20. *
  21. * @var string
  22. * @access private
  23. */
  24. private $_tableName;
  25. /**
  26. * schema name
  27. *
  28. * @var string
  29. * @access private
  30. */
  31. private $_schema;
  32. /**
  33. * key fields
  34. *
  35. * @var array
  36. * @access private
  37. */
  38. private $_fieldsKey;
  39. /**
  40. * fields
  41. *
  42. * @var array
  43. * @access private
  44. */
  45. private $_fields;
  46. /**
  47. * table Foreign Keys
  48. *
  49. * @var array
  50. * @access private
  51. */
  52. private $_fieldsForeign;
  53. /**
  54. * table FROM
  55. *
  56. * @var string
  57. * @access private
  58. */
  59. private $_from;
  60. /**
  61. * Generated calc fields
  62. *
  63. * @var array
  64. * @access private
  65. */
  66. private $_fieldsCalc;
  67. /**
  68. * error
  69. *
  70. * @var array
  71. * @access private
  72. */
  73. private $_errorExec;
  74. /**
  75. * __construct()
  76. *
  77. * @access public
  78. * @param string $tableName
  79. * @param resource $engine
  80. * @param boolen $autoStructure
  81. * @param string $schema
  82. * @return mteTableSql
  83. */
  84. function __construct($tableName = '', $engine, $autoStructure = true, $schema = '') {
  85. // Invoking parent constructor
  86. parent::__construct($engine);
  87. // Initialize
  88. $this->initialize();
  89. $this->setTableName($tableName);
  90. $this->setSchemaName($schema);
  91. $this->setFrom();
  92. $this->clearErrorExec();
  93. // Structure
  94. if ($autoStructure) {
  95. $this->setFields();
  96. $this->setFieldsKey();
  97. }
  98. }
  99. /**
  100. * __destruct()
  101. *
  102. * @access publica
  103. * @return void
  104. */
  105. function __destruct() {
  106. }
  107. /**
  108. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  109. * I N T E R N A L M E T H O D S
  110. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  111. */
  112. /**
  113. * Initialize class attributes
  114. * @access public
  115. * @return void
  116. */
  117. public function initialize() {
  118. $this->_fields = array ();
  119. $this->_fieldsCalc = array ();
  120. $this->_fieldsForeign = array ();
  121. $this->_fieldsKey = array ();
  122. }
  123. public function setFrom($from = ''){
  124. $this->_from = ($from == '')?$this->getTableName():$from;
  125. }
  126. public function getFrom(){
  127. return $this->_from;
  128. }
  129. /**
  130. * setFieldsKey()
  131. * Sets phisical key fields from table
  132. *
  133. * @access private
  134. * @return void
  135. */
  136. public function setFieldsKey($data = '') {
  137. if ($data == '') {
  138. if ($this->getTableName() != '') {
  139. $this->_fieldsKey = $this->getEngine()->getFieldsKeyName($this->getTableName());
  140. }
  141. }
  142. else {
  143. $this->_fieldsKey = $this->_exlodeParam($data);
  144. }
  145. }
  146. /**
  147. * setFields()
  148. * Sets phisical field from table
  149. *
  150. * @access private
  151. * @return void
  152. */
  153. public function setFields($data = '') {
  154. if ($data == '') {
  155. if ($this->getTableName() != '') {
  156. $this->_fields = $this->getEngine()->getFieldsName($this->getTableName());
  157. }
  158. }
  159. else {
  160. $this->_fields = $this->_exlodeParam($data);
  161. }
  162. }
  163. /**
  164. *
  165. * Search on every array for the given fieldName
  166. *
  167. * @access private
  168. * @param string $fieldName
  169. * @return boolean
  170. */
  171. private function _fieldExist($fieldName) {
  172. return @in_array($fieldName, $this->getFields()) ||
  173. @in_array($fieldName, $this->getFieldsCalc()) ||
  174. @in_array($fieldName, $this->getFieldsForeign());
  175. }
  176. /**
  177. *
  178. * escaping special chars on record
  179. *
  180. * @param array $record
  181. * @return unknown
  182. */
  183. private function _escaped($record) {
  184. if (is_array($record)) {
  185. foreach ($record as $key=>$value) {
  186. $record[$key] = '\''.(get_magic_quotes_gpc() == 1)?addslashes($value):
  187. $value.'\'';
  188. }
  189. }
  190. return $record;
  191. }
  192. /**
  193. *
  194. * @access private
  195. * @param string $param
  196. * @return array
  197. */
  198. private function _exlodeParam($param) {
  199. if (is_array($param)) {
  200. $result = $param;
  201. }
  202. else {
  203. $result = array ();
  204. if ($param != '') {
  205. $param = str_replace(array("\t"," ","\r"), '', $param);
  206. // $param = ereg_replace("\t", "", ereg_replace(" ", "", ereg_replace("\n", "", ereg_replace("\r", "", $param))));
  207. $result = explode(',', $param);
  208. if (is_array($result)) {
  209. foreach ($result as $key=>$element) {
  210. $result[$key] = str_replace(' ', '', $element);
  211. }
  212. }
  213. }
  214. }
  215. return $result;
  216. }
  217. /**
  218. *
  219. * validate record fields against table fields
  220. *
  221. * @param array $record
  222. * @return unknown
  223. */
  224. private function _fieldControl($record) {
  225. if ((is_array($record)) && (is_array($this->getFields()))) {
  226. foreach ($this->getFields() as $key=>$fieldName) {
  227. if (!array_key_exists($fieldName, $record)) {
  228. $record[$fieldName] = '';
  229. }
  230. }
  231. foreach ($record as $key=>$fieldName) {
  232. if (!in_array($key, $this->getFields())) {
  233. unset ($record[$key]);
  234. }
  235. }
  236. }
  237. return $record;
  238. }
  239. /**
  240. *
  241. * Returns data based on WHERE and ORDER clauses
  242. *
  243. * @access public
  244. * @param string $fieldsToShow
  245. * @return string
  246. */
  247. private function _getSql($fieldsToShow = '*', $where = '', $order = '', $distinct = false, $foreignFields = TRUE) {
  248. return $this->getSql($fieldsToShow, $where, $order, $distinct, $foreignFields);
  249. }
  250. public function getSql($fieldsToShow = '*', $where = '', $order = '', $distinct = false, $foreignFields = TRUE) {
  251. // All fields
  252. if ($fieldsToShow == '*') {
  253. $fieldsToShow = implode(',', $this->_fields);
  254. // Foreign fields
  255. if ($foreignFields && count($this->_fieldsForeign) > 0) {
  256. if ($fieldsToShow != '') {
  257. $fieldsToShow .= ',';
  258. }
  259. $fieldsToShow .= implode(',', array_keys($this->_fieldsForeign));
  260. }
  261. // Calc fields
  262. if (count($this->_fieldsCalc) > 0) {
  263. if ($fieldsToShow != '') {
  264. $fieldsToShow .= ',';
  265. }
  266. $fieldsToShow .= implode(',', array_keys($this->_fieldsCalc));
  267. }
  268. }
  269. // Remove blanks
  270. $auxFields = explode(',', str_replace(' ', '', $fieldsToShow));
  271. //auxFields (array)
  272. $sqlFields = array ();
  273. foreach ($auxFields as $key=>$value) {
  274. //add table common fields
  275. if (in_array($value, $this->_fields)) {
  276. $sqlFields[$key] = $this->getTableName().".".$value;
  277. }
  278. //add table foreign fields
  279. if (in_array($value, array_keys($this->_fieldsForeign))) {
  280. $sqlFields[$key] = ($this->_fieldsForeign[$value]['addPrefix']?$this->_fieldsForeign[$value]['tableF'].".":'').$this->_fieldsForeign[$value]['descF']." AS ".$value;
  281. }
  282. //add calc fields
  283. if (in_array($value, array_keys($this->_fieldsCalc))) {
  284. $sqlFields[$key] = $this->_fieldsCalc[$value]." AS ".$value;
  285. }
  286. // add count fields
  287. if (strtoupper($value) == 'COUNT(*)') {
  288. $sqlFields['COUNT(*)'] = 'COUNT(*)';
  289. }
  290. }
  291. $fieldsToShow = implode(',', $sqlFields);
  292. //FROM AND INNER JOINS
  293. $query = 'SELECT '.($distinct?'DISTINCT ':'').$fieldsToShow.' FROM '.$this->getFrom();
  294. $arrayFieldsForeign = $this->getFieldsForeign();
  295. $inner = array ();
  296. foreach ($arrayFieldsForeign as $key=>$value) {
  297. if (!array_key_exists($value['tableF'], $inner)) {
  298. $inner[$value['tableF']] = " INNER JOIN ".$value['tableF']." ON ".$this->getTableName().".".$value['key']."=".$value['tableF'].".".$value['keyF'];
  299. }
  300. }
  301. $query = $query.implode("\n", $inner);
  302. // WHERE:
  303. if ($where != '') {
  304. // Calc fields
  305. if (count($this->_fieldsCalc) > 0) {
  306. foreach ($this->_fieldsCalc as $auxFieldKey => $auxFieldValue) {
  307. if(!array_key_exists($auxFieldKey, $sqlFields)){
  308. $where = str_replace($auxFieldKey,"($auxFieldValue)", $where);
  309. }
  310. }
  311. }
  312. $query .= ' WHERE '.$where;
  313. }
  314. // ORDER BY:
  315. if ($order != '') {
  316. $query .= ' ORDER BY '.$order;
  317. }
  318. return $query;
  319. }
  320. /**
  321. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  322. * P R O P E R T I E S
  323. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  324. */
  325. /**
  326. * Sets table name
  327. *
  328. * @access public
  329. * @param string $tb
  330. * @return void
  331. */
  332. public function setTableName($tb) {
  333. $this->_tableName = $tb;
  334. }
  335. /**
  336. * Devuelve nombre de la tabla
  337. *
  338. * @access public
  339. * @return string
  340. */
  341. public function getTableName() {
  342. $result = $this->_tableName;
  343. if ($this->getSchemaName() != '') {
  344. $result = $this->getSchemaName().'.'.$this->_tableName;
  345. }
  346. return ($result);
  347. }
  348. /**
  349. * Sets table name
  350. *
  351. * @access public
  352. * @param string $tb
  353. * @return void
  354. */
  355. public function setSchemaName($value = '') {
  356. $this->_schema = $value;
  357. }
  358. /**
  359. * Devuelve nombre de la tabla
  360. *
  361. * @access public
  362. * @return string
  363. */
  364. public function getSchemaName() {
  365. return ($this->_schema);
  366. }
  367. /**
  368. * Devuelve el array _fields
  369. *
  370. * @access public
  371. * @return array
  372. */
  373. public function getFields() {
  374. return $this->_fields;
  375. }
  376. /**
  377. * Devuelve el array _fieldsKey
  378. *
  379. * @access public
  380. * @return array
  381. */
  382. public function getFieldsKey() {
  383. return $this->_fieldsKey;
  384. }
  385. /**
  386. * Devuelve el array _fieldsCalc
  387. *
  388. * @access public
  389. * @return array
  390. */
  391. public function getFieldsCalc() {
  392. return $this->_fieldsCalc;
  393. }
  394. /**
  395. * Devuelve el array _fieldsForeign
  396. *
  397. * @access public
  398. * @return array
  399. */
  400. public function getFieldsForeign() {
  401. return $this->_fieldsForeign;
  402. }
  403. /**
  404. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  405. * F I E L D M A N A G M E N T M E T H O D S
  406. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  407. */
  408. /**
  409. * devuelve where id
  410. *
  411. * @param array $record
  412. * @return string
  413. */
  414. public function getWherePrimaryKeys($record) {
  415. $where = new mteWhereSQL();
  416. if (is_array($this->getFieldsKey())) {
  417. foreach ($this->getFieldsKey() as $fieldName) {
  418. $where->addAND($fieldName, '=', "'".$record[$fieldName]."'");
  419. }
  420. }
  421. return $where->fetch();
  422. }
  423. /**
  424. * Agrega campo foraneo a la estructura de la tabla
  425. * (sirve para simular FK cuando el SGBD no lo soporta)
  426. *
  427. * @access public
  428. * @param string $fieldName el nombre que se le dara al campo
  429. * @param string $fieldKey es el campo foreign de this
  430. * @param string $tableForeign es la tabla externa
  431. * @param string $fieldKeyForeign es el campo externo
  432. * @param string $fieldDescForeign es la descripcion del campo
  433. * @return void
  434. */
  435. public function addFieldForeignKey($fieldName, $fieldKey, $tableForeign, $fieldKeyForeign = '', $fieldDescForeign = '', $addPrefix = true) {
  436. // Si no existe
  437. if (($fieldName != '') && (!$this->_fieldExist($fieldName))) {
  438. $this->_fieldsForeign[$fieldName] = array ('key'=>$fieldKey, 'tableF'=>$tableForeign, 'keyF'=>($fieldKeyForeign == '')?$fieldKey:$fieldKeyForeign, 'descF'=>$fieldDescForeign, 'addPrefix'=>$addPrefix);
  439. }
  440. }
  441. /**
  442. * Agrega un campo calculado
  443. *
  444. * @access public
  445. * @param string $fieldName
  446. * @param string $expresion Campo calculado
  447. * @return void
  448. */
  449. public function addFieldCalcSql($fieldName, $expresion) {
  450. // Si no existe
  451. if (($fieldName != '') && (!$this->_fieldExist($fieldName))) {
  452. $this->_fieldsCalc[$fieldName] = $expresion;
  453. }
  454. }
  455. /**
  456. * Agrega un campo calculado al array de campos calculados
  457. *
  458. * @access public
  459. * @param string $fieldName nombre que tendra el campo calculado
  460. * @param array $toConcat array de strings a concatenar
  461. * @return void
  462. */
  463. public function addFieldCalcConcat($fieldName = '', $toConcat = '') {
  464. $this->addFieldCalcSql($fieldName, $this->getEngine()->getConcat($toConcat));
  465. }
  466. /**
  467. * Carga desde un array los datos de un record
  468. *
  469. * @access public
  470. * @return array
  471. */
  472. public function toRecord($record, $data) {
  473. if (is_array($record)) {
  474. foreach ($record as $fieldName=>$value) {
  475. if ( isset ($data[$fieldName])) {
  476. $record[$fieldName] = $data[$fieldName];
  477. }
  478. }
  479. }
  480. return $record;
  481. }
  482. /**
  483. *
  484. *
  485. * @access public
  486. * @param string $field
  487. * @return string
  488. */
  489. public function getFieldName($field) {
  490. $result = $field;
  491. if (in_array($field, $this->_fields)) {
  492. $result = $this->getTableName().".".$field;
  493. }
  494. if (array_key_exists($field, $this->_fieldsForeign)) {
  495. $result = ($this->_fieldsForeign[$field]['addPrefix']?$this->_fieldsForeign[$field]['tableF'].".":'').$this->_fieldsForeign[$field]['descF'];
  496. }
  497. // return
  498. return $result;
  499. }
  500. /**
  501. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  502. * D A T A M A N A G M E N T M E T H O D S
  503. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  504. */
  505. /**
  506. * Devuelve un mteRecordSet conteniendo los valores de la columna parametro
  507. *
  508. * @access public
  509. * @param string $fieldsToShow
  510. * @param string $where
  511. * @param string $order
  512. * @return mteRecordSet
  513. */
  514. public function getColumnValues($fieldName = '', $where = '', $order = '', $distinct = false) {
  515. // sql
  516. $result = $this->getEngine()->executeSql($this->getSql($fieldName, $where, $order, $distinct));
  517. if ($result) {
  518. $recordSet = new mteRecordSet();
  519. if (is_array($result)) {
  520. $recordSet->addData($result);
  521. }
  522. $recordSet->first();
  523. // result
  524. $result = $recordSet;
  525. }
  526. return $result;
  527. }
  528. /**
  529. * Devuelve la primer columna del primer registro segun el orden indicado en el parametro
  530. * @access public
  531. * @param string $fieldName Este parametro contendra solo un campo
  532. * @param string $where
  533. * @param string $order
  534. * @return Object o boolean
  535. */
  536. public function getValue($fieldName = '', $where = '', $order = '') {
  537. $result = $this->getRecordSet($fieldName, $where, $order, 1, 0, false);
  538. $result->first();
  539. $value = '';
  540. if (is_array($result->record)) {
  541. $value = array_shift($result->record);
  542. }
  543. return $value;
  544. }
  545. /**
  546. * Devuelve el maximo identificador de la tabla
  547. *
  548. * @access public
  549. * @param string $fieldName si viene vacio toma el primer pk de la tabla,sino retorna el maximo del campo parametro (que se asume es pk)
  550. * @return Object o boolean
  551. */
  552. public function lastId($fieldName = '') {
  553. if ($fieldName == '') {
  554. $primaryKeys = $this->getFieldsKey();
  555. $fieldName = $primaryKeys[0];
  556. }
  557. $result = $this->getEngine()->executeSql('SELECT MAX('.$fieldName.') FROM '.$this->getTableName());
  558. if (is_array($result)) {
  559. return array_shift($result[0]);
  560. }
  561. else {
  562. return false;
  563. }
  564. }
  565. /**
  566. * Inserta el nuevo registro y devuelve error o exito asume que los formatos de datos
  567. * son correctos, por ejemplo, campo integer necesita un entero como valor (ademas
  568. * llama a before insert y after insert)
  569. *
  570. * @access public
  571. * @param array $record
  572. * @return string devuelve '' en caso de exito
  573. */
  574. public function insertRecord( & $record) {
  575. $error = '';
  576. if ((is_array($record)) && (is_array($this->getFields()))) {
  577. // agrega campos que no estan el record y escapea
  578. $record = $this->_escaped($this->_fieldControl($record));
  579. // ejecuta before insert si es que existe
  580. if (method_exists($this, 'beforeInsert')) {
  581. $error = $this->beforeInsert($record);
  582. }
  583. if ($error == '') {
  584. if (is_array($record)) {
  585. $pairs = array ();
  586. foreach ($this->getFields() as $field) {
  587. if($record[$field] == 'NULL'){
  588. $pairs[] = $record[$field];
  589. }
  590. else{
  591. $pairs[] = "'".$record[$field]."'";
  592. }
  593. }
  594. $result = $this->getEngine()->executeSQL('INSERT INTO '.$this->getTableName().' ('.implode(',', $this->getFields()).
  595. ') VALUES ('.implode(',', $pairs).')');
  596. if ($result === false) {
  597. $error = $this->getEngine()->getEventMsg();
  598. }
  599. else {
  600. if (method_exists($this, 'afterInsert')) {
  601. $error = $this->afterInsert($record);
  602. }
  603. }
  604. }
  605. }
  606. }
  607. else {
  608. $error = __('INSERT - Not Enough Parameters').' ('.$this->getTableName().')';
  609. }
  610. return $error;
  611. }
  612. /**
  613. * Actualiza el registro y devuelve error o exito (ademas llama a beforeUpdate y afterUpdate)
  614. *
  615. * @access public
  616. * @param array $record campos a actualizar
  617. * @param string $where filtro para actualizar la tabla
  618. * @return string
  619. */
  620. public function updateRecord( & $record, $where = '') {
  621. $error = '';
  622. if ((is_array($record)) && (is_array($this->getFields()))) {
  623. // escapea datos
  624. $record = $this->_escaped($record);
  625. // ejecuta before update si es que existe
  626. if (method_exists($this, 'beforeUpdate')) {
  627. $error = $this->beforeUpdate($record);
  628. }
  629. if ($error == '') {
  630. if (is_array($record)) {
  631. $pairs = array ();
  632. foreach ($this->getFields() as $field) {
  633. if($record[$field] == 'NULL'){
  634. $pairs[] = $field."=".$record[$field];
  635. }
  636. else{
  637. $pairs[] = $field."='".$record[$field]."'";
  638. }
  639. }
  640. if ($where == '') {
  641. $where = $this->getWherePrimaryKeys($record);
  642. }
  643. $result = $this->getEngine()->executeSQL('UPDATE '.$this->getTableName().' SET '.implode(',', $pairs).' WHERE '.$where);
  644. if ($result === false) {
  645. $error = $this->getEngine()->getEventMsg();
  646. }
  647. else {
  648. if (method_exists($this, 'afterUpdate')) {
  649. $error = $this->afterUpdate($record);
  650. }
  651. }
  652. }
  653. }
  654. }
  655. else {
  656. $error = __('UPDATE - Not Enough Parameters').' ('.$this->getTableName().')';
  657. }
  658. return $error;
  659. }
  660. /**
  661. * borra el registro y devuelve error o exito
  662. * (ademas llama a before delete y after delete)
  663. *
  664. * @access public
  665. * @param string $where
  666. * @paramarray $record El record es por si no se le pasa where,
  667. * el record contiene los registros a borrar
  668. * por lo que se construye el where a partir de
  669. * los registros a borrar
  670. * @return string
  671. */
  672. public function deleteRecord( & $record, $where = '') {
  673. $error = '';
  674. if ((is_array($record)) && (is_array($this->getFields()))) {
  675. // agrega campos que no estan el record y escapea
  676. $record = $this->_escaped($this->_fieldControl($record));
  677. // ejecuta before delete si es que existe
  678. if (method_exists($this, 'beforeDelete')) {
  679. $error = $this->beforeDelete($record);
  680. }
  681. if ($error == '') {
  682. if (is_array($record)) {
  683. if ($where == '') {
  684. $where = $this->getWherePrimaryKeys($record);
  685. }
  686. $result = $this->getEngine()->executeSQL('DELETE FROM '.$this->getTableName().' WHERE '.$where);
  687. if ($result === false) {
  688. $error = $this->getEngine()->getEventMsg();
  689. }
  690. else {
  691. if (method_exists($this, 'afterDelete')) {
  692. $error = $this->afterDelete($record);
  693. }
  694. }
  695. }
  696. }
  697. }
  698. else {
  699. $error = __('DELETE - Not Enough Parameters').' ('.$this->getTableName().')';
  700. }
  701. return $error;
  702. }
  703. /**
  704. *
  705. * @param <type> $where
  706. * @return <type>
  707. */
  708. public function deleteRecords($where){
  709. $error = '';
  710. if ($where != ''){
  711. $result = $this->getEngine()->executeSQL('DELETE FROM '.$this->getTableName().' WHERE '.$where);
  712. if ($result === false) {
  713. $error = $this->getEngine()->getEventMsg();
  714. }
  715. }
  716. else {
  717. $error = __('MASSIVE DELETE - Not Enough Parameters').' ('.$this->getTableName().')';
  718. }
  719. return $error;
  720. }
  721. /**
  722. * Retorna el primer registro segun el where y orden recibidos como parametro
  723. *
  724. * @access public
  725. * @param string $order
  726. * @param string $where
  727. * @return array
  728. */
  729. public function getRecord($where = '', $order = '', $calcFields = true, $foreignFields = TRUE) {
  730. // Antes de cargar
  731. if (method_exists($this, 'beforeGetRecord')) {
  732. $this->beforeGetRecord($record);
  733. }
  734. // Cargo record
  735. $recordSet = $this->getRecordSet('*', $where, $order, 1, 0, false, false, $foreignFields);
  736. $recordSet->first();
  737. $record = $recordSet->record;
  738. // Antes de cargar
  739. if (method_exists($this, 'afterGetRecord')) {
  740. $this->afterGetRecord($record);
  741. }
  742. // Genero campos calculados
  743. if ((method_exists($this, 'onCalcFields')) && ($calcFields)) {
  744. $error = $this->onCalcFields($record);
  745. }
  746. // Devuelvo
  747. return $record;
  748. }
  749. /**
  750. * Retorna
  751. *
  752. * @access public
  753. * @param array $columns Esto engloba campos, FK, PK, calculados en caso que * sea '*' y sino es un array de campos
  754. * @param string $where
  755. * @param string $order
  756. * @param number $numRows Cantidad de registros a mostrar
  757. * @param number $offset A partir de que registro se quiere mostrar
  758. * @return mteRecordSet
  759. */
  760. public function getRecordSet($columns = '*', $where = '', $order = '', $numRows = -1, $offset = -1, $calcFields = true, $distinct = false, $foreignFields = TRUE) {
  761. // result
  762. $recordSetResult = parent::getRecordSet($this->getSql($columns, $where, $order, $distinct, $foreignFields), $numRows, $offset);
  763. // Genero campos calculados
  764. if ($calcFields && (method_exists($this, 'onCalcFields'))) {
  765. $recordSetCalc = new mteRecordSet();
  766. $recordSetResult->first();
  767. while (!$recordSetResult->isEOF()) {
  768. // campo calculado
  769. $record = $recordSetResult->record;
  770. $this->onCalcFields($record);
  771. // Agrego al nuevo recordset
  772. $recordSetCalc->addRecord($record);
  773. // next
  774. $recordSetResult->next();
  775. }
  776. $recordSetCalc->first();
  777. return $recordSetCalc;
  778. }
  779. else {
  780. $recordSetResult->first();
  781. return $recordSetResult;
  782. }
  783. }
  784. /**
  785. * Retorna true si para el where hay registros o false si no
  786. *
  787. * @access public
  788. * @param string $where
  789. * @return boolean
  790. */
  791. public function exists($where = '') {
  792. return ($this->recordCount($where) > 0);
  793. }
  794. /**
  795. * Devuelve cuantos registros cumplen la condicion
  796. *
  797. * @access public
  798. * @param string $where
  799. * @return int
  800. */
  801. public function recordCount($where = '') {
  802. return $this->getValue("COUNT(*)", $where);
  803. }
  804. /**
  805. * Devuelve cantidad de paginas para el filtro parametro
  806. *
  807. * @access public
  808. * @param string $where
  809. * @param int $numRows Cantidad de filas por cada pagina
  810. * @return int Cantidad de paginas
  811. */
  812. public function getTotalPages($numRows = 50, $where = '') {
  813. if ($numRows == 0) {
  814. $numRows = MTE_GRID_ROWS;
  815. }
  816. $numRecs = $this->recordCount($where);
  817. $result = (int)($numRecs/$numRows);
  818. if ($numRecs%$numRows > 0) {
  819. $result = $result+1;
  820. }
  821. return $result == 0?1:$result;
  822. }
  823. /**
  824. * Devuelve un registro en blanco (adentro pregunta si existe el metodo
  825. * onnewrecord en el hijo de table x ej, TPersona)
  826. *
  827. * @access public
  828. * @param
  829. * @return array o string (error)
  830. */
  831. public function getEmptyRecord() {
  832. // Genero campos
  833. $record = array ();
  834. foreach ($this->getFields() as $fieldName) {
  835. $record[$fieldName] = '';
  836. }
  837. if (method_exists($this, 'onNewRecord')) {
  838. $this->onNewRecord($record);
  839. }
  840. return $record;
  841. }
  842. /**
  843. *
  844. * @param string $fieldKey
  845. * @param string $fieldDesc
  846. * @param string $where
  847. * @param string $order
  848. * @return array
  849. */
  850. public function getArrayCombo($where = '', $order = '', $fieldKey = '', $fieldDesc = ''){
  851. $result = array();
  852. // Field Key
  853. if ($fieldKey == ''){
  854. $aux = $this->getFieldsKey();
  855. $fieldKey = array_shift($aux);
  856. }
  857. // Desc
  858. if ($fieldDesc == ''){
  859. $aux = $this->getFields();
  860. $fieldDesc = $aux[1];
  861. }
  862. // Order
  863. if ($order == ''){
  864. $order = $fieldDesc;
  865. }
  866. $recordSet = $this->getRecordSet($fieldKey.','.$fieldDesc, $where, $order);
  867. $recordSet->first();
  868. while (!$recordSet->isEOF()){
  869. $desc = '';
  870. foreach (explode(',',$fieldDesc) as $field) {
  871. $desc .= ' '.$recordSet->record[$field];
  872. }
  873. $result[$recordSet->record[$fieldKey]] = $desc;
  874. $recordSet->next();
  875. }
  876. return $result;
  877. }
  878. /**
  879. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  880. * E R R O R M A N A G M E N T
  881. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  882. */
  883. /**
  884. * Limpia manejador de errores de ejecucion
  885. *
  886. * @access public
  887. * @param
  888. * @return void
  889. *
  890. */
  891. public function clearErrorExec() {
  892. $this->_errorExec = array ();
  893. }
  894. /**
  895. * Agrega error de ejecucion
  896. *
  897. * @access public
  898. * @param string $error
  899. * @return void
  900. *
  901. */
  902. public function addErrorExec($error = '') {
  903. if ($error != '') {
  904. $this->_errorExec[] = $error;
  905. }
  906. }
  907. /**
  908. * devuelve array errores
  909. *
  910. * @access public
  911. * @return array
  912. *
  913. */
  914. public function getErrorExec() {
  915. return $this->_errorExec;
  916. }
  917. /**
  918. * Devuelve cantidad de errores
  919. *
  920. * @access public
  921. * @return integer
  922. */
  923. public function countErrorExec() {
  924. return count($this->_errorExec);
  925. }
  926. /**
  927. * Parsea errores
  928. *
  929. * @access public
  930. * @param string $msgIni
  931. * @param string $msgEnd
  932. * @param string $glue
  933. * @return string
  934. *
  935. */
  936. public function parseErrorExec($msgIni = '', $msgEnd = '', $glue = '') {
  937. return $this->countErrorExec() > 0?"\n".$msgIni.$glue.implode($glue, $this->_errorExec).$glue.$msgEnd:
  938. '';
  939. }
  940. /**
  941. * Gets error literal
  942. *
  943. * @access public
  944. * @return string
  945. */
  946. public function getLiteralError() {
  947. // Literals
  948. $literal = '';
  949. if ($this->countErrorExec() > 0) {
  950. $literal = $this->countErrorExec().' '.__('error(s) found');
  951. }
  952. // Returns
  953. return $literal;
  954. }
  955. }
  956. ?>