Usar o Framework com sql server Olá pessoal! Para conseguir trabalhar com sql server foi necessário alterar duas classes: 1º - TConnection: a extensão mssql já não funciona há muito tempo. A microsoft desenvolveu uma extensão para conexão com php e continua dando manutenção. Basta instalar e fazer o php reconhecê-la. A mudança será feita na linha 73 e a string ficará da seguinte forma:...
ES
Usar o Framework com sql server  
Fechado
Olá pessoal!

Para conseguir trabalhar com sql server foi necessário alterar duas classes:

1º - TConnection: a extensão mssql já não funciona há muito tempo. A microsoft desenvolveu uma extensão para conexão com php e continua dando manutenção. Basta instalar e fazer o php reconhecê-la.
A mudança será feita na linha 73 e a string ficará da seguinte forma:
 
  1. <?php $conn = new PDO("sqlsrv:Server={$host};Database={$name}", $user, $pass); ?>


2º - TSqlSelect: linha 33 passa a ter a seguinte sintaxe:
 
  1. <?php if (($driver == 'sqlsrv') or ($driver == 'dblib')) ?>

Caso alguém tenha enfrentado esse problema espero que essas informações ajude.
Só lamento o Adianti Studio ainda não comportar o driver para sql server. Estou aguardando Pablo.

abs
Eliezer

Curso Dominando o Adianti Framework

O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado!


Dominando o Adianti Framework Quero me inscrever agora!

Comentários (9)


ES

Olá Pablo,
Depois de conseguir conexão com o banco de dados fiz uma listagem para teste e eis que começaram os primeiros problemas.

A listagem foi preenchida perfeitamente mas apareceu a tela de mensagem com o seguinte erro:
Error SQLSTATE[42000]: [Microsoft][SQL Server Native Client 10.0][SQL Server]Nenhum nome de coluna especificado para a coluna 1 de 'TAB'.

Tentei várias coisas mas nada deu certo.
Abaixo coloco os códigos das classes model e control:

Model
 
  1. <?php /**
  2. * EstoqueProd Active Record
  3. * @author EliezerM
  4. */
  5. class EstoqueProd extends TRecord
  6. {
  7. const TABLENAME = 'ESTOQUE_PRODUTOS';
  8. const PRIMARYKEY= 'PRODUTO';
  9. const IDPOLICY = 'serial'; // {max, serial}
  10. /**
  11. * Constructor method
  12. */
  13. public function __construct($id = NULL)
  14. {
  15. parent::__construct($id);
  16. parent::addAttribute('PRODUTO');
  17. parent::addAttribute('COR_PRODUTO');
  18. parent::addAttribute('FILIAL');
  19. parent::addAttribute('ESTOQUE');
  20. }
  21. } ?>


Control
 
  1. <?php
  2. /**
  3. * Bens_moveisList Listing
  4. * @author <your name here>
  5. */
  6. class ProdutosEstLis extends TPage
  7. {
  8. private $form; // registration form
  9. private $datagrid; // listing
  10. private $pageNavigation;
  11. private $loaded;
  12. /**
  13. * Class constructor
  14. * Creates the page, the form and the listing
  15. */
  16. public function __construct()
  17. {
  18. parent::__construct();
  19. // creates the form
  20. $this->form = new TForm('form_search_Est_Prod');
  21. // creates a table
  22. $table = new TTable;
  23. // add the table inside the form
  24. $this->form->add($table);
  25. // create the form fields
  26. $filter = new TEntry('PRODUTO');
  27. $filter->setValue(TSession::getValue('EstoqueProd_PRODUTO'));
  28. // add a row for the filter field
  29. $row=$table->addRow();
  30. $row->addCell(new TLabel('Produto:'));
  31. $row->addCell($filter);
  32. // create two action buttons to the form
  33. $find_button = new TButton('find');
  34. $new_button = new TButton('new');
  35. // define the button actions
  36. $find_button->setAction(new TAction(array($this, 'onSearch')), _t('Find'));
  37. $find_button->setImage('ico_find.png');
  38. $new_button->setAction(new TAction(array('EstoqueProdForm', 'onEdit')), _t('New'));
  39. $new_button->setImage('ico_new.png');
  40. // add a row for the form actions
  41. $row=$table->addRow();
  42. $row->addCell($find_button);
  43. $row->addCell($new_button);
  44. // define wich are the form fields
  45. $this->form->setFields(array($filter, $find_button, $new_button));
  46. // creates a DataGrid
  47. $this->datagrid = new TDataGrid;
  48. $this->datagrid->setHeight(320);
  49. // creates the datagrid columns
  50. $id = new TDataGridColumn('PRODUTO', 'Produto', 'center', 100);
  51. $patrimonio = new TDataGridColumn('COR_PRODUTO', 'Cor', 'center', 30);
  52. $desc_pat = new TDataGridColumn('FILIAL', 'Filial', 'left', 180);
  53. $item = new TDataGridColumn('ESTOQUE', 'Qtde', 'right', 50);
  54. // add the columns to the DataGrid
  55. $this->datagrid->addColumn($id);
  56. $this->datagrid->addColumn($patrimonio);
  57. $this->datagrid->addColumn($desc_pat);
  58. $this->datagrid->addColumn($item);
  59. // creates the datagrid actions
  60. $order2= new TAction(array($this, 'onReload'));
  61. $order3= new TAction(array($this, 'onReload'));
  62. $order4= new TAction(array($this, 'onReload'));
  63. // define the ordering parameters
  64. $order2->setParameter('order', 'PRODUTO');
  65. $order3->setParameter('order', 'COR_PRODUTO');
  66. $order4->setParameter('order', 'FILIAL');
  67. // assign the ordering actions
  68. $patrimonio->setAction($order2);
  69. $desc_pat->setAction($order3);
  70. $item->setAction($order4);
  71. // creates two datagrid actions
  72. $action1 = new TDataGridAction(array('EstoqueProdForm', 'onEdit'));
  73. $action1->setLabel(_t('Edit'));
  74. $action1->setImage('ico_edit.png');
  75. $action1->setField('id');
  76. $action2 = new TDataGridAction(array($this, 'onDelete'));
  77. $action2->setLabel(_t('Delete'));
  78. $action2->setImage('ico_delete.png');
  79. $action2->setField('id');
  80. // add the actions to the datagrid
  81. $this->datagrid->addAction($action1);
  82. $this->datagrid->addAction($action2);
  83. // create the datagrid model
  84. $this->datagrid->createModel();
  85. // creates the page navigation
  86. $this->pageNavigation = new TPageNavigation;
  87. $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
  88. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  89. // creates the page structure using a table
  90. $table = new TTable;
  91. // add a row to the form
  92. $row = $table->addRow();
  93. $row->addCell($this->form);
  94. // add a row to the datagrid
  95. $row = $table->addRow();
  96. $row->addCell($this->datagrid);
  97. // add a row for page navigation
  98. $row = $table->addRow();
  99. $row->addCell($this->pageNavigation);
  100. // add the table inside the page
  101. parent::add($table);
  102. }
  103. /**
  104. * method onSearch()
  105. * Register the filter in the session when the user performs a search
  106. */
  107. function onSearch()
  108. {
  109. // get the search form data
  110. $data = $this->form->getData();
  111. TSession::setValue('EstoqueProd_filter', NULL);
  112. TSession::setValue('EstoqueProd_PRODUTO', '');
  113. // check if the user has filled the form
  114. if (isset($data->patrimonio))
  115. {
  116. // creates a filter using what the user has typed
  117. $filter = new TFilter('PRODUTO', 'like', "%{$data->patrimonio}%");
  118. // stores the filter in the session
  119. TSession::setValue('EstoqueProd_filter', $filter);
  120. TSession::setValue('EstoqueProd_PRODUTO', $data->patrimonio);
  121. // fill the form with data again
  122. $this->form->setData($data);
  123. }
  124. $param=array();
  125. $param['offset'] =0;
  126. $param['first_page']=1;
  127. $this->onReload($param);
  128. }
  129. /**
  130. * method onReload()
  131. * Load the datagrid with the database objects
  132. */
  133. function onReload($param = NULL)
  134. {
  135. try
  136. {
  137. // open a transaction with database 'con_mysql'
  138. TTransaction::open('con_mssql');
  139. // creates a repository for Bens_moveis
  140. $repository = new TRepository('EstoqueProd');
  141. $limit = 10;
  142. // creates a criteria
  143. $criteria = new TCriteria;
  144. $criteria->setProperties($param); // order, offset
  145. $criteria->setProperty('limit', $limit);
  146. if (TSession::getValue('EstoqueProd_filter'))
  147. {
  148. // add the filter stored in the session to the criteria
  149. $criteria->add(TSession::getValue('EstoqueProd_filter'));
  150. }
  151. // load the objects according to criteria
  152. $objects = $repository->load($criteria);
  153. $this->datagrid->clear();
  154. if ($objects)
  155. {
  156. // iterate the collection of active records
  157. foreach ($objects as $object)
  158. {
  159. //altera o valor para iso-8859-1
  160. $object->FILIAL = iconv('utf-8','iso-8859-1', $object->FILIAL);
  161. // add the object inside the datagrid
  162. $this->datagrid->addItem($object);
  163. }
  164. }
  165. // reset the criteria for record count
  166. $criteria->resetProperties();
  167. $count= $repository->count($criteria);
  168. $this->pageNavigation->setCount($count); // count of records
  169. $this->pageNavigation->setProperties($param); // order, page
  170. $this->pageNavigation->setLimit($limit); // limit
  171. // close the transaction
  172. TTransaction::close();
  173. $this->loaded = true;
  174. }
  175. catch (Exception $e) // in case of exception
  176. {
  177. // shows the exception error message
  178. new TMessage('error', '<b>Error</b> ' . $e->getMessage());
  179. // undo all pending operations
  180. TTransaction::rollback();
  181. }
  182. }
  183. /**
  184. * method onDelete()
  185. * executed whenever the user clicks at the delete button
  186. * Ask if the user really wants to delete the record
  187. */
  188. function onDelete($param)
  189. {
  190. // get the parameter $key
  191. $key=$param['key'];
  192. // define two actions
  193. $action = new TAction(array($this, 'Delete'));
  194. // define the action parameters
  195. $action->setParameter('key', $key);
  196. // shows a dialog to the user
  197. new TQuestion(TAdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  198. }
  199. /**
  200. * method Delete()
  201. * Delete a record
  202. */
  203. function Delete($param)
  204. {
  205. try
  206. {
  207. // get the parameter $key
  208. $key=$param['key'];
  209. // open a transaction with database 'con_mysql'
  210. TTransaction::open('con_mssql');
  211. // instantiates object Bens_moveis
  212. $object = new EstoqueProd($key);
  213. // deletes the object from the database
  214. $object->delete();
  215. // close the transaction
  216. TTransaction::close();
  217. // reload the listing
  218. $this->onReload();
  219. // shows the success message
  220. new TMessage('info', TAdiantiCoreTranslator::translate('Record deleted'));
  221. }
  222. catch (Exception $e) // in case of exception
  223. {
  224. // shows the exception error message
  225. new TMessage('error', '<b>Error</b> ' . $e->getMessage());
  226. // undo all pending operations
  227. TTransaction::rollback();
  228. }
  229. }
  230. /**
  231. * method show()
  232. * Shows the page
  233. */
  234. function show()
  235. {
  236. // check if the datagrid is already loaded
  237. if (!$this->loaded)
  238. {
  239. $this->onReload();
  240. }
  241. parent::show();
  242. }
  243. }
  244. ?>


Se tiver alguma idéia agradeço.

abs

Eliezer</your>
PD

Oi Eliezer,

Você poderia mandar registrar os LOGS, e depois executar os SQL diretamente no SQL Server para ver qual Instrução SQL foi montada com erro:

www.adianti.com.br/doc-framework-Persistence-Objects-RegisterLog

um abraço,
Pablo
ES

Pablo,
veja o que o log registrou e sinceramente não estou entendendo a instrução.

2013-02-03 08:41:31 :: ** SELECIONANDO ESTOQUE

2013-02-03 08:41:31 :: SELECT * FROM ( SELECT TOP 10 * FROM ( SELECT TOP 10 * FROM ESTOQUE_PRODUTOS WHERE (PRODUTO like '%%') ORDER BY 1 ASC) AS TAB ORDER BY 1 DESC) AS TAB2 ORDER BY PRODUTO

2013-02-03 08:41:31 :: SELECT count(*) FROM ( SELECT TOP 0 count(*) FROM ( SELECT TOP 0 count(*) FROM ESTOQUE_PRODUTOS WHERE (PRODUTO like '%%') ORDER BY 1 ASC) AS TAB ORDER BY 1 DESC) AS TAB2


Se puder me ajudar agradeço

abs
Eliezer
ES

Olá Pablo
É com enorme satisfação que informo a todos os interessados que consegui resolver os erros apresentados na paginação SQL Server e coloco a solução abaixo.
Pablo, se você puder testar, melhorar e homologar para a próxima versão ficarei imensamente grato. Segue:

Alteração da Classe TSqlSelect método getInstructionSqlServer() a partir da linha 117, o código ficará assim:
 
  1. <?php
  2. if (isset($limit) and $limit != NULL and (!isset($offset) or $offset == NULL))
  3. {
  4. $this->sql = " SELECT TOP {$limit} " . implode(',', $this->columns) . " FROM {$this->entity} {$sql_where} {$sql_order}";
  5. }
  6. else if (isset($limit) and isset($offset) and $limit != NULL and $offset != NULL)
  7. {
  8. // monsta a instrução de SELECT
  9. $this->sql = "SELECT TOP {$limit} * FROM (SELECT ROW_NUMBER() OVER ({$sql_order}) AS TAB, *
  10. FROM " . $this->entity . " {$sql_where}) AS TAB2
  11. WHERE TAB > (({$offset} - 1) * {$limit})";
  12. }
  13. ?>


PS.: O SQL que trabalho é o 2008 e portanto não testei esse código nessa versão.

abs

Eliezer

ES

Desculpe a falta de informação mas eu não testei o código no SQL 2012, só testei no 2008

att.
Eliezer
PD

Só pra ficar registrado aqui. A próxima versão do framework virá com suporte nativo à Sql Server e Oracle.

abs,
Pablo
ES

Gostei D+ dessa notícia!!!!

Muito obrigado!

abs,
Eliezer
VC

Pablo, perdão por postar em um post tão antigo, mas vi a interação do Eliezer e me chamou a atenção.... Estou testando o Studio e ao tentar criar as tabelas básicas do Template 3 ocorreu um erro na criação da System_User, não sei se o SQL vai permitir esta criação, poderia por favor me orientar se preciso mudar algo para aceitar? Meu SQL é o 2014 e fica na KingHost.

Abraços

Valdir
CL

Olá pessoal, o erro

42000 continua com o SQL Server no Studio 5.6 ?