Laravel timestamps to show milliseconds - php

I need to store updated_at timestamp with high precision on a laravel application, using the format "m-d-Y H:i:s.u" (including milisseconds)
According to laravel documentation, I can customize the date format by setting the $dateFormat property on a class, but...
The main problem is that Laravel's schema builder adds a column of type timestamp in the database when I use $table->nullableTimestamps() And according to mysql documentation, columns of type TIMESTAMP only allow the precision up to seconds..
Any ideas on how I could achieve that?

You can't because the PHP PDO driver doesn't support fractional seconds in timestamps. A work around is to select the timestamp as a string instead so the PDO driver doesn't know its really a timestamp, simply by doing $query->selectRaw(DB::raw("CONCAT(my_date_column) as my_date_column")) however this means you can't use the default select for all fields so querying becomes a real pain. Also you need to override getDateFormat on the model.
// override to include micro seconds when dates are put into mysql.
protected function getDateFormat()
{
return 'Y-m-d H:i:s.u';
}
Finally in your migration rather than nullableTimestamps, outside of the Schema callback do:
DB::statement("ALTER TABLE `$tableName` ADD COLUMN created_at TIMESTAMP(3) NULL");
Note this example was for 3 decimal places however you can have up to 6 if you like, by changing the 3 to a 6 in two places, in the alter table and in the sprintf and also adjusting the multiplier * 1000 to 1000000 for 6.
Hopefully some day PHP PDO will be updated to fix this, but its been over 5 years and nothings changed so I don't have my hopes up. In case you are interested in the details, see this bug report:
http://grokbase.com/t/php/php-bugs/11524dvh68/php-bug-bug-54648-new-pdo-forces-format-of-datetime-fields
I found that link in this other answer which might help you more understand the issue:
https://stackoverflow.com/a/22990991/259521
PHP is really showing its age lately, and I would consider this issue one of my reasons for considering moving to the more modern Node.js.

Based on malhal's answer, I was able to get fractional timestamp reading to work here. Pasting the answer here for convenience:
class BaseModel extends Model
{
protected $dateFormat = 'Y-m-d\TH:i:s.u';
protected function asDateTime($value)
{
try {
return parent::asDateTime($value);
} catch (\InvalidArgumentException $e) {
return parent::asDateTime(new \DateTimeImmutable($value));
}
}
public function newQuery()
{
$query = parent::newQuery();
if($this->usesTimestamps()) {
$table = $this->getTable();
$column = $this->getDeletedAtColumn();
$query->addSelect(DB::raw("concat($table.$column) as $column"));
}
return $query;
}
}
There is a lot going on here because it gets the query with scopes applied and then adds a select for the updated_at column to the end, which overwrites any previously loaded updated_at column later while Laravel hydrates the Model from the query. For being an ugly hack, it worked surprisingly well the very first time.
Timestamps are stored internally as Carbon in Laravel:
dd(MyModel->first()->updated_at->format('Y-m-d H:i:s.u'));
Output:
2017-04-14 22:37:47.426131
Also be sure to run a migration to convert your columns to fractional timestamps. Microsecond precision raises the size of timestamps from 4 bytes to 7 bytes but this is 2017, don't let saving a byte or two by choosing millisecond precision cost you a fortune later when you find yourself serving stale cache entries:
\DB::statement("ALTER TABLE my_table MODIFY updated_at TIMESTAMP(6) NULL DEFAULT NULL");
Sadly I haven't found a way to modify the migration schema timestamps() function to do this.

Related

xmldb_field Moodle change column type

I'm trying to change the column type from a character varying (10) to that of a date.
I can run it individually like so:
ALTER TABLE "tbl_name" ALTER "col_name" TYPE timestamp USING (col_name ::timestamp);
But after throwing this into the upgrade.php script, it barfs on me and requires the USING clause which I can't seem to get to work. Or if there even is a way...
Here's my upgrade.php script:
$table = new xmldb_table('tbl_name');
$field = new xmldb_field('col_name', XMLDB_TYPE_DATETIME);
if ($dbman->field_exists($table, $field)) {
$dbman->change_field_notnull($table, $field);
}
When logging into the Moodle admin and running the update, I get the following error:
ERROR: column "col_name" cannot be cast automatically to type timestamp without time zone HINT: You might need to specify "USING col_name::timestamp without time zone".
Any ideas?
Thanks!
As noted in the Moodle docs (https://docs.moodle.org/dev/XMLDB_column_types) you should avoid using datetime fields - all timestamps in Moodle are declared as integer(10).
If you're using the XMLDB Editor built into Moodle to generate your database table definitions (and you really should do that), then it does not give the option of using the datetime field type.

sequence id increment with date - laravel

I'm trying to create an increment number licence with the current date of the year + an increment number but i really don't know how to do this i know MYSQl does not support sequences but i would like to know if there is a way to solve the problem
here my controller
public function create(){
$licence = new Licence ;
$licence ->num_licence = Carbon::now()->year -- i would like here to put the current year like 2017 with a random unique number to get the format like 20170001 for exemple !
...
how to acheice this? thanks in advance :)
you can use uniqid function with current year as prefix.
public function create(){
$licence = new Licence ;
$num_liscence_exist=true;
while($num_liscence_exist){
$num_liscence=uniqid(Carbon::now()->year);
if (!Liscence_Table::where('num_liscence', '=',"'".$num_liscence."'")->exists()) {
$liscence->num_liscence=$num_liscence;
$num_liscence_exist=false;
}
}
}
Generate the random id using uniqid() and concatenate with date:
public function create(){
$liscence=new Liscence();
$year = Carbon::now()->year;
$liscence->num_liscence= $year. uniqid();
$liscence->save();
}
using uniqid() get unique number or also you can use time stamp with it:
$liscence=new Liscence();
$year = Carbon::now()->year;
$liscence->num_liscence= $year. strtoupper(uniqid()) . Carbon::now()->timestamp;
$liscence->save();
Will look like : 2017ABC011486543961
A sequence needs to be stored somewhere so I doubt there's a sensible pure-PHP solution. But since you're already using MySQL there's no reason to not use it. I'd create a database table for that, something like:
CREATE TABLE licence_sequence (
sequence_year YEAR NOT NULL,
next_value INT UNSIGNED NOT NULL DEFAULT 1,
PRIMARY KEY (sequence_year, next_value)
)
ENGINE=InnoDB;
(Ugly sequence_year name was chosen to avoid having to quote it every time.)
You then have to manage this from code, including:
Ensuring you have rows for every year as you need them (this can be as simple as populating data for all years for next century).
Ensuring you don't assign the same value to different items.
A rough overview of stuff to consider:
You can (and should) make your licence number a unique index to avoid dupes.
You can use transactions to avoid unnecessary gaps. Transaction should wrap all the operations involved:
Get next sequence number
Save it into new licence
Increment next number
You need to ensure atomic operations in a multi-tasking environment. This is the hardest part. I've been lately being playing with MySQL named locks and they seem to work correctly.

Missing leading Zero's when inserting Strings

I actually get very mad about PHP and SQLite3 and the way some of my strings behave there.
I try to save opening hours but in strings instead of numeric to prevent problem with leading zeros (and still have it now haha... -.-).
Hours and minutes have their own column but when I insert '0x' the zero is gone and whatever x is, is left in the database. :/
Im sure im just missing some little damn part somewhere...
I already checked the INSERT-statement but found nothing at all.
Example for an insert string:
INSERT INTO opening INSERT INTO opening (start_day, end_day, start_hour, start_minute, end_hour, end_minute) VALUES('Montag', 'Freitag', '00', '00', '01', '00')
But the output is:
11|Montag|Freitag|0|0|1|0
Part of the Code:
class Database_Opening_Hours extends SQLite3{
function __construct() {
if(!file_exists("../../data/opening_hours/opening_hours.sqlite")){
$this->open("../../data/opening_hours/opening_hours.sqlite");
$this->exec('CREATE TABLE opening (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, start_day STRING, end_day STRING, start_hour STRING, start_minute STRING, end_hour STRING, end_minute STRING)');
}
else{
$this->open("../../data/opening_hours/opening_hours.sqlite");
}
}
}
$db = new Database_Opening_Hours();
$insert = "INSERT INTO opening (start_day, end_day, start_hour, start_minute, end_hour, end_minute) VALUES('".htmlspecialchars($_GET["start_day"])."','".htmlspecialchars($_GET["end_day"])."','".$start_hour."','".$start_minute."','".$end_hour."','".$end_minute."')";
if($db->exec($insert)){
$db->close();
unset($db);
echo "Insert erfolgreich";
}else{
$db->close();
unset($db);
echo "Nicht wirklich...";
}
Fairly sure that the type of your columns is set to an integer (or any other number type) instead of TEXT.
Make sure to double check the column data type and actually dump the table for us to check if it's really set to TEXT.
This is caused by SQLite using dynamic typing. From the FAQ:
This is a feature, not a bug. SQLite uses dynamic typing. It does not enforce data type constraints. Data of any type can (usually) be inserted into any column. You can put arbitrary length strings into integer columns, floating point numbers in boolean columns, or dates in character columns. The datatype you assign to a column in the CREATE TABLE command does not restrict what data can be put into that column. Every column is able to hold an arbitrary length string.
And from the linked page (emphasis mine):
In order to maximize compatibility between SQLite and other database engines, SQLite supports the concept of "type affinity" on columns. The type affinity of a column is the recommended type for data stored in that column. The important idea here is that the type is recommended, not required. Any column can still store any type of data. It is just that some columns, given the choice, will prefer to use one storage class over another. The preferred storage class for a column is called its "affinity".
So SQLite is dynamically casting your values to integer.
I would suggest combining start_hour and start_minute into start_time (the same for the end_ fields) and storing the value in the format 00:00.
SQLite will store this 'as-is' but is smart enough to recognise a time value and allow you to perform date/time operations:
select time(start_time, '+1 hour') from opening
I had this problem with C/C++ because I did not quote the strings:
insert into test values('aa', 'bb');
use varchar instead of string, I had the same problem then I used varchar(length) and it worked fine

Insert current time to MySQL table using CDbMigration

How should I use MySQL's FROM UNIXTIME correctly in CDbMigration in Yii 1.x?
I have borrowed solution of converting current time given as timestamp, to MySQL's DateTime field from this answer and when just printing it:
echo 'FROM_UNIXTIME('.$base.')'."\n";
echo 'FROM_UNIXTIME('.$sixDaysLater.')'."\n";
everything seems fine:
FROM_UNIXTIME(1418223600)
FROM_UNIXTIME(1418742000)
But, when I'm trying to use the same technique as a part of my migration:
$this->insert('contents', array
(
'author_id'=>1,
'type'=>5,
'status'=>1,
'category'=>1,
'title'=>'title',
'body'=>'body',
'creation_date'=>'FROM_UNIXTIME('.$base.')',
'modification_date'=>'FROM_UNIXTIME('.$base.')',
'availability_date'=>'FROM_UNIXTIME('.$sixDaysLater.')',
'short'=>'short'
));
This fails -- that is, migration goes fine, but I can see in phpMyAdmin, that related fields for this record has been populated with zeros (0000-00-00 00:00:00), not with the expected value.
What am I missing? Is it, because values in insert are being encoded / escaped?
You can use CDBExpression instead:
new CDbExpression("NOW()");
I mean:
'creation_date'=>new CDbExpression("NOW()")
Or if you want to use FROM UNIXTIME you can do the same.
CDbExpression represents a DB expression that does not need escaping.

Cassandra / PHPCassa: How do I select all composite columns with a UUID1 after a certain time?

I have a column family in cassandra which records all the events emitted by a particular user over a specified time period.
I'm using a composite column consisting of a UUID1 and a UTF8 string. I'd like to select all the columns after a paticular time.
// Code to create the column family.
use phpcassa\SystemManager;
$sys = new SystemManager('127.0.0.1');
$sys->create_column_family($keyspace, 'UserActivity', array(
"comparator_type" => "CompositeType(LexicalUUIDType, UTF8Type)",
"key_validation_class" => "UTF8Type"
));
In the code below I try to read the data. Initially I tried creating an array with just the event type set at the 1 index, however although this seemed to work I got lots of errors in the log. Now, I'm trying to set a timestamp in the past and base a UUID1 on it. No errors - but no data either.
// Code to read data
$activityFam = new ColumnFamily($this->pool, 'UserActivity');
$activityFam->insert_format = ColumnFamily::ARRAY_FORMAT;
$activityFam->return_format = ColumnFamily::ARRAY_FORMAT;
$fiveMinPrev = $this->dateFactory->getDateTime();
$fiveMinPrev->sub(new \DateInterval("PT5M"));
$uuid = \phpcassa\UUID::uuid1(null, $fiveMinPrev->getTimestamp());
// Get the most recent SESSION event from the users activity log.
$slice = new ColumnSlice(array(0 => $uuid, 1=>self::EVENT_SESSION));
$columns = $activityFam->get($someUserId, $slice);
How do I achieve selecting columns from a specified time onwards?
Thanks,
Bah!
I realised this is exactly the correct approach to take however it seems I wasn't using a timestamp generated by my 'DateFactory' (which allows me to freeze and manipulate time during testing) to base the timestamp on when I actually inserted the record.
Thus producing incorrect results!

Categories