In the previous Time Fields - Integer Fields example, the time fields are written with second-level timestamps. But what if we want to control the granularity of time writing and write millisecond-level timestamps? We can use SoftTimeOption to control the granularity of the written time values.

Example SQL

Here’s the MySQL table structure used in the following example code. Since we need to write values with a granularity finer than seconds, the field type uses big int for storage.

  1. CREATE TABLE `user` (
  2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  3. `name` varchar(45) NOT NULL,
  4. `status` tinyint DEFAULT 0,
  5. `created_at` bigint unsigned DEFAULT NULL,
  6. `updated_at` bigint unsigned DEFAULT NULL,
  7. `deleted_at` bigint unsigned DEFAULT NULL,
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Time Fields - SoftTimeOption - 图1tip

If you try to test and view the SQL statements executed by ORM operations, it is recommended to enable debug mode (Documents: ORM Senior - Debug Mode), and the SQL statements will automatically be printed in the log output.

created_at Write Time

  1. // INSERT INTO `user`(`name`,`created_at`,`updated_at`,`deleted_at`) VALUES('john',1731484186556,1731484186556,0)
  2. g.Model("user").SoftTime(gdb.SoftTimeOption{
  3. SoftTimeType: gdb.SoftTimeTypeTimestampMilli,
  4. }).Data(g.Map{"name": "john"}).Insert()

The SoftTimeType controls the time granularity, with the following granularity options:

  1. const (
  2. SoftTimeTypeAuto SoftTimeType = 0 // (Default) Auto detect the field type by table field type.
  3. SoftTimeTypeTime SoftTimeType = 1 // Using datetime as the field value.
  4. SoftTimeTypeTimestamp SoftTimeType = 2 // In unix seconds.
  5. SoftTimeTypeTimestampMilli SoftTimeType = 3 // In unix milliseconds.
  6. SoftTimeTypeTimestampMicro SoftTimeType = 4 // In unix microseconds.
  7. SoftTimeTypeTimestampNano SoftTimeType = 5 // In unix nanoseconds.
  8. )