/
SqliteDriver.php
94 lines (78 loc) · 2.48 KB
/
SqliteDriver.php
1
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace Lazy\SchemaSqlBuilder;
use Lazy\Schema\SchemaDeclare;
use Lazy\QueryDriver;
/**
* Schema SQL builder
*
* @see http://www.sqlite.org/docs.html
*/
class SqliteDriver
extends BaseDriver
implements DriverInterface
{
function buildColumnSql($schema, $column) {
$name = $column->name;
$isa = $column->isa ?: 'str';
$type = $column->type;
if( ! $type && $isa == 'str' )
$type = 'text';
$sql = $this->driver->getQuoteColumn( $name );
$sql .= ' ' . $type;
if( $column->required )
$sql .= " not null";
/**
* if it's callable, we should not write the result into sql schema
*/
if( null !== ($default = $column->default)
&& ! is_callable($column->default ) )
{
// for raw sql default value
if( is_array($default) ) {
$sql .= ' default ' . $default[0];
} else {
$sql .= ' default ' . $this->driver->inflate($default);
}
}
if( $column->primary )
$sql .= ' primary key';
if( $column->autoIncrement )
$sql .= ' autoincrement';
if( $column->unique )
$sql .= ' unique';
// build reference
// track(
// FOREIGN KEY(trackartist) REFERENCES artist(artistid)
// artist_id INTEGER REFERENCES artist
// )
foreach( $schema->relations as $rel ) {
switch( $rel['type'] ) {
// XXX: keep this
case SchemaDeclare::belongs_to:
$fs = new $rel['foreign']['schema'];
$fcName = $rel['foreign']['column'];
$fc = $fs->columns[$fcName];
break;
case SchemaDeclare::has_one:
if( $rel['self']['column'] == $name ) {
$fs = new $rel['foreign']['schema'];
$sql .= ' references ' . $fs->getTable();
}
break;
}
}
return $sql;
}
public function build(SchemaDeclare $schema)
{
$sql = 'CREATE TABLE '
. $this->driver->getQuoteTableName($schema->getTable()) . " ( \n";
$columnSql = array();
foreach( $schema->columns as $name => $column ) {
$columnSql[] = $this->buildColumnSql( $schema, $column );
}
$sql .= join(",\n",$columnSql);
$sql .= "\n);\n";
return $sql;
}
}