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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ per table, one module of constants per enum), `connection.rb` (shared helpers) a
* **Style:** SQL lives in frozen heredoc constants (`GET_AUTHOR_SQL`), comments above a query become its doc comment,
table / column / enum comments of the schema become doc comments of the models. The code is RuboCop-clean; where a
name from your schema breaks a RuboCop naming rule (`"UserId"`, `naïve`), that class or method gets a `rubocop:disable`.
A result column without a usable name (`SELECT 1, now()`) is named by its position: `column_1`, `column_2`, ...

### Transactions
```ruby
Expand Down Expand Up @@ -160,7 +161,7 @@ server; duplicate keys and invalid values raise `Mysql2::Error` instead of being
|---|:---:|:---:|:---:|---|
| `sqlc.arg` | ✅ | ✅ | ✅ | names a parameter (unnamed ones such as `ANY($1::BIGINT[])` become `param1`, ...) |
| `sqlc.narg` | ✅ | ✅ | ✅ | a nullable parameter (`T?`, defaults to `nil`) |
| `sqlc.slice` | 🚫 | ✅ | ✅ | `IN (sqlc.slice(ids))` takes an `Array` (an empty one matches nothing). PostgreSQL: use `= ANY($1::bigint[])` with an array |
| `sqlc.slice` | 🚫 | ✅ | ✅ | `IN (sqlc.slice(ids))` takes an `Array` (an empty one: `IN` matches nothing, `NOT IN` everything). PostgreSQL: use `= ANY($1::bigint[])` with an array |
| `sqlc.embed` | ✅ | ✅ | ✅ | the row gets an attribute holding the table's model (`author`, `author2` for the same table twice); `nil` when an outer join found no row |

🚫 = not offered by sqlc for that database.
Expand Down
5 changes: 5 additions & 0 deletions docs/Coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,10 @@ only when the behavior is rejected or decided during generation and generated co
| Fiber scheduler concurrency / MySQL no prepared-statement leaks | [`test_queries_run_concurrently_under_the_fiber_scheduler`](../tests/end2end_pg.rb#test_queries_run_concurrently_under_the_fiber_scheduler) | [`test_generated_queries_overlap_under_sync_including_transactions`](../tests/end2end_mysql2.rb#test_generated_queries_overlap_under_sync_including_transactions), [`test_generated_queries_do_not_create_server_side_prepared_statements`](../tests/end2end_mysql2.rb#test_generated_queries_do_not_create_server_side_prepared_statements) | [`test_fibers_sharing_a_database_take_turns`](../tests/end2end_sqlite3.rb#test_fibers_sharing_a_database_take_turns) | |
| Duplicate result columns, unsupported options, invalid `:copyfrom` clauses and generation errors | E2E cannot reach generation-time rejection | E2E cannot reach generation-time rejection | E2E cannot reach generation-time rejection | [`test_duplicate_result_columns_are_rejected`](../test/features_test.rb#test_duplicate_result_columns_are_rejected), [`test_copyfrom_keeps_or_rejects_conflict_clauses`](../test/features_test.rb#test_copyfrom_keeps_or_rejects_conflict_clauses), [`test_unknown_options_are_rejected_with_a_hint`](../test/options_test.rb#test_unknown_options_are_rejected_with_a_hint), [`test_query_names_cannot_replace_generated_methods`](../test/features_test.rb#test_query_names_cannot_replace_generated_methods) |
| RuboCop style, query/schema comments and source SQL constants | [`test_flow`](../tests/end2end_pg.rb#test_flow) | [`test_flow`](../tests/end2end_mysql2.rb#test_flow) | [`test_flow`](../tests/end2end_sqlite3.rb#test_flow) | [`test_generated_ruby_is_formatted_like_ruby`](../test/features_test.rb#test_generated_ruby_is_formatted_like_ruby), [`test_query_comments_become_doc_comments`](../test/features_test.rb#test_query_comments_become_doc_comments), [`test_table_column_and_enum_comments_become_doc_comments`](../test/features_test.rb#test_table_column_and_enum_comments_become_doc_comments), [`test_sql_is_a_frozen_raw_heredoc`](../test/features_test.rb#test_sql_is_a_frozen_raw_heredoc) |
| Unnamed result columns (`column_1`, ...) and aliases with quotes | [`test_unnamed_result_columns_are_read_by_position`](../tests/end2end_pg.rb#test_unnamed_result_columns_are_read_by_position), [`test_alias_with_a_quote_is_read`](../tests/end2end_pg.rb#test_alias_with_a_quote_is_read) | [`test_unnamed_result_columns_are_read_by_position`](../tests/end2end_mysql2.rb#test_unnamed_result_columns_are_read_by_position), [`test_alias_with_a_quote_is_read`](../tests/end2end_mysql2.rb#test_alias_with_a_quote_is_read) | [`test_unnamed_result_columns_are_read_by_position`](../tests/end2end_sqlite3.rb#test_unnamed_result_columns_are_read_by_position), [`test_alias_with_a_quote_is_read`](../tests/end2end_sqlite3.rb#test_alias_with_a_quote_is_read) | |
| Empty `sqlc.slice`: `IN` matches nothing, `NOT IN` everything | unit: PostgreSQL uses arrays instead of slices | [`test_empty_slice_matches_nothing`](../tests/end2end_mysql2.rb#test_empty_slice_matches_nothing), [`test_not_in_an_empty_slice_matches_everything`](../tests/end2end_mysql2.rb#test_not_in_an_empty_slice_matches_everything) | [`test_empty_slice_matches_nothing`](../tests/end2end_sqlite3.rb#test_empty_slice_matches_nothing), [`test_not_in_an_empty_slice_matches_everything`](../tests/end2end_sqlite3.rb#test_not_in_an_empty_slice_matches_everything) | |
| A transaction ended by the database keeps the original error; a query abandoned by Timeout is cancelled | [`test_query_abandoned_by_a_timeout_is_cancelled`](../tests/end2end_pg.rb#test_query_abandoned_by_a_timeout_is_cancelled) | [`test_deadlock_in_a_nested_transaction_raises_the_deadlock_error`](../tests/end2end_mysql2.rb#test_deadlock_in_a_nested_transaction_raises_the_deadlock_error) | [`test_conflict_that_ends_the_transaction_raises_the_constraint_error`](../tests/end2end_sqlite3.rb#test_conflict_that_ends_the_transaction_raises_the_constraint_error) | |
| Top-level Float JSON parameters, Symbol enum values | [`test_top_level_float_json_parameters_round_trip_exactly`](../tests/end2end_pg.rb#test_top_level_float_json_parameters_round_trip_exactly) | [`test_symbol_enum_value_is_bound_as_its_name`](../tests/end2end_mysql2.rb#test_symbol_enum_value_is_bound_as_its_name) | not SQLite (no enums / JSON encoding) | |
| Modules sharing a connection keep separate prepared statements | [`test_generator_options_preserve_runtime_values_and_generate_expected_layouts`](../tests/end2end_options.rb#test_generator_options_preserve_runtime_values_and_generate_expected_layouts) | not MySQL (no server-side prepared statements) | not SQLite (statements are per call) | [`test_statements_are_named_after_the_module_and_query_class`](../test/features_test.rb#test_statements_are_named_after_the_module_and_query_class) |

CI runs `test/coverage_map_test.rb`, which checks every linked test method exists in its referenced `tests/` or `test/` file.
9 changes: 9 additions & 0 deletions examples/authors/mysql/query.sql
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,12 @@ SELECT * FROM name_cases WHERE id = sqlc.arg(id);

-- name: TruncateNameCases :exec
TRUNCATE TABLE name_cases;

-- name: GetUnnamedColumns :one
SELECT 1, 'two';

-- name: GetQuotedAlias :one
SELECT 1 AS `it's`;

-- name: GetAuthorsNotInIds :many
SELECT * FROM authors WHERE id NOT IN (sqlc.slice('ids')) ORDER BY id;
6 changes: 6 additions & 0 deletions examples/authors/postgresql/query.sql
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,9 @@ SELECT * FROM name_cases WHERE id = sqlc.arg(id);

-- name: TruncateNameCases :exec
TRUNCATE TABLE name_cases;

-- name: GetUnnamedColumns :one
SELECT 1, 'two';

-- name: GetQuotedAlias :one
SELECT 1 AS "it's";
12 changes: 12 additions & 0 deletions examples/authors/sqlite/query.sql
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,15 @@ SELECT * FROM name_cases WHERE id = sqlc.arg(id);

-- name: TruncateNameCases :exec
DELETE FROM name_cases;

-- name: GetUnnamedColumns :one
SELECT 1, 'two';

-- name: GetQuotedAlias :one
SELECT 1 AS "it's";

-- name: GetAuthorsNotInIds :many
SELECT * FROM authors WHERE id NOT IN (sqlc.slice('ids')) ORDER BY id;

-- name: CreateAuthorOrRollback :exec
INSERT OR ROLLBACK INTO authors (id, name) VALUES (?, ?);
72 changes: 69 additions & 3 deletions examples/mysql2/query_sql.rb
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,29 @@ class GetHTTPServerRow < Data.define(
TRUNCATE TABLE name_cases
SQL

GET_UNNAMED_COLUMNS_SQL = <<~'SQL'
SELECT 1, 'two'
SQL

# rubocop:disable Naming/VariableNumber
class GetUnnamedColumnsRow < Data.define(:column_1, :column_2)
end
# rubocop:enable Naming/VariableNumber

GET_QUOTED_ALIAS_SQL = <<~'SQL'
SELECT 1 AS `it's`
SQL

class GetQuotedAliasRow < Data.define(:it_s)
end

GET_AUTHORS_NOT_IN_IDS_SQL = <<~'SQL'
SELECT id, name, bio FROM authors WHERE id NOT IN (/*SLICE:ids*/?) ORDER BY id
SQL

class GetAuthorsNotInIdsRow < Data.define(:id, :name, :bio)
end

class QuerySql
# Raised by the bang variants (get_author!) when the query returns no row.
class NotFound < StandardError; end
Expand Down Expand Up @@ -475,9 +498,14 @@ def transaction(isolation: nil)
failed = false
begin
yield self
rescue Exception # rubocop:disable Lint/RescueException
rescue Exception => e # rubocop:disable Lint/RescueException
failed = true
client.query(rollback)
begin
client.query(rollback)
rescue Mysql2::Error
# a deadlock / lock wait timeout already rolled back the transaction: its savepoints are gone
raise unless e.is_a?(Mysql2::Error)
end
raise
ensure
begin
Expand Down Expand Up @@ -1142,6 +1170,43 @@ def truncate_name_cases
end
end

def get_unnamed_columns
with_client('get_unnamed_columns') do |client|
result = client.query(bind_params(client, GET_UNNAMED_COLUMNS_SQL, []), as: :array)
row = result.first
row && GetUnnamedColumnsRow.new(row[0], row[1])
end
end

# Like #get_unnamed_columns, but raises NotFound when there is no row.
def get_unnamed_columns!(...)
get_unnamed_columns(...) || raise(NotFound, 'GetUnnamedColumns returned no row')
end

def get_quoted_alias
with_client('get_quoted_alias') do |client|
result = client.query(bind_params(client, GET_QUOTED_ALIAS_SQL, []), as: :array)
row = result.first
row && GetQuotedAliasRow.new(row[0])
end
end

# Like #get_quoted_alias, but raises NotFound when there is no row.
def get_quoted_alias!(...)
get_quoted_alias(...) || raise(NotFound, 'GetQuotedAlias returned no row')
end

def get_authors_not_in_ids(ids:)
with_client('get_authors_not_in_ids') do |client|
query_params = [*ids]
sql = GET_AUTHORS_NOT_IN_IDS_SQL.gsub('/*SLICE:ids*/?', slice_placeholders(ids))
result = client.query(bind_params(client, sql, query_params), as: :array)
result.map do |row|
GetAuthorsNotInIdsRow.new(row[0], row[1], row[2])
end
end
end

private

def instrument(name)
Expand Down Expand Up @@ -1174,6 +1239,7 @@ def with_client(name)
def quote(client, value)
case value
when NilClass then 'NULL'
when Symbol then quote(client, value.to_s)
when TrueClass then 'TRUE'
when FalseClass then 'FALSE'
when Integer then value.to_s
Expand Down Expand Up @@ -1291,7 +1357,7 @@ def load_data(client, sql, strict: true)
end

def slice_placeholders(values)
values.empty? ? 'NULL' : Array.new(values.size, '?').join(', ')
values.empty? ? 'SELECT NULL WHERE FALSE' : Array.new(values.size, '?').join(', ')
end
end
end
34 changes: 34 additions & 0 deletions examples/mysql2/query_sql.rbs
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,30 @@ module Mysql2Codegen

TRUNCATE_NAME_CASES_SQL: String

GET_UNNAMED_COLUMNS_SQL: String

class GetUnnamedColumnsRow
attr_reader column_1: Integer
attr_reader column_2: String
def initialize: ( Integer column_1, String column_2) -> void
end

GET_QUOTED_ALIAS_SQL: String

class GetQuotedAliasRow
attr_reader it_s: Integer
def initialize: ( Integer it_s) -> void
end

GET_AUTHORS_NOT_IN_IDS_SQL: String

class GetAuthorsNotInIdsRow
attr_reader id: Integer
attr_reader name: String
attr_reader bio: String?
def initialize: ( Integer id, String name, String? bio) -> void
end

class QuerySql
class NotFound < StandardError
end
Expand Down Expand Up @@ -615,6 +639,16 @@ module Mysql2Codegen

def truncate_name_cases: -> void

def get_unnamed_columns: -> GetUnnamedColumnsRow?

def get_unnamed_columns!: -> GetUnnamedColumnsRow

def get_quoted_alias: -> GetQuotedAliasRow?

def get_quoted_alias!: -> GetQuotedAliasRow

def get_authors_not_in_ids: (ids: Array[Integer]) -> Array[GetAuthorsNotInIdsRow]

private

def instrument: [T] (String name) { () -> T } -> T
Expand Down
Loading
Loading