1: <?php
2: /**
3: * @filesource Kotchasan/Database/Schema.php
4: *
5: * @copyright 2016 Goragod.com
6: * @license http://www.kotchasan.com/license/
7: *
8: * @see http://www.kotchasan.com/
9: */
10:
11: namespace Kotchasan\Database;
12:
13: /**
14: * Database schema.
15: *
16: * @author Goragod Wiriya <admin@goragod.com>
17: *
18: * @since 1.0
19: */
20: class Schema
21: {
22: /**
23: * Database object
24: *
25: * @var Driver
26: */
27: private $db;
28: /**
29: * รายการ Schema ที่โหลดแล้ว
30: *
31: * @var array
32: */
33: private $tables = array();
34:
35: /**
36: * Create Schema Class
37: *
38: * @param Driver $db
39: *
40: * @return \static
41: */
42: public static function create(Driver $db)
43: {
44: $obj = new static();
45: $obj->db = $db;
46: return $obj;
47: }
48:
49: /**
50: * อ่านรายชื่อฟิลด์ของตาราง
51: * คืนค่ารายชื่อฟิลด์ทั้งหมดในตาราง.
52: *
53: * @return array
54: */
55: public function fields($table)
56: {
57: if (empty($table)) {
58: throw new \InvalidArgumentException('table name empty in fields');
59: } else {
60: $this->init($table);
61: return array_keys($this->tables[$table]);
62: }
63: }
64:
65: /**
66: * อ่านข้อมูล Schema จากตาราง.
67: *
68: * @param string $table
69: */
70: private function init($table)
71: {
72: if (empty($this->tables[$table])) {
73: $sql = "SHOW FULL COLUMNS FROM $table";
74: $columns = $this->db->cacheOn()->customQuery($sql, true);
75: if (empty($columns)) {
76: throw new \InvalidArgumentException($this->db->getError());
77: } else {
78: $datas = array();
79: foreach ($columns as $column) {
80: $datas[$column['Field']] = $column;
81: }
82: $this->tables[$table] = $datas;
83: }
84: }
85: }
86: }
87: