LoginSignup
1
0

More than 3 years have passed since last update.

SQLiteでFizzBuzz的な

Last updated at Posted at 2020-05-23

Summary

Sqlでfizzbuzzしてみた

Sqliteでfizzbuzzしてみた

fshrapでfizzbuzzしてみた

とりあえず、メモ書き程度に・・・

つまりは

sqliteのユーザー定義関数をfsharpでかいてべた書きのsqlを実行する

こんな感じ

sqlの実行部


open Callmekohei.MySqlite.MySqlite3

let foo () =
  let db = SQ3 @"C:\Users\callmekohei\Desktop\db/tmp.sqlite"
  let sql =
    @"

-- BigSky : SQLite3 で generate_series(連番)
-- https://mattn.kaoriya.net/software/lang/sql/20150428194911.htm
with
  recursive generate_series(x) as (
    select 1
    union all
    select x+1 from generate_series limit 15
  )

-- ★ここでfizzbuzz関数を使えるのがポイント!
select fizzbuzz(x)
from generate_series
      ;

    ;; "
  db.ConnectionOpen
  db.DumpQuery sql
  db.ConnectionClose

[<EntryPoint>]
let main argv =
  foo()
  0 // return an integer exit code

sqliteのユーザー定義関数


// MySqlite.fs(自作)の一部分

  [<SQLiteFunction(Name = "fizzbuzz", Arguments = 1, FuncType = FunctionType.Scalar)>]
  type Foo () =
    inherit SQLiteFunction()
    override obj.Invoke(args:obj[]) =

      int( string(args.[0]) )
      |> fun x ->
        match x with
        | x when x % 5 = 0 && x % 3 = 0 -> "FizzBuzz"
        | x when x % 3 = 0 -> "Fizz"
        | x when x % 5 = 0 -> "Buzz"
        | x -> string x

      |> fun x -> box<_> x


  type public Sq3Impl( con : System.Data.SQLite.SQLiteConnection) =

    let bindFunction(connection:SQLiteConnection, func ) =
        let attributes =
          func.GetType().GetCustomAttributes(typeof<SQLiteFunctionAttribute>, true)
          |> fun x -> unbox<SQLiteFunctionAttribute>(Array.item 0 x)
        connection.BindFunction(attributes, func)

    member this.ConnectionOpen : unit =
      con.Open()
      bindFunction (con, (new Foo()) )

実行結果

実験 $ dotnet run
fizzbuzz(x)
-----------
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

感想

これは!

相当お仕事に役立ちそう!

参考

Big Sky SQLite3 で generate_series(連番)
C#とPowerShellで色々なDBを操作してみる
SQLite.net SQLiteFunction not working in Linq to SQL

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0