floitet

patroni-test.fsx

Nov 18th, 2020
137
349 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #r "patroni-test/bin/Debug/net5.0/Npgsql.dll"
  2.  
  3. open System
  4. open Npgsql
  5. open System.Threading
  6. open System.Diagnostics
  7.  
  8. let connStrignEntryPoint = "Host=haproxy;Port=5000;Username=approle;Password=appass;Database=postgres"
  9. let dbName = "patronitestdb"
  10.  
  11.  
  12. // time you want the scipt to be up writing to database
  13.  
  14. let testTimeLenght = TimeSpan.FromMinutes(5.)
  15.  
  16.  
  17. let CreateDbIfNotPresent (conStr: string, dbName: string) =
  18.     use conn = new NpgsqlConnection(connStrignEntryPoint)
  19.     use command = new NpgsqlCommand(sprintf @"SELECT DATNAME FROM pg_catalog.pg_database WHERE DATNAME = '%s'" dbName, conn)
  20.     conn.Open()
  21.     let createDb () =
  22.         use cmd = new NpgsqlCommand( sprintf "CREATE DATABASE %s" dbName, conn)
  23.         cmd.ExecuteNonQuery() |> ignore        
  24.     try
  25.         command.ExecuteScalar().ToString() |> ignore  
  26.         conn.Close()          
  27.     with
  28.         | :? System.NullReferenceException as ex -> createDb(); conn.Close()  
  29.  
  30.  
  31.  
  32.  
  33. CreateDbIfNotPresent(connStrignEntryPoint, dbName)
  34.  
  35. let connStringFinal = connStrignEntryPoint.Replace("postgres", dbName)          
  36.  
  37. let WriteToTableForSetTime (connStr: string) =
  38.    
  39.     use conn = new NpgsqlConnection(connStr)
  40.     conn.Open()
  41.     use cmd = new NpgsqlCommand(@"create table if not exists records (time time not null)", conn)
  42.     cmd.ExecuteNonQuery() |> ignore
  43.     conn.Close()
  44.     let mutable flag = true
  45.     let stopwatch = Stopwatch()
  46.     stopwatch.Start()
  47.    
  48.     let writeTime () =
  49.       try
  50.         conn.Open()
  51.         use cmd = new NpgsqlCommand( @"insert into records values (@p)", conn)
  52.         let time = DateTimeOffset.Now
  53.         printfn "%O" time
  54.         cmd.Parameters.AddWithValue("p", time) |> ignore
  55.         cmd.ExecuteNonQuery() |> ignore
  56.         conn.Close()
  57.       with _ -> printfn "Error"; conn.Close()  
  58.  
  59.  
  60.     while (flag) do                
  61.         Thread.Sleep(1000)
  62.         writeTime() |> ignore
  63.         if (stopwatch.Elapsed > testTimeLenght) then flag <- false
  64.            
  65.     stopwatch.Stop()
  66.  
  67.  
  68.  
  69. WriteToTableForSetTime(connStringFinal)
RAW Paste Data