· 5 years ago · Nov 18, 2020, 11:00 PM
1#r "patroni-test/bin/Debug/net5.0/Npgsql.dll"
2
3open System
4open Npgsql
5open System.Threading
6open System.Diagnostics
7
8let connStrignEntryPoint = "Host=haproxy;Port=5000;Username=approle;Password=appass;Database=postgres"
9let dbName = "patronitestdb"
10
11
12// time you want the scipt to be up writing to database
13
14let testTimeLenght = TimeSpan.FromMinutes(5.)
15
16
17let 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
33CreateDbIfNotPresent(connStrignEntryPoint, dbName)
34
35let connStringFinal = connStrignEntryPoint.Replace("postgres", dbName)
36
37let 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
69WriteToTableForSetTime(connStringFinal)