1
//! Phase 7 of `doc/ops/0010-common-lisp-booleans.org`: `(eq? nil v)` / `(eq?
2
//! t v)` against a Money-typed `v` (a type `nil_repr` says is never `t` or
3
//! `nil`) must evaluate `v` once and yield `nil`, not the old
4
//! "= expects numeric arguments, got nil" compile error.
5
//!
6
//! Index and Ratio operands are covered without a database in
7
//! `scripting/nms/tests/comparison.rs`; a Money-typed runtime value only
8
//! exists behind the DB-backed `account-balance` host fn, so that case lives
9
//! here end to end: nomiscript form -> `rpc::Session` -> `server::command::*`
10
//! -> real Postgres.
11
//!
12
//! Gated on the `db` feature. Run via:
13
//!   DATABASE_URL=postgres://… cargo test -p tests-integration --features db
14

            
15
#![cfg(feature = "db")]
16

            
17
use rpc::{ScriptCtx, Session};
18
use server::db::install_test_pool;
19
use sqlx::PgPool;
20
use supp_macro::local_db_sqlx_test;
21
use uuid::Uuid;
22

            
23
5
async fn setup() {}
24

            
25
5
async fn insert_test_user(pool: &PgPool, id: Uuid) -> anyhow::Result<()> {
26
5
    sqlx::query!(
27
        "INSERT INTO users (
28
            id, user_name, email, photo, verified, user_password,
29
            user_role, database_name, created_at
30
        ) VALUES (
31
            $1, 'rpc-test-user', 'rpc-test@example.com', 'default.png',
32
            TRUE, 'irrelevant', 'user', 'rpc-test', NOW()
33
        )",
34
        id
35
    )
36
5
    .execute(pool)
37
5
    .await?;
38
5
    Ok(())
39
5
}
40

            
41
9
fn extract_id_field(response: &str) -> Option<String> {
42
9
    let needle = ":value \"";
43
9
    let start = response.find(needle)? + needle.len();
44
9
    let end = start + response[start..].find('"')?;
45
9
    Some(response[start..end].to_string())
46
9
}
47

            
48
/// Builds a fresh user with one account holding a real Money balance (a
49
/// single split of `100` in a fresh commodity), so `(account-balance
50
/// "<acct>")` produces a genuine runtime `Commodity` value rather than the
51
/// "no commodity yet" error.
52
3
async fn account_with_balance(pool: &PgPool) -> anyhow::Result<(Session, String)> {
53
3
    let user_id = Uuid::new_v4();
54
3
    insert_test_user(pool, user_id).await?;
55
3
    let mut session = Session::new(ScriptCtx::new(user_id)).expect("Session::new");
56

            
57
3
    let resp = session
58
3
        .handle_form("(:id 1 :form (create-commodity \"BAR\" \"Bar Coin\"))")
59
3
        .await;
60
3
    let commodity = extract_id_field(&resp).expect("commodity id");
61
3
    let resp = session
62
3
        .handle_form("(:id 2 :form (create-account \"Bar-A\" \"\"))")
63
3
        .await;
64
3
    let acct_a = extract_id_field(&resp).expect("account A id");
65
3
    let resp = session
66
3
        .handle_form("(:id 3 :form (create-account \"Bar-B\" \"\"))")
67
3
        .await;
68
3
    let acct_b = extract_id_field(&resp).expect("account B id");
69

            
70
3
    let tx = format!(
71
        "(:id 4 :form (create-transaction \"(:post-date \\\"2026-02-01T00:00:00Z\\\" \
72
         :note \\\"bar-tx\\\" \
73
3
         :splits ((:account-id \\\"{acct_a}\\\" :commodity-id \\\"{commodity}\\\" :value -100) \
74
3
                  (:account-id \\\"{acct_b}\\\" :commodity-id \\\"{commodity}\\\" :value 100)))\"))"
75
    );
76
3
    session.handle_form(&tx).await;
77

            
78
3
    Ok((session, acct_a))
79
3
}
80

            
81
#[local_db_sqlx_test]
82
async fn eq_nil_against_money_is_nil(pool: PgPool) -> anyhow::Result<()> {
83
    let (mut session, acct) = account_with_balance(&pool).await?;
84
    let response = session
85
        .handle_form(&format!(
86
            "(:id 5 :form (eq? nil (account-balance \"{acct}\")))"
87
        ))
88
        .await;
89
    assert!(response.contains(":id 5"), "got: {response}");
90
    assert!(
91
        response.contains(":value nil)"),
92
        "expected nil, got: {response}"
93
    );
94
}
95

            
96
#[local_db_sqlx_test]
97
async fn eq_money_against_nil_is_nil_reversed_order(pool: PgPool) -> anyhow::Result<()> {
98
    let (mut session, acct) = account_with_balance(&pool).await?;
99
    let response = session
100
        .handle_form(&format!(
101
            "(:id 6 :form (eq? (account-balance \"{acct}\") nil))"
102
        ))
103
        .await;
104
    assert!(response.contains(":id 6"), "got: {response}");
105
    assert!(
106
        response.contains(":value nil)"),
107
        "expected nil, got: {response}"
108
    );
109
}
110

            
111
#[local_db_sqlx_test]
112
async fn eq_t_against_money_is_nil(pool: PgPool) -> anyhow::Result<()> {
113
    let (mut session, acct) = account_with_balance(&pool).await?;
114
    let response = session
115
        .handle_form(&format!(
116
            "(:id 7 :form (eq? t (account-balance \"{acct}\")))"
117
        ))
118
        .await;
119
    assert!(response.contains(":id 7"), "got: {response}");
120
    assert!(
121
        response.contains(":value nil)"),
122
        "expected nil, got: {response}"
123
    );
124
}
125

            
126
/// The Money operand's real effect (a live DB lookup) must run — `eq?`
127
/// evaluating it for effect only, then discarding the value, must not skip
128
/// the call. `account-balance` on an unknown account id is an error, so if
129
/// the operand's evaluation were dropped this would wrongly succeed as nil.
130
#[local_db_sqlx_test]
131
async fn eq_nil_against_money_still_runs_the_operand(pool: PgPool) -> anyhow::Result<()> {
132
    let user_id = Uuid::new_v4();
133
    insert_test_user(&pool, user_id).await?;
134
    let mut session = Session::new(ScriptCtx::new(user_id)).expect("Session::new");
135

            
136
    let response = session
137
        .handle_form(
138
            "(:id 8 :form (eq? nil (account-balance \"00000000-0000-0000-0000-000000000000\")))",
139
        )
140
        .await;
141
    assert!(
142
        response.contains(":error") || response.contains(":code"),
143
        "expected the account-balance lookup to still run and fail, got: {response}"
144
    );
145
}
146

            
147
/// The exact shape found in review: the Money operand isn't the bare host-fn
148
/// call but a `(setf <defparameter> (account-balance …))` — a compile-time
149
/// (non-`WasmLocal`-backed) place assigned a runtime RHS. Before the SETF
150
/// fix (`compile_const_place_setf_rhs`), the const place's RHS rode
151
/// `eval_value` alone, which never emits wasm, so `account-balance` was
152
/// never actually called and this wrongly reported `nil` instead of the
153
/// missing-account error.
154
#[local_db_sqlx_test]
155
async fn eq_nil_against_setf_of_money_still_runs_the_operand(pool: PgPool) -> anyhow::Result<()> {
156
    let user_id = Uuid::new_v4();
157
    insert_test_user(&pool, user_id).await?;
158
    let mut session = Session::new(ScriptCtx::new(user_id)).expect("Session::new");
159

            
160
    let response = session
161
        .handle_form(
162
            "(:id 9 :form (progn (defparameter p7x 0) \
163
             (eq? nil (setf p7x (account-balance \"00000000-0000-0000-0000-000000000000\")))))",
164
        )
165
        .await;
166
    assert!(
167
        response.contains(":error") || response.contains(":code"),
168
        "expected the account-balance lookup (via SETF) to still run and fail, got: {response}"
169
    );
170
}