1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25:
26: 27: 28: 29: 30: 31: 32: 33:
34: class DboMssql extends DboSource {
35: 36: 37: 38: 39:
40: var $description = "MS SQL DBO Driver";
41: 42: 43: 44: 45:
46: var $startQuote = "[";
47: 48: 49: 50: 51:
52: var $endQuote = "]";
53: 54: 55: 56: 57: 58:
59: var $__fieldMappings = array();
60: 61: 62: 63: 64:
65: var $_baseConfig = array(
66: 'persistent' => true,
67: 'host' => 'localhost',
68: 'login' => 'root',
69: 'password' => '',
70: 'database' => 'cake',
71: 'port' => '1433',
72: );
73: 74: 75: 76: 77:
78: var $columns = array(
79: 'primary_key' => array('name' => 'IDENTITY (1, 1) NOT NULL'),
80: 'string' => array('name' => 'varchar', 'limit' => '255'),
81: 'text' => array('name' => 'text'),
82: 'integer' => array('name' => 'int', 'formatter' => 'intval'),
83: 'float' => array('name' => 'numeric', 'formatter' => 'floatval'),
84: 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
85: 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
86: 'time' => array('name' => 'datetime', 'format' => 'H:i:s', 'formatter' => 'date'),
87: 'date' => array('name' => 'datetime', 'format' => 'Y-m-d', 'formatter' => 'date'),
88: 'binary' => array('name' => 'image'),
89: 'boolean' => array('name' => 'bit')
90: );
91: 92: 93: 94: 95: 96:
97: var $_commands = array(
98: 'begin' => 'BEGIN TRANSACTION',
99: 'commit' => 'COMMIT',
100: 'rollback' => 'ROLLBACK'
101: );
102: 103: 104: 105: 106: 107:
108: var $__lastQueryHadError = false;
109: 110: 111: 112: 113: 114:
115: function __construct($config, $autoConnect = true) {
116: if ($autoConnect) {
117: if (!function_exists('mssql_min_message_severity')) {
118: trigger_error("PHP SQL Server interface is not installed, cannot continue. For troubleshooting information, see http://php.net/mssql/", E_USER_WARNING);
119: }
120: mssql_min_message_severity(15);
121: mssql_min_error_severity(2);
122: }
123: return parent::__construct($config, $autoConnect);
124: }
125: 126: 127: 128: 129:
130: function connect() {
131: $config = $this->config;
132:
133: $os = env('OS');
134: if (!empty($os) && strpos($os, 'Windows') !== false) {
135: $sep = ',';
136: } else {
137: $sep = ':';
138: }
139: $this->connected = false;
140:
141: if (is_numeric($config['port'])) {
142: $port = $sep . $config['port'];
143: } elseif ($config['port'] === null) {
144: $port = '';
145: } else {
146: $port = '\\' . $config['port'];
147: }
148:
149: if (!$config['persistent']) {
150: $this->connection = mssql_connect($config['host'] . $port, $config['login'], $config['password'], true);
151: } else {
152: $this->connection = mssql_pconnect($config['host'] . $port, $config['login'], $config['password']);
153: }
154:
155: if (mssql_select_db($config['database'], $this->connection)) {
156: $this->_execute("SET DATEFORMAT ymd");
157: $this->connected = true;
158: }
159: return $this->connected;
160: }
161: 162: 163: 164: 165:
166: function enabled() {
167: return extension_loaded('mssql');
168: }
169: 170: 171: 172: 173:
174: function disconnect() {
175: @mssql_free_result($this->results);
176: $this->connected = !@mssql_close($this->connection);
177: return !$this->connected;
178: }
179: 180: 181: 182: 183: 184: 185:
186: function _execute($sql) {
187: $result = @mssql_query($sql, $this->connection);
188: $this->__lastQueryHadError = ($result === false);
189: return $result;
190: }
191: 192: 193: 194: 195:
196: function listSources() {
197: $cache = parent::listSources();
198:
199: if ($cache != null) {
200: return $cache;
201: }
202: $result = $this->fetchAll('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES', false);
203:
204: if (!$result || empty($result)) {
205: return array();
206: } else {
207: $tables = array();
208:
209: foreach ($result as $table) {
210: $tables[] = $table[0]['TABLE_NAME'];
211: }
212:
213: parent::listSources($tables);
214: return $tables;
215: }
216: }
217: 218: 219: 220: 221: 222:
223: function describe(&$model) {
224: $cache = parent::describe($model);
225:
226: if ($cache != null) {
227: return $cache;
228: }
229:
230: $table = $this->fullTableName($model, false);
231: $cols = $this->fetchAll("SELECT COLUMN_NAME as Field, DATA_TYPE as Type, COL_LENGTH('" . $table . "', COLUMN_NAME) as Length, IS_NULLABLE As [Null], COLUMN_DEFAULT as [Default], COLUMNPROPERTY(OBJECT_ID('" . $table . "'), COLUMN_NAME, 'IsIdentity') as [Key], NUMERIC_SCALE as Size FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $table . "'", false);
232:
233: $fields = false;
234: foreach ($cols as $column) {
235: $field = $column[0]['Field'];
236: $fields[$field] = array(
237: 'type' => $this->column($column[0]['Type']),
238: 'null' => (strtoupper($column[0]['Null']) == 'YES'),
239: 'default' => preg_replace("/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/", "$1", $column[0]['Default']),
240: 'length' => intval($column[0]['Length']),
241: 'key' => ($column[0]['Key'] == '1') ? 'primary' : false
242: );
243: if ($fields[$field]['default'] === 'null') {
244: $fields[$field]['default'] = null;
245: } else {
246: $this->value($fields[$field]['default'], $fields[$field]['type']);
247: }
248:
249: if ($fields[$field]['key'] && $fields[$field]['type'] == 'integer') {
250: $fields[$field]['length'] = 11;
251: } elseif (!$fields[$field]['key']) {
252: unset($fields[$field]['key']);
253: }
254: if (in_array($fields[$field]['type'], array('date', 'time', 'datetime', 'timestamp'))) {
255: $fields[$field]['length'] = null;
256: }
257: }
258: $this->__cacheDescription($this->fullTableName($model, false), $fields);
259: return $fields;
260: }
261: 262: 263: 264: 265: 266: 267: 268:
269: function value($data, $column = null, $safe = false) {
270: $parent = parent::value($data, $column, $safe);
271:
272: if ($parent != null) {
273: return $parent;
274: }
275: if ($data === null) {
276: return 'NULL';
277: }
278: if (in_array($column, array('integer', 'float', 'binary')) && $data === '') {
279: return 'NULL';
280: }
281: if ($data === '') {
282: return "''";
283: }
284:
285: switch ($column) {
286: case 'boolean':
287: $data = $this->boolean((bool)$data);
288: break;
289: default:
290: if (get_magic_quotes_gpc()) {
291: $data = stripslashes(str_replace("'", "''", $data));
292: } else {
293: $data = str_replace("'", "''", $data);
294: }
295: break;
296: }
297:
298: if (in_array($column, array('integer', 'float', 'binary')) && is_numeric($data)) {
299: return $data;
300: }
301: return "'" . $data . "'";
302: }
303: 304: 305: 306: 307: 308: 309: 310:
311: function fields(&$model, $alias = null, $fields = array(), $quote = true) {
312: if (empty($alias)) {
313: $alias = $model->alias;
314: }
315: $fields = parent::fields($model, $alias, $fields, false);
316: $count = count($fields);
317:
318: if ($count >= 1 && strpos($fields[0], 'COUNT(*)') === false) {
319: $result = array();
320: for ($i = 0; $i < $count; $i++) {
321: $prepend = '';
322:
323: if (strpos($fields[$i], 'DISTINCT') !== false) {
324: $prepend = 'DISTINCT ';
325: $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
326: }
327: $fieldAlias = count($this->__fieldMappings);
328:
329: if (!preg_match('/\s+AS\s+/i', $fields[$i])) {
330: if (substr($fields[$i], -1) == '*') {
331: if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
332: $build = explode('.', $fields[$i]);
333: $AssociatedModel = $model->{$build[0]};
334: } else {
335: $AssociatedModel = $model;
336: }
337:
338: $_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema()));
339: $result = array_merge($result, $_fields);
340: continue;
341: }
342:
343: if (strpos($fields[$i], '.') === false) {
344: $this->__fieldMappings[$alias . '__' . $fieldAlias] = $alias . '.' . $fields[$i];
345: $fieldName = $this->name($alias . '.' . $fields[$i]);
346: $fieldAlias = $this->name($alias . '__' . $fieldAlias);
347: } else {
348: $build = explode('.', $fields[$i]);
349: $this->__fieldMappings[$build[0] . '__' . $fieldAlias] = $fields[$i];
350: $fieldName = $this->name($build[0] . '.' . $build[1]);
351: $fieldAlias = $this->name(preg_replace("/^\[(.+)\]$/", "$1", $build[0]) . '__' . $fieldAlias);
352: }
353: if ($model->getColumnType($fields[$i]) == 'datetime') {
354: $fieldName = "CONVERT(VARCHAR(20), {$fieldName}, 20)";
355: }
356: $fields[$i] = "{$fieldName} AS {$fieldAlias}";
357: }
358: $result[] = $prepend . $fields[$i];
359: }
360: return $result;
361: } else {
362: return $fields;
363: }
364: }
365: 366: 367: 368: 369: 370: 371: 372: 373: 374: 375:
376: function create(&$model, $fields = null, $values = null) {
377: if (!empty($values)) {
378: $fields = array_combine($fields, $values);
379: }
380: $primaryKey = $this->_getPrimaryKey($model);
381:
382: if (array_key_exists($primaryKey, $fields)) {
383: if (empty($fields[$primaryKey])) {
384: unset($fields[$primaryKey]);
385: } else {
386: $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' ON');
387: }
388: }
389: $result = parent::create($model, array_keys($fields), array_values($fields));
390: if (array_key_exists($primaryKey, $fields) && !empty($fields[$primaryKey])) {
391: $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' OFF');
392: }
393: return $result;
394: }
395: 396: 397: 398: 399: 400: 401: 402: 403: 404:
405: function update(&$model, $fields = array(), $values = null, $conditions = null) {
406: if (!empty($values)) {
407: $fields = array_combine($fields, $values);
408: }
409: if (isset($fields[$model->primaryKey])) {
410: unset($fields[$model->primaryKey]);
411: }
412: if (empty($fields)) {
413: return true;
414: }
415: return parent::update($model, array_keys($fields), array_values($fields), $conditions);
416: }
417: 418: 419: 420: 421:
422: function lastError() {
423: if ($this->__lastQueryHadError) {
424: $error = mssql_get_last_message();
425: if ($error && !preg_match('/contexto de la base de datos a|contesto di database|changed database|contexte de la base de don|datenbankkontext/i', $error)) {
426: return $error;
427: }
428: }
429: return null;
430: }
431: 432: 433: 434: 435: 436:
437: function lastAffected() {
438: if ($this->_result) {
439: return mssql_rows_affected($this->connection);
440: }
441: return null;
442: }
443: 444: 445: 446: 447: 448:
449: function lastNumRows() {
450: if ($this->_result) {
451: return @mssql_num_rows($this->_result);
452: }
453: return null;
454: }
455: 456: 457: 458: 459: 460:
461: function lastInsertId($source = null) {
462: $id = $this->fetchRow('SELECT SCOPE_IDENTITY() AS insertID', false);
463: return $id[0]['insertID'];
464: }
465: 466: 467: 468: 469: 470: 471:
472: function limit($limit, $offset = null) {
473: if ($limit) {
474: $rt = '';
475: if (!strpos(strtolower($limit), 'top') || strpos(strtolower($limit), 'top') === 0) {
476: $rt = ' TOP';
477: }
478: $rt .= ' ' . $limit;
479: if (is_int($offset) && $offset > 0) {
480: $rt .= ' OFFSET ' . $offset;
481: }
482: return $rt;
483: }
484: return null;
485: }
486: 487: 488: 489: 490: 491:
492: function column($real) {
493: if (is_array($real)) {
494: $col = $real['name'];
495:
496: if (isset($real['limit'])) {
497: $col .= '(' . $real['limit'] . ')';
498: }
499: return $col;
500: }
501: $col = str_replace(')', '', $real);
502: $limit = null;
503: if (strpos($col, '(') !== false) {
504: list($col, $limit) = explode('(', $col);
505: }
506:
507: if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
508: return $col;
509: }
510: if ($col == 'bit') {
511: return 'boolean';
512: }
513: if (strpos($col, 'int') !== false) {
514: return 'integer';
515: }
516: if (strpos($col, 'char') !== false) {
517: return 'string';
518: }
519: if (strpos($col, 'text') !== false) {
520: return 'text';
521: }
522: if (strpos($col, 'binary') !== false || $col == 'image') {
523: return 'binary';
524: }
525: if (in_array($col, array('float', 'real', 'decimal', 'numeric'))) {
526: return 'float';
527: }
528: return 'text';
529: }
530: 531: 532: 533: 534:
535: function resultSet(&$results) {
536: $this->results =& $results;
537: $this->map = array();
538: $numFields = mssql_num_fields($results);
539: $index = 0;
540: $j = 0;
541:
542: while ($j < $numFields) {
543: $column = mssql_field_name($results, $j);
544:
545: if (strpos($column, '__')) {
546: if (isset($this->__fieldMappings[$column]) && strpos($this->__fieldMappings[$column], '.')) {
547: $map = explode('.', $this->__fieldMappings[$column]);
548: } elseif (isset($this->__fieldMappings[$column])) {
549: $map = array(0, $this->__fieldMappings[$column]);
550: } else {
551: $map = array(0, $column);
552: }
553: $this->map[$index++] = $map;
554: } else {
555: $this->map[$index++] = array(0, $column);
556: }
557: $j++;
558: }
559: }
560: 561: 562: 563: 564: 565: 566:
567: function renderStatement($type, $data) {
568: switch (strtolower($type)) {
569: case 'select':
570: extract($data);
571: $fields = trim($fields);
572:
573: if (strpos($limit, 'TOP') !== false && strpos($fields, 'DISTINCT ') === 0) {
574: $limit = 'DISTINCT ' . trim($limit);
575: $fields = substr($fields, 9);
576: }
577:
578: if (preg_match('/offset\s+([0-9]+)/i', $limit, $offset)) {
579: $limit = preg_replace('/\s*offset.*$/i', '', $limit);
580: preg_match('/top\s+([0-9]+)/i', $limit, $limitVal);
581: $offset = intval($offset[1]) + intval($limitVal[1]);
582: $rOrder = $this->__switchSort($order);
583: list($order2, $rOrder) = array($this->__mapFields($order), $this->__mapFields($rOrder));
584: return "SELECT * FROM (SELECT {$limit} * FROM (SELECT TOP {$offset} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}) AS Set1 {$rOrder}) AS Set2 {$order2}";
585: } else {
586: return "SELECT {$limit} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}";
587: }
588: break;
589: case "schema":
590: extract($data);
591:
592: foreach ($indexes as $i => $index) {
593: if (preg_match('/PRIMARY KEY/', $index)) {
594: unset($indexes[$i]);
595: break;
596: }
597: }
598:
599: foreach (array('columns', 'indexes') as $var) {
600: if (is_array(${$var})) {
601: ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
602: }
603: }
604: return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
605: break;
606: default:
607: return parent::renderStatement($type, $data);
608: break;
609: }
610: }
611: 612: 613: 614: 615: 616: 617:
618: function __switchSort($order) {
619: $order = preg_replace('/\s+ASC/i', '__tmp_asc__', $order);
620: $order = preg_replace('/\s+DESC/i', ' ASC', $order);
621: return preg_replace('/__tmp_asc__/', ' DESC', $order);
622: }
623: 624: 625: 626: 627: 628: 629:
630: function __mapFields($sql) {
631: if (empty($sql) || empty($this->__fieldMappings)) {
632: return $sql;
633: }
634: foreach ($this->__fieldMappings as $key => $val) {
635: $sql = preg_replace('/' . preg_quote($val) . '/', $this->name($key), $sql);
636: $sql = preg_replace('/' . preg_quote($this->name($val)) . '/', $this->name($key), $sql);
637: }
638: return $sql;
639: }
640: 641: 642: 643: 644: 645: 646: 647:
648: function read(&$model, $queryData = array(), $recursive = null) {
649: $results = parent::read($model, $queryData, $recursive);
650: $this->__fieldMappings = array();
651: return $results;
652: }
653: 654: 655: 656: 657:
658: function fetchResult() {
659: if ($row = mssql_fetch_row($this->results)) {
660: $resultRow = array();
661: $i = 0;
662:
663: foreach ($row as $index => $field) {
664: list($table, $column) = $this->map[$index];
665: $resultRow[$table][$column] = $row[$index];
666: $i++;
667: }
668: return $resultRow;
669: } else {
670: return false;
671: }
672: }
673: 674: 675: 676: 677: 678: 679: 680:
681: function insertMulti($table, $fields, $values) {
682: $primaryKey = $this->_getPrimaryKey($table);
683: $hasPrimaryKey = $primaryKey != null && (
684: (is_array($fields) && in_array($primaryKey, $fields)
685: || (is_string($fields) && strpos($fields, $this->startQuote . $primaryKey . $this->endQuote) !== false))
686: );
687:
688: if ($hasPrimaryKey) {
689: $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' ON');
690: }
691: parent::insertMulti($table, $fields, $values);
692: if ($hasPrimaryKey) {
693: $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' OFF');
694: }
695: }
696: 697: 698: 699: 700: 701: 702:
703: function buildColumn($column) {
704: $result = preg_replace('/(int|integer)\([0-9]+\)/i', '$1', parent::buildColumn($column));
705: if (strpos($result, 'DEFAULT NULL') !== false) {
706: $result = str_replace('DEFAULT NULL', 'NULL', $result);
707: } else if (array_keys($column) == array('type', 'name')) {
708: $result .= ' NULL';
709: }
710: return $result;
711: }
712: 713: 714: 715: 716: 717: 718:
719: function buildIndex($indexes, $table = null) {
720: $join = array();
721:
722: foreach ($indexes as $name => $value) {
723: if ($name == 'PRIMARY') {
724: $join[] = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
725: } else if (isset($value['unique']) && $value['unique']) {
726: $out = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE";
727:
728: if (is_array($value['column'])) {
729: $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
730: } else {
731: $value['column'] = $this->name($value['column']);
732: }
733: $out .= "({$value['column']});";
734: $join[] = $out;
735: }
736: }
737: return $join;
738: }
739: 740: 741: 742: 743: 744: 745:
746: function _getPrimaryKey($model) {
747: if (is_object($model)) {
748: $schema = $model->schema();
749: } else {
750: $schema = $this->describe($model);
751: }
752:
753: foreach ($schema as $field => $props) {
754: if (isset($props['key']) && $props['key'] == 'primary') {
755: return $field;
756: }
757: }
758: return null;
759: }
760: }
761: ?>