-
Notifications
You must be signed in to change notification settings - Fork 102
feat(schema_cache): column
type + query
#163
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
psteinroe
merged 6 commits into
supabase-community:main
from
juleswritescode:schema_cache/columns
Jan 2, 2025
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0ba5470
draft: query columns type
juleswritescode 0d1cb65
updated
juleswritescode 8336135
cleanup
juleswritescode 2838b65
handwritten column incoming
juleswritescode 502649c
add test
juleswritescode d2cce8b
remove unused iimport
juleswritescode File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,202 @@ | ||
use crate::schema_cache::SchemaCacheItem; | ||
|
||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub enum ColumnClassKind { | ||
OrdinaryTable, | ||
View, | ||
MaterializedView, | ||
ForeignTable, | ||
PartitionedTable, | ||
} | ||
|
||
impl From<&str> for ColumnClassKind { | ||
fn from(value: &str) -> Self { | ||
match value { | ||
"r" => ColumnClassKind::OrdinaryTable, | ||
"v" => ColumnClassKind::View, | ||
"m" => ColumnClassKind::MaterializedView, | ||
"f" => ColumnClassKind::ForeignTable, | ||
"p" => ColumnClassKind::PartitionedTable, | ||
_ => panic!( | ||
"Columns belonging to a class with pg_class.relkind = '{}' should be filtered out in the query.", | ||
value | ||
), | ||
} | ||
} | ||
} | ||
|
||
impl From<String> for ColumnClassKind { | ||
fn from(value: String) -> Self { | ||
ColumnClassKind::from(value.as_str()) | ||
} | ||
} | ||
|
||
impl From<char> for ColumnClassKind { | ||
fn from(value: char) -> Self { | ||
ColumnClassKind::from(String::from(value)) | ||
} | ||
} | ||
|
||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub struct Column { | ||
pub name: String, | ||
|
||
pub table_name: String, | ||
pub table_oid: i64, | ||
/// What type of class does this column belong to? | ||
pub class_kind: ColumnClassKind, | ||
|
||
pub schema_name: String, | ||
pub type_id: i64, | ||
pub is_nullable: bool, | ||
|
||
pub is_primary_key: bool, | ||
pub is_unique: bool, | ||
|
||
/// The Default "value" of the column. Might be a function call, hence "_expr". | ||
pub default_expr: Option<String>, | ||
|
||
pub varchar_length: Option<i32>, | ||
|
||
/// Comment inserted via `COMMENT ON COLUMN my_table.my_comment '...'`, if present. | ||
pub comment: Option<String>, | ||
} | ||
|
||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub struct ForeignKeyReference { | ||
pub schema: Option<String>, | ||
pub table: String, | ||
pub column: String, | ||
} | ||
|
||
impl SchemaCacheItem for Column { | ||
type Item = Column; | ||
|
||
async fn load(pool: &sqlx::PgPool) -> Result<Vec<Self::Item>, sqlx::Error> { | ||
sqlx::query_file_as!(Column, "src/queries/columns.sql") | ||
.fetch_all(pool) | ||
.await | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use pg_test_utils::test_database::get_new_test_db; | ||
use sqlx::Executor; | ||
|
||
use crate::{columns::ColumnClassKind, SchemaCache}; | ||
|
||
#[tokio::test] | ||
async fn loads_columns() { | ||
let test_db = get_new_test_db().await; | ||
|
||
let setup = r#" | ||
create table public.users ( | ||
id serial primary key, | ||
name varchar(255) not null, | ||
is_vegetarian bool default false, | ||
middle_name varchar(255) | ||
); | ||
|
||
create schema real_estate; | ||
|
||
create table real_estate.addresses ( | ||
user_id serial references users(id), | ||
postal_code smallint not null, | ||
street text, | ||
city text | ||
); | ||
|
||
create table real_estate.properties ( | ||
id serial primary key, | ||
owner_id int references users(id), | ||
square_meters smallint not null | ||
); | ||
|
||
comment on column real_estate.properties.owner_id is 'users might own many houses'; | ||
"#; | ||
|
||
test_db | ||
.execute(setup) | ||
.await | ||
.expect("Failed to setup test database"); | ||
|
||
let cache = SchemaCache::load(&test_db) | ||
.await | ||
.expect("Failed to load Schema Cache"); | ||
|
||
let public_schema_columns = cache | ||
.columns | ||
.iter() | ||
.filter(|c| c.schema_name.as_str() == "public") | ||
.count(); | ||
|
||
assert_eq!(public_schema_columns, 4); | ||
|
||
let real_estate_schema_columns = cache | ||
.columns | ||
.iter() | ||
.filter(|c| c.schema_name.as_str() == "real_estate") | ||
.count(); | ||
|
||
assert_eq!(real_estate_schema_columns, 7); | ||
|
||
let user_id_col = cache.find_col("id", "users", None).unwrap(); | ||
assert_eq!(user_id_col.class_kind, ColumnClassKind::OrdinaryTable); | ||
assert_eq!(user_id_col.comment, None); | ||
assert_eq!( | ||
user_id_col.default_expr, | ||
Some("nextval('users_id_seq'::regclass)".into()) | ||
); | ||
assert_eq!(user_id_col.is_nullable, false); | ||
assert_eq!(user_id_col.is_primary_key, true); | ||
assert_eq!(user_id_col.is_unique, true); | ||
assert_eq!(user_id_col.varchar_length, None); | ||
|
||
let user_name_col = cache.find_col("name", "users", None).unwrap(); | ||
assert_eq!(user_name_col.class_kind, ColumnClassKind::OrdinaryTable); | ||
assert_eq!(user_name_col.comment, None); | ||
assert_eq!(user_name_col.default_expr, None); | ||
assert_eq!(user_name_col.is_nullable, false); | ||
assert_eq!(user_name_col.is_primary_key, false); | ||
assert_eq!(user_name_col.is_unique, false); | ||
assert_eq!(user_name_col.varchar_length, Some(255)); | ||
|
||
let user_is_veg_col = cache.find_col("is_vegetarian", "users", None).unwrap(); | ||
assert_eq!(user_is_veg_col.class_kind, ColumnClassKind::OrdinaryTable); | ||
assert_eq!(user_is_veg_col.comment, None); | ||
assert_eq!(user_is_veg_col.default_expr, Some("false".into())); | ||
assert_eq!(user_is_veg_col.is_nullable, true); | ||
assert_eq!(user_is_veg_col.is_primary_key, false); | ||
assert_eq!(user_is_veg_col.is_unique, false); | ||
assert_eq!(user_is_veg_col.varchar_length, None); | ||
|
||
let user_middle_name_col = cache.find_col("middle_name", "users", None).unwrap(); | ||
assert_eq!( | ||
user_middle_name_col.class_kind, | ||
ColumnClassKind::OrdinaryTable | ||
); | ||
assert_eq!(user_middle_name_col.comment, None); | ||
assert_eq!(user_middle_name_col.default_expr, None); | ||
assert_eq!(user_middle_name_col.is_nullable, true); | ||
assert_eq!(user_middle_name_col.is_primary_key, false); | ||
assert_eq!(user_middle_name_col.is_unique, false); | ||
assert_eq!(user_middle_name_col.varchar_length, Some(255)); | ||
|
||
let properties_owner_id_col = cache | ||
.find_col("owner_id", "properties", Some("real_estate")) | ||
.unwrap(); | ||
assert_eq!( | ||
properties_owner_id_col.class_kind, | ||
ColumnClassKind::OrdinaryTable | ||
); | ||
assert_eq!( | ||
properties_owner_id_col.comment, | ||
Some("users might own many houses".into()) | ||
); | ||
assert_eq!(properties_owner_id_col.is_nullable, true); | ||
assert_eq!(properties_owner_id_col.is_primary_key, false); | ||
assert_eq!(properties_owner_id_col.is_unique, false); | ||
assert_eq!(properties_owner_id_col.varchar_length, None); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,6 +2,7 @@ | |
|
||
#![allow(dead_code)] | ||
|
||
mod columns; | ||
mod functions; | ||
mod schema_cache; | ||
mod schemas; | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
with | ||
available_tables as ( | ||
select | ||
c.relname as table_name, | ||
c.oid as table_oid, | ||
c.relkind as class_kind, | ||
n.nspname as schema_name | ||
from | ||
pg_catalog.pg_class c | ||
join pg_catalog.pg_namespace n on n.oid = c.relnamespace | ||
where | ||
-- r: normal tables | ||
-- v: views | ||
-- m: materialized views | ||
-- f: foreign tables | ||
-- p: partitioned tables | ||
c.relkind in ('r', 'v', 'm', 'f', 'p') | ||
), | ||
available_indexes as ( | ||
select | ||
unnest (ix.indkey) as attnum, | ||
ix.indisprimary as is_primary, | ||
ix.indisunique as is_unique, | ||
ix.indrelid as table_oid | ||
from | ||
pg_catalog.pg_class c | ||
join pg_catalog.pg_index ix on c.oid = ix.indexrelid | ||
where | ||
c.relkind = 'i' | ||
) | ||
select | ||
atts.attname as name, | ||
ts.table_name, | ||
ts.table_oid :: int8 as "table_oid!", | ||
ts.class_kind :: char as "class_kind!", | ||
ts.schema_name, | ||
atts.atttypid :: int8 as "type_id!", | ||
not atts.attnotnull as "is_nullable!", | ||
nullif( | ||
information_schema._pg_char_max_length (atts.atttypid, atts.atttypmod), | ||
-1 | ||
) as varchar_length, | ||
pg_get_expr (def.adbin, def.adrelid) as default_expr, | ||
coalesce(ix.is_primary, false) as "is_primary_key!", | ||
coalesce(ix.is_unique, false) as "is_unique!", | ||
pg_catalog.col_description (ts.table_oid, atts.attnum) as comment | ||
from | ||
pg_catalog.pg_attribute atts | ||
join available_tables ts on atts.attrelid = ts.table_oid | ||
left join available_indexes ix on atts.attrelid = ix.table_oid | ||
and atts.attnum = ix.attnum | ||
left join pg_catalog.pg_attrdef def on atts.attrelid = def.adrelid | ||
and atts.attnum = def.adnum | ||
where | ||
-- system columns, such as `cmax` or `tableoid`, have negative `attnum`s | ||
atts.attnum >= 0 | ||
order by | ||
schema_name desc, | ||
table_name, | ||
atts.attnum; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note that if we're using compound indexes, e.g.
(user_id, tax_number)
, we'd haveis_primary == true
fortax_number
.This might be problematic for index suggestions etc. – wdyt?