lua-astra 0.47.0

🔥 Blazingly Fast 🔥 runtime environment for Lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use mlua::{ExternalError, LuaSerdeExt, UserData};
use sqlx::{Pool, Postgres, Row, Sqlite, migrate::MigrateDatabase};
use std::{str::FromStr, sync::LazyLock};
use tokio::sync::Mutex;

#[derive(Debug, Clone, serde::Deserialize)]
struct AstraSQLConnectionOption {
    max_connections: Option<u32>,
    extensions: Vec<String>,
    extensions_with_entrypoint: Vec<(String, String)>,
    is_immutable: bool,
    other_options: Vec<(String, String)>,
}

pub static DATABASE_POOLS: LazyLock<Mutex<Vec<DatabaseType>>> =
    LazyLock::new(|| Mutex::new(Vec::new()));

#[derive(Debug, Clone)]
pub enum DatabaseType {
    Sqlite(Pool<Sqlite>),
    Postgres(Pool<Postgres>),
}

#[derive(Debug, Clone)]
pub struct Database {
    pub db: Option<DatabaseType>,
}
impl Database {
    pub fn register_to_lua(lua: &mlua::Lua) -> mlua::Result<()> {
        let database_constructor = lua.create_async_function(
            |lua,
             (database_type, url, connection_options): (
                String,
                String,
                mlua::Value,
            )| async move {
                let connection_options = lua.from_value::<AstraSQLConnectionOption>(connection_options)?;
                let max_connections = connection_options.max_connections.unwrap_or(10);

                // pre checkup
                if database_type == *"sqlite" {
                    match Sqlite::database_exists(url.as_str()).await {
                        Ok(exists) => {
                            if !exists {
                                match Sqlite::create_database(url.as_str()).await {
                                    Ok(()) => {}
                                    Err(e) => println!("Error creating the Sqlite DB: {e:#?}"),
                                }
                            }
                        }
                        Err(e) => println!("Error checking if the Sqlite DB exists: {e:#?}"),
                    }
                }

                match database_type.as_str() {
                    "sqlite" => {
                        match sqlx::sqlite::SqliteConnectOptions::from_str(
                            format!("sqlite:{url}").as_str(),
                        ) {
                            Ok(options) => {
                                let mut options = options.create_if_missing(true);

                                for i in connection_options.extensions {
                                    options = options.extension(i)
                                }
                                for (name, entry_point) in
                                    connection_options.extensions_with_entrypoint
                                {
                                    options = options.extension_with_entrypoint(name, entry_point)
                                }
                                options = options.immutable(connection_options.is_immutable);

                                match sqlx::sqlite::SqlitePoolOptions::new()
                                    .max_connections(max_connections)
                                    .connect_with(options)
                                    .await
                                {
                                    Ok(pool) => {
                                        let pool = DatabaseType::Sqlite(pool);

                                        let mut database_pools = DATABASE_POOLS.lock().await;
                                        database_pools.push(pool.clone());

                                        Ok(Database { db: Some(pool) })
                                    }
                                    Err(e) => Err(mlua::Error::runtime(format!(
                                        "Error connecting to Sqlite: {e:#?}"
                                    ))),
                                }
                            }
                            Err(e) => Err(e.into_lua_err()),
                        }
                    }
                    "postgres" => {
                        //
                        match sqlx::postgres::PgConnectOptions::from_str(url.as_str()) {
                            Ok(options) => {
                                match sqlx::postgres::PgPoolOptions::new()
                                    .max_connections(max_connections)
                                    .connect_with(options.options(connection_options.other_options))
                                    .await
                                {
                                    Ok(pool) => {
                                        let pool = DatabaseType::Postgres(pool);

                                        let mut database_pools = DATABASE_POOLS.lock().await;
                                        database_pools.push(pool.clone());

                                        Ok(Database { db: Some(pool) })
                                    }
                                    Err(e) => Err(mlua::Error::runtime(format!(
                                        "Error connecting to Postgres: {e:#?}"
                                    ))),
                                }
                            }
                            Err(e) => Err(e.into_lua_err()),
                        }
                    }
                    _ => Err(mlua::Error::runtime(
                        "Could not recognize the database type",
                    )),
                }
            },
        )?;
        lua.globals()
            .set("astra_internal__database_connect", database_constructor)?;

        Ok(())
    }
}
impl UserData for Database {
    fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
        macro_rules! parse_sql_fn {
            ($function_name:ident, $row_type:ty) => {
                fn $function_name(lua: &mlua::Lua, row: &$row_type) -> mlua::Result<mlua::Table> {
                    use sqlx::Column;

                    let table = lua.create_table()?;

                    macro_rules! try_set_value {
                        ($i:expr, $key:expr, $ty:ty) => {
                            if let Ok(v) = row.try_get::<$ty, _>($i) {
                                table.set($key, v)?;
                                continue;
                            } else if let Ok(v) = row.try_get::<Option<$ty>, _>($i) {
                                table.set($key, v)?;
                                continue;
                            }
                        };
                    }

                    macro_rules! try_set_lua_value {
                        ($i:expr, $key:expr, $ty:ty) => {
                            if let Ok(v) = row.try_get::<$ty, _>($i) {
                                table.set($key, lua.to_value(&v)?)?;
                                continue;
                            } else if let Ok(v) = row.try_get::<Option<$ty>, _>($i) {
                                table.set($key, lua.to_value(&v)?)?;
                                continue;
                            }
                        };
                    }

                    for i in 0..row.len() {
                        let key = row.column(i).name();

                        try_set_value!(i, key, i64);
                        try_set_value!(i, key, i32);
                        try_set_value!(i, key, i16);
                        try_set_value!(i, key, i8);
                        try_set_value!(i, key, f32);
                        try_set_value!(i, key, f64);
                        try_set_value!(i, key, bool);
                        try_set_value!(i, key, String);
                        try_set_value!(i, key, Vec<u8>);

                        try_set_lua_value!(i, key, serde_json::Value);
                        try_set_lua_value!(i, key, chrono::DateTime<chrono::Utc>);
                        try_set_lua_value!(i, key, uuid::Uuid);

                        // fallback if all fail
                        table.set(key, mlua::Value::Nil)?;
                    }

                    Ok(table)
                }
            };
        }
        // This is because of the duplicated code that would break or
        // become too complicated if traits are introduced.
        //
        // Maybe one day a better solution will be introduced.
        parse_sql_fn!(parse_sql_to_lua_postgres, sqlx::postgres::PgRow);
        parse_sql_fn!(parse_sql_to_lua_sqlite, sqlx::sqlite::SqliteRow);

        macro_rules! query_builder_fn {
            ($function_name:ident, $return_type:ty) => {
                #[allow(mismatched_lifetime_syntaxes)]
                fn $function_name(
                    lua: mlua::Lua,
                    sql: &str,
                    parameters: Option<mlua::Table>,
                ) -> $return_type {
                    let mut query = sqlx::query(sql);

                    match parameters {
                        Some(param_values) => {
                            // turn parameters into actual values
                            for param in param_values
                                .sequence_values::<mlua::Value>()
                                .filter_map(|value| match value {
                                    Ok(value) => Some(value),
                                    Err(_) => None,
                                })
                                .collect::<Vec<_>>()
                            {
                                match param {
                                    mlua::Value::String(value) => {
                                        query = query.bind(value.to_string_lossy())
                                    }
                                    mlua::Value::Number(value) => query = query.bind(value),
                                    mlua::Value::Integer(value) => query = query.bind(value),
                                    mlua::Value::Boolean(value) => query = query.bind(value),
                                    mlua::Value::Table(_) => {
                                        if let Ok(json) =
                                            lua.from_value::<serde_json::Value>(param.clone())
                                        {
                                            query = query.bind(json)
                                        }
                                    }

                                    _ => {}
                                }
                            }
                        }
                        None => {}
                    };

                    query
                }
            };
        }
        query_builder_fn!(
            query_builder_postgres,
            sqlx::query::Query<'_, sqlx::Postgres, sqlx::postgres::PgArguments>
        );
        query_builder_fn!(
            query_builder_sqlite,
            sqlx::query::Query<'_, sqlx::Sqlite, sqlx::sqlite::SqliteArguments>
        );

        methods.add_async_method(
            "execute",
            |lua, this, (sql, parameters): (String, Option<mlua::Table>)| async move {
                match &this.db {
                    Some(db) => match &db {
                        DatabaseType::Sqlite(pool) => {
                            let query = query_builder_sqlite(lua.clone(), &sql, parameters);

                            match query.execute(pool).await {
                                Ok(_) => Ok(()),
                                Err(e) => Err(mlua::Error::runtime(format!(
                                    "Error executing the query: {e:#?}"
                                ))),
                            }
                        }
                        DatabaseType::Postgres(pool) => {
                            let query = query_builder_postgres(lua.clone(), &sql, parameters);

                            match query.execute(pool).await {
                                Ok(_) => Ok(()),
                                Err(e) => Err(mlua::Error::runtime(format!(
                                    "Error executing the query: {e:#?}"
                                ))),
                            }
                        }
                    },
                    None => Err(mlua::Error::runtime("The connection is closed")),
                }
            },
        );

        macro_rules! query_pragma {
            ($type:ty, $lua:ident, $sql:ident, $db:ident) => {
                match &$db {
                    DatabaseType::Sqlite(pool) => {
                        match sqlx::query_scalar::<_, $type>(&$sql)
                            .fetch_optional(pool)
                            .await
                        {
                            Ok(row) => {
                                if let Some(row) = row {
                                    $lua.to_value(&row)
                                } else {
                                    Ok(mlua::Value::Nil)
                                }
                            }
                            Err(e) => Err(e.into_lua_err()),
                        }
                    }
                    DatabaseType::Postgres(pool) => {
                        match sqlx::query_scalar::<_, $type>(&$sql)
                            .fetch_optional(pool)
                            .await
                        {
                            Ok(row) => {
                                if let Some(row) = row {
                                    $lua.to_value(&row)
                                } else {
                                    Ok(mlua::Value::Nil)
                                }
                            }
                            Err(e) => Err(e.into_lua_err()),
                        }
                    }
                }
            };
        }

        methods.add_async_method("query_pragma_int", |lua, this, sql: String| async move {
            match &this.db {
                Some(db) => query_pragma!(i32, lua, sql, db), // returns NULL not nil
                None => Err(mlua::Error::runtime("The connection is closed")),
            }
        });

        methods.add_async_method("query_pragma_text", |lua, this, sql: String| async move {
            match &this.db {
                Some(db) => query_pragma!(String, lua, sql, db),
                None => Err(mlua::Error::runtime("The connection is closed")),
            }
        });

        methods.add_async_method(
            "query_one",
            |lua, this, (sql, parameters): (String, Option<mlua::Table>)| async move {
                match &this.db {
                    Some(db) => match &db {
                        DatabaseType::Sqlite(pool) => {
                            let query = query_builder_sqlite(lua.clone(), &sql, parameters);

                            match query.fetch_one(pool).await {
                                Ok(row) => Ok(parse_sql_to_lua_sqlite(&lua, &row)?),
                                Err(e) => Err(mlua::Error::runtime(format!(
                                    "Error executing the query: {e:#?}"
                                ))),
                            }
                        }
                        DatabaseType::Postgres(pool) => {
                            let query = query_builder_postgres(lua.clone(), &sql, parameters);

                            match query.fetch_one(pool).await {
                                Ok(row) => Ok(parse_sql_to_lua_postgres(&lua, &row)?),
                                Err(e) => Err(mlua::Error::runtime(format!(
                                    "Error executing the query: {e:#?}"
                                ))),
                            }
                        }
                    },
                    None => Err(mlua::Error::runtime("The connection is closed")),
                }
            },
        );

        methods.add_async_method(
            "query_all",
            |lua, this, (sql, parameters): (String, Option<mlua::Table>)| async move {
                match &this.db {
                    Some(db) => match &db {
                        DatabaseType::Sqlite(pool) => {
                            let query = query_builder_sqlite(lua.clone(), &sql, parameters);

                            match query.fetch_all(pool).await {
                                Ok(rows) => {
                                    let mut vec = Vec::new();

                                    for row in rows {
                                        let sql_row_lua = parse_sql_to_lua_sqlite(&lua, &row)?;
                                        vec.push(sql_row_lua);
                                    }

                                    Ok(vec)
                                }
                                Err(e) => Err(mlua::Error::runtime(format!(
                                    "Error executing the query: {e:#?}"
                                ))),
                            }
                        }
                        DatabaseType::Postgres(pool) => {
                            let query = query_builder_postgres(lua.clone(), &sql, parameters);

                            match query.fetch_all(pool).await {
                                Ok(rows) => {
                                    let mut vec = Vec::new();

                                    for row in rows {
                                        let sql_row_lua = parse_sql_to_lua_postgres(&lua, &row)?;
                                        vec.push(sql_row_lua);
                                    }

                                    Ok(vec)
                                }
                                Err(e) => Err(mlua::Error::runtime(format!(
                                    "Error executing the query: {e:#?}"
                                ))),
                            }
                        }
                    },
                    None => Err(mlua::Error::runtime("The connection is closed")),
                }
            },
        );

        methods.add_async_method_mut("close", |_, mut this, _: ()| async move {
            if let Some(db) = &this.db {
                match db {
                    DatabaseType::Sqlite(pool) => pool.close().await,
                    DatabaseType::Postgres(pool) => pool.close().await,
                };
            }
            this.db = None;

            Ok(())
        });
    }
}