Help us learn about your current experience with the documentation.
Take the survey.
SQL views OverviewAt GitLab, we use SQL views as an abstraction layer over PostgreSQL’s system catalogs (pg_*
tables). This makes it easier to query the system catalogs from Rails.
For example, the SQL view postgres_sequences
is an abstraction layer over pg_sequence
and other pg_*
tables. It’s queried using the following Rails model:
module Gitlab
module Database
# Backed by the postgres_sequences view
class PostgresSequence < SharedModel
self.primary_key = :seq_name
scope :by_table_name, ->(table_name) { where(table_name: table_name) }
scope :by_col_name, ->(col_name) { where(col_name: col_name) }
end
end
end
This allows us to manage database maintenance tasks through Ruby code:
Gitlab::Database::PostgresSequence.by_table_name('web_hook_logs')
=> #<Gitlab::Database::PostgresSequence:0x0000000301a1d7a0
seq_name: "web_hook_logs_id_seq",
table_name: "web_hook_logs",
col_name: "id",
seq_max: 9223372036854775807,
seq_min: 1,
seq_start: 1>
Benefits
Using these views provides several advantages:
When working with views, always use ActiveRecord models with appropriate scopes and relationships instead of raw SQL queries. Views are read-only by design. When adding new views, ensure proper migrations, models, tests, and documentation are in place.
TestingWhen testing views, use the swapout_view_for_table
helper to temporarily replace a view with a table. This way you can use factories to create records similar to ones returned by the view.
RSpec.describe Gitlab::Database::PostgresSequence do
include Database::DatabaseHelpers
before do
swapout_view_for_table(:postgres_sequences, connection: ApplicationRecord.connection)
end
end
Further Reading
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4