Database functions
It is possible to set the default value when creating or altering a column. To just set a value you can use the following fluent syntax:
Create.Table("TestTable").WithColumn("Name").AsString().Nullable().WithDefaultValue("test");
In addition, in the event you want to pass in arbitrary SQL to the WithDefaultValue
method, you can do so using [raw sql](xref:raw-sql.md]:
Create.Table("TestTable").WithColumn("Name").AsString().Nullable().WithDefaultValue(RawSql.Insert("SYSUTCDATETIME()"));
However, you can take advantage of some database functions to set the default value. The SystemMethods
enum contains five database functions:
Function | Description |
---|---|
NewGuid | Creates a new GUID |
NewSequentialId | Creates a new sequential GUID |
CurrentDateTime | The current (local) timestamp |
CurrentDateTimeOffset | The current (local) timestamp with time zone |
CurrentUTCDateTime | The current (UTC) timestamp |
CurrentUser | The current user name |
These are specific to each database, for example CurrentDateTime calls the GETDATE() function for Sql Server and the now() function for Postgres. By using WithDefault instead of WithDefaultValue, you can pass in one of the enum values.
Create.Table("TestTable").WithColumn("Created").AsDateTime().Nullable().WithDefault(SystemMethods.CurrentDateTime);
Function/Database support matrix
Server | NewGuid | NewSequentialId | CurrentDateTime | CurrentDateTimeOffset | CurrentUTCDateTime | CurrentUser |
---|---|---|---|---|---|---|
DB2 | ☐ | ☐ | ☑ | ☐ | ☑ | ☑ |
Firebird | ☑ | ☑ 1 | ☑ | ☐ | ☐ | ☐ |
Hana | ☐ | ☐ | ☑ | ☐ | ☑ | ☐ |
JET | ☐ | ☐ | ☐ | ☐ | ☐ | ☐ |
MySQL | ☑ | ☑ 1 | ☑ | ☐ | ☑ | ☑ |
Oracle | ☑ | ☑ 1 | ☑ | ☑ | ☑ | ☑ |
Postgres | ☑ 2 | ☑ 2 | ☑ | ☐ | ☑ | ☑ |
Redshift | ☐ | ☐ | ☑ | ☑ 3 | ☑ | ☑ |
SQLite | ☐ | ☐ | ☑ | ☐ | ☑ | ☐ |
SQL Anywhere | ☑ | ☑ 1 | ☑ | ☑ 3 | ☑ | ☑ |
SQL Server 2000 | ☑ | ☑ | ☑ | ☑ 4 | ☑ | ☑ |
SQL Server 2008 | ☑ | ☑ | ☑ | ☑ | ☑ | ☑ |
SQL Server CE | ☑ | ☑ | ☑ | ☑ 4 | ☑ | ☑ |
1 Is the same as NewGuid
2 uuid-ossp extension is required
3 Implicitly contains the offset
4 Same as CurrentDateTime