A platform for community discussion. Free, open, simple.
DEV: Add `badges` converter and importer steps (#33019)
Selase Krakani404dcc7623e4
diff --git a/migrations/config/intermediate_db.yml b/migrations/config/intermediate_db.ymlindex 3402826649c..ebc282bf85c 100644--- a/migrations/config/intermediate_db.yml+++ b/migrations/config/intermediate_db.yml@@ -7,6 +7,14 @@ output:schema:tables:+ badges:+ columns:+ add:+ - name: "existing_id"+ datatype: "numeric"+ exclude:+ - "grant_count"+ - "system"user_emails:columns:include:@@ -68,7 +76,6 @@ schema:- "backup_metadata"- "badge_groupings"- "badge_types"- - "badges"- "bookmarks"- "categories"- "categories_web_hooks"diff --git a/migrations/db/intermediate_db_schema/100-base-schema.sql b/migrations/db/intermediate_db_schema/100-base-schema.sqlindex 4af3ad9e9ef..13408c2f3dd 100644--- a/migrations/db/intermediate_db_schema/100-base-schema.sql+++ b/migrations/db/intermediate_db_schema/100-base-schema.sql@@ -2,6 +2,30 @@-- update the "config/intermediate_db.yml" configuration file and then run-- `bin/cli schema generate` to regenerate this file.+CREATE TABLE badges+(+ original_id NUMERIC NOT NULL PRIMARY KEY,+ allow_title BOOLEAN,+ auto_revoke BOOLEAN,+ badge_grouping_id NUMERIC,+ badge_type_id NUMERIC NOT NULL,+ created_at DATETIME,+ description TEXT,+ enabled BOOLEAN,+ existing_id NUMERIC,+ icon TEXT,+ image_upload_id TEXT,+ listable BOOLEAN,+ long_description TEXT,+ multiple_grant BOOLEAN,+ name TEXT NOT NULL,+ "query" TEXT,+ show_in_post_header BOOLEAN,+ show_posts BOOLEAN,+ target_posts BOOLEAN,+ "trigger" INTEGER+);+CREATE TABLE user_emails(email TEXT NOT NULL,diff --git a/migrations/lib/converters/discourse/steps/badges.rb b/migrations/lib/converters/discourse/steps/badges.rbnew file mode 100644index 00000000000..b8cb8c86759--- /dev/null+++ b/migrations/lib/converters/discourse/steps/badges.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++module Migrations::Converters::Discourse+ class Badges < ::Migrations::Converters::Base::ProgressStep+ attr_accessor :source_db++ def execute+ super+ @upload_creator = UploadCreator.new(column_prefix: "image")+ end++ def max_progress+ @source_db.count <<~SQL+ SELECT COUNT(*) FROM badges+ SQL+ end++ def items+ @source_db.query <<~SQL+ SELECT b.*,+ up.url AS image_url,+ up.original_filename AS image_filename,+ up.origin AS image_origin,+ up.user_id AS image_user_id+ FROM badges b+ LEFT JOIN uploads up ON b.image_upload_id = up.id+ ORDER BY b.id+ SQL+ end++ def process_item(item)+ IntermediateDB::Badge.create(+ original_id: item[:id],+ name: item[:name],+ description: item[:description],+ badge_type_id: item[:badge_type_id],+ created_at: item[:created_at],+ allow_title: item[:allow_title],+ multiple_grant: item[:multiple_grant],+ icon: item[:icon],+ listable: item[:listable],+ target_posts: item[:target_posts],+ query: item[:query],+ enabled: item[:enabled],+ existing_id: item[:system] ? item[:name] : nil,+ auto_revoke: item[:auto_revoke],+ badge_grouping_id: item[:badge_grouping_id],+ trigger: item[:trigger],+ show_posts: item[:show_posts],+ long_description: item[:long_description],+ image_upload_id: @upload_creator.create_for(item),+ show_in_post_header: item[:show_in_post_header],+ )+ end+ end+enddiff --git a/migrations/lib/database/intermediate_db/badge.rb b/migrations/lib/database/intermediate_db/badge.rbnew file mode 100644index 00000000000..cf3e64f7de2--- /dev/null+++ b/migrations/lib/database/intermediate_db/badge.rb@@ -0,0 +1,84 @@+# frozen_string_literal: true++# This file is auto-generated from the IntermediateDB schema. To make changes,+# update the "config/intermediate_db.yml" configuration file and then run+# `bin/cli schema generate` to regenerate this file.++module Migrations::Database::IntermediateDB+ module Badge+ SQL = <<~SQL+ INSERT INTO badges (+ original_id,+ allow_title,+ auto_revoke,+ badge_grouping_id,+ badge_type_id,+ created_at,+ description,+ enabled,+ existing_id,+ icon,+ image_upload_id,+ listable,+ long_description,+ multiple_grant,+ name,+ "query",+ show_in_post_header,+ show_posts,+ target_posts,+ "trigger"+ )+ VALUES (+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?+ )+ SQL++ def self.create(+ original_id:,+ allow_title: nil,+ auto_revoke: nil,+ badge_grouping_id: nil,+ badge_type_id:,+ created_at: nil,+ description: nil,+ enabled: nil,+ existing_id: nil,+ icon: nil,+ image_upload_id: nil,+ listable: nil,+ long_description: nil,+ multiple_grant: nil,+ name:,+ query: nil,+ show_in_post_header: nil,+ show_posts: nil,+ target_posts: nil,+ trigger: nil+ )+ ::Migrations::Database::IntermediateDB.insert(+ SQL,+ original_id,+ ::Migrations::Database.format_boolean(allow_title),+ ::Migrations::Database.format_boolean(auto_revoke),+ badge_grouping_id,+ badge_type_id,+ ::Migrations::Database.format_datetime(created_at),+ description,+ ::Migrations::Database.format_boolean(enabled),+ existing_id,+ icon,+ image_upload_id,+ ::Migrations::Database.format_boolean(listable),+ long_description,+ ::Migrations::Database.format_boolean(multiple_grant),+ name,+ query,+ ::Migrations::Database.format_boolean(show_in_post_header),+ ::Migrations::Database.format_boolean(show_posts),+ ::Migrations::Database.format_boolean(target_posts),+ trigger,+ )+ end+ end+enddiff --git a/migrations/lib/importer/copy_step.rb b/migrations/lib/importer/copy_step.rbindex 825072b2a7b..8e118542023 100644--- a/migrations/lib/importer/copy_step.rb+++ b/migrations/lib/importer/copy_step.rb@@ -147,6 +147,13 @@ module Migrations::Importerrowend+ def ensure_valid_value(value:, allowed_set:, default_value:)+ return value if allowed_set.include?(value)++ yield(value, default_value) if block_given?+ default_value+ end+def find_mapping_type(table_name)constant_name = table_name.to_s.upcasediff --git a/migrations/lib/importer/mapping_type.rb b/migrations/lib/importer/mapping_type.rbindex bd1eff2a201..d2e16c61949 100644--- a/migrations/lib/importer/mapping_type.rb+++ b/migrations/lib/importer/mapping_type.rb@@ -3,6 +3,7 @@module Migrations::Importermodule MappingTypeUSERS = 1+ BADGES = 2UPLOADS = 10endenddiff --git a/migrations/lib/importer/steps/badge_upload_references.rb b/migrations/lib/importer/steps/badge_upload_references.rbnew file mode 100644index 00000000000..00f3aacd23c--- /dev/null+++ b/migrations/lib/importer/steps/badge_upload_references.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++module Migrations::Importer::Steps+ class BadgeUploadReferences < ::Migrations::Importer::Step+ depends_on :badges++ def execute+ super++ DB.exec(<<~SQL)+ INSERT INTO upload_references (upload_id, target_type, target_id, created_at, updated_at)+ SELECT image_upload_id, 'Badge', id, created_at, updated_at+ FROM badges b+ WHERE image_upload_id IS NOT NULL+ ON CONFLICT DO NOTHING+ SQL+ end+ end+enddiff --git a/migrations/lib/importer/steps/badges.rb b/migrations/lib/importer/steps/badges.rbnew file mode 100644index 00000000000..7af0fbb9b3a--- /dev/null+++ b/migrations/lib/importer/steps/badges.rb@@ -0,0 +1,161 @@+# frozen_string_literal: true++module Migrations::Importer::Steps+ class Badges < ::Migrations::Importer::CopyStep+ DEFAULT_ICON = "certificate"+ DUPLICATE_SUFFIX = "_1"+ VALID_TRIGGERS =+ Badge::Trigger+ .constants(false)+ .filter_map { Badge::Trigger.const_get(_1) unless _1 == :DeprecatedPostProcessed }+ .to_set+ .freeze++ depends_on :uploads+ store_mapped_ids true++ requires_mapping :ids_by_name, "SELECT name, id FROM badges"+ requires_set :existing_ids, "SELECT id FROM badges"+ requires_set :existing_names, "SELECT name FROM badges"+ requires_set :existing_badge_grouping_ids, "SELECT id FROM badge_groupings"+ requires_set :existing_badge_type_ids, "SELECT id FROM badge_types"++ column_names %i[+ id+ name+ description+ badge_type_id+ created_at+ updated_at+ allow_title+ multiple_grant+ icon+ listable+ target_posts+ query+ enabled+ auto_revoke+ badge_grouping_id+ trigger+ show_posts+ long_description+ image_upload_id+ show_in_post_header+ ]++ total_rows_query <<~SQL, MappingType::BADGES+ SELECT COUNT(*)+ FROM badges b+ LEFT JOIN mapped.ids mb ON b.original_id = mb.original_id AND mb.type = ?+ WHERE mb.original_id IS NULL+ SQL++ rows_query <<~SQL, MappingType::BADGES, MappingType::UPLOADS+ SELECT b.*,+ mup.discourse_id AS resolved_image_upload_id+ FROM badges b+ LEFT JOIN mapped.ids mb ON b.original_id = mb.original_id AND mb.type = ?1+ LEFT JOIN mapped.ids mup ON b.image_upload_id = mup.original_id AND mup.type = ?2+ WHERE mb.original_id IS NULL+ ORDER BY b.ROWID+ SQL++ private++ def transform_row(row)+ if (existing_id = row[:existing_id])+ row[:id] = resolve_existing_id(existing_id)++ return nil if row[:id]+ end++ row[:name] = ensure_unique_name(row[:name])++ row[:allow_title] ||= false+ row[:multiple_grant] ||= false+ row[:show_posts] ||= false+ row[:show_in_post_header] ||= false+ row[:target_posts] ||= false+ row[:auto_revoke] = true if row[:auto_revoke].nil?+ row[:enabled] = true if row[:enabled].nil?+ row[:listable] = true if row[:listable].nil?++ row[:icon] = DEFAULT_ICON if row[:icon].blank?+ row[:trigger] = ensure_valid_trigger(row)+ row[:badge_grouping_id] = ensure_valid_value(+ value: row[:badge_grouping_id],+ allowed_set: @existing_badge_grouping_ids,+ default_value: BadgeGrouping::Other,+ )+ row[:badge_type_id] = ensure_valid_value(+ value: row[:badge_type_id],+ allowed_set: @existing_badge_type_ids,+ default_value: BadgeType::Silver,+ )+ row[:query] = ensure_valid_query(row)++ row[:image_upload_id] = row[:resolved_image_upload_id]++ super+ end++ def resolve_existing_id(existing_id)+ if existing_id.match?(/\A\d+\z/)+ id = existing_id.to_i+ @existing_ids.include?(id) ? id : nil+ else+ @ids_by_name[existing_id]+ end+ end++ def ensure_unique_name(name)+ return name if @existing_names.add?(name)++ new_name = name + DUPLICATE_SUFFIX+ new_name.next! until @existing_names.add?(new_name)++ new_name+ end++ def ensure_valid_trigger(row)+ ensure_valid_value(+ value: row[:trigger],+ allowed_set: VALID_TRIGGERS,+ default_value: Badge::Trigger::None,+ ) do |invalid, default|+ # TODO(selase): Adopt importer framework warning implementation once available+ puts " #{row[:name]}: Invalid badge trigger '#{invalid}', using default '#{default}'"+ end+ end++ def ensure_valid_query(row)+ query = row[:query].presence++ return nil unless query++ name = row[:name]++ unless SiteSetting.enable_badge_sql?+ # TODO(selase):+ # Adopt importer framework warning implementation once available+ # No need to log this for every badge, just once will suffice. Maybe some+ # top-level prerequisite check with warnings+ puts " #{name}: Badge SQL is not enabled"+ return nil+ end++ begin+ BadgeGranter.contract_checks!(+ query,+ target_posts: row[:target_posts],+ trigger: row[:trigger],+ )+ query+ rescue StandardError => e+ # TODO(selase): Adopt importer framework warning implementation once available+ puts " #{name}: Invalid badge query: #{e.message}"+ nil+ end+ end+ end+enddiff --git a/migrations/spec/lib/database/intermediate_db/badge_spec.rb b/migrations/spec/lib/database/intermediate_db/badge_spec.rbnew file mode 100644index 00000000000..1508ed07549--- /dev/null+++ b/migrations/spec/lib/database/intermediate_db/badge_spec.rb@@ -0,0 +1,5 @@+# frozen_string_literal: true++RSpec.describe ::Migrations::Database::IntermediateDB::Badge do+ it_behaves_like "a database entity"+end