Sha256: 3e1b058c5b014cc1fa25d1e15be1c3f339eec681d7a02c3352c354ef446555a3

Contents?: true

Size: 1.58 KB

Versions: 2

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

require "active_record"

class InitialSchema < ActiveRecord::Migration[6.0]
  def change
    create_table :tags, if_not_exists: true do |t|
      t.string :name, null: false
    end

    create_table :alerts, if_not_exists: true do |t|
      t.string :title, null: false
      t.string :description, null: true
      t.string :source, null: false
      t.timestamps
    end

    create_table :artifacts, if_not_exists: true do |t|
      t.string :data, null: false
      t.string :data_type, null: false
      t.belongs_to :alert, foreign_key: true
      t.timestamps
    end

    create_table :taggings, if_not_exists: true do |t|
      t.integer :tag_id
      t.integer :alert_id
    end

    add_index :taggings, :tag_id, if_not_exists: true
    add_index :taggings, [:tag_id, :alert_id], unique: true, if_not_exists: true
  end
end

def adapter
  return "postgresql" if Mihari.config.database.start_with?("postgresql://", "postgres://")

  "sqlite3"
end

module Mihari
  class Database
    class << self
      def connect
        case adapter
        when "postgresql"
          ActiveRecord::Base.establish_connection(Mihari.config.database)
        else
          ActiveRecord::Base.establish_connection(
            adapter: adapter,
            database: Mihari.config.database
          )
        end

        ActiveRecord::Migration.verbose = false
        InitialSchema.migrate(:up)
      rescue
        # Do nothing
      end

      def destroy!
        InitialSchema.migrate(:down) if ActiveRecord::Base.connected?
      end
    end
  end
end

Mihari::Database.connect

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mihari-1.5.1 lib/mihari/database.rb
mihari-1.5.0 lib/mihari/database.rb