mshtml: Added IHTMLStyleSheet::get_rules implementation.
[wine] / dlls / msi / database.c
1 /*
2  * Implementation of the Microsoft Installer (msi.dll)
3  *
4  * Copyright 2002,2003,2004,2005 Mike McCormack for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdarg.h>
22
23 #define COBJMACROS
24 #define NONAMELESSUNION
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "wine/debug.h"
31 #include "wine/unicode.h"
32 #include "msi.h"
33 #include "msiquery.h"
34 #include "msipriv.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "msiserver.h"
38
39 #include "initguid.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(msi);
42
43 DEFINE_GUID( CLSID_MsiDatabase, 0x000c1084, 0x0000, 0x0000,
44              0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46);
45 DEFINE_GUID( CLSID_MsiPatch, 0x000c1086, 0x0000, 0x0000,
46              0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46);
47
48 /*
49  *  .MSI  file format
50  *
51  *  An .msi file is a structured storage file.
52  *  It contains a number of streams.
53  *  A stream for each table in the database.
54  *  Two streams for the string table in the database.
55  *  Any binary data in a table is a reference to a stream.
56  */
57
58 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
59 {
60     MSIDATABASE *db = (MSIDATABASE *) arg;
61
62     msi_free(db->path);
63     free_cached_tables( db );
64     msi_free_transforms( db );
65     msi_destroy_stringtable( db->strings );
66     IStorage_Release( db->storage );
67     if (db->deletefile)
68     {
69         DeleteFileW( db->deletefile );
70         msi_free( db->deletefile );
71     }
72 }
73
74 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
75 {
76     IStorage *stg = NULL;
77     HRESULT r;
78     MSIDATABASE *db = NULL;
79     UINT ret = ERROR_FUNCTION_FAILED;
80     LPCWSTR szMode, save_path;
81     STATSTG stat;
82     BOOL created = FALSE;
83     WCHAR path[MAX_PATH];
84
85     static const WCHAR backslash[] = {'\\',0};
86     static WCHAR szTables[]  = { '_','T','a','b','l','e','s',0 };
87
88     TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
89
90     if( !pdb )
91         return ERROR_INVALID_PARAMETER;
92
93     save_path = szDBPath;
94     szMode = szPersist;
95     if( HIWORD( szPersist ) )
96     {
97         if (!CopyFileW( szDBPath, szPersist, FALSE ))
98             return ERROR_OPEN_FAILED;
99
100         szDBPath = szPersist;
101         szPersist = MSIDBOPEN_TRANSACT;
102         created = TRUE;
103     }
104
105     if( szPersist == MSIDBOPEN_READONLY )
106     {
107         r = StgOpenStorage( szDBPath, NULL,
108               STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
109     }
110     else if( szPersist == MSIDBOPEN_CREATE || szPersist == MSIDBOPEN_CREATEDIRECT )
111     {
112         /* FIXME: MSIDBOPEN_CREATE should case STGM_TRANSACTED flag to be
113          * used here: */
114         r = StgCreateDocfile( szDBPath,
115               STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg);
116         if( r == ERROR_SUCCESS )
117         {
118             IStorage_SetClass( stg, &CLSID_MsiDatabase );
119             /* create the _Tables stream */
120             r = write_stream_data(stg, szTables, NULL, 0, TRUE);
121             if (!FAILED(r))
122                 r = msi_init_string_table( stg );
123         }
124         created = TRUE;
125     }
126     else if( szPersist == MSIDBOPEN_TRANSACT )
127     {
128         /* FIXME: MSIDBOPEN_TRANSACT should case STGM_TRANSACTED flag to be
129          * used here: */
130         r = StgOpenStorage( szDBPath, NULL,
131               STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
132     }
133     else if( szPersist == MSIDBOPEN_DIRECT )
134     {
135         r = StgOpenStorage( szDBPath, NULL,
136               STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
137     }
138     else
139     {
140         ERR("unknown flag %p\n",szPersist);
141         return ERROR_INVALID_PARAMETER;
142     }
143
144     if( FAILED( r ) || !stg )
145     {
146         FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
147         return ERROR_FUNCTION_FAILED;
148     }
149
150     r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
151     if( FAILED( r ) )
152     {
153         FIXME("Failed to stat storage\n");
154         goto end;
155     }
156
157     if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
158          !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) ) 
159     {
160         ERR("storage GUID is not a MSI database GUID %s\n",
161              debugstr_guid(&stat.clsid) );
162         goto end;
163     }
164
165     db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
166                               MSI_CloseDatabase );
167     if( !db )
168     {
169         FIXME("Failed to allocate a handle\n");
170         goto end;
171     }
172
173     if (!strchrW( save_path, '\\' ))
174     {
175         GetCurrentDirectoryW( MAX_PATH, path );
176         lstrcatW( path, backslash );
177         lstrcatW( path, save_path );
178     }
179     else
180         lstrcpyW( path, save_path );
181
182     db->path = strdupW( path );
183
184     if( TRACE_ON( msi ) )
185         enum_stream_names( stg );
186
187     db->storage = stg;
188     db->mode = szMode;
189     if (created)
190         db->deletefile = strdupW( szDBPath );
191     else
192         db->deletefile = NULL;
193     list_init( &db->tables );
194     list_init( &db->transforms );
195
196     db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
197     if( !db->strings )
198         goto end;
199
200     msi_table_set_strref( db->bytes_per_strref );
201     ret = ERROR_SUCCESS;
202
203     msiobj_addref( &db->hdr );
204     IStorage_AddRef( stg );
205     *pdb = db;
206
207 end:
208     if( db )
209         msiobj_release( &db->hdr );
210     if( stg )
211         IStorage_Release( stg );
212
213     return ret;
214 }
215
216 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
217 {
218     MSIDATABASE *db;
219     UINT ret;
220
221     TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
222
223     ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
224     if( ret == ERROR_SUCCESS )
225     {
226         *phDB = alloc_msihandle( &db->hdr );
227         if (! *phDB)
228             ret = ERROR_NOT_ENOUGH_MEMORY;
229         msiobj_release( &db->hdr );
230     }
231
232     return ret;
233 }
234
235 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
236 {
237     HRESULT r = ERROR_FUNCTION_FAILED;
238     LPWSTR szwDBPath = NULL, szwPersist = NULL;
239
240     TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
241
242     if( szDBPath )
243     {
244         szwDBPath = strdupAtoW( szDBPath );
245         if( !szwDBPath )
246             goto end;
247     }
248
249     if( HIWORD(szPersist) )
250     {
251         szwPersist = strdupAtoW( szPersist );
252         if( !szwPersist )
253             goto end;
254     }
255     else
256         szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
257
258     r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
259
260 end:
261     if( HIWORD(szPersist) )
262         msi_free( szwPersist );
263     msi_free( szwDBPath );
264
265     return r;
266 }
267
268 static LPWSTR msi_read_text_archive(LPCWSTR path)
269 {
270     HANDLE file;
271     LPSTR data = NULL;
272     LPWSTR wdata = NULL;
273     DWORD read, size = 0;
274
275     file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
276     if (file == INVALID_HANDLE_VALUE)
277         return NULL;
278
279     size = GetFileSize( file, NULL );
280     data = msi_alloc( size + 1 );
281     if (!data)
282         goto done;
283
284     if (!ReadFile( file, data, size, &read, NULL ))
285         goto done;
286
287     data[size] = '\0';
288     wdata = strdupAtoW( data );
289
290 done:
291     CloseHandle( file );
292     msi_free( data );
293     return wdata;
294 }
295
296 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
297 {
298     LPWSTR ptr = *line, save;
299     DWORD i, count = 1;
300
301     *entries = NULL;
302
303     /* stay on this line */
304     while (*ptr && *ptr != '\n')
305     {
306         /* entries are separated by tabs */
307         if (*ptr == '\t')
308             count++;
309
310         ptr++;
311     }
312
313     *entries = msi_alloc(count * sizeof(LPWSTR));
314     if (!*entries)
315         return;
316
317     /* store pointers into the data */
318     for (i = 0, ptr = *line; i < count; i++)
319     {
320         save = ptr;
321
322         while (*ptr && *ptr != '\t' && *ptr != '\n') ptr++;
323
324         /* NULL-separate the data */
325         if (*ptr)
326             *ptr++ = '\0';
327
328         (*entries)[i] = save;
329     }
330
331     /* move to the next line if there's more, else EOF */
332     *line = ptr;
333
334     if (num_entries)
335         *num_entries = count;
336 }
337
338 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
339 {
340     LPWSTR prelude;
341     DWORD size;
342
343     static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
344
345     size = sizeof(create_fmt) + lstrlenW(table) - 2;
346     prelude = msi_alloc(size * sizeof(WCHAR));
347     if (!prelude)
348         return NULL;
349
350     sprintfW(prelude, create_fmt, table);
351     return prelude;
352 }
353
354 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
355 {
356     LPWSTR columns;
357     LPCWSTR type;
358     DWORD sql_size = 1, i, len;
359     WCHAR expanded[128], *ptr;
360     WCHAR size[10], comma[2], extra[30];
361
362     static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
363     static const WCHAR size_fmt[] = {'(','%','s',')',0};
364     static const WCHAR type_char[] = {'C','H','A','R',0};
365     static const WCHAR type_int[] = {'I','N','T',0};
366     static const WCHAR type_long[] = {'L','O','N','G',0};
367     static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
368     static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
369
370     columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
371     if (!columns)
372         return NULL;
373
374     for (i = 0; i < num_columns; i++)
375     {
376         type = NULL;
377         comma[1] = size[0] = extra[0] = '\0';
378
379         if (i == num_columns - 1)
380             comma[0] = '\0';
381         else
382             comma[0] = ',';
383
384         ptr = &types[i][1];
385         len = atolW(ptr);
386         extra[0] = '\0';
387
388         switch (types[i][0])
389         {
390             case 'l':
391                 lstrcpyW(extra, type_notnull);
392             case 'L':
393                 lstrcatW(extra, localizable);
394                 type = type_char;
395                 sprintfW(size, size_fmt, ptr);
396                 break;
397             case 's':
398                 lstrcpyW(extra, type_notnull);
399             case 'S':
400                 type = type_char;
401                 sprintfW(size, size_fmt, ptr);
402                 break;
403             case 'i':
404                 lstrcpyW(extra, type_notnull);
405             case 'I':
406                 if (len == 2)
407                     type = type_int;
408                 else
409                     type = type_long;
410                 break;
411         }
412
413         sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
414         sql_size += lstrlenW(expanded);
415
416         columns = msi_realloc(columns, sql_size * sizeof(WCHAR));
417         if (!columns)
418             return NULL;
419
420         lstrcatW(columns, expanded);
421     }
422
423     return columns;
424 }
425
426 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
427 {
428     LPWSTR postlude, keys, ptr;
429     DWORD size, key_size, i;
430
431     static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
432     static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
433
434     for (i = 0, size = 1; i < num_keys; i++)
435         size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
436
437     keys = msi_alloc(size * sizeof(WCHAR));
438     if (!keys)
439         return NULL;
440
441     for (i = 0, ptr = keys; i < num_keys; i++)
442     {
443         key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
444         sprintfW(ptr, key_fmt, primary_keys[i]);
445         ptr += key_size;
446     }
447
448     /* remove final ', ' */
449     *(ptr - 2) = '\0';
450
451     size = lstrlenW(postlude_fmt) + size - 1;
452     postlude = msi_alloc(size * sizeof(WCHAR));
453     if (!postlude)
454         goto done;
455
456     sprintfW(postlude, postlude_fmt, keys);
457
458 done:
459     msi_free(keys);
460     return postlude;
461 }
462
463 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
464 {
465     UINT r;
466     DWORD size;
467     MSIQUERY *view;
468     LPWSTR create_sql;
469     LPWSTR prelude, columns_sql, postlude;
470
471     prelude = msi_build_createsql_prelude(labels[0]);
472     columns_sql = msi_build_createsql_columns(columns, types, num_columns);
473     postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
474
475     if (!prelude || !columns_sql || !postlude)
476         return ERROR_OUTOFMEMORY;
477
478     size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
479     create_sql = msi_alloc(size * sizeof(WCHAR));
480     if (!create_sql)
481         return ERROR_OUTOFMEMORY;
482
483     lstrcpyW(create_sql, prelude);
484     lstrcatW(create_sql, columns_sql);
485     lstrcatW(create_sql, postlude);
486
487     msi_free(prelude);
488     msi_free(columns_sql);
489     msi_free(postlude);
490
491     r = MSI_DatabaseOpenViewW( db, create_sql, &view );
492     msi_free(create_sql);
493
494     if (r != ERROR_SUCCESS)
495         return r;
496
497     r = MSI_ViewExecute(view, NULL);
498     MSI_ViewClose(view);
499     msiobj_release(&view->hdr);
500
501     return r;
502 }
503
504 static LPWSTR msi_build_insertsql_prelude(LPWSTR table)
505 {
506     LPWSTR prelude;
507     DWORD size;
508
509     static const WCHAR insert_fmt[] = {'I','N','S','E','R','T',' ','I','N','T','O',' ','`','%','s','`',' ','(',' ',0};
510
511     size = sizeof(insert_fmt) + lstrlenW(table) - 2;
512     prelude = msi_alloc(size * sizeof(WCHAR));
513     if (!prelude)
514         return NULL;
515
516     sprintfW(prelude, insert_fmt, table);
517     return prelude;
518 }
519
520 static LPWSTR msi_build_insertsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
521 {
522     LPWSTR columns;
523     DWORD sql_size = 1, i;
524     WCHAR expanded[128];
525
526     static const WCHAR column_fmt[] =  {'`','%','s','`',',',' ',0};
527
528     columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
529     if (!columns)
530         return NULL;
531
532     for (i = 0; i < num_columns; i++)
533     {
534         sprintfW(expanded, column_fmt, columns_data[i]);
535         sql_size += lstrlenW(expanded);
536
537         if (i == num_columns - 1)
538         {
539             sql_size -= 2;
540             expanded[lstrlenW(expanded) - 2] = '\0';
541         }
542
543         columns = msi_realloc(columns, sql_size * sizeof(WCHAR));
544         if (!columns)
545             return NULL;
546
547         lstrcatW(columns, expanded);
548     }
549
550     return columns;
551 }
552
553 static LPWSTR msi_build_insertsql_data(LPWSTR **records, LPWSTR *types, DWORD num_columns, DWORD irec)
554 {
555     LPWSTR columns;
556     DWORD sql_size = 1, i;
557     WCHAR expanded[128];
558
559     static const WCHAR str_fmt[] = {'\'','%','s','\'',',',' ',0};
560     static const WCHAR int_fmt[] = {'%','s',',',' ',0};
561     static const WCHAR empty[] = {'\'','\'',',',' ',0};
562
563     columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
564     if (!columns)
565         return NULL;
566
567     for (i = 0; i < num_columns; i++)
568     {
569         switch (types[i][0])
570         {
571             case 'L': case 'l': case 'S': case 's':
572                 sprintfW(expanded, str_fmt, records[irec][i]);
573                 break;
574             case 'I': case 'i':
575                 if (*records[0][i])
576                     sprintfW(expanded, int_fmt, records[irec][i]);
577                 else
578                     lstrcpyW(expanded, empty);
579                 break;
580             default:
581                 return NULL;
582         }
583
584         if (i == num_columns - 1)
585             expanded[lstrlenW(expanded) - 2] = '\0';
586
587         sql_size += lstrlenW(expanded);
588         columns = msi_realloc(columns, sql_size * sizeof(WCHAR));
589         if (!columns)
590             return NULL;
591
592         lstrcatW(columns, expanded);
593     }
594
595     return columns;
596 }
597
598 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
599                                      LPWSTR *labels, LPWSTR **records,
600                                      int num_columns, int num_records)
601 {
602     MSIQUERY *view;
603     LPWSTR insert_sql;
604     DWORD size, i;
605     UINT r = ERROR_SUCCESS;
606
607     static const WCHAR mid[] = {' ',')',' ','V','A','L','U','E','S',' ','(',' ',0};
608     static const WCHAR end[] = {' ',')',0};
609
610     LPWSTR prelude = msi_build_insertsql_prelude(labels[0]);
611     LPWSTR columns_sql = msi_build_insertsql_columns(columns, types, num_columns);
612     
613     for (i = 0; i < num_records; i++)
614     {
615         LPWSTR data = msi_build_insertsql_data(records, types, num_columns, i);
616
617         size = lstrlenW(prelude) + lstrlenW(columns_sql) + sizeof(mid) + lstrlenW(data) + sizeof(end) - 1; 
618         insert_sql = msi_alloc(size * sizeof(WCHAR));
619         if (!insert_sql)
620             return ERROR_OUTOFMEMORY;
621     
622         lstrcpyW(insert_sql, prelude);
623         lstrcatW(insert_sql, columns_sql);
624         lstrcatW(insert_sql, mid);
625         lstrcatW(insert_sql, data);
626         lstrcatW(insert_sql, end);
627
628         msi_free(data);
629
630         r = MSI_DatabaseOpenViewW( db, insert_sql, &view );
631         msi_free(insert_sql);
632
633         if (r != ERROR_SUCCESS)
634             goto done;
635
636         r = MSI_ViewExecute(view, NULL);
637         MSI_ViewClose(view);
638         msiobj_release(&view->hdr);
639     }
640
641 done:
642     msi_free(prelude);
643     msi_free(columns_sql);
644
645     return r;
646 }
647
648 UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
649 {
650     UINT r;
651     DWORD len, i;
652     DWORD num_labels;
653     DWORD num_columns, num_records = 0;
654     LPWSTR *columns, *types, *labels;
655     LPWSTR path, ptr, data;
656     LPWSTR **records;
657
658     static const WCHAR backslash[] = {'\\',0};
659
660     TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
661
662     if( folder == NULL || file == NULL )
663         return ERROR_INVALID_PARAMETER;
664
665     len = lstrlenW(folder) + lstrlenW(backslash) + lstrlenW(file) + 1;
666     path = msi_alloc( len * sizeof(WCHAR) );
667     if (!path)
668         return ERROR_OUTOFMEMORY;
669
670     lstrcpyW( path, folder );
671     lstrcatW( path, backslash );
672     lstrcatW( path, file );
673
674     data = msi_read_text_archive( path );
675
676     ptr = data;
677     msi_parse_line( &ptr, &columns, &num_columns );
678     msi_parse_line( &ptr, &types, NULL );
679     msi_parse_line( &ptr, &labels, &num_labels );
680
681     records = msi_alloc(sizeof(LPWSTR *));
682     if (!records)
683         return ERROR_OUTOFMEMORY;
684
685     /* read in the table records */
686     while (*ptr)
687     {
688         msi_parse_line( &ptr, &records[num_records], NULL );
689
690         num_records++;
691         records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
692         if (!records)
693             return ERROR_OUTOFMEMORY;
694     }
695
696     r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
697     if (r != ERROR_SUCCESS)
698         goto done;
699
700     r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records );
701
702 done:
703     msi_free(path);
704     msi_free(data);
705     msi_free(columns);
706     msi_free(types);
707     msi_free(labels);
708
709     for (i = 0; i < num_records; i++)
710         msi_free(records[i]);
711
712     msi_free(records);
713
714     return r;
715 }
716
717 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
718 {
719     MSIDATABASE *db;
720     UINT r;
721
722     TRACE("%lx %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
723
724     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
725     if( !db )
726     {
727         IWineMsiRemoteDatabase *remote_database;
728
729         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
730         if ( !remote_database )
731             return ERROR_INVALID_HANDLE;
732
733         IWineMsiRemoteDatabase_Release( remote_database );
734         WARN("MsiDatabaseImport not allowed during a custom action!\n");
735
736         return ERROR_SUCCESS;
737     }
738
739     r = MSI_DatabaseImport( db, szFolder, szFilename );
740     msiobj_release( &db->hdr );
741     return r;
742 }
743
744 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
745                LPCSTR szFolder, LPCSTR szFilename )
746 {
747     LPWSTR path = NULL, file = NULL;
748     UINT r = ERROR_OUTOFMEMORY;
749
750     TRACE("%lx %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
751
752     if( szFolder )
753     {
754         path = strdupAtoW( szFolder );
755         if( !path )
756             goto end;
757     }
758
759     if( szFilename )
760     {
761         file = strdupAtoW( szFilename );
762         if( !file )
763             goto end;
764     }
765
766     r = MsiDatabaseImportW( handle, path, file );
767
768 end:
769     msi_free( path );
770     msi_free( file );
771
772     return r;
773 }
774
775 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
776 {
777     UINT i, count, len, r = ERROR_SUCCESS;
778     const char *sep;
779     char *buffer;
780     DWORD sz;
781
782     len = 0x100;
783     buffer = msi_alloc( len );
784     if ( !buffer )
785         return ERROR_OUTOFMEMORY;
786
787     count = MSI_RecordGetFieldCount( row );
788     for ( i=start; i<=count; i++ )
789     {
790         sz = len;
791         r = MSI_RecordGetStringA( row, i, buffer, &sz );
792         if (r == ERROR_MORE_DATA)
793         {
794             char *p = msi_realloc( buffer, sz + 1 );
795             if (!p)
796                 break;
797             len = sz + 1;
798             buffer = p;
799         }
800         sz = len;
801         r = MSI_RecordGetStringA( row, i, buffer, &sz );
802         if (r != ERROR_SUCCESS)
803             break;
804
805         if (!WriteFile( handle, buffer, sz, &sz, NULL ))
806         {
807             r = ERROR_FUNCTION_FAILED;
808             break;
809         }
810
811         sep = (i < count) ? "\t" : "\r\n";
812         if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
813         {
814             r = ERROR_FUNCTION_FAILED;
815             break;
816         }
817     }
818     msi_free( buffer );
819     return r;
820 }
821
822 static UINT msi_export_row( MSIRECORD *row, void *arg )
823 {
824     return msi_export_record( arg, row, 1 );
825 }
826
827 UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
828                LPCWSTR folder, LPCWSTR file )
829 {
830     static const WCHAR query[] = {
831         's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
832     static const WCHAR szbs[] = { '\\', 0 };
833     MSIRECORD *rec = NULL;
834     MSIQUERY *view = NULL;
835     LPWSTR filename;
836     HANDLE handle;
837     UINT len, r;
838
839     TRACE("%p %s %s %s\n", db, debugstr_w(table),
840           debugstr_w(folder), debugstr_w(file) );
841
842     if( folder == NULL || file == NULL )
843         return ERROR_INVALID_PARAMETER;
844
845     len = lstrlenW(folder) + lstrlenW(file) + 2;
846     filename = msi_alloc(len * sizeof (WCHAR));
847     if (!filename)
848         return ERROR_OUTOFMEMORY;
849
850     lstrcpyW( filename, folder );
851     lstrcatW( filename, szbs );
852     lstrcatW( filename, file );
853
854     handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
855                           NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
856     msi_free( filename );
857     if (handle == INVALID_HANDLE_VALUE)
858         return ERROR_FUNCTION_FAILED;
859
860     r = MSI_OpenQuery( db, &view, query, table );
861     if (r == ERROR_SUCCESS)
862     {
863         /* write out row 1, the column names */
864         r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
865         if (r == ERROR_SUCCESS)
866         {
867             msi_export_record( handle, rec, 1 );
868             msiobj_release( &rec->hdr );
869         }
870
871         /* write out row 2, the column types */
872         r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
873         if (r == ERROR_SUCCESS)
874         {
875             msi_export_record( handle, rec, 1 );
876             msiobj_release( &rec->hdr );
877         }
878
879         /* write out row 3, the table name + keys */
880         r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
881         if (r == ERROR_SUCCESS)
882         {
883             MSI_RecordSetStringW( rec, 0, table );
884             msi_export_record( handle, rec, 0 );
885             msiobj_release( &rec->hdr );
886         }
887
888         /* write out row 4 onwards, the data */
889         r = MSI_IterateRecords( view, 0, msi_export_row, handle );
890         msiobj_release( &view->hdr );
891     }
892
893     CloseHandle( handle );
894
895     return r;
896 }
897
898 /***********************************************************************
899  * MsiExportDatabaseW        [MSI.@]
900  *
901  * Writes a file containing the table data as tab separated ASCII.
902  *
903  * The format is as follows:
904  *
905  * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
906  * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
907  * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
908  *
909  * Followed by the data, starting at row 1 with one row per line
910  *
911  * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
912  */
913 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
914                LPCWSTR szFolder, LPCWSTR szFilename )
915 {
916     MSIDATABASE *db;
917     UINT r;
918
919     TRACE("%lx %s %s %s\n", handle, debugstr_w(szTable),
920           debugstr_w(szFolder), debugstr_w(szFilename));
921
922     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
923     if( !db )
924     {
925         IWineMsiRemoteDatabase *remote_database;
926
927         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
928         if ( !remote_database )
929             return ERROR_INVALID_HANDLE;
930
931         IWineMsiRemoteDatabase_Release( remote_database );
932         WARN("MsiDatabaseExport not allowed during a custom action!\n");
933
934         return ERROR_SUCCESS;
935     }
936
937     r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
938     msiobj_release( &db->hdr );
939     return r;
940 }
941
942 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
943                LPCSTR szFolder, LPCSTR szFilename )
944 {
945     LPWSTR path = NULL, file = NULL, table = NULL;
946     UINT r = ERROR_OUTOFMEMORY;
947
948     TRACE("%lx %s %s %s\n", handle, debugstr_a(szTable),
949           debugstr_a(szFolder), debugstr_a(szFilename));
950
951     if( szTable )
952     {
953         table = strdupAtoW( szTable );
954         if( !table )
955             goto end;
956     }
957
958     if( szFolder )
959     {
960         path = strdupAtoW( szFolder );
961         if( !path )
962             goto end;
963     }
964
965     if( szFilename )
966     {
967         file = strdupAtoW( szFilename );
968         if( !file )
969             goto end;
970     }
971
972     r = MsiDatabaseExportW( handle, table, path, file );
973
974 end:
975     msi_free( table );
976     msi_free( path );
977     msi_free( file );
978
979     return r;
980 }
981
982 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
983 {
984     MSIDBSTATE ret = MSIDBSTATE_READ;
985     MSIDATABASE *db;
986
987     TRACE("%ld\n", handle);
988
989     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
990     if( !db )
991     {
992         IWineMsiRemoteDatabase *remote_database;
993
994         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
995         if ( !remote_database )
996             return MSIDBSTATE_ERROR;
997
998         IWineMsiRemoteDatabase_Release( remote_database );
999         WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1000
1001         return MSIDBSTATE_READ;
1002     }
1003
1004     if (db->mode != MSIDBOPEN_READONLY )
1005         ret = MSIDBSTATE_WRITE;
1006     msiobj_release( &db->hdr );
1007
1008     return ret;
1009 }
1010
1011 typedef struct _msi_remote_database_impl {
1012     const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1013     MSIHANDLE database;
1014     LONG refs;
1015 } msi_remote_database_impl;
1016
1017 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
1018 {
1019     return (msi_remote_database_impl *)iface;
1020 }
1021
1022 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1023                                           REFIID riid,LPVOID *ppobj)
1024 {
1025     if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1026         IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1027     {
1028         IUnknown_AddRef( iface );
1029         *ppobj = iface;
1030         return S_OK;
1031     }
1032
1033     return E_NOINTERFACE;
1034 }
1035
1036 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1037 {
1038     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1039
1040     return InterlockedIncrement( &This->refs );
1041 }
1042
1043 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1044 {
1045     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1046     ULONG r;
1047
1048     r = InterlockedDecrement( &This->refs );
1049     if (r == 0)
1050     {
1051         MsiCloseHandle( This->database );
1052         msi_free( This );
1053     }
1054     return r;
1055 }
1056
1057 HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1058                                       BSTR table, MSICONDITION *persistent )
1059 {
1060     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1061     *persistent = MsiDatabaseIsTablePersistentW(This->database, (LPWSTR)table);
1062     return S_OK;
1063 }
1064
1065 HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1066                                    BSTR table, MSIHANDLE *keys )
1067 {
1068     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1069     UINT r = MsiDatabaseGetPrimaryKeysW(This->database, (LPWSTR)table, keys);
1070     return HRESULT_FROM_WIN32(r);
1071 }
1072
1073 HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1074                                           UINT updatecount, MSIHANDLE *suminfo )
1075 {
1076     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1077     UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1078     return HRESULT_FROM_WIN32(r);
1079 }
1080
1081 HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1082                              BSTR query, MSIHANDLE *view )
1083 {
1084     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1085     UINT r = MsiDatabaseOpenViewW(This->database, (LPWSTR)query, view);
1086     return HRESULT_FROM_WIN32(r);
1087 }
1088
1089 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1090 {
1091     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1092     This->database = handle;
1093     return S_OK;
1094 }
1095
1096 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
1097 {
1098     mrd_QueryInterface,
1099     mrd_AddRef,
1100     mrd_Release,
1101     mrd_IsTablePersistent,
1102     mrd_GetPrimaryKeys,
1103     mrd_GetSummaryInformation,
1104     mrd_OpenView,
1105     mrd_SetMsiHandle,
1106 };
1107
1108 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
1109 {
1110     msi_remote_database_impl *This;
1111
1112     This = msi_alloc( sizeof *This );
1113     if (!This)
1114         return E_OUTOFMEMORY;
1115
1116     This->lpVtbl = &msi_remote_database_vtbl;
1117     This->database = 0;
1118     This->refs = 1;
1119
1120     *ppObj = This;
1121
1122     return S_OK;
1123 }