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