From ccdc08617b6aa3f740075edffb7f09f30df5557f Mon Sep 17 00:00:00 2001 From: Shintani Teppei Date: Tue, 17 Sep 2024 00:35:39 +0900 Subject: [PATCH] sqlite3: Add database and pragmas (#667) I added the type definitions needed for my use case for the sqlite3 gem. https://github.com/sparklemotion/sqlite3-ruby --- gems/sqlite3/2.0/_test/test.rb | 27 +++++++++++++++++++++++++++ gems/sqlite3/2.0/database.rbs | 20 ++++++++++++++++++++ gems/sqlite3/2.0/pragmas.rbs | 5 +++++ 3 files changed, 52 insertions(+) create mode 100644 gems/sqlite3/2.0/_test/test.rb create mode 100644 gems/sqlite3/2.0/database.rbs create mode 100644 gems/sqlite3/2.0/pragmas.rbs diff --git a/gems/sqlite3/2.0/_test/test.rb b/gems/sqlite3/2.0/_test/test.rb new file mode 100644 index 00000000..7fc8263b --- /dev/null +++ b/gems/sqlite3/2.0/_test/test.rb @@ -0,0 +1,27 @@ +# Write Ruby code to test the RBS. +# It is type checked by `steep check` command. + +require "sqlite3" + +SQLite3::Database.new("test.db").execute("SELECT * FROM users").each do |row| + row[0] # Array +end +SQLite3::Database.new("test.db").execute("SELECT * FROM users") do |row| + row[0] # Array +end + +SQLite3::Database.new("test.db", results_as_hash: true).execute("SELECT * FROM users").each do |row| + row['id'] # Hash +end + +SQLite3::Database.new("test.db", results_as_hash: false).execute("SELECT * FROM users").each do |row| + row[0] # Array +end + +SQLite3::Database.new("test.db") do |db| + db.busy_timeout = 5000 +end + +db = SQLite3::Database.new("test.db") +db.execute("INSERT INTO users (name) VALUES ('john')") +db.changes + 1 diff --git a/gems/sqlite3/2.0/database.rbs b/gems/sqlite3/2.0/database.rbs new file mode 100644 index 00000000..0f9f47b9 --- /dev/null +++ b/gems/sqlite3/2.0/database.rbs @@ -0,0 +1,20 @@ +module SQLite3 + type row_value_type = String | Integer | Float | nil + type result_as_hash = Hash[String, row_value_type] + type result_as_array = Array[row_value_type] + + class Database[ResultType] + include Pragmas + + def self.new: (String file, results_as_hash: true, **untyped) ?{ (Database[result_as_hash]) -> void } -> Database[result_as_hash] + | (String file, results_as_hash: false, **untyped) ?{ (Database[result_as_array]) -> void } -> Database[result_as_array] + | (String file, **untyped) ?{ (Database[result_as_array]) -> void } -> Database[result_as_array] + + def execute: (String sql, *untyped) -> Array[ResultType] + | (String sql, *untyped) { (ResultType) -> void } -> void + + def get_first_row: (String sql, *untyped) -> ResultType? + + def changes: () -> Integer + end +end diff --git a/gems/sqlite3/2.0/pragmas.rbs b/gems/sqlite3/2.0/pragmas.rbs new file mode 100644 index 00000000..f1d02d3d --- /dev/null +++ b/gems/sqlite3/2.0/pragmas.rbs @@ -0,0 +1,5 @@ +module SQLite3 + module Pragmas + def busy_timeout=: (Integer) -> void + end +end