Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Migrate all datetime columns to timestampz

Oliver Güntherb3505de84333
diff --git a/config/initializers/postgresql_timestamp.rb b/config/initializers/postgresql_timestamp.rb
new file mode 100644
index 00000000000..8804d89e586
--- /dev/null
+++ b/config/initializers/postgresql_timestamp.rb
@@ -0,0 +1,4 @@
+Rails.application.config.after_initialize do
+ # Use timestampz to create new timestamp columns, so that we get WITH TIME ZONE support
+ ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.datetime_type = :timestamptz
+end
diff --git a/db/migrate/20220831081937_migrate_timestamps_to_with_timezone.rb b/db/migrate/20220831081937_migrate_timestamps_to_with_timezone.rb
new file mode 100644
index 00000000000..07bc16e5b8a
--- /dev/null
+++ b/db/migrate/20220831081937_migrate_timestamps_to_with_timezone.rb
@@ -0,0 +1,49 @@
+class MigrateTimestampsToWithTimezone < ActiveRecord::Migration[7.0]
+ def up
+ migrate_to_timestampz
+ end
+
+ def down
+ migrate_to_timestamp
+ end
+
+ private
+
+ def migrate_to_timestampz
+ execute <<~SQL.squish
+ DO $$
+ DECLARE
+ t record;
+ BEGIN
+ FOR t IN
+ SELECT column_name, table_name, data_type
+ FROM information_schema.columns
+ WHERE
+ table_schema = ANY (SELECT unnest(string_to_array(replace(setting, '"$user"', CURRENT_USER), ', ')) FROM pg_settings WHERE name = 'search_path')
+ AND data_type = 'timestamp without time zone'
+ LOOP
+ EXECUTE 'ALTER TABLE ' || t.table_name || ' ALTER COLUMN ' || t.column_name || ' TYPE timestamp with time zone USING ' || t.column_name || ' AT TIME ZONE ''UTC''';
+ END LOOP;
+ END$$;
+ SQL
+ end
+
+ def migrate_to_timestamp
+ execute <<~SQL.squish
+ DO $$
+ DECLARE
+ t record;
+ BEGIN
+ FOR t IN
+ SELECT column_name, table_name, data_type
+ FROM information_schema.columns
+ WHERE
+ table_schema = ANY (SELECT unnest(string_to_array(replace(setting, '"$user"', CURRENT_USER), ', ')) FROM pg_settings WHERE name = 'search_path')
+ AND data_type = 'timestamp with time zone'
+ LOOP
+ EXECUTE 'ALTER TABLE ' || t.table_name || ' ALTER COLUMN ' || t.column_name || ' TYPE timestamp without time zone USING ' || t.column_name || ' AT TIME ZONE ''UTC''';
+ END LOOP;
+ END$$;
+ SQL
+ end
+end