mirror of
https://github.com/scinote-eln/scinote-web.git
synced 2024-12-30 20:23:14 +08:00
69 lines
1.9 KiB
Ruby
69 lines
1.9 KiB
Ruby
module DatabaseHelper
|
|
|
|
# Check if database adapter equals to the specified name
|
|
def db_adapter_is?(adapter_name)
|
|
ActiveRecord::Base.connection.adapter_name == adapter_name
|
|
end
|
|
|
|
# Create PostgreSQL extension. PostgreSQL only!
|
|
def create_extension(ext_name)
|
|
ActiveRecord::Base.connection.execute(
|
|
"CREATE EXTENSION #{ext_name};"
|
|
)
|
|
end
|
|
|
|
# Drop PostgreSQL extension. PostgreSQL only!
|
|
def drop_extension(ext_name)
|
|
ActiveRecord::Base.connection.execute(
|
|
"DROP EXTENSION #{ext_name};"
|
|
)
|
|
end
|
|
|
|
# Create gist trigram index. PostgreSQL only!
|
|
def add_gist_index(table, column)
|
|
ActiveRecord::Base.connection.execute(
|
|
"CREATE INDEX index_#{table}_on_#{column} ON " +
|
|
"#{table} USING gist (#{column} gist_trgm_ops);"
|
|
)
|
|
end
|
|
|
|
# Get size of whole table & its indexes
|
|
# (in bytes). PostgreSQL only!
|
|
def get_table_size(table)
|
|
ActiveRecord::Base.connection.execute(
|
|
"SELECT pg_total_relation_size('#{table}');"
|
|
).getvalue(0, 0).to_i
|
|
end
|
|
|
|
# Get octet length (in bytes) of given column
|
|
# of specified SINGLE ActiveRecord. PostgreSQL only!
|
|
def get_octet_length_record(object, column)
|
|
get_octet_length(
|
|
object.class.to_s.tableize,
|
|
column,
|
|
object.id
|
|
)
|
|
end
|
|
|
|
# Get octet length (in bytes) of given column
|
|
# in table for specific id. PostgreSQL only!
|
|
def get_octet_length(table, column, id)
|
|
ActiveRecord::Base.connection.execute(
|
|
"SELECT octet_length(cast(t.#{column} as text)) FROM #{table} " +
|
|
"AS t WHERE t.id = #{id};"
|
|
).getvalue(0, 0).to_i
|
|
end
|
|
|
|
# Adds email domain constraint to the users table.
|
|
def add_email_constraint(domain)
|
|
ActiveRecord::Base.connection.execute(
|
|
"ALTER TABLE " \
|
|
"users " \
|
|
"DROP CONSTRAINT IF EXISTS email_must_be_company_email, " \
|
|
"ADD CONSTRAINT " \
|
|
"email_must_be_company_email " \
|
|
"CHECK ( email ~* '^[A-Za-z0-9._%-]+@#{domain}' ) " \
|
|
"not valid;"
|
|
)
|
|
end
|
|
end
|