mssql.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PHP versions 4 and 5 |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
  6. // | Stig. S. Bakken, Lukas Smith |
  7. // | All rights reserved. |
  8. // +----------------------------------------------------------------------+
  9. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
  10. // | API as well as database abstraction for PHP applications. |
  11. // | This LICENSE is in the BSD license style. |
  12. // | |
  13. // | Redistribution and use in source and binary forms, with or without |
  14. // | modification, are permitted provided that the following conditions |
  15. // | are met: |
  16. // | |
  17. // | Redistributions of source code must retain the above copyright |
  18. // | notice, this list of conditions and the following disclaimer. |
  19. // | |
  20. // | Redistributions in binary form must reproduce the above copyright |
  21. // | notice, this list of conditions and the following disclaimer in the |
  22. // | documentation and/or other materials provided with the distribution. |
  23. // | |
  24. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
  25. // | Lukas Smith nor the names of his contributors may be used to endorse |
  26. // | or promote products derived from this software without specific prior|
  27. // | written permission. |
  28. // | |
  29. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  30. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  31. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
  32. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
  33. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
  34. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  35. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  36. // | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
  37. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  38. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  39. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
  40. // | POSSIBILITY OF SUCH DAMAGE. |
  41. // +----------------------------------------------------------------------+
  42. // | Authors: Frank M. Kromann <frank@kromann.info> |
  43. // | David Coallier <davidc@php.net> |
  44. // | Lorenzo Alberton <l.alberton@quipo.it> |
  45. // +----------------------------------------------------------------------+
  46. //
  47. // $Id$
  48. //
  49. require_once 'MDB2/Driver/Manager/Common.php';
  50. // {{{ class MDB2_Driver_Manager_mssql
  51. /**
  52. * MDB2 MSSQL driver for the management modules
  53. *
  54. * @package MDB2
  55. * @category Database
  56. * @author Frank M. Kromann <frank@kromann.info>
  57. * @author David Coallier <davidc@php.net>
  58. * @author Lorenzo Alberton <l.alberton@quipo.it>
  59. */
  60. class MDB2_Driver_Manager_mssql extends MDB2_Driver_Manager_Common
  61. {
  62. // {{{ createDatabase()
  63. /**
  64. * create a new database
  65. *
  66. * @param string $name name of the database that should be created
  67. * @param array $options array with collation info
  68. *
  69. * @return mixed MDB2_OK on success, a MDB2 error on failure
  70. * @access public
  71. */
  72. function createDatabase($name, $options = array())
  73. {
  74. $db = $this->getDBInstance();
  75. if (MDB2::isError($db)) {
  76. return $db;
  77. }
  78. $name = $db->quoteIdentifier($name, true);
  79. $query = "CREATE DATABASE $name";
  80. if ($db->options['database_device']) {
  81. $query.= ' ON '.$db->options['database_device'];
  82. $query.= $db->options['database_size'] ? '=' .
  83. $db->options['database_size'] : '';
  84. }
  85. if (!empty($options['collation'])) {
  86. $query .= ' COLLATE ' . $options['collation'];
  87. }
  88. return $db->standaloneQuery($query, null, true);
  89. }
  90. // }}}
  91. // {{{ alterDatabase()
  92. /**
  93. * alter an existing database
  94. *
  95. * @param string $name name of the database that is intended to be changed
  96. * @param array $options array with name, collation info
  97. *
  98. * @return mixed MDB2_OK on success, a MDB2 error on failure
  99. * @access public
  100. */
  101. function alterDatabase($name, $options = array())
  102. {
  103. $db = $this->getDBInstance();
  104. if (MDB2::isError($db)) {
  105. return $db;
  106. }
  107. $query = '';
  108. if (!empty($options['name'])) {
  109. $query .= ' MODIFY NAME = ' .$db->quoteIdentifier($options['name'], true);
  110. }
  111. if (!empty($options['collation'])) {
  112. $query .= ' COLLATE ' . $options['collation'];
  113. }
  114. if (!empty($query)) {
  115. $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true) . $query;
  116. return $db->standaloneQuery($query, null, true);
  117. }
  118. return MDB2_OK;
  119. }
  120. // }}}
  121. // {{{ dropDatabase()
  122. /**
  123. * drop an existing database
  124. *
  125. * @param string $name name of the database that should be dropped
  126. *
  127. * @return mixed MDB2_OK on success, a MDB2 error on failure
  128. * @access public
  129. */
  130. function dropDatabase($name)
  131. {
  132. $db = $this->getDBInstance();
  133. if (MDB2::isError($db)) {
  134. return $db;
  135. }
  136. $name = $db->quoteIdentifier($name, true);
  137. return $db->standaloneQuery("DROP DATABASE $name", null, true);
  138. }
  139. // }}}
  140. // {{{ _getTemporaryTableQuery()
  141. /**
  142. * Override the parent method.
  143. *
  144. * @return string The string required to be placed between "CREATE" and "TABLE"
  145. * to generate a temporary table, if possible.
  146. */
  147. function _getTemporaryTableQuery()
  148. {
  149. return '';
  150. }
  151. // }}}
  152. // {{{ _getAdvancedFKOptions()
  153. /**
  154. * Return the FOREIGN KEY query section dealing with non-standard options
  155. * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
  156. *
  157. * @param array $definition
  158. *
  159. * @return string
  160. * @access protected
  161. */
  162. function _getAdvancedFKOptions($definition)
  163. {
  164. $query = '';
  165. if (!empty($definition['onupdate'])) {
  166. $query .= ' ON UPDATE '.$definition['onupdate'];
  167. }
  168. if (!empty($definition['ondelete'])) {
  169. $query .= ' ON DELETE '.$definition['ondelete'];
  170. }
  171. return $query;
  172. }
  173. // }}}
  174. // {{{ createTable()
  175. /**
  176. * create a new table
  177. *
  178. * @param string $name Name of the database that should be created
  179. * @param array $fields Associative array that contains the definition of each field of the new table
  180. * The indexes of the array entries are the names of the fields of the table an
  181. * the array entry values are associative arrays like those that are meant to be
  182. * passed with the field definitions to get[Type]Declaration() functions.
  183. *
  184. * Example
  185. * array(
  186. *
  187. * 'id' => array(
  188. * 'type' => 'integer',
  189. * 'unsigned' => 1,
  190. * 'notnull' => 1,
  191. * 'default' => 0,
  192. * ),
  193. * 'name' => array(
  194. * 'type' => 'text',
  195. * 'length' => 12,
  196. * ),
  197. * 'description' => array(
  198. * 'type' => 'text',
  199. * 'length' => 12,
  200. * )
  201. * );
  202. * @param array $options An associative array of table options:
  203. * array(
  204. * 'comment' => 'Foo',
  205. * 'temporary' => true|false,
  206. * );
  207. *
  208. * @return mixed MDB2_OK on success, a MDB2 error on failure
  209. * @access public
  210. */
  211. function createTable($name, $fields, $options = array())
  212. {
  213. if (!empty($options['temporary'])) {
  214. $name = '#'.$name;
  215. }
  216. return parent::createTable($name, $fields, $options);
  217. }
  218. // }}}
  219. // {{{ truncateTable()
  220. /**
  221. * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
  222. * it falls back to a DELETE FROM TABLE query)
  223. *
  224. * @param string $name name of the table that should be truncated
  225. * @return mixed MDB2_OK on success, a MDB2 error on failure
  226. * @access public
  227. */
  228. function truncateTable($name)
  229. {
  230. $db = $this->getDBInstance();
  231. if (MDB2::isError($db)) {
  232. return $db;
  233. }
  234. $name = $db->quoteIdentifier($name, true);
  235. $result = $db->exec("TRUNCATE TABLE $name");
  236. if (MDB2::isError($result)) {
  237. return $result;
  238. }
  239. return MDB2_OK;
  240. }
  241. // }}}
  242. // {{{ vacuum()
  243. /**
  244. * Optimize (vacuum) all the tables in the db (or only the specified table)
  245. * and optionally run ANALYZE.
  246. *
  247. * @param string $table table name (all the tables if empty)
  248. * @param array $options an array with driver-specific options:
  249. * - timeout [int] (in seconds) [mssql-only]
  250. * - analyze [boolean] [pgsql and mysql]
  251. * - full [boolean] [pgsql-only]
  252. * - freeze [boolean] [pgsql-only]
  253. *
  254. * NB: you have to run the NSControl Create utility to enable VACUUM
  255. *
  256. * @return mixed MDB2_OK success, a MDB2 error on failure
  257. * @access public
  258. */
  259. function vacuum($table = null, $options = array())
  260. {
  261. $db = $this->getDBInstance();
  262. if (MDB2::isError($db)) {
  263. return $db;
  264. }
  265. $timeout = isset($options['timeout']) ? (int)$options['timeout'] : 300;
  266. $query = 'NSControl Create';
  267. $result = $db->exec($query);
  268. if (MDB2::isError($result)) {
  269. return $result;
  270. }
  271. $result = $db->exec('EXEC NSVacuum '.$timeout);
  272. if (MDB2::isError($result)) {
  273. return $result;
  274. }
  275. return MDB2_OK;
  276. }
  277. // }}}
  278. // {{{ alterTable()
  279. /**
  280. * alter an existing table
  281. *
  282. * @param string $name name of the table that is intended to be changed.
  283. * @param array $changes associative array that contains the details of each type
  284. * of change that is intended to be performed. The types of
  285. * changes that are currently supported are defined as follows:
  286. *
  287. * name
  288. *
  289. * New name for the table.
  290. *
  291. * add
  292. *
  293. * Associative array with the names of fields to be added as
  294. * indexes of the array. The value of each entry of the array
  295. * should be set to another associative array with the properties
  296. * of the fields to be added. The properties of the fields should
  297. * be the same as defined by the MDB2 parser.
  298. *
  299. *
  300. * remove
  301. *
  302. * Associative array with the names of fields to be removed as indexes
  303. * of the array. Currently the values assigned to each entry are ignored.
  304. * An empty array should be used for future compatibility.
  305. *
  306. * rename
  307. *
  308. * Associative array with the names of fields to be renamed as indexes
  309. * of the array. The value of each entry of the array should be set to
  310. * another associative array with the entry named name with the new
  311. * field name and the entry named Declaration that is expected to contain
  312. * the portion of the field declaration already in DBMS specific SQL code
  313. * as it is used in the CREATE TABLE statement.
  314. *
  315. * change
  316. *
  317. * Associative array with the names of the fields to be changed as indexes
  318. * of the array. Keep in mind that if it is intended to change either the
  319. * name of a field and any other properties, the change array entries
  320. * should have the new names of the fields as array indexes.
  321. *
  322. * The value of each entry of the array should be set to another associative
  323. * array with the properties of the fields to that are meant to be changed as
  324. * array entries. These entries should be assigned to the new values of the
  325. * respective properties. The properties of the fields should be the same
  326. * as defined by the MDB2 parser.
  327. *
  328. * Example
  329. * array(
  330. * 'name' => 'userlist',
  331. * 'add' => array(
  332. * 'quota' => array(
  333. * 'type' => 'integer',
  334. * 'unsigned' => 1
  335. * )
  336. * ),
  337. * 'remove' => array(
  338. * 'file_limit' => array(),
  339. * 'time_limit' => array()
  340. * ),
  341. * 'change' => array(
  342. * 'name' => array(
  343. * 'length' => '20',
  344. * 'definition' => array(
  345. * 'type' => 'text',
  346. * 'length' => 20,
  347. * ),
  348. * )
  349. * ),
  350. * 'rename' => array(
  351. * 'sex' => array(
  352. * 'name' => 'gender',
  353. * 'definition' => array(
  354. * 'type' => 'text',
  355. * 'length' => 1,
  356. * 'default' => 'M',
  357. * ),
  358. * )
  359. * )
  360. * )
  361. *
  362. * @param boolean $check indicates whether the function should just check if the DBMS driver
  363. * can perform the requested table alterations if the value is true or
  364. * actually perform them otherwise.
  365. *
  366. * @return mixed MDB2_OK on success, a MDB2 error on failure
  367. * @access public
  368. */
  369. function alterTable($name, $changes, $check)
  370. {
  371. $db = $this->getDBInstance();
  372. if (MDB2::isError($db)) {
  373. return $db;
  374. }
  375. $name_quoted = $db->quoteIdentifier($name, true);
  376. foreach ($changes as $change_name => $change) {
  377. switch ($change_name) {
  378. case 'remove':
  379. case 'rename':
  380. case 'add':
  381. case 'change':
  382. case 'name':
  383. break;
  384. default:
  385. return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
  386. 'change type "'.$change_name.'" not yet supported', __FUNCTION__);
  387. }
  388. }
  389. if ($check) {
  390. return MDB2_OK;
  391. }
  392. $idxname_format = $db->getOption('idxname_format');
  393. $db->setOption('idxname_format', '%s');
  394. if (!empty($changes['remove']) && is_array($changes['remove'])) {
  395. $result = $this->_dropConflictingIndices($name, array_keys($changes['remove']));
  396. if (MDB2::isError($result)) {
  397. $db->setOption('idxname_format', $idxname_format);
  398. return $result;
  399. }
  400. $result = $this->_dropConflictingConstraints($name, array_keys($changes['remove']));
  401. if (MDB2::isError($result)) {
  402. $db->setOption('idxname_format', $idxname_format);
  403. return $result;
  404. }
  405. $query = '';
  406. foreach ($changes['remove'] as $field_name => $field) {
  407. if ($query) {
  408. $query.= ', ';
  409. }
  410. $field_name = $db->quoteIdentifier($field_name, true);
  411. $query.= 'COLUMN ' . $field_name;
  412. }
  413. $result = $db->exec("ALTER TABLE $name_quoted DROP $query");
  414. if (MDB2::isError($result)) {
  415. $db->setOption('idxname_format', $idxname_format);
  416. return $result;
  417. }
  418. }
  419. if (!empty($changes['rename']) && is_array($changes['rename'])) {
  420. foreach ($changes['rename'] as $field_name => $field) {
  421. $field_name = $db->quoteIdentifier($field_name, true);
  422. $result = $db->exec("sp_rename '$name_quoted.$field_name', '".$field['name']."', 'COLUMN'");
  423. if (MDB2::isError($result)) {
  424. $db->setOption('idxname_format', $idxname_format);
  425. return $result;
  426. }
  427. }
  428. }
  429. if (!empty($changes['add']) && is_array($changes['add'])) {
  430. $query = '';
  431. foreach ($changes['add'] as $field_name => $field) {
  432. if ($query) {
  433. $query.= ', ';
  434. } else {
  435. $query.= 'ADD ';
  436. }
  437. $query.= $db->getDeclaration($field['type'], $field_name, $field);
  438. }
  439. $result = $db->exec("ALTER TABLE $name_quoted $query");
  440. if (MDB2::isError($result)) {
  441. $db->setOption('idxname_format', $idxname_format);
  442. return $result;
  443. }
  444. }
  445. $dropped_indices = array();
  446. $dropped_constraints = array();
  447. if (!empty($changes['change']) && is_array($changes['change'])) {
  448. $dropped = $this->_dropConflictingIndices($name, array_keys($changes['change']));
  449. if (MDB2::isError($dropped)) {
  450. $db->setOption('idxname_format', $idxname_format);
  451. return $dropped;
  452. }
  453. $dropped_indices = array_merge($dropped_indices, $dropped);
  454. $dropped = $this->_dropConflictingConstraints($name, array_keys($changes['change']));
  455. if (MDB2::isError($dropped)) {
  456. $db->setOption('idxname_format', $idxname_format);
  457. return $dropped;
  458. }
  459. $dropped_constraints = array_merge($dropped_constraints, $dropped);
  460. foreach ($changes['change'] as $field_name => $field) {
  461. //MSSQL doesn't allow multiple ALTER COLUMNs in one query
  462. $query = 'ALTER COLUMN ';
  463. //MSSQL doesn't allow changing the DEFAULT value of a field in altering mode
  464. if (array_key_exists('default', $field['definition'])) {
  465. unset($field['definition']['default']);
  466. }
  467. $query .= $db->getDeclaration($field['definition']['type'], $field_name, $field['definition']);
  468. $result = $db->exec("ALTER TABLE $name_quoted $query");
  469. if (MDB2::isError($result)) {
  470. $db->setOption('idxname_format', $idxname_format);
  471. return $result;
  472. }
  473. }
  474. }
  475. // restore the dropped conflicting indices and constraints
  476. foreach ($dropped_indices as $index_name => $index) {
  477. $result = $this->createIndex($name, $index_name, $index);
  478. if (MDB2::isError($result)) {
  479. $db->setOption('idxname_format', $idxname_format);
  480. return $result;
  481. }
  482. }
  483. foreach ($dropped_constraints as $constraint_name => $constraint) {
  484. $result = $this->createConstraint($name, $constraint_name, $constraint);
  485. if (MDB2::isError($result)) {
  486. $db->setOption('idxname_format', $idxname_format);
  487. return $result;
  488. }
  489. }
  490. $db->setOption('idxname_format', $idxname_format);
  491. if (!empty($changes['name'])) {
  492. $new_name = $db->quoteIdentifier($changes['name'], true);
  493. $result = $db->exec("sp_rename '$name_quoted', '$new_name'");
  494. if (MDB2::isError($result)) {
  495. return $result;
  496. }
  497. }
  498. return MDB2_OK;
  499. }
  500. // }}}
  501. // {{{ _dropConflictingIndices()
  502. /**
  503. * Drop the indices that prevent a successful ALTER TABLE action
  504. *
  505. * @param string $table table name
  506. * @param array $fields array of names of the fields affected by the change
  507. *
  508. * @return array dropped indices definitions
  509. */
  510. function _dropConflictingIndices($table, $fields)
  511. {
  512. $db = $this->getDBInstance();
  513. if (MDB2::isError($db)) {
  514. return $db;
  515. }
  516. $dropped = array();
  517. $index_names = $this->listTableIndexes($table);
  518. if (MDB2::isError($index_names)) {
  519. return $index_names;
  520. }
  521. $db->loadModule('Reverse');
  522. $indexes = array();
  523. foreach ($index_names as $index_name) {
  524. $idx_def = $db->reverse->getTableIndexDefinition($table, $index_name);
  525. if (!MDB2::isError($idx_def)) {
  526. $indexes[$index_name] = $idx_def;
  527. }
  528. }
  529. foreach ($fields as $field_name) {
  530. foreach ($indexes as $index_name => $index) {
  531. if (!isset($dropped[$index_name]) && array_key_exists($field_name, $index['fields'])) {
  532. $dropped[$index_name] = $index;
  533. $result = $this->dropIndex($table, $index_name);
  534. if (MDB2::isError($result)) {
  535. return $result;
  536. }
  537. }
  538. }
  539. }
  540. return $dropped;
  541. }
  542. // }}}
  543. // {{{ _dropConflictingConstraints()
  544. /**
  545. * Drop the constraints that prevent a successful ALTER TABLE action
  546. *
  547. * @param string $table table name
  548. * @param array $fields array of names of the fields affected by the change
  549. *
  550. * @return array dropped constraints definitions
  551. */
  552. function _dropConflictingConstraints($table, $fields)
  553. {
  554. $db = $this->getDBInstance();
  555. if (MDB2::isError($db)) {
  556. return $db;
  557. }
  558. $dropped = array();
  559. $constraint_names = $this->listTableConstraints($table);
  560. if (MDB2::isError($constraint_names)) {
  561. return $constraint_names;
  562. }
  563. $db->loadModule('Reverse');
  564. $constraints = array();
  565. foreach ($constraint_names as $constraint_name) {
  566. $cons_def = $db->reverse->getTableConstraintDefinition($table, $constraint_name);
  567. if (!MDB2::isError($cons_def)) {
  568. $constraints[$constraint_name] = $cons_def;
  569. }
  570. }
  571. foreach ($fields as $field_name) {
  572. foreach ($constraints as $constraint_name => $constraint) {
  573. if (!isset($dropped[$constraint_name]) && array_key_exists($field_name, $constraint['fields'])) {
  574. $dropped[$constraint_name] = $constraint;
  575. $result = $this->dropConstraint($table, $constraint_name);
  576. if (MDB2::isError($result)) {
  577. return $result;
  578. }
  579. }
  580. }
  581. // also drop implicit DEFAULT constraints
  582. $default = $this->_getTableFieldDefaultConstraint($table, $field_name);
  583. if (!MDB2::isError($default) && !empty($default)) {
  584. $result = $this->dropConstraint($table, $default);
  585. if (MDB2::isError($result)) {
  586. return $result;
  587. }
  588. }
  589. }
  590. return $dropped;
  591. }
  592. // }}}
  593. // {{{ _getTableFieldDefaultConstraint()
  594. /**
  595. * Get the default constraint for a table field
  596. *
  597. * @param string $table name of table that should be used in method
  598. * @param string $field name of field that should be used in method
  599. *
  600. * @return mixed name of default constraint on success, a MDB2 error on failure
  601. * @access private
  602. */
  603. function _getTableFieldDefaultConstraint($table, $field)
  604. {
  605. $db = $this->getDBInstance();
  606. if (MDB2::isError($db)) {
  607. return $db;
  608. }
  609. $table = $db->quoteIdentifier($table, true);
  610. $field = $db->quote($field, 'text');
  611. $query = "SELECT OBJECT_NAME(syscolumns.cdefault)
  612. FROM syscolumns
  613. WHERE syscolumns.id = object_id('$table')
  614. AND syscolumns.name = $field
  615. AND syscolumns.cdefault <> 0";
  616. return $db->queryOne($query);
  617. }
  618. // }}}
  619. // {{{ listTables()
  620. /**
  621. * list all tables in the current database
  622. *
  623. * @return mixed array of table names on success, a MDB2 error on failure
  624. * @access public
  625. */
  626. function listTables()
  627. {
  628. $db = $this->getDBInstance();
  629. if (MDB2::isError($db)) {
  630. return $db;
  631. }
  632. $query = 'EXEC sp_tables @table_type = "\'TABLE\'"';
  633. $table_names = $db->queryCol($query, null, 2);
  634. if (MDB2::isError($table_names)) {
  635. return $table_names;
  636. }
  637. $result = array();
  638. foreach ($table_names as $table_name) {
  639. if (!$this->_fixSequenceName($table_name, true)) {
  640. $result[] = $table_name;
  641. }
  642. }
  643. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  644. $result = array_map(($db->options['field_case'] == CASE_LOWER ?
  645. 'strtolower' : 'strtoupper'), $result);
  646. }
  647. return $result;
  648. }
  649. // }}}
  650. // {{{ listTableFields()
  651. /**
  652. * list all fields in a table in the current database
  653. *
  654. * @param string $table name of table that should be used in method
  655. *
  656. * @return mixed array of field names on success, a MDB2 error on failure
  657. * @access public
  658. */
  659. function listTableFields($table)
  660. {
  661. $db = $this->getDBInstance();
  662. if (MDB2::isError($db)) {
  663. return $db;
  664. }
  665. $table = $db->quote($table, 'text');
  666. $columns = $db->queryCol("SELECT c.name
  667. FROM syscolumns c
  668. LEFT JOIN sysobjects o ON c.id = o.id
  669. WHERE o.name = $table");
  670. if (MDB2::isError($columns)) {
  671. return $columns;
  672. }
  673. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  674. $columns = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $columns);
  675. }
  676. return $columns;
  677. }
  678. // }}}
  679. // {{{ listTableIndexes()
  680. /**
  681. * list all indexes in a table
  682. *
  683. * @param string $table name of table that should be used in method
  684. *
  685. * @return mixed array of index names on success, a MDB2 error on failure
  686. * @access public
  687. */
  688. function listTableIndexes($table)
  689. {
  690. $db = $this->getDBInstance();
  691. if (MDB2::isError($db)) {
  692. return $db;
  693. }
  694. $key_name = 'INDEX_NAME';
  695. $pk_name = 'PK_NAME';
  696. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  697. if ($db->options['field_case'] == CASE_LOWER) {
  698. $key_name = strtolower($key_name);
  699. $pk_name = strtolower($pk_name);
  700. } else {
  701. $key_name = strtoupper($key_name);
  702. $pk_name = strtoupper($pk_name);
  703. }
  704. }
  705. $table = $db->quote($table, 'text');
  706. $query = "EXEC sp_statistics @table_name=$table";
  707. $indexes = $db->queryCol($query, 'text', $key_name);
  708. if (MDB2::isError($indexes)) {
  709. return $indexes;
  710. }
  711. $query = "EXEC sp_pkeys @table_name=$table";
  712. $pk_all = $db->queryCol($query, 'text', $pk_name);
  713. $result = array();
  714. foreach ($indexes as $index) {
  715. if (!in_array($index, $pk_all) && ($index = $this->_fixIndexName($index))) {
  716. $result[$index] = true;
  717. }
  718. }
  719. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  720. $result = array_change_key_case($result, $db->options['field_case']);
  721. }
  722. return array_keys($result);
  723. }
  724. // }}}
  725. // {{{ listDatabases()
  726. /**
  727. * list all databases
  728. *
  729. * @return mixed array of database names on success, a MDB2 error on failure
  730. * @access public
  731. */
  732. function listDatabases()
  733. {
  734. $db = $this->getDBInstance();
  735. if (MDB2::isError($db)) {
  736. return $db;
  737. }
  738. $result = $db->queryCol('SELECT name FROM sys.databases');
  739. if (MDB2::isError($result)) {
  740. return $result;
  741. }
  742. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  743. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  744. }
  745. return $result;
  746. }
  747. // }}}
  748. // {{{ listUsers()
  749. /**
  750. * list all users
  751. *
  752. * @return mixed array of user names on success, a MDB2 error on failure
  753. * @access public
  754. */
  755. function listUsers()
  756. {
  757. $db = $this->getDBInstance();
  758. if (MDB2::isError($db)) {
  759. return $db;
  760. }
  761. $result = $db->queryCol('SELECT DISTINCT loginame FROM master..sysprocesses');
  762. if (MDB2::isError($result) || empty($result)) {
  763. return $result;
  764. }
  765. foreach (array_keys($result) as $k) {
  766. $result[$k] = trim($result[$k]);
  767. }
  768. return $result;
  769. }
  770. // }}}
  771. // {{{ listFunctions()
  772. /**
  773. * list all functions in the current database
  774. *
  775. * @return mixed array of function names on success, a MDB2 error on failure
  776. * @access public
  777. */
  778. function listFunctions()
  779. {
  780. $db = $this->getDBInstance();
  781. if (MDB2::isError($db)) {
  782. return $db;
  783. }
  784. $query = "SELECT name
  785. FROM sysobjects
  786. WHERE objectproperty(id, N'IsMSShipped') = 0
  787. AND (objectproperty(id, N'IsTableFunction') = 1
  788. OR objectproperty(id, N'IsScalarFunction') = 1)";
  789. /*
  790. SELECT ROUTINE_NAME
  791. FROM INFORMATION_SCHEMA.ROUTINES
  792. WHERE ROUTINE_TYPE = 'FUNCTION'
  793. */
  794. $result = $db->queryCol($query);
  795. if (MDB2::isError($result)) {
  796. return $result;
  797. }
  798. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  799. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  800. }
  801. return $result;
  802. }
  803. // }}}
  804. // {{{ listTableTriggers()
  805. /**
  806. * list all triggers in the database that reference a given table
  807. *
  808. * @param string table for which all referenced triggers should be found
  809. *
  810. * @return mixed array of trigger names on success, otherwise, false which
  811. * could be a db error if the db is not instantiated or could
  812. * be the results of the error that occured during the
  813. * querying of the sysobject module.
  814. * @access public
  815. */
  816. function listTableTriggers($table = null)
  817. {
  818. $db = $this->getDBInstance();
  819. if (MDB2::isError($db)) {
  820. return $db;
  821. }
  822. $table = $db->quote($table, 'text');
  823. $query = "SELECT o.name
  824. FROM sysobjects o
  825. WHERE xtype = 'TR'
  826. AND OBJECTPROPERTY(o.id, 'IsMSShipped') = 0";
  827. if (null !== $table) {
  828. $query .= " AND object_name(parent_obj) = $table";
  829. }
  830. $result = $db->queryCol($query);
  831. if (MDB2::isError($result)) {
  832. return $result;
  833. }
  834. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE &&
  835. $db->options['field_case'] == CASE_LOWER)
  836. {
  837. $result = array_map(($db->options['field_case'] == CASE_LOWER ?
  838. 'strtolower' : 'strtoupper'), $result);
  839. }
  840. return $result;
  841. }
  842. // }}}
  843. // {{{ listViews()
  844. /**
  845. * list all views in the current database
  846. *
  847. * @param string database, the current is default
  848. *
  849. * @return mixed array of view names on success, a MDB2 error on failure
  850. * @access public
  851. */
  852. function listViews()
  853. {
  854. $db = $this->getDBInstance();
  855. if (MDB2::isError($db)) {
  856. return $db;
  857. }
  858. $query = "SELECT name
  859. FROM sysobjects
  860. WHERE xtype = 'V'";
  861. /*
  862. SELECT *
  863. FROM sysobjects
  864. WHERE objectproperty(id, N'IsMSShipped') = 0
  865. AND objectproperty(id, N'IsView') = 1
  866. */
  867. $result = $db->queryCol($query);
  868. if (MDB2::isError($result)) {
  869. return $result;
  870. }
  871. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE &&
  872. $db->options['field_case'] == CASE_LOWER)
  873. {
  874. $result = array_map(($db->options['field_case'] == CASE_LOWER ?
  875. 'strtolower' : 'strtoupper'), $result);
  876. }
  877. return $result;
  878. }
  879. // }}}
  880. // {{{ dropIndex()
  881. /**
  882. * drop existing index
  883. *
  884. * @param string $table name of table that should be used in method
  885. * @param string $name name of the index to be dropped
  886. *
  887. * @return mixed MDB2_OK on success, a MDB2 error on failure
  888. * @access public
  889. */
  890. function dropIndex($table, $name)
  891. {
  892. $db = $this->getDBInstance();
  893. if (MDB2::isError($db)) {
  894. return $db;
  895. }
  896. $table = $db->quoteIdentifier($table, true);
  897. $name = $db->quoteIdentifier($db->getIndexName($name), true);
  898. $result = $db->exec("DROP INDEX $table.$name");
  899. if (MDB2::isError($result)) {
  900. return $result;
  901. }
  902. return MDB2_OK;
  903. }
  904. // }}}
  905. // {{{ listTableConstraints()
  906. /**
  907. * list all constraints in a table
  908. *
  909. * @param string $table name of table that should be used in method
  910. *
  911. * @return mixed array of constraint names on success, a MDB2 error on failure
  912. * @access public
  913. */
  914. function listTableConstraints($table)
  915. {
  916. $db = $this->getDBInstance();
  917. if (MDB2::isError($db)) {
  918. return $db;
  919. }
  920. $table = $db->quote($table, 'text');
  921. $query = "SELECT c.constraint_name
  922. FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS c
  923. WHERE c.constraint_catalog = DB_NAME()
  924. AND c.table_name = $table";
  925. $constraints = $db->queryCol($query);
  926. if (MDB2::isError($constraints)) {
  927. return $constraints;
  928. }
  929. $result = array();
  930. foreach ($constraints as $constraint) {
  931. $constraint = $this->_fixIndexName($constraint);
  932. if (!empty($constraint)) {
  933. $result[$constraint] = true;
  934. }
  935. }
  936. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  937. $result = array_change_key_case($result, $db->options['field_case']);
  938. }
  939. return array_keys($result);
  940. }
  941. // }}}
  942. // {{{ createSequence()
  943. /**
  944. * create sequence
  945. *
  946. * @param string $seq_name name of the sequence to be created
  947. * @param string $start start value of the sequence; default is 1
  948. *
  949. * @return mixed MDB2_OK on success, a MDB2 error on failure
  950. * @access public
  951. */
  952. function createSequence($seq_name, $start = 1)
  953. {
  954. $db = $this->getDBInstance();
  955. if (MDB2::isError($db)) {
  956. return $db;
  957. }
  958. $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
  959. $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true);
  960. $query = "CREATE TABLE $sequence_name ($seqcol_name " .
  961. "INT PRIMARY KEY CLUSTERED IDENTITY($start,1) NOT NULL)";
  962. $res = $db->exec($query);
  963. if (MDB2::isError($res)) {
  964. return $res;
  965. }
  966. $query = "SET IDENTITY_INSERT $sequence_name ON ".
  967. "INSERT INTO $sequence_name ($seqcol_name) VALUES ($start)";
  968. $res = $db->exec($query);
  969. if (!MDB2::isError($res)) {
  970. return MDB2_OK;
  971. }
  972. $result = $db->exec("DROP TABLE $sequence_name");
  973. if (MDB2::isError($result)) {
  974. return $db->raiseError($result, null, null,
  975. 'could not drop inconsistent sequence table', __FUNCTION__);
  976. }
  977. return $db->raiseError($res, null, null,
  978. 'could not create sequence table', __FUNCTION__);
  979. }
  980. // }}}
  981. // {{{ dropSequence()
  982. /**
  983. * This function drops an existing sequence
  984. *
  985. * @param string $seq_name name of the sequence to be dropped
  986. *
  987. * @return mixed MDB2_OK on success, a MDB2 error on failure
  988. * @access public
  989. */
  990. function dropSequence($seq_name)
  991. {
  992. $db = $this->getDBInstance();
  993. if (MDB2::isError($db)) {
  994. return $db;
  995. }
  996. $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
  997. $result = $db->exec("DROP TABLE $sequence_name");
  998. if (MDB2::isError($result)) {
  999. return $result;
  1000. }
  1001. return MDB2_OK;
  1002. }
  1003. // }}}
  1004. // {{{ listSequences()
  1005. /**
  1006. * list all sequences in the current database
  1007. *
  1008. * @return mixed array of sequence names on success, a MDB2 error on failure
  1009. * @access public
  1010. */
  1011. function listSequences()
  1012. {
  1013. $db = $this->getDBInstance();
  1014. if (MDB2::isError($db)) {
  1015. return $db;
  1016. }
  1017. $query = "SELECT name FROM sysobjects WHERE xtype = 'U'";
  1018. $table_names = $db->queryCol($query);
  1019. if (MDB2::isError($table_names)) {
  1020. return $table_names;
  1021. }
  1022. $result = array();
  1023. foreach ($table_names as $table_name) {
  1024. if ($sqn = $this->_fixSequenceName($table_name, true)) {
  1025. $result[] = $sqn;
  1026. }
  1027. }
  1028. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1029. $result = array_map(($db->options['field_case'] == CASE_LOWER ?
  1030. 'strtolower' : 'strtoupper'), $result);
  1031. }
  1032. return $result;
  1033. }
  1034. // }}}
  1035. }
  1036. // }}}
  1037. ?>