Add sqlite support

This commit is contained in:
Citlali del Rey 2023-02-22 21:35:46 -08:00
parent de5c4c13d4
commit e999d1309e
Signed by: nullobsi
GPG Key ID: 933A1F44222C2634
5 changed files with 43 additions and 6 deletions

View File

@ -9,6 +9,7 @@ WriteMakefile(
'Mojolicious' => '9.27',
'Mojolicious::Plugin::OpenAPI' => '5.07',
'Mojo::Pg' => '4.27',
'Mojo::SQLite' => '3.009',
'Crypt::Random' => '1.25',
'Number::Bytes::Human' => '0.11',
},

View File

@ -5,6 +5,7 @@ use experimental q/signatures/;
use Mojo::Base 'Mojolicious', -signatures;
use Mojo::Pg;
use Mojo::SQLite;
use IpfsUpload::Model::Users;
use IpfsUpload::Model::Pins;
use IpfsUpload::Util;
@ -30,12 +31,19 @@ sub startup($self) {
},
);
if ($config->{database}->{type} ne "postgres") {
die "Only postgres is supported";
my @dbs = qw/postgres sqlite/;
my $dbtype = $config->{database}->{type};
if (not grep $_ eq $dbtype, @dbs) {
die "Database type is not supported";
}
$self->helper(sql => sub ($app) {
state $sql = Mojo::Pg->new($config->{'database'}->{connection});
if ($dbtype eq "postgres") {
state $sql = Mojo::Pg->new($config->{database}->{connection});
} elsif ($dbtype eq "sqlite") {
state $sql = Mojo::SQLite->new($config->{database}->{connection});
}
});
$self->helper(pins => sub ($app) {

View File

@ -40,7 +40,7 @@ sub cid_count($self, $cid) {
}
sub count($self, $where) {
return $self->sql->db->select_p('pins', 'count(*)', $where)->then(sub ($res) {
return $self->sql->db->select_p('pins', 'count(*) as count', $where)->then(sub ($res) {
return $res->hash->{count};
});
}

View File

@ -59,8 +59,9 @@ sub list_tokens($self, $uid) {
sub getOrMake($self, $username) {
return $self->sql->db->select_p('users', ['uid'], {username => $username})->then(sub ($res) {
if ($res->rows != 0) {
return $res->hash->{uid};
my $val = $res->hash;
if (defined $val) {
return $val->{uid};
}
return $self->sql->db->insert_p('users', {username => $username}, {returning => 'uid'})->then(sub ($n) {
return $n->hash->{uid};

27
schema/schema.sql Normal file
View File

@ -0,0 +1,27 @@
create table users (
uid integer not null primary key,
username text unique not null
);
create table access_token (
uid integer NOT NULL,
token text unique NOT NULL,
app_name text NOT NULL,
id integer NOT NULL primary key,
foreign key (uid) references users(uid)
);
create table pins (
id text not null primary key default (lower(hex( randomblob(4)) || '-' || hex( randomblob(2))
|| '-' || '4' || substr( hex( randomblob(2)), 2) || '-'
|| substr('AB89', 1 + (abs(random()) % 4) , 1) ||
substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6)))),
created_at text default (strftime('%Y-%m-%dT%H:%M:%SZ')) not null,
cid text not null,
name text not null,
uid integer not null,
app_name text not null,
foreign key (uid) references users(uid)
);
create unique index pins_cid_uid_uindex on pins (cid, uid);