#!/usr/bin/env tclsh

set testdir [file dirname $argv0]
source $testdir/tester.tcl

# Test qualified table name access to main database
do_execsql_test_small attach-main-qualified {
    SELECT count(id) FROM main.demo;
} {5}


# Test unqualified vs qualified access
do_execsql_test_small attach-unqualified-vs-qualified {
    SELECT COUNT(*) FROM demo;
    SELECT COUNT(*) FROM main.demo;
} {5
5}

# Test attach reserved name - main (should fail)
do_execsql_test_error attach-reserved-main {
   ATTACH DATABASE "testing/testing_small.db" AS main
} {(.*in use.*)}

# Test attach reserved name - temp (should fail)
do_execsql_test_error attach-reserved-temp {
   ATTACH DATABASE "testing/testing_small.db" AS temp
} {(.*in use.*)}

# Test attach duplicate database name - arbitrary (should fail)
do_execsql_test_error attach-duplicate-name {
    ATTACH DATABASE "testing/testing_small.db" as small;
    ATTACH DATABASE "testing/testing_small.db" as small;
} {(.*in use.*)}

# Test querying attached file database
do_execsql_test_on_specific_db {:memory:} attach-db-query {
    ATTACH DATABASE "testing/testing_small.db" AS small;
    SELECT value FROM small.demo where id = 1;
} {A}

# Test detach database
do_execsql_test_on_specific_db {:memory:} detach-database {
    ATTACH DATABASE "testing/testing_small.db" AS small;
    DETACH DATABASE small;
    pragma database_list;
} {0|main|}

# Test detach non-existent database (should fail)
do_execsql_test_error detach-non-existent {
    DETACH DATABASE nonexistent;
} {(.*no such database.*)}

# Test attach in-memory database
do_execsql_test_on_specific_db {:memory:} attach-memory-database {
    ATTACH DATABASE ':memory:' AS mem;
    pragma database_list;
} {0|main|
2|mem|}

# Test join between main and attached database
do_execsql_test_on_specific_db {:memory:} attach-cross-database-join {
    ATTACH DATABASE "testing/testing_small.db" as small;
    create table joiners (id int, otherid int);
    insert into joiners (id, otherid) values (1,1);
    insert into joiners (id, otherid) values (3,3);
    select s.value from joiners j inner join small.demo s where j.otherid = s.id;
} {A
B}

# Test queries after detach (should fail for detached database)
do_execsql_test_error query-after-detach {
    ATTACH DATABASE "testing/testing_small.db" as small;
    DETACH DATABASE small;
    select * from small.sqlite_schema;
} {(.*no such.*)}

# regression test for https://github.com/tursodatabase/turso/issues/3540
do_execsql_test_on_specifc_db {:memory:} attach-from-memory-db {
	CREATE TABLE t(a);
	INSERT INTO t SELECT value from generate_series(1,10);
	ATTACH DATABASE 'testing/testing.db' as a;
	SELECT * from a.products, t LIMIT 1;
} {1|hat|79.0|1}
