a tiny mvc framework for php using php-activerecord
1<?php
2class DatabaseLoader
3{
4 private $db;
5 static $instances = array();
6
7 public function __construct($db)
8 {
9 $this->db = $db;
10
11 if (!isset(static::$instances[$db->protocol]))
12 static::$instances[$db->protocol] = 0;
13
14 if (static::$instances[$db->protocol]++ == 0)
15 {
16 // drop and re-create the tables one time only
17 $this->drop_tables();
18 $this->exec_sql_script($db->protocol);
19 }
20 }
21
22 public function reset_table_data()
23 {
24 foreach ($this->get_fixture_tables() as $table)
25 {
26 if ($this->db->protocol == 'oci' && $table == 'rm-bldg')
27 continue;
28
29 $this->db->query('DELETE FROM ' . $this->quote_name($table));
30 $this->load_fixture_data($table);
31 }
32
33 try {
34 $this->exec_sql_script("{$this->db->protocol}-after-fixtures");
35 } catch (Exception $e) {
36 // ignore
37 }
38 }
39
40 public function drop_tables()
41 {
42 $tables = $this->db->tables();
43
44 foreach ($this->get_fixture_tables() as $table)
45 {
46 if ($this->db->protocol == 'oci')
47 {
48 $table = strtoupper($table);
49
50 if ($table == 'RM-BLDG')
51 continue;
52 }
53
54 if (in_array($table,$tables))
55 $this->db->query('DROP TABLE ' . $this->quote_name($table));
56
57 if ($this->db->protocol == 'oci')
58 {
59 try {
60 $this->db->query("DROP SEQUENCE {$table}_seq");
61 } catch (ActiveRecord\DatabaseException $e) {
62 // ignore
63 }
64 }
65 }
66 }
67
68 public function exec_sql_script($file)
69 {
70 foreach (explode(';',$this->get_sql($file)) as $sql)
71 {
72 if (trim($sql) != '')
73 $this->db->query($sql);
74 }
75 }
76
77 public function get_fixture_tables()
78 {
79 $tables = array();
80
81 foreach (glob(__DIR__ . '/../fixtures/*.csv') as $file)
82 {
83 $info = pathinfo($file);
84 $tables[] = $info['filename'];
85 }
86
87 return $tables;
88 }
89
90 public function get_sql($file)
91 {
92 $file = __DIR__ . "/../sql/$file.sql";
93
94 if (!file_exists($file))
95 throw new Exception("File not found: $file");
96
97 return file_get_contents($file);
98 }
99
100 public function load_fixture_data($table)
101 {
102 $fp = fopen(__DIR__ . "/../fixtures/$table.csv",'r');
103 $fields = fgetcsv($fp);
104
105 if (!empty($fields))
106 {
107 $markers = join(',',array_fill(0,count($fields),'?'));
108 $table = $this->quote_name($table);
109
110 foreach ($fields as &$name)
111 $name = $this->quote_name($name);
112
113 $fields = join(',',$fields);
114
115 while (($values = fgetcsv($fp)))
116 $this->db->query("INSERT INTO $table($fields) VALUES($markers)",$values);
117 }
118 fclose($fp);
119 }
120
121 public function quote_name($name)
122 {
123 if ($this->db->protocol == 'oci')
124 $name = strtoupper($name);
125
126 return $this->db->quote_name($name);
127 }
128}
129?>