-
Notifications
You must be signed in to change notification settings - Fork 1
Table queries
SqlBuilder also includes query classes for table-definition statements.
These are:
CreateTableQueryAlterTableQueryDropTableQuery
Unlike the select/insert/update/delete APIs, these are class-based only. There are no builder equivalents at the moment.
To define a create-table query, implement:
createTable(): stringcreateDefinition(): array
use GT\SqlBuilder\Query\Table\CreateTableQuery;
class CreateStudentTable extends CreateTableQuery {
public function createTable():string {
return "student";
}
public function createDefinition():array {
return [
"id varchar(32) not null",
"first_name varchar(32)",
"last_name varchar(32)",
"dob date",
"primary key(id)",
];
}
}If createDefinition() returns an empty array, the query throws SqlBuilderException.
To define an alter-table query, implement:
alterTable(): stringalterOptions(): array
use GT\SqlBuilder\Query\Table\AlterTableQuery;
class AlterStudentTable extends AlterTableQuery {
public function alterTable():string {
return "student";
}
public function alterOptions():array {
return [
"add column telephone int after dob",
"add column email varchar(256) after id",
];
}
}If alterOptions() is empty, the query throws SqlBuilderException.
DropTableQuery is the simplest of the three:
use GT\SqlBuilder\Query\Table\DropTableQuery;
class DropStudentTable extends DropTableQuery {
public function dropTable():string {
return "student";
}
}If you want if exists, include it in the returned string:
public function dropTable():string {
return "if exists student";
}CreateTableQuery definitions and AlterTableQuery options can include SqlQuery objects, not only plain strings.
That is a niche feature, but it is useful when one fragment is easier to model as its own object.
All three table-query classes inherit the usual preQuery() and postQuery() hooks.
That means you can add comments or engine-specific fragments around the main statement when needed.
It is often tempting to make a schema query class highly dynamic. In practice, these classes are easiest to maintain when they represent one concrete statement:
- create one specific table
- alter one table in one defined way
- drop one table
If you need a full migration system, pair these queries with the tool that coordinates execution order and safety in your application.
To see the library patterns gathered into one place, continue with Examples.
PHP.GT/SqlBuilder is a separately maintained component of PHP.GT/WebEngine