lundi 19 octobre 2015

SQLite3 multiple primary key fields with autoincrement (rails project)

I'm trying to create a SQLite3 database for use with a Rails application. I have the same database created already in MySQL and am trying to replicate the same in SQLite3.

The create syntax for MySQL is

CREATE TABLE `leaderboard_A` (
  `league` tinyint(1) NOT NULL,
  `id` bigint(10) NOT NULL,
  `cut` tinyint(1) NOT NULL,
  `wd` tinyint(1) NOT NULL,
  `tie` tinyint(1) NOT NULL,
  `pos` int(4) NOT NULL,
  `pos_s` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `to_par` smallint(3) NOT NULL,
  `to_par_s` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
  `hole` varchar(8) COLLATE utf8_unicode_ci NOT NULL,
  `round` smallint(6) NOT NULL,
  `round_s` varchar(8) COLLATE utf8_unicode_ci NOT NULL,
  `round_1` int(11) NOT NULL,
  `round_2` int(11) NOT NULL,
  `round_3` int(11) NOT NULL,
  `round_4` int(11) NOT NULL,
  `total` smallint(4) NOT NULL,
  `tournament_id` varchar(13) COLLATE utf8_unicode_ci NOT NULL,
  `tournament_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `year` smallint(4) NOT NULL,
  PRIMARY KEY (`league`,`id`,`tournament_id`),
  KEY `pos` (`pos`),
  KEY `player_key` (`name`,`tournament_name`,`year`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

I believe I need to have an ID column added in for my SQLite3 schema. Is it possible to have an autoincrement column in my SQLite3 aswell as making other columns primary too?

I have some SQLite3 SQL written already with just a slightly different column setup as below.

CREATE TABLE IF NOT EXISTS Leaderboard (
id INTEGER,
current_position TEXT, 
current_round INTEGER,
country TEXT, 
is_amateur BOOLEAN, 
first_name TEXT, 
last_name TEXT,
name TEXT,
player_id INTEGER,
round1 INTEGER,
round2 INTEGER,
round3 INTEGER,
round4 INTEGER,
start_position TEXT,
status TEXT,
thru INTEGER,
today INTEGER,
total INTEGER,
tournament_name TEXT,
tournament_id INTEGER,
start_date datetime,
end_date datetime,
year INTEGER, 
PRIMARY KEY (id, player_id, tournament_id, year)
)

My eventual solution is to read in a JSON record and update the details if it exists and if not create the record using the SQL below

INSERT OR REPLACE INTO Leaderboard (
current_position, current_round, country, is_amateur, first_name, last_name, name, player_id, round1, round2, round3, round4, start_position, status, thru, today, total, tournament_name, tournament_id, start_date, end_date, year)
 VALUES
('1','4','USA','false','Jordan','Spieth','Spieth, Jordan','34046','68','67','71','69','T1','active','18','-1','-78','US Open','026','2015-06-18','2015-06-21','2015')

Any feedback, suggestions or fixes would be appreciated. New to working all this out. :)

Aucun commentaire:

Enregistrer un commentaire