# Source for file Sqlite.php

Documentation is available at Sqlite.php

1. <?php
2. /*
3. * $Id: Sqlite.php 2288 2007-08-29 21:51:49Z Jonathan.Wage $
4. *
5. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16. *
17. * This software consists of voluntary contributions made by many individuals
18. * and is licensed under the LGPL. For more information, see
19. * <http://www.phpdoctrine.com>.
20. */
21. Doctrine::autoload('Doctrine_Export');
22. /**
23. * Doctrine_Export_Sqlite
24. *
25. * @package Doctrine
26. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
27. * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
28. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
29. * @category Object Relational Mapping
30. * @link www.phpdoctrine.com
31. * @since 1.0
32. * @version $Revision: 2288 $
33. */
34. class Doctrine_Export_Sqlite extends Doctrine_Export
35. {
36. /**
37. * drop an existing database
38. *
39. * @param string $name name of the database that should be dropped
40. * @throws Doctrine_Export_Exception if the database file does not exist
41. * @throws Doctrine_Export_Exception if something failed during the removal of the database file
42. * @return void
43. */
44. public function dropDatabase($name)
45. {
46. $databaseFile = $this->conn->getDatabaseFile($name);
47. if (!@file_exists($databaseFile)) {
48. throw new Doctrine_Export_Exception('database does not exist');
49. }
50. $result = @unlink($databaseFile);
51. if ( ! $result) {
52. throw new Doctrine_Export_Exception('could not remove the database file');
53. }
54. }
56. /**
57. * Get the stucture of a field into an array
58. *
59. * @param string $table name of the table on which the index is to be created
60. * @param string $name name of the index to be created
61. * @param array $definition associative array that defines properties of the index to be created.
62. * Currently, only one property named FIELDS is supported. This property
63. * is also an associative with the names of the index fields as array
64. * indexes. Each entry of this array is set to another type of associative
65. * array that specifies properties of the index that are specific to
66. * each field.
67. *
68. * Currently, only the sorting property is supported. It should be used
69. * to define the sorting direction of the index. It may be set to either
70. * ascending or descending.
71. *
72. * Not all DBMS support index sorting direction configuration. The DBMS
73. * drivers of those that do not support it ignore this property. Use the
74. * function support() to determine whether the DBMS driver can manage indexes.
76. * Example
77. * array(
78. * 'fields' => array(
79. * 'user_name' => array(
80. * 'sorting' => 'ascending'
81. * ),
82. * 'last_login' => array()
83. * )
84. * )
85. * @throws PDOException
86. * @return void
87. */
88. public function createIndexSql($table, $name, array $definition)
89. {
90. $table = $this->conn->quoteIdentifier($table, true);
91. $name = $this->conn->formatter->getIndexName($name);
92. $query = 'CREATE INDEX ' . $name . ' ON ' . $table;
93. $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')';
95. return $query;
96. }
97. /**
98. * getIndexFieldDeclarationList
99. * Obtain DBMS specific SQL code portion needed to set an index
100. * declaration to be used in statements like CREATE TABLE.
101. *
102. * @return string
103. */
104. public function getIndexFieldDeclarationList(array $fields)
105. {
106. $declFields = array();
108. foreach ($fields as $fieldName => $field) {
109. $fieldString = $fieldName;
111. if (is_array($field)) {
112. if (isset($field['sorting'])) {
113. $sort = strtoupper($field['sorting']);
114. switch ($sort) {
115. case 'ASC':
116. case 'DESC':
117. $fieldString .= ' ' . $sort;
118. break;
119. default:
120. throw new Doctrine_Export_Exception('Unknown index sorting option given.');
121. }
122. }
123. } else {
124. $fieldString = $field;
125. }
126. $declFields[] = $fieldString;
127. }
128. return implode(', ', $declFields);
129. }
130. /**
131. * create a new table
132. *
133. * @param string $name Name of the database that should be created
134. * @param array $fields Associative array that contains the definition of each field of the new table
135. * The indexes of the array entries are the names of the fields of the table an
136. * the array entry values are associative arrays like those that are meant to be
137. * passed with the field definitions to get[Type]Declaration() functions.
138. * array(
139. * 'id' => array(
140. * 'type' => 'integer',
141. * 'unsigned' => 1
142. * 'notnull' => 1
143. * 'default' => 0
144. * ),
145. * 'name' => array(
146. * 'type' => 'text',
147. * 'length' => 12
148. * ),
149. * 'password' => array(
150. * 'type' => 'text',
151. * 'length' => 12
152. * )
153. * );
154. * @param array $options An associative array of table options:
155. *
156. * @return void
157. */
158. public function createTableSql($name, array $fields, array $options = array())
159. {
160. if ( ! $name) {
161. throw new Doctrine_Export_Exception('no valid table name specified');
162. }
164. if (empty($fields)) {
165. throw new Doctrine_Export_Exception('no fields specified for table '.$name);
166. }
167. $queryFields = $this->getFieldDeclarationList($fields);
169. $autoinc = false;
170. foreach($fields as $field) {
171. if(isset($field['autoincrement']) && $field['autoincrement'] ||
172. (isset($field['autoinc']) && $field['autoinc'])) {
173. $autoinc = true;
174. break;
175. }
176. }
178. if ( ! $autoinc && isset($options['primary']) && ! empty($options['primary'])) {
179. $queryFields.= ', PRIMARY KEY('.implode(', ', array_values($options['primary'])).')';
180. }
182. $name = $this->conn->quoteIdentifier($name, true);
183. $sql = 'CREATE TABLE ' . $name . ' (' . $queryFields;
185. if ($check = $this->getCheckDeclaration($fields)) {
186. $sql .= ', ' . $check;
187. }
189. if (isset($options['checks']) && $check = $this->getCheckDeclaration($options['checks'])) {
190. $sql .= ', ' . $check;
191. }
193. $sql .= ')';
195. $query[] = $sql;
197. if (isset($options['indexes']) && ! empty($options['indexes'])) {
198. foreach ($options['indexes'] as $index => $definition) {
199. $query[] = $this->createIndexSql($name, $index, $definition);
200. }
201. }
202. return $query;
205. /**
206. try {
208. if ( ! empty($fk)) {
209. $this->conn->beginTransaction();
210. }
212. $ret = $this->conn->exec($query);
214. if ( ! empty($fk)) {
215. foreach ($fk as $definition) {
217. $query = 'CREATE TRIGGER doctrine_' . $name . '_cscd_delete '
218. . 'AFTER DELETE ON ' . $name . ' FOR EACH ROW '
219. . 'BEGIN '
220. . 'DELETE FROM ' . $definition['foreignTable'] . ' WHERE ';
222. $local = (array) $definition['local'];
223. foreach((array) $definition['foreign'] as $k => $field) {
224. $query .= $field . ' = old.' . $local[$k] . ';';
225. }
227. $query .= 'END;';
229. $this->conn->exec($query);
230. }
232. $this->conn->commit();
233. }
236. } catch(Doctrine_Exception $e) {
238. $this->conn->rollback();
240. throw $e;
241. }
242. */
243. }
244. /**
245. * getAdvancedForeignKeyOptions
246. * Return the FOREIGN KEY query section dealing with non-standard options
247. * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
248. *
249. * @param array $definition foreign key definition
250. * @return string
251. * @access protected
252. */
253. public function getAdvancedForeignKeyOptions(array $definition)
254. {
255. $query = '';
256. if (isset($definition['match'])) {
257. $query .= ' MATCH ' . $definition['match'];
258. }
259. if (isset($definition['onUpdate'])) {
260. $query .= ' ON UPDATE ' . $definition['onUpdate'];
261. }
262. if (isset($definition['onDelete'])) {
263. $query .= ' ON DELETE ' . $definition['onDelete'];
264. }
265. if (isset($definition['deferrable'])) {
266. $query .= ' DEFERRABLE';
267. } else {
268. $query .= ' NOT DEFERRABLE';
269. }
270. if (isset($definition['feferred'])) {
271. $query .= ' INITIALLY DEFERRED';
272. } else {
273. $query .= ' INITIALLY IMMEDIATE';
274. }
275. return $query;
276. }
277. /**
278. * create sequence
279. *
280. * @param string $seqName name of the sequence to be created
281. * @param string $start start value of the sequence; default is 1
282. * @param array $options An associative array of table options:
283. * array(
284. * 'comment' => 'Foo',
285. * 'charset' => 'utf8',
286. * 'collate' => 'utf8_unicode_ci',
287. * );
288. * @return boolean
289. */
290. public function createSequence($seqName, $start = 1, array $options = array())
291. {
292. $sequenceName = $this->conn->quoteIdentifier($this->conn->getSequenceName($seqName), true);
293. $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine::ATTR_SEQCOL_NAME), true);
294. $query = 'CREATE TABLE ' . $sequenceName . ' (' . $seqcolName . ' INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)';
296. $this->conn->exec($query);
298. if ($start == 1) {
299. return true;
300. }
302. try {
303. $this->conn->exec('INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES (' . ($start-1) . ')');
304. return true;
305. } catch(Doctrine_Connection_Exception $e) {
306. // Handle error
308. try {
309. $result = $db->exec('DROP TABLE ' . $sequenceName);
310. } catch(Doctrine_Connection_Exception $e) {
311. throw new Doctrine_Export_Exception('could not drop inconsistent sequence table');
312. }
313. }
314. throw new Doctrine_Export_Exception('could not create sequence table');
315. }
316. /**
317. * drop existing sequence
318. *
319. * @param string $sequenceName name of the sequence to be dropped
320. * @return string
321. */
322. public function dropSequenceSql($sequenceName)
323. {
324. $sequenceName = $this->conn->quoteIdentifier($this->conn->getSequenceName($sequenceName), true);
326. return 'DROP TABLE ' . $sequenceName;
327. }
328. }