Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions crates/squawk_linter/src/rules/require_table_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,20 @@ pub(crate) fn require_table_schema(ctx: &mut Linter, parse: &Parse<SourceFile>)
ast::Stmt::DropTable(drop_table) => {
check_path(ctx, drop_table.path(), drop_table.syntax());
}
_ => {}
_ => (),
}
}
}

fn check_path(ctx: &mut Linter, path: Option<ast::Path>, syntax: &squawk_syntax::SyntaxNode) {
if let Some(path) = path {
if path.qualifier().is_none() {
ctx.report(Violation::for_node(
Rule::RequireTableSchema,
"Table name is not schema-qualified. Use schema.table (e.g., public.my_table)."
.into(),
syntax,
));
}
if let Some(path) = path
&& path.qualifier().is_none()
{
ctx.report(Violation::for_node(
Rule::RequireTableSchema,
"Table name is not schema-qualified. Use schema.table (e.g., public.my_table).".into(),
syntax,
));
}
}

Expand Down
38 changes: 38 additions & 0 deletions docs/docs/require-table-schema.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
id: require-table-schema
title: require-table-schema
---

## problem

Without an explicit schema, Postgres uses the `search_path` when looking up tables and similar objects. This can result in ambiguity as to what specific table you're acting on.

```sql
-- bad
create table posts(id bigint);

alter table posts add column name text;

drop table posts;

create table posts as select 1;
```

## solution

Specify the schema (i.e., `public`) alongside the table names in your DDL.

```sql
-- good
create table public.posts(id bigint);

alter table public.posts add column name text;

drop table public.posts;

create table public.posts as select 1;
```

## links

- https://www.postgresql.org/docs/current/ddl-schemas.html#DDL-SCHEMAS-PATH
1 change: 1 addition & 0 deletions docs/sidebars.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ module.exports = {
"require-timeout-settings",
"ban-uncommitted-transaction",
"require-enum-value-ordering",
"require-table-schema",
// xtask:new-rule:error-name
],
},
Expand Down
5 changes: 5 additions & 0 deletions docs/src/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,11 @@ const rules = [
tags: ["schema"],
description: "Require BEFORE or AFTER when adding enum values",
},
{
name: "require-table-schema",
tags: ["schema"],
description: "Require explicit schema in table DDL to avoid ambiguity.",
},
// xtask:new-rule:rule-doc-meta
]

Expand Down
Loading