PHP.GT

Table queries

SqlBuilder also includes query classes for table-definition statements.

These are:

  • CreateTableQuery
  • AlterTableQuery
  • DropTableQuery

Unlike the select/insert/update/delete APIs, these are class-based only. There are no builder equivalents at the moment.

CreateTableQuery

To define a create-table query, implement:

  • createTable(): string
  • createDefinition(): 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.

AlterTableQuery

To define an alter-table query, implement:

  • alterTable(): string
  • alterOptions(): 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

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";
}

SqlQuery objects inside definitions and options

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.

preQuery() and postQuery() still apply

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.

Keep these classes focused

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.